4 * Read uncompressed and compressed metadata and file resources.
8 * Copyright (C) 2012 Eric Biggers
10 * This file is part of wimlib, a library for working with WIM files.
12 * wimlib is free software; you can redistribute it and/or modify it under the
13 * terms of the GNU General Public License as published by the Free Software
14 * Foundation; either version 3 of the License, or (at your option) any later
17 * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
21 * You should have received a copy of the GNU General Public License along with
22 * wimlib; if not, see http://www.gnu.org/licenses/.
31 #include <ntfs-3g/attrib.h>
32 #include <ntfs-3g/inode.h>
33 #include <ntfs-3g/dir.h>
36 #include "wimlib_internal.h"
37 #include "lookup_table.h"
51 * Reads all or part of a compressed resource into an in-memory buffer.
53 * @fp: The FILE* for the WIM file.
54 * @resource_compressed_size: The compressed size of the resource.
55 * @resource_uncompressed_size: The uncompressed size of the resource.
56 * @resource_offset: The offset of the start of the resource from
57 * the start of the stream @fp.
58 * @resource_ctype: The compression type of the resource.
59 * @len: The number of bytes of uncompressed data to read from
61 * @offset: The offset of the bytes to read within the uncompressed
63 * @contents_len: An array into which the uncompressed data is written.
64 * It must be at least @len bytes long.
66 * Returns zero on success, nonzero on failure.
68 static int read_compressed_resource(FILE *fp, u64 resource_compressed_size,
69 u64 resource_uncompressed_size,
70 u64 resource_offset, int resource_ctype,
71 u64 len, u64 offset, u8 contents_ret[])
74 DEBUG2("comp size = %"PRIu64", uncomp size = %"PRIu64", "
75 "res offset = %"PRIu64"",
76 resource_compressed_size,
77 resource_uncompressed_size,
79 DEBUG2("resource_ctype = %s, len = %"PRIu64", offset = %"PRIu64"",
80 wimlib_get_compression_type_string(resource_ctype), len, offset);
85 int (*decompress)(const void *, uint, void *, uint);
86 /* Set the appropriate decompress function. */
87 if (resource_ctype == WIM_COMPRESSION_TYPE_LZX)
88 decompress = lzx_decompress;
90 decompress = xpress_decompress;
92 /* The structure of a compressed resource consists of a table of chunk
93 * offsets followed by the chunks themselves. Each chunk consists of
94 * compressed data, and there is one chunk for each WIM_CHUNK_SIZE =
95 * 32768 bytes of the uncompressed file, with the last chunk having any
98 * The chunk offsets are measured relative to the end of the chunk
99 * table. The first chunk is omitted from the table in the WIM file
100 * because its offset is implicitly given by the fact that it directly
101 * follows the chunk table and therefore must have an offset of 0.
104 /* Calculate how many chunks the resource conists of in its entirety. */
105 u64 num_chunks = (resource_uncompressed_size + WIM_CHUNK_SIZE - 1) /
107 /* As mentioned, the first chunk has no entry in the chunk table. */
108 u64 num_chunk_entries = num_chunks - 1;
111 /* The index of the chunk that the read starts at. */
112 u64 start_chunk = offset / WIM_CHUNK_SIZE;
113 /* The byte offset at which the read starts, within the start chunk. */
114 u64 start_chunk_offset = offset % WIM_CHUNK_SIZE;
116 /* The index of the chunk that contains the last byte of the read. */
117 u64 end_chunk = (offset + len - 1) / WIM_CHUNK_SIZE;
118 /* The byte offset of the last byte of the read, within the end chunk */
119 u64 end_chunk_offset = (offset + len - 1) % WIM_CHUNK_SIZE;
121 /* Number of chunks that are actually needed to read the requested part
123 u64 num_needed_chunks = end_chunk - start_chunk + 1;
125 /* If the end chunk is not the last chunk, an extra chunk entry is
126 * needed because we need to know the offset of the chunk after the last
127 * chunk read to figure out the size of the last read chunk. */
128 if (end_chunk != num_chunks - 1)
131 /* Declare the chunk table. It will only contain offsets for the chunks
132 * that are actually needed for this read. */
133 u64 chunk_offsets[num_needed_chunks];
135 /* Set the implicit offset of the first chunk if it is included in the
138 * Note: M$'s documentation includes a picture that shows the first
139 * chunk starting right after the chunk entry table, labeled as offset
140 * 0x10. However, in the actual file format, the offset is measured
141 * from the end of the chunk entry table, so the first chunk has an
143 if (start_chunk == 0)
144 chunk_offsets[0] = 0;
146 /* According to M$'s documentation, if the uncompressed size of
147 * the file is greater than 4 GB, the chunk entries are 8-byte
148 * integers. Otherwise, they are 4-byte integers. */
149 u64 chunk_entry_size = (resource_uncompressed_size >= (u64)1 << 32) ?
152 /* Size of the full chunk table in the WIM file. */
153 u64 chunk_table_size = chunk_entry_size * num_chunk_entries;
155 /* Read the needed chunk offsets from the table in the WIM file. */
157 /* Index, in the WIM file, of the first needed entry in the
159 u64 start_table_idx = (start_chunk == 0) ? 0 : start_chunk - 1;
161 /* Number of entries we need to actually read from the chunk
162 * table (excludes the implicit first chunk). */
163 u64 num_needed_chunk_entries = (start_chunk == 0) ?
164 num_needed_chunks - 1 : num_needed_chunks;
166 /* Skip over unneeded chunk table entries. */
167 u64 file_offset_of_needed_chunk_entries = resource_offset +
168 start_table_idx * chunk_entry_size;
169 if (fseeko(fp, file_offset_of_needed_chunk_entries, SEEK_SET) != 0) {
170 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
171 "chunk table of compressed resource",
172 file_offset_of_needed_chunk_entries);
173 return WIMLIB_ERR_READ;
176 /* Number of bytes we need to read from the chunk table. */
177 size_t size = num_needed_chunk_entries * chunk_entry_size;
179 u8 chunk_tab_buf[size];
181 if (fread(chunk_tab_buf, 1, size, fp) != size)
184 /* Now fill in chunk_offsets from the entries we have read in
187 u64 *chunk_tab_p = chunk_offsets;
188 if (start_chunk == 0)
191 if (chunk_entry_size == 4) {
192 u32 *entries = (u32*)chunk_tab_buf;
193 while (num_needed_chunk_entries--)
194 *chunk_tab_p++ = le32_to_cpu(*entries++);
196 u64 *entries = (u64*)chunk_tab_buf;
197 while (num_needed_chunk_entries--)
198 *chunk_tab_p++ = le64_to_cpu(*entries++);
201 /* Done with the chunk table now. We must now seek to the first chunk
202 * that is needed for the read. */
204 u64 file_offset_of_first_needed_chunk = resource_offset +
205 chunk_table_size + chunk_offsets[0];
206 if (fseeko(fp, file_offset_of_first_needed_chunk, SEEK_SET) != 0) {
207 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
208 "first chunk of compressed resource",
209 file_offset_of_first_needed_chunk);
210 return WIMLIB_ERR_READ;
213 /* Pointer to current position in the output buffer for uncompressed
215 u8 *out_p = (u8*)contents_ret;
217 /* Buffer for compressed data. While most compressed chunks will have a
218 * size much less than WIM_CHUNK_SIZE, WIM_CHUNK_SIZE - 1 is the maximum
219 * size in the worst-case. This assumption is valid only if chunks that
220 * happen to compress to more than the uncompressed size (i.e. a
221 * sequence of random bytes) are always stored uncompressed. But this seems
222 * to be the case in M$'s WIM files, even though it is undocumented. */
223 u8 compressed_buf[WIM_CHUNK_SIZE - 1];
226 /* Decompress all the chunks. */
227 for (u64 i = start_chunk; i <= end_chunk; i++) {
229 DEBUG2("Chunk %"PRIu64" (start %"PRIu64", end %"PRIu64").",
230 i, start_chunk, end_chunk);
232 /* Calculate the sizes of the compressed chunk and of the
233 * uncompressed chunk. */
234 uint compressed_chunk_size, uncompressed_chunk_size;
235 if (i != num_chunks - 1) {
236 /* All the chunks except the last one in the resource
237 * expand to WIM_CHUNK_SIZE uncompressed, and the amount
238 * of compressed data for the chunk is given by the
239 * difference of offsets in the chunk offset table. */
240 compressed_chunk_size = chunk_offsets[i + 1 - start_chunk] -
241 chunk_offsets[i - start_chunk];
242 uncompressed_chunk_size = WIM_CHUNK_SIZE;
244 /* The last compressed chunk consists of the remaining
245 * bytes in the file resource, and the last uncompressed
246 * chunk has size equal to however many bytes are left-
247 * that is, the remainder of the uncompressed size when
248 * divided by WIM_CHUNK_SIZE.
250 * Note that the resource_compressed_size includes the
251 * chunk table, so the size of it must be subtracted. */
252 compressed_chunk_size = resource_compressed_size -
254 chunk_offsets[i - start_chunk];
256 uncompressed_chunk_size = resource_uncompressed_size %
259 /* If the remainder is 0, the last chunk actually
260 * uncompresses to a full WIM_CHUNK_SIZE bytes. */
261 if (uncompressed_chunk_size == 0)
262 uncompressed_chunk_size = WIM_CHUNK_SIZE;
265 DEBUG2("compressed_chunk_size = %u, "
266 "uncompressed_chunk_size = %u",
267 compressed_chunk_size, uncompressed_chunk_size);
270 /* Figure out how much of this chunk we actually need to read */
272 if (i == start_chunk)
273 start_offset = start_chunk_offset;
278 end_offset = end_chunk_offset;
280 end_offset = WIM_CHUNK_SIZE - 1;
282 u64 partial_chunk_size = end_offset + 1 - start_offset;
283 bool is_partial_chunk = (partial_chunk_size !=
284 uncompressed_chunk_size);
286 DEBUG2("start_offset = %u, end_offset = %u", start_offset,
288 DEBUG2("partial_chunk_size = %u", partial_chunk_size);
290 /* This is undocumented, but chunks can be uncompressed. This
291 * appears to always be the case when the compressed chunk size
292 * is equal to the uncompressed chunk size. */
293 if (compressed_chunk_size == uncompressed_chunk_size) {
294 /* Probably an uncompressed chunk */
296 if (start_offset != 0) {
297 if (fseeko(fp, start_offset, SEEK_CUR) != 0) {
298 ERROR_WITH_ERRNO("Uncompressed partial "
299 "chunk fseek() error");
300 return WIMLIB_ERR_READ;
303 if (fread(out_p, 1, partial_chunk_size, fp) !=
307 /* Compressed chunk */
310 /* Read the compressed data into compressed_buf. */
311 if (fread(compressed_buf, 1, compressed_chunk_size,
312 fp) != compressed_chunk_size)
315 /* For partial chunks we must buffer the uncompressed
316 * data because we don't need all of it. */
317 if (is_partial_chunk) {
318 u8 uncompressed_buf[uncompressed_chunk_size];
320 ret = decompress(compressed_buf,
321 compressed_chunk_size,
323 uncompressed_chunk_size);
325 return WIMLIB_ERR_DECOMPRESSION;
326 memcpy(out_p, uncompressed_buf + start_offset,
329 ret = decompress(compressed_buf,
330 compressed_chunk_size,
332 uncompressed_chunk_size);
334 return WIMLIB_ERR_DECOMPRESSION;
338 /* Advance the pointer into the uncompressed output data by the
339 * number of uncompressed bytes that were written. */
340 out_p += partial_chunk_size;
347 ERROR("Unexpected EOF in compressed file resource");
349 ERROR_WITH_ERRNO("Error reading compressed file resource");
350 return WIMLIB_ERR_READ;
354 * Reads uncompressed data from an open file stream.
356 int read_uncompressed_resource(FILE *fp, u64 offset, u64 len,
359 if (fseeko(fp, offset, SEEK_SET) != 0) {
360 ERROR("Failed to seek to byte %"PRIu64" of input file "
361 "to read uncompressed resource (len = %"PRIu64")",
363 return WIMLIB_ERR_READ;
365 if (fread(contents_ret, 1, len, fp) != len) {
367 ERROR("Unexpected EOF in uncompressed file resource");
369 ERROR("Failed to read %"PRIu64" bytes from "
370 "uncompressed resource at offset %"PRIu64,
373 return WIMLIB_ERR_READ;
381 /* Reads the contents of a struct resource_entry, as represented in the on-disk
382 * format, from the memory pointed to by @p, and fills in the fields of @entry.
383 * A pointer to the byte after the memory read at @p is returned. */
384 const u8 *get_resource_entry(const u8 *p, struct resource_entry *entry)
389 p = get_u56(p, &size);
390 p = get_u8(p, &flags);
392 entry->flags = flags;
393 p = get_u64(p, &entry->offset);
394 p = get_u64(p, &entry->original_size);
398 /* Copies the struct resource_entry @entry to the memory pointed to by @p in the
399 * on-disk format. A pointer to the byte after the memory written at @p is
401 u8 *put_resource_entry(u8 *p, const struct resource_entry *entry)
403 p = put_u56(p, entry->size);
404 p = put_u8(p, entry->flags);
405 p = put_u64(p, entry->offset);
406 p = put_u64(p, entry->original_size);
411 * Reads some data from the resource corresponding to a WIM lookup table entry.
413 * @lte: The WIM lookup table entry for the resource.
414 * @buf: Buffer into which to write the data.
415 * @size: Number of bytes to read.
416 * @offset: Offset at which to start reading the resource.
417 * @raw: If %true, compressed data is read literally rather than being
418 * decompressed first.
420 * Returns zero on success, nonzero on failure.
422 int read_wim_resource(const struct lookup_table_entry *lte, u8 buf[],
423 size_t size, u64 offset, bool raw)
425 /* We shouldn't be allowing read over-runs in any part of the library.
428 wimlib_assert(offset + size <= lte->resource_entry.size);
430 wimlib_assert(offset + size <= lte->resource_entry.original_size);
435 switch (lte->resource_location) {
436 case RESOURCE_IN_WIM:
437 /* The resource is in a WIM file, and its WIMStruct is given by
438 * the lte->wim member. The resource may be either compressed
439 * or uncompressed. */
440 wimlib_assert(lte->wim);
441 wimlib_assert(lte->wim->fp);
442 ctype = wim_resource_compression_type(lte);
444 wimlib_assert(ctype != WIM_COMPRESSION_TYPE_NONE ||
445 (lte->resource_entry.original_size ==
446 lte->resource_entry.size));
448 if (raw || ctype == WIM_COMPRESSION_TYPE_NONE)
449 return read_uncompressed_resource(lte->wim->fp,
450 lte->resource_entry.offset + offset,
453 return read_compressed_resource(lte->wim->fp,
454 lte->resource_entry.size,
455 lte->resource_entry.original_size,
456 lte->resource_entry.offset,
457 ctype, size, offset, buf);
459 case RESOURCE_IN_STAGING_FILE:
460 case RESOURCE_IN_FILE_ON_DISK:
461 /* The resource is in some file on the external filesystem and
462 * needs to be read uncompressed */
463 wimlib_assert(lte->file_on_disk);
464 wimlib_assert(<e->file_on_disk == <e->staging_file_name);
465 /* Use existing file pointer if available; otherwise open one
467 if (lte->file_on_disk_fp) {
468 fp = lte->file_on_disk_fp;
470 fp = fopen(lte->file_on_disk, "rb");
472 ERROR_WITH_ERRNO("Failed to open the file "
473 "`%s'", lte->file_on_disk);
474 return WIMLIB_ERR_OPEN;
477 ret = read_uncompressed_resource(fp, offset, size, buf);
478 if (fp != lte->file_on_disk_fp)
482 case RESOURCE_IN_ATTACHED_BUFFER:
483 /* The resource is directly attached uncompressed in an
484 * in-memory buffer. */
485 wimlib_assert(lte->attached_buffer);
486 memcpy(buf, lte->attached_buffer + offset, size);
490 case RESOURCE_IN_NTFS_VOLUME:
491 wimlib_assert(lte->ntfs_loc);
494 if (lte->ntfs_loc->is_reparse_point)
495 adjusted_offset = offset + 8;
497 adjusted_offset = offset;
498 if (ntfs_attr_pread(lte->attr, offset, size, buf) == size) {
501 ERROR_WITH_ERRNO("Error reading NTFS attribute "
503 lte->ntfs_loc->path_utf8);
504 return WIMLIB_ERR_NTFS_3G;
517 * Reads all the data from the resource corresponding to a WIM lookup table
520 * @lte: The WIM lookup table entry for the resource.
521 * @buf: Buffer into which to write the data. It must be at least
522 * wim_resource_size(lte) bytes long.
524 * Returns 0 on success; nonzero on failure.
526 int read_full_wim_resource(const struct lookup_table_entry *lte, u8 buf[])
528 return read_wim_resource(lte, buf, wim_resource_size(lte), 0, false);
531 /* Chunk table that's located at the beginning of each compressed resource in
532 * the WIM. (This is not the on-disk format; the on-disk format just has an
533 * array of offsets.) */
537 u64 original_resource_size;
538 u64 bytes_per_chunk_entry;
546 * Allocates and initializes a chunk table, and reserves space for it in the
550 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
553 struct chunk_table **chunk_tab_ret)
555 u64 size = wim_resource_size(lte);
556 u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
557 size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
558 struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
563 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
565 ret = WIMLIB_ERR_NOMEM;
568 chunk_tab->file_offset = file_offset;
569 chunk_tab->num_chunks = num_chunks;
570 chunk_tab->original_resource_size = size;
571 chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
572 chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
574 chunk_tab->cur_offset = 0;
575 chunk_tab->cur_offset_p = chunk_tab->offsets;
577 if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
578 chunk_tab->table_disk_size) {
579 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
581 ret = WIMLIB_ERR_WRITE;
587 *chunk_tab_ret = chunk_tab;
592 * Compresses a chunk of a WIM resource.
594 * @chunk: Uncompressed data of the chunk.
595 * @chunk_size: Size of the uncompressed chunk in bytes.
596 * @compressed_chunk: Pointer to output buffer of size at least
597 * (@chunk_size - 1) bytes.
598 * @compressed_chunk_len_ret: Pointer to an unsigned int into which the size
599 * of the compressed chunk will be
601 * @ctype: Type of compression to use. Must be WIM_COMPRESSION_TYPE_LZX
602 * or WIM_COMPRESSION_TYPE_XPRESS.
604 * Returns zero if compressed succeeded, and nonzero if the chunk could not be
605 * compressed to any smaller than @chunk_size. This function cannot fail for
608 static int compress_chunk(const u8 chunk[], unsigned chunk_size,
609 u8 compressed_chunk[],
610 unsigned *compressed_chunk_len_ret,
613 int (*compress)(const void *, unsigned, void *, unsigned *);
615 case WIM_COMPRESSION_TYPE_LZX:
616 compress = lzx_compress;
618 case WIM_COMPRESSION_TYPE_XPRESS:
619 compress = xpress_compress;
625 return (*compress)(chunk, chunk_size, compressed_chunk,
626 compressed_chunk_len_ret);
630 * Writes a chunk of a WIM resource to an output file.
632 * @chunk: Uncompressed data of the chunk.
633 * @chunk_size: Size of the chunk (<= WIM_CHUNK_SIZE)
634 * @out_fp: FILE * to write tho chunk to.
635 * @out_ctype: Compression type to use when writing the chunk (ignored if no
636 * chunk table provided)
637 * @chunk_tab: Pointer to chunk table being created. It is updated with the
638 * offset of the chunk we write.
640 * Returns 0 on success; nonzero on failure.
642 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
643 FILE *out_fp, int out_ctype,
644 struct chunk_table *chunk_tab)
647 unsigned out_chunk_size;
649 wimlib_assert(chunk_size <= WIM_CHUNK_SIZE);
653 out_chunk_size = chunk_size;
655 u8 *compressed_chunk = alloca(chunk_size);
658 ret = compress_chunk(chunk, chunk_size, compressed_chunk,
659 &out_chunk_size, out_ctype);
661 out_chunk = compressed_chunk;
664 out_chunk_size = chunk_size;
666 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
667 chunk_tab->cur_offset += out_chunk_size;
670 if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
671 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
672 return WIMLIB_ERR_WRITE;
678 * Finishes a WIM chunk tale and writes it to the output file at the correct
681 * The final size of the full compressed resource is returned in the
682 * @compressed_size_p.
685 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
686 FILE *out_fp, u64 *compressed_size_p)
688 size_t bytes_written;
689 if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
690 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
691 "WIM file", chunk_tab->file_offset);
692 return WIMLIB_ERR_WRITE;
695 if (chunk_tab->bytes_per_chunk_entry == 8) {
696 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
698 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
699 ((u32*)chunk_tab->offsets)[i] =
700 cpu_to_le32(chunk_tab->offsets[i]);
702 bytes_written = fwrite((u8*)chunk_tab->offsets +
703 chunk_tab->bytes_per_chunk_entry,
704 1, chunk_tab->table_disk_size, out_fp);
705 if (bytes_written != chunk_tab->table_disk_size) {
706 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
708 return WIMLIB_ERR_WRITE;
710 if (fseeko(out_fp, 0, SEEK_END) != 0) {
711 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
712 return WIMLIB_ERR_WRITE;
714 *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
719 * Writes a WIM resource to a FILE * opened for writing. The resource may be
720 * written uncompressed or compressed depending on the @out_ctype parameter.
722 * If by chance the resource compresses to more than the original size (this may
723 * happen with random data or files than are pre-compressed), the resource is
724 * instead written uncompressed (and this is reflected in the @out_res_entry by
725 * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
727 * @lte: The lookup table entry for the WIM resource.
728 * @out_fp: The FILE * to write the resource to.
729 * @out_ctype: The compression type of the resource to write. Note: if this is
730 * the same as the compression type of the WIM resource we
731 * need to read, we simply copy the data (i.e. we do not
732 * uncompress it, then compress it again).
733 * @out_res_entry: If non-NULL, a resource entry that is filled in with the
734 * offset, original size, compressed size, and compression flag
735 * of the output resource.
737 * Returns 0 on success; nonzero on failure.
739 static int write_wim_resource(struct lookup_table_entry *lte,
740 FILE *out_fp, int out_ctype,
741 struct resource_entry *out_res_entry)
745 u64 old_compressed_size;
746 u64 new_compressed_size;
749 struct chunk_table *chunk_tab = NULL;
753 ntfs_inode *ni = NULL;
758 /* Original size of the resource */
759 original_size = wim_resource_size(lte);
761 /* Compressed size of the resource (as it exists now) */
762 old_compressed_size = wim_resource_compressed_size(lte);
764 /* Current offset in output file */
765 file_offset = ftello(out_fp);
766 if (file_offset == -1) {
767 ERROR_WITH_ERRNO("Failed to get offset in output "
769 return WIMLIB_ERR_WRITE;
772 /* Are the compression types the same? If so, do a raw copy (copy
773 * without decompressing and recompressing the data). */
774 raw = (wim_resource_compression_type(lte) == out_ctype
775 && out_ctype != WIM_COMPRESSION_TYPE_NONE);
777 bytes_remaining = old_compressed_size;
779 bytes_remaining = original_size;
781 /* Empty resource; nothing needs to be done, so just return success. */
782 if (bytes_remaining == 0)
785 /* Buffer for reading chunks for the resource */
786 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
788 /* If we are writing a compressed resource and not doing a raw copy, we
789 * need to initialize the chunk table */
790 if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
791 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
797 /* If the WIM resource is in an external file, open a FILE * to it so we
798 * don't have to open a temporary one in read_wim_resource() for each
800 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
801 && !lte->file_on_disk_fp)
803 wimlib_assert(lte->file_on_disk);
804 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
805 if (!lte->file_on_disk_fp) {
806 ERROR_WITH_ERRNO("Failed to open the file `%s' for "
807 "reading", lte->file_on_disk);
808 ret = WIMLIB_ERR_OPEN;
813 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
816 struct ntfs_location *loc = lte->ntfs_loc;
818 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
820 ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
821 "volume", loc->path_utf8);
822 ret = WIMLIB_ERR_NTFS_3G;
825 lte->attr = ntfs_attr_open(ni,
826 loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
827 (ntfschar*)loc->stream_name_utf16,
828 loc->stream_name_utf16_num_chars);
830 ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
831 "NTFS volume", loc->path_utf8);
832 ret = WIMLIB_ERR_NTFS_3G;
838 /* If we aren't doing a raw copy, we will compute the SHA1 message
839 * digest of the resource as we read it, and verify it's the same as the
840 * hash given in the lookup table entry once we've finished reading the
846 /* While there are still bytes remaining in the WIM resource, read a
847 * chunk of the resource, update SHA1, then write that chunk using the
848 * desired compression type. */
850 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
851 ret = read_wim_resource(lte, buf, to_read, offset, raw);
855 sha1_update(&ctx, buf, to_read);
856 ret = write_wim_resource_chunk(buf, to_read, out_fp,
857 out_ctype, chunk_tab);
860 bytes_remaining -= to_read;
862 } while (bytes_remaining);
864 /* Raw copy: The new compressed size is the same as the old compressed
867 * Using WIM_COMPRESSION_TYPE_NONE: The new compressed size is the
870 * Using a different compression type: Call
871 * finish_wim_resource_chunk_tab() and it will provide the new
875 new_compressed_size = old_compressed_size;
877 if (out_ctype == WIM_COMPRESSION_TYPE_NONE)
878 new_compressed_size = original_size;
880 ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
881 &new_compressed_size);
887 /* Verify SHA1 message digest of the resource, unless we are doing a raw
888 * write (in which case we never even saw the uncompressed data). Or,
889 * if the hash we had before is all 0's, just re-set it to be the new
892 u8 md[SHA1_HASH_SIZE];
893 sha1_final(md, &ctx);
894 if (is_zero_hash(lte->hash)) {
895 copy_hash(lte->hash, md);
896 } else if (!hashes_equal(md, lte->hash)) {
897 ERROR("WIM resource has incorrect hash!");
898 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
899 ERROR("We were reading it from `%s'; maybe it changed "
900 "while we were reading it.",
903 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
908 if (!raw && new_compressed_size >= original_size &&
909 out_ctype != WIM_COMPRESSION_TYPE_NONE)
911 /* Oops! We compressed the resource to larger than the original
912 * size. Write the resource uncompressed instead. */
913 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
914 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
915 "of output WIM file", file_offset);
916 ret = WIMLIB_ERR_WRITE;
919 ret = write_wim_resource(lte, out_fp, WIM_COMPRESSION_TYPE_NONE,
923 if (fflush(out_fp) != 0) {
924 ERROR_WITH_ERRNO("Failed to flush output WIM file");
925 ret = WIMLIB_ERR_WRITE;
928 if (ftruncate(fileno(out_fp), file_offset + out_res_entry->size) != 0) {
929 ERROR_WITH_ERRNO("Failed to truncate output WIM file");
930 ret = WIMLIB_ERR_WRITE;
934 wimlib_assert(new_compressed_size <= original_size || raw);
936 out_res_entry->size = new_compressed_size;
937 out_res_entry->original_size = original_size;
938 out_res_entry->offset = file_offset;
939 out_res_entry->flags = lte->resource_entry.flags
940 & ~WIM_RESHDR_FLAG_COMPRESSED;
941 if (out_ctype != WIM_COMPRESSION_TYPE_NONE)
942 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
945 if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
946 && lte->file_on_disk_fp) {
947 fclose(lte->file_on_disk_fp);
948 lte->file_on_disk_fp = NULL;
951 else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
953 ntfs_attr_close(lte->attr);
956 ntfs_inode_close(ni);
965 /* Like write_wim_resource(), but the resource is specified by a buffer of
966 * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
967 * the buffer to @hash. */
968 static int write_wim_resource_from_buffer(const u8 *buf, u64 buf_size,
969 FILE *out_fp, int out_ctype,
970 struct resource_entry *out_res_entry,
971 u8 hash[SHA1_HASH_SIZE])
973 /* Set up a temporary lookup table entry that we provide to
974 * write_wim_resource(). */
975 struct lookup_table_entry lte;
977 lte.resource_entry.flags = 0;
978 lte.resource_entry.original_size = buf_size;
979 lte.resource_entry.size = buf_size;
980 lte.resource_entry.offset = 0;
981 lte.resource_location = RESOURCE_IN_ATTACHED_BUFFER;
982 lte.attached_buffer = (u8*)buf;
984 zero_out_hash(lte.hash);
985 ret = write_wim_resource(<e, out_fp, out_ctype, out_res_entry);
988 copy_hash(hash, lte.hash);
993 * Extracts the first @size bytes of the WIM resource specified by @lte to the
994 * open file descriptor @fd.
996 * Returns 0 on success; nonzero on failure.
998 int extract_wim_resource_to_fd(const struct lookup_table_entry *lte, int fd,
1001 u64 bytes_remaining = size;
1002 u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
1005 u8 hash[SHA1_HASH_SIZE];
1010 while (bytes_remaining) {
1011 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
1012 ret = read_wim_resource(lte, buf, to_read, offset, false);
1015 sha1_update(&ctx, buf, to_read);
1016 if (full_write(fd, buf, to_read) < to_read) {
1017 ERROR_WITH_ERRNO("Error extracting WIM resource");
1018 return WIMLIB_ERR_WRITE;
1020 bytes_remaining -= to_read;
1023 sha1_final(hash, &ctx);
1024 if (!hashes_equal(hash, lte->hash)) {
1025 ERROR("Invalid checksum on a WIM resource "
1026 "(detected when extracting to external file)");
1027 ERROR("The following WIM resource is invalid:");
1028 print_lookup_table_entry(lte);
1029 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
1035 * Extracts the WIM resource specified by @lte to the open file descriptor @fd.
1037 * Returns 0 on success; nonzero on failure.
1039 int extract_full_wim_resource_to_fd(const struct lookup_table_entry *lte, int fd)
1041 return extract_wim_resource_to_fd(lte, fd, wim_resource_size(lte));
1045 * Copies the file resource specified by the lookup table entry @lte from the
1046 * input WIM to the output WIM that has its FILE * given by
1047 * ((WIMStruct*)wim)->out_fp.
1049 * The output_resource_entry, out_refcnt, and part_number fields of @lte are
1052 * Metadata resources are not copied (they are handled elsewhere for joining and
1055 int copy_resource(struct lookup_table_entry *lte, void *wim)
1060 if ((lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) &&
1064 ret = write_wim_resource(lte, w->out_fp,
1065 wim_resource_compression_type(lte),
1066 <e->output_resource_entry);
1069 lte->out_refcnt = lte->refcnt;
1070 lte->part_number = w->hdr.part_number;
1075 * Writes a dentry's resources, including the main file resource as well as all
1076 * alternate data streams, to the output file.
1078 * @dentry: The dentry for the file.
1079 * @wim_p: A pointer to the WIMStruct containing @dentry.
1081 * @return zero on success, nonzero on failure.
1083 int write_dentry_resources(struct dentry *dentry, void *wim_p)
1085 WIMStruct *w = wim_p;
1087 struct lookup_table_entry *lte;
1088 int ctype = wimlib_get_compression_type(w);
1090 if (w->write_flags & WIMLIB_WRITE_FLAG_VERBOSE) {
1091 wimlib_assert(dentry->full_path_utf8);
1092 printf("Writing streams for `%s'\n", dentry->full_path_utf8);
1095 for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1096 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1097 if (lte && ++lte->out_refcnt == 1) {
1098 ret = write_wim_resource(lte, w->out_fp, ctype,
1099 <e->output_resource_entry);
1108 * Reads the metadata metadata resource from the WIM file. The metadata
1109 * resource consists of the security data, followed by the directory entry for
1110 * the root directory, followed by all the other directory entries in the
1111 * filesystem. The subdir_offset field of each directory entry gives the start
1112 * of its child entries from the beginning of the metadata resource. An
1113 * end-of-directory is signaled by a directory entry of length '0', really of
1114 * length 8, because that's how long the 'length' field is.
1116 * @fp: The FILE* for the input WIM file.
1117 * @wim_ctype: The compression type of the WIM file.
1118 * @imd: Pointer to the image metadata structure. Its `metadata_lte'
1119 * member specifies the lookup table entry for the metadata
1120 * resource. The rest of the image metadata entry will be filled
1121 * in by this function.
1123 * @return: Zero on success, nonzero on failure.
1125 int read_metadata_resource(WIMStruct *w, struct image_metadata *imd)
1130 struct dentry *dentry;
1131 struct inode_table inode_tab;
1132 const struct lookup_table_entry *metadata_lte;
1134 u64 metadata_offset;
1135 struct hlist_head inode_list;
1137 metadata_lte = imd->metadata_lte;
1138 metadata_len = wim_resource_size(metadata_lte);
1139 metadata_offset = metadata_lte->resource_entry.offset;
1141 DEBUG("Reading metadata resource: length = %"PRIu64", "
1142 "offset = %"PRIu64"", metadata_len, metadata_offset);
1144 /* There is no way the metadata resource could possibly be less than (8
1145 * + WIM_DENTRY_DISK_SIZE) bytes, where the 8 is for security data (with
1146 * no security descriptors) and WIM_DENTRY_DISK_SIZE is for the root
1148 if (metadata_len < 8 + WIM_DENTRY_DISK_SIZE) {
1149 ERROR("Expected at least %u bytes for the metadata resource",
1150 8 + WIM_DENTRY_DISK_SIZE);
1151 return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
1154 /* Allocate memory for the uncompressed metadata resource. */
1155 buf = MALLOC(metadata_len);
1158 ERROR("Failed to allocate %"PRIu64" bytes for uncompressed "
1159 "metadata resource", metadata_len);
1160 return WIMLIB_ERR_NOMEM;
1163 /* Read the metadata resource into memory. (It may be compressed.) */
1164 ret = read_full_wim_resource(metadata_lte, buf);
1168 DEBUG("Finished reading metadata resource into memory.");
1170 /* The root directory entry starts after security data, aligned on an
1171 * 8-byte boundary within the metadata resource.
1173 * The security data starts with a 4-byte integer giving its total
1174 * length, so if we round that up to an 8-byte boundary that gives us
1175 * the offset of the root dentry.
1177 * Here we read the security data into a wim_security_data structure,
1178 * and if successful, go ahead and calculate the offset in the metadata
1179 * resource of the root dentry. */
1181 ret = read_security_data(buf, metadata_len, &imd->security_data);
1185 get_u32(buf, &dentry_offset);
1186 if (dentry_offset == 0)
1188 dentry_offset = (dentry_offset + 7) & ~7;
1190 /* Allocate memory for the root dentry and read it into memory */
1191 dentry = MALLOC(sizeof(struct dentry));
1193 ERROR("Failed to allocate %zu bytes for root dentry",
1194 sizeof(struct dentry));
1195 ret = WIMLIB_ERR_NOMEM;
1196 goto out_free_security_data;
1199 ret = read_dentry(buf, metadata_len, dentry_offset, dentry);
1201 /* This is the root dentry, so set its pointers correctly. */
1202 dentry->parent = dentry;
1203 dentry->next = dentry;
1204 dentry->prev = dentry;
1206 goto out_free_dentry_tree;
1207 inode_add_dentry(dentry, dentry->d_inode);
1209 /* Now read the entire directory entry tree into memory. */
1210 DEBUG("Reading dentry tree");
1211 ret = read_dentry_tree(buf, metadata_len, dentry);
1213 goto out_free_dentry_tree;
1215 /* Calculate the full paths in the dentry tree. */
1216 DEBUG("Calculating dentry full paths");
1217 ret = for_dentry_in_tree(dentry, calculate_dentry_full_path, NULL);
1219 goto out_free_dentry_tree;
1221 /* Build hash table that maps hard link group IDs to dentry sets */
1222 DEBUG("Building link group table");
1223 ret = init_inode_table(&inode_tab, 9001);
1225 goto out_free_dentry_tree;
1227 for_dentry_in_tree(dentry, inode_table_insert, &inode_tab);
1229 DEBUG("Fixing inconsistencies in the hard link groups");
1230 ret = fix_inodes(&inode_tab, &inode_list);
1231 destroy_inode_table(&inode_tab);
1233 goto out_free_dentry_tree;
1235 DEBUG("Running miscellaneous verifications on the dentry tree");
1236 for_lookup_table_entry(w->lookup_table, lte_zero_real_refcnt, NULL);
1237 ret = for_dentry_in_tree(dentry, verify_dentry, w);
1239 goto out_free_dentry_tree;
1241 DEBUG("Done reading image metadata");
1243 imd->root_dentry = dentry;
1244 imd->inode_list = inode_list;
1246 out_free_dentry_tree:
1247 free_dentry_tree(dentry, NULL);
1248 out_free_security_data:
1249 free_security_data(imd->security_data);
1250 imd->security_data = NULL;
1256 /* Write the metadata resource for the current WIM image. */
1257 int write_metadata_resource(WIMStruct *w)
1263 struct dentry *root;
1264 struct lookup_table_entry *lte;
1265 u64 metadata_original_size;
1266 const struct wim_security_data *sd;
1267 const unsigned random_tail_len = 20;
1269 DEBUG("Writing metadata resource for image %d", w->current_image);
1271 root = wim_root_dentry(w);
1272 sd = wim_security_data(w);
1274 /* We do not allow the security data pointer to be NULL, although it may
1275 * point to an empty security data with no entries. */
1278 /* Offset of first child of the root dentry. It's equal to:
1279 * - The total length of the security data, rounded to the next 8-byte
1281 * - plus the total length of the root dentry,
1282 * - plus 8 bytes for an end-of-directory entry following the root
1283 * dentry (shouldn't really be needed, but just in case...)
1285 subdir_offset = ((sd->total_length + 7) & ~7) +
1286 dentry_correct_total_length(root) + 8;
1288 /* Calculate the subdirectory offsets for the entire dentry tree. */
1289 calculate_subdir_offsets(root, &subdir_offset);
1291 /* Total length of the metadata resource (uncompressed) */
1292 metadata_original_size = subdir_offset + random_tail_len;
1294 /* Allocate a buffer to contain the uncompressed metadata resource */
1295 buf = MALLOC(metadata_original_size);
1297 ERROR("Failed to allocate %"PRIu64" bytes for "
1298 "metadata resource", metadata_original_size);
1299 return WIMLIB_ERR_NOMEM;
1302 /* Write the security data into the resource buffer */
1303 p = write_security_data(sd, buf);
1305 /* Write the dentry tree into the resource buffer */
1306 DEBUG("Writing dentry tree.");
1307 p = write_dentry_tree(root, p);
1310 * Append 20 random bytes to the metadata resource so that we don't have
1311 * identical metadata resources if we happen to append exactly the same
1312 * image twice without any changes in timestamps. If this were to
1313 * happen, it would cause confusion about the number and order of images
1316 randomize_byte_array(p, random_tail_len);
1318 /* We MUST have exactly filled the buffer; otherwise we calculated its
1319 * size incorrectly or wrote the data incorrectly. */
1320 wimlib_assert(p - buf + random_tail_len == metadata_original_size);
1322 /* Get the lookup table entry for the metadata resource so we can update
1324 lte = wim_metadata_lookup_table_entry(w);
1326 /* Write the metadata resource to the output WIM using the proper
1327 * compression type. The lookup table entry for the metadata resource
1329 ret = write_wim_resource_from_buffer(buf, metadata_original_size,
1331 wimlib_get_compression_type(w),
1332 <e->output_resource_entry,
1337 /* It's very likely the SHA1 message digest of the metadata resource
1338 * changed, so re-insert the lookup table entry into the lookup table.
1340 lookup_table_unlink(w->lookup_table, lte);
1341 lookup_table_insert(w->lookup_table, lte);
1343 /* We do not allow a metadata resource to be referenced multiple times,
1344 * and the 20 random bytes appended to it should make it extremely
1345 * likely for each metadata resource to be unique, even if the exact
1346 * same image is captured. */
1347 wimlib_assert(lte->out_refcnt == 0);
1348 lte->out_refcnt = 1;
1350 /* Make sure that the resource entry is written marked with the metadata
1352 lte->output_resource_entry.flags |= WIM_RESHDR_FLAG_METADATA;
1354 /* All the data has been written to the new WIM; no need for the buffer