4 * Code for reading blobs and resources, including compressed WIM resources.
8 * Copyright (C) 2012, 2013, 2015 Eric Biggers
10 * This file is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option) any
15 * This file is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this file; if not, see http://www.gnu.org/licenses/.
32 #include "wimlib/alloca.h"
33 #include "wimlib/assert.h"
34 #include "wimlib/bitops.h"
35 #include "wimlib/blob_table.h"
36 #include "wimlib/endianness.h"
37 #include "wimlib/error.h"
38 #include "wimlib/file_io.h"
39 #include "wimlib/ntfs_3g.h"
40 #include "wimlib/resource.h"
41 #include "wimlib/sha1.h"
42 #include "wimlib/wim.h"
43 #include "wimlib/win32.h"
46 * Compressed WIM resources
48 * A compressed resource in a WIM consists of a number of compressed chunks,
49 * each of which decompresses to a fixed chunk size (given in the WIM header;
50 * usually 32768) except possibly the last, which always decompresses to any
51 * remaining bytes. In addition, immediately before the chunks, a table (the
52 * "chunk table") provides the offset, in bytes relative to the end of the chunk
53 * table, of the start of each compressed chunk, except for the first chunk
54 * which is omitted as it always has an offset of 0. Therefore, a compressed
55 * resource with N chunks will have a chunk table with N - 1 entries.
57 * Additional information:
59 * - Entries in the chunk table are 4 bytes each, except if the uncompressed
60 * size of the resource is greater than 4 GiB, in which case the entries in
61 * the chunk table are 8 bytes each. In either case, the entries are unsigned
62 * little-endian integers.
64 * - The chunk table is included in the compressed size of the resource provided
65 * in the corresponding entry in the WIM's blob table.
67 * - The compressed size of a chunk is never greater than the uncompressed size.
68 * From the compressor's point of view, chunks that would have compressed to a
69 * size greater than or equal to their original size are in fact stored
70 * uncompressed. From the decompresser's point of view, chunks with
71 * compressed size equal to their uncompressed size are in fact uncompressed.
73 * Furthermore, wimlib supports its own "pipable" WIM format, and for this the
74 * structure of compressed resources was modified to allow piped reading and
75 * writing. To make sequential writing possible, the chunk table is placed
76 * after the chunks rather than before the chunks, and to make sequential
77 * reading possible, each chunk is prefixed with a 4-byte header giving its
78 * compressed size as a 32-bit, unsigned, little-endian integer. Otherwise the
79 * details are the same.
89 * read_compressed_wim_resource() -
91 * Read data from a compressed WIM resource.
94 * Description of the compressed WIM resource to read from.
96 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
97 * read, sorted by increasing offset.
99 * Number of ranges in @ranges; must be at least 1.
101 * Callback function to feed the data being read. Each call provides the
102 * next chunk of the requested data, uncompressed. Each chunk will be of
103 * nonzero size and will not cross range boundaries, but otherwise will be
104 * of unspecified size.
106 * Parameter to pass to @cb_ctx.
108 * Possible return values:
110 * WIMLIB_ERR_SUCCESS (0)
111 * WIMLIB_ERR_READ (errno set)
112 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
113 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
114 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
116 * or other error code returned by the @cb function.
119 read_compressed_wim_resource(const struct wim_resource_descriptor * const rdesc,
120 const struct data_range * const ranges,
121 const size_t num_ranges,
122 const consume_data_callback_t cb,
128 u64 *chunk_offsets = NULL;
131 bool chunk_offsets_malloced = false;
132 bool ubuf_malloced = false;
133 bool cbuf_malloced = false;
134 struct wimlib_decompressor *decompressor = NULL;
137 wimlib_assert(rdesc != NULL);
138 wimlib_assert(resource_is_compressed(rdesc));
139 wimlib_assert(cb != NULL);
140 wimlib_assert(num_ranges != 0);
141 for (size_t i = 0; i < num_ranges; i++) {
142 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
143 i + 1, num_ranges, ranges[i].size, ranges[i].offset,
144 rdesc->uncompressed_size);
145 wimlib_assert(ranges[i].size != 0);
146 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
147 wimlib_assert(ranges[i].offset + ranges[i].size <= rdesc->uncompressed_size);
149 for (size_t i = 0; i < num_ranges - 1; i++)
150 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
152 /* Get the offsets of the first and last bytes of the read. */
153 const u64 first_offset = ranges[0].offset;
154 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
156 /* Get the file descriptor for the WIM. */
157 struct filedes * const in_fd = &rdesc->wim->in_fd;
159 /* Determine if we're reading a pipable resource from a pipe or not. */
160 const bool is_pipe_read = (rdesc->is_pipable && !filedes_is_seekable(in_fd));
162 /* Determine if the chunk table is in an alternate format. */
163 const bool alt_chunk_table = (rdesc->flags & WIM_RESHDR_FLAG_SOLID)
166 /* Get the maximum size of uncompressed chunks in this resource, which
167 * we require be a power of 2. */
168 u64 cur_read_offset = rdesc->offset_in_wim;
169 int ctype = rdesc->compression_type;
170 u32 chunk_size = rdesc->chunk_size;
171 if (alt_chunk_table) {
172 /* Alternate chunk table format. Its header specifies the chunk
173 * size and compression format. Note: it could be read here;
174 * however, the relevant data was already loaded into @rdesc by
175 * read_blob_table(). */
176 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
179 if (!is_power_of_2(chunk_size)) {
180 ERROR("Invalid compressed resource: "
181 "expected power-of-2 chunk size (got %"PRIu32")",
183 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
185 goto out_free_memory;
188 /* Get valid decompressor. */
189 if (ctype == rdesc->wim->decompressor_ctype &&
190 chunk_size == rdesc->wim->decompressor_max_block_size)
192 /* Cached decompressor. */
193 decompressor = rdesc->wim->decompressor;
194 rdesc->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
195 rdesc->wim->decompressor = NULL;
197 ret = wimlib_create_decompressor(ctype, chunk_size,
200 if (ret != WIMLIB_ERR_NOMEM)
202 goto out_free_memory;
206 const u32 chunk_order = fls32(chunk_size);
208 /* Calculate the total number of chunks the resource is divided into. */
209 const u64 num_chunks = (rdesc->uncompressed_size + chunk_size - 1) >> chunk_order;
211 /* Calculate the 0-based indices of the first and last chunks containing
212 * data that needs to be passed to the callback. */
213 const u64 first_needed_chunk = first_offset >> chunk_order;
214 const u64 last_needed_chunk = last_offset >> chunk_order;
216 /* Calculate the 0-based index of the first chunk that actually needs to
217 * be read. This is normally first_needed_chunk, but for pipe reads we
218 * must always start from the 0th chunk. */
219 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
221 /* Calculate the number of chunk offsets that are needed for the chunks
223 const u64 num_needed_chunk_offsets =
224 last_needed_chunk - read_start_chunk + 1 +
225 (last_needed_chunk < num_chunks - 1);
227 /* Calculate the number of entries in the chunk table. Normally, it's
228 * one less than the number of chunks, since the first chunk has no
229 * entry. But in the alternate chunk table format, the chunk entries
230 * contain chunk sizes, not offsets, and there is one per chunk. */
231 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
233 /* Set the size of each chunk table entry based on the resource's
234 * uncompressed size. */
235 const u64 chunk_entry_size = get_chunk_entry_size(rdesc->uncompressed_size,
238 /* Calculate the size of the chunk table in bytes. */
239 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
241 /* Calculate the size of the chunk table in bytes, including the header
242 * in the case of the alternate chunk table format. */
243 const u64 chunk_table_full_size =
244 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
248 /* Read the needed chunk table entries into memory and use them
249 * to initialize the chunk_offsets array. */
251 u64 first_chunk_entry_to_read;
252 u64 last_chunk_entry_to_read;
254 if (alt_chunk_table) {
255 /* The alternate chunk table contains chunk sizes, not
256 * offsets, so we always must read all preceding entries
257 * in order to determine offsets. */
258 first_chunk_entry_to_read = 0;
259 last_chunk_entry_to_read = last_needed_chunk;
261 /* Here we must account for the fact that the first
262 * chunk has no explicit chunk table entry. */
264 if (read_start_chunk == 0)
265 first_chunk_entry_to_read = 0;
267 first_chunk_entry_to_read = read_start_chunk - 1;
269 if (last_needed_chunk == 0)
270 last_chunk_entry_to_read = 0;
272 last_chunk_entry_to_read = last_needed_chunk - 1;
274 if (last_needed_chunk < num_chunks - 1)
275 last_chunk_entry_to_read++;
278 const u64 num_chunk_entries_to_read =
279 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
281 const u64 chunk_offsets_alloc_size =
282 max(num_chunk_entries_to_read,
283 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
285 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
288 if (chunk_offsets_alloc_size <= STACK_MAX) {
289 chunk_offsets = alloca(chunk_offsets_alloc_size);
291 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
292 if (chunk_offsets == NULL)
294 chunk_offsets_malloced = true;
297 const size_t chunk_table_size_to_read =
298 num_chunk_entries_to_read * chunk_entry_size;
300 const u64 file_offset_of_needed_chunk_entries =
302 + (first_chunk_entry_to_read * chunk_entry_size)
303 + (rdesc->is_pipable ? (rdesc->size_in_wim - chunk_table_size) : 0);
305 void * const chunk_table_data =
307 chunk_offsets_alloc_size -
308 chunk_table_size_to_read;
310 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
311 file_offset_of_needed_chunk_entries);
315 /* Now fill in chunk_offsets from the entries we have read in
316 * chunk_tab_data. We break aliasing rules here to avoid having
317 * to allocate yet another array. */
318 typedef le64 _may_alias_attribute aliased_le64_t;
319 typedef le32 _may_alias_attribute aliased_le32_t;
320 u64 * chunk_offsets_p = chunk_offsets;
322 if (alt_chunk_table) {
324 aliased_le32_t *raw_entries = chunk_table_data;
326 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
327 u32 entry = le32_to_cpu(raw_entries[i]);
328 if (i >= read_start_chunk)
329 *chunk_offsets_p++ = cur_offset;
332 if (last_needed_chunk < num_chunks - 1)
333 *chunk_offsets_p = cur_offset;
335 if (read_start_chunk == 0)
336 *chunk_offsets_p++ = 0;
338 if (chunk_entry_size == 4) {
339 aliased_le32_t *raw_entries = chunk_table_data;
340 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
341 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
343 aliased_le64_t *raw_entries = chunk_table_data;
344 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
345 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
349 /* Set offset to beginning of first chunk to read. */
350 cur_read_offset += chunk_offsets[0];
351 if (rdesc->is_pipable)
352 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
354 cur_read_offset += chunk_table_size;
357 /* Allocate buffer for holding the uncompressed data of each chunk. */
358 if (chunk_size <= STACK_MAX) {
359 ubuf = alloca(chunk_size);
361 ubuf = MALLOC(chunk_size);
364 ubuf_malloced = true;
367 /* Allocate a temporary buffer for reading compressed chunks, each of
368 * which can be at most @chunk_size - 1 bytes. This excludes compressed
369 * chunks that are a full @chunk_size bytes, which are actually stored
371 if (chunk_size - 1 <= STACK_MAX) {
372 cbuf = alloca(chunk_size - 1);
374 cbuf = MALLOC(chunk_size - 1);
377 cbuf_malloced = true;
380 /* Set current data range. */
381 const struct data_range *cur_range = ranges;
382 const struct data_range * const end_range = &ranges[num_ranges];
383 u64 cur_range_pos = cur_range->offset;
384 u64 cur_range_end = cur_range->offset + cur_range->size;
386 /* Read and process each needed chunk. */
387 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
389 /* Calculate uncompressed size of next chunk. */
391 if ((i == num_chunks - 1) && (rdesc->uncompressed_size & (chunk_size - 1)))
392 chunk_usize = (rdesc->uncompressed_size & (chunk_size - 1));
394 chunk_usize = chunk_size;
396 /* Calculate compressed size of next chunk. */
399 struct pwm_chunk_hdr chunk_hdr;
401 ret = full_pread(in_fd, &chunk_hdr,
402 sizeof(chunk_hdr), cur_read_offset);
405 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
407 if (i == num_chunks - 1) {
408 chunk_csize = rdesc->size_in_wim -
409 chunk_table_full_size -
410 chunk_offsets[i - read_start_chunk];
411 if (rdesc->is_pipable)
412 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
414 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
415 chunk_offsets[i - read_start_chunk];
418 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
419 ERROR("Invalid chunk size in compressed resource!");
421 ret = WIMLIB_ERR_DECOMPRESSION;
422 goto out_free_memory;
424 if (rdesc->is_pipable)
425 cur_read_offset += sizeof(struct pwm_chunk_hdr);
427 /* Offsets in the uncompressed resource at which this chunk
428 * starts and ends. */
429 const u64 chunk_start_offset = i << chunk_order;
430 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
432 if (chunk_end_offset <= cur_range_pos) {
434 /* The next range does not require data in this chunk,
436 cur_read_offset += chunk_csize;
440 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
446 /* Read the chunk and feed data to the callback
450 if (chunk_csize == chunk_usize)
455 ret = full_pread(in_fd,
462 if (read_buf == cbuf) {
463 DEBUG("Decompressing chunk %"PRIu64" "
464 "(csize=%"PRIu32" usize=%"PRIu32")",
465 i, chunk_csize, chunk_usize);
466 ret = wimlib_decompress(cbuf,
472 ERROR("Failed to decompress data!");
473 ret = WIMLIB_ERR_DECOMPRESSION;
475 goto out_free_memory;
478 cur_read_offset += chunk_csize;
480 /* At least one range requires data in this chunk. */
482 size_t start, end, size;
484 /* Calculate how many bytes of data should be
485 * sent to the callback function, taking into
486 * account that data sent to the callback
487 * function must not overlap range boundaries.
489 start = cur_range_pos - chunk_start_offset;
490 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
493 ret = (*cb)(&ubuf[start], size, cb_ctx);
496 goto out_free_memory;
498 cur_range_pos += size;
499 if (cur_range_pos == cur_range_end) {
500 /* Advance to next range. */
501 if (++cur_range == end_range) {
502 cur_range_pos = ~0ULL;
504 cur_range_pos = cur_range->offset;
505 cur_range_end = cur_range->offset + cur_range->size;
508 } while (cur_range_pos < chunk_end_offset);
513 last_offset == rdesc->uncompressed_size - 1 &&
517 /* If reading a pipable resource from a pipe and the full data
518 * was requested, skip the chunk table at the end so that the
519 * file descriptor is fully clear of the resource after this
521 cur_read_offset += chunk_table_size;
522 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
531 wimlib_free_decompressor(rdesc->wim->decompressor);
532 rdesc->wim->decompressor = decompressor;
533 rdesc->wim->decompressor_ctype = ctype;
534 rdesc->wim->decompressor_max_block_size = chunk_size;
536 if (chunk_offsets_malloced)
546 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
547 "from compressed WIM resource!", last_offset - first_offset + 1);
549 ret = WIMLIB_ERR_NOMEM;
550 goto out_free_memory;
553 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
554 goto out_free_memory;
558 fill_zeroes(u64 size, consume_data_callback_t cb, void *cb_ctx)
560 if (unlikely(size)) {
561 u8 buf[min(size, BUFFER_SIZE)];
563 memset(buf, 0, sizeof(buf));
569 len = min(size, BUFFER_SIZE);
570 ret = cb(buf, len, cb_ctx);
579 /* Read raw data from a file descriptor at the specified offset, feeding the
580 * data it in chunks into the specified callback function. */
582 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
583 consume_data_callback_t cb, void *cb_ctx)
586 size_t bytes_to_read;
590 bytes_to_read = min(sizeof(buf), size);
591 ret = full_pread(in_fd, buf, bytes_to_read, offset);
593 ERROR_WITH_ERRNO("Read error");
596 ret = cb(buf, bytes_to_read, cb_ctx);
599 size -= bytes_to_read;
600 offset += bytes_to_read;
605 /* A consume_data_callback_t implementation that simply concatenates all chunks
608 bufferer_cb(const void *chunk, size_t size, void *_ctx)
612 *buf_p = mempcpy(*buf_p, chunk, size);
617 * read_partial_wim_resource()-
619 * Read a range of data from an uncompressed or compressed resource in a WIM
623 * Description of the WIM resource to read from.
625 * Offset within the uncompressed resource at which to start reading.
627 * Number of bytes to read.
629 * Callback function to feed the data being read. Each call provides the
630 * next chunk of the requested data, uncompressed. Each chunk will be of
631 * nonzero size and will not cross range boundaries, but otherwise will be
632 * of unspecified size.
634 * Parameter to pass to @cb_ctx.
637 * WIMLIB_ERR_SUCCESS (0)
638 * WIMLIB_ERR_READ (errno set)
639 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
640 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
641 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
643 * or other error code returned by the @cb function.
646 read_partial_wim_resource(const struct wim_resource_descriptor *rdesc,
647 u64 offset, u64 size,
648 consume_data_callback_t cb, void *cb_ctx)
651 wimlib_assert(offset + size >= offset);
652 wimlib_assert(offset + size <= rdesc->uncompressed_size);
654 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
655 "%"PRIu64" => %"PRIu64" @ %"PRIu64,
656 size, offset, rdesc->uncompressed_size,
657 rdesc->size_in_wim, rdesc->offset_in_wim);
663 if (resource_is_compressed(rdesc)) {
664 struct data_range range = {
668 return read_compressed_wim_resource(rdesc, &range, 1,
671 /* Reading uncompressed resource. For completeness, handle the
672 * weird case where size_in_wim < uncompressed_size. */
678 if (likely(offset + size <= rdesc->size_in_wim) ||
684 if (offset >= rdesc->size_in_wim) {
688 read_size = rdesc->size_in_wim - offset;
689 zeroes_size = offset + size - rdesc->size_in_wim;
693 ret = read_raw_file_data(&rdesc->wim->in_fd,
694 rdesc->offset_in_wim + offset,
701 return fill_zeroes(zeroes_size, cb, cb_ctx);
705 /* Read the specified range of uncompressed data from the specified blob, which
706 * must be located into a WIM file, into the specified buffer. */
708 read_partial_wim_blob_into_buf(const struct blob_descriptor *blob,
709 size_t size, u64 offset, void *_buf)
713 wimlib_assert(blob->blob_location == BLOB_IN_WIM);
715 return read_partial_wim_resource(blob->rdesc,
716 blob->offset_in_res + offset,
722 /* A consume_data_callback_t implementation that simply ignores the data
725 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
730 /* Skip over the data of the specified WIM resource. */
732 skip_wim_resource(struct wim_resource_descriptor *rdesc)
734 DEBUG("Skipping resource (size=%"PRIu64")", rdesc->uncompressed_size);
735 return read_partial_wim_resource(rdesc, 0, rdesc->uncompressed_size,
736 skip_chunk_cb, NULL);
740 read_wim_blob_prefix(const struct blob_descriptor *blob, u64 size,
741 consume_data_callback_t cb, void *cb_ctx)
743 return read_partial_wim_resource(blob->rdesc, blob->offset_in_res, size,
747 /* This function handles reading blob data that is located in an external file,
748 * such as a file that has been added to the WIM image through execution of a
749 * wimlib_add_command.
751 * This assumes the file can be accessed using the standard POSIX open(),
752 * read(), and close(). On Windows this will not necessarily be the case (since
753 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
754 * encrypted), so Windows uses its own code for its equivalent case. */
756 read_file_on_disk_prefix(const struct blob_descriptor *blob, u64 size,
757 consume_data_callback_t cb, void *cb_ctx)
763 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, blob->file_on_disk);
765 raw_fd = topen(blob->file_on_disk, O_BINARY | O_RDONLY);
767 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", blob->file_on_disk);
768 return WIMLIB_ERR_OPEN;
770 filedes_init(&fd, raw_fd);
771 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
778 read_staging_file_prefix(const struct blob_descriptor *blob, u64 size,
779 consume_data_callback_t cb, void *cb_ctx)
785 DEBUG("Reading %"PRIu64" bytes from staging file \"%s\"",
786 size, blob->staging_file_name);
788 raw_fd = openat(blob->staging_dir_fd, blob->staging_file_name,
789 O_RDONLY | O_NOFOLLOW);
791 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
792 blob->staging_file_name);
793 return WIMLIB_ERR_OPEN;
795 filedes_init(&fd, raw_fd);
796 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
802 /* This function handles the trivial case of reading blob data that is, in fact,
803 * already located in an in-memory buffer. */
805 read_buffer_prefix(const struct blob_descriptor *blob,
806 u64 size, consume_data_callback_t cb, void *cb_ctx)
808 return (*cb)(blob->attached_buffer, size, cb_ctx);
811 typedef int (*read_blob_prefix_handler_t)(const struct blob_descriptor *blob,
813 consume_data_callback_t cb,
817 * read_blob_prefix()-
819 * Reads the first @size bytes from a generic "blob", which may be located in
820 * any one of several locations, such as in a WIM file (compressed or
821 * uncompressed), in an external file, or directly in an in-memory buffer.
823 * This function feeds the data to a callback function @cb in chunks of
826 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
827 * the blob data cannot be successfully read (for a number of different reasons,
828 * depending on the blob location), or if @cb returned nonzero in which case
829 * that error code will be returned.
832 read_blob_prefix(const struct blob_descriptor *blob, u64 size,
833 consume_data_callback_t cb, void *cb_ctx)
835 static const read_blob_prefix_handler_t handlers[] = {
836 [BLOB_IN_WIM] = read_wim_blob_prefix,
837 [BLOB_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
838 [BLOB_IN_ATTACHED_BUFFER] = read_buffer_prefix,
840 [BLOB_IN_STAGING_FILE] = read_staging_file_prefix,
843 [BLOB_IN_NTFS_VOLUME] = read_ntfs_attribute_prefix,
846 [BLOB_IN_WINNT_FILE_ON_DISK] = read_winnt_stream_prefix,
847 [BLOB_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
850 wimlib_assert(blob->blob_location < ARRAY_LEN(handlers)
851 && handlers[blob->blob_location] != NULL);
852 wimlib_assert(size <= blob->size);
853 return handlers[blob->blob_location](blob, size, cb, cb_ctx);
856 /* Read the full uncompressed data of the specified blob into the specified
857 * buffer, which must have space for at least blob->size bytes. */
859 read_full_blob_into_buf(const struct blob_descriptor *blob, void *_buf)
862 return read_blob_prefix(blob, blob->size, bufferer_cb, &buf);
865 /* Retrieve the full uncompressed data of the specified blob. A buffer large
866 * enough hold the data is allocated and returned in @buf_ret. */
868 read_full_blob_into_alloc_buf(const struct blob_descriptor *blob, void **buf_ret)
873 if ((size_t)blob->size != blob->size) {
874 ERROR("Can't read %"PRIu64" byte blob into memory", blob->size);
875 return WIMLIB_ERR_NOMEM;
878 buf = MALLOC(blob->size);
880 return WIMLIB_ERR_NOMEM;
882 ret = read_full_blob_into_buf(blob, buf);
892 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
893 * `wim_reshdr' and the corresponding WIM file. A buffer large enough hold the
894 * data is allocated and returned in @buf_ret. */
896 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
898 struct wim_resource_descriptor rdesc;
899 struct blob_descriptor blob;
901 wim_res_hdr_to_desc(reshdr, wim, &rdesc);
902 blob_set_is_located_in_nonsolid_wim_resource(&blob, &rdesc);
904 return read_full_blob_into_alloc_buf(&blob, buf_ret);
908 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
909 u8 hash[SHA1_HASH_SIZE])
911 struct wim_resource_descriptor rdesc;
912 struct blob_descriptor blob;
915 wim_res_hdr_to_desc(reshdr, wim, &rdesc);
916 blob_set_is_located_in_nonsolid_wim_resource(&blob, &rdesc);
919 ret = sha1_blob(&blob);
922 copy_hash(hash, blob.hash);
926 struct blobifier_context {
927 struct read_blob_list_callbacks cbs;
928 struct blob_descriptor *cur_blob;
929 struct blob_descriptor *next_blob;
931 struct blob_descriptor *final_blob;
932 size_t list_head_offset;
935 static struct blob_descriptor *
936 next_blob(struct blob_descriptor *blob, size_t list_head_offset)
938 struct list_head *cur;
940 cur = (struct list_head*)((u8*)blob + list_head_offset);
942 return (struct blob_descriptor*)((u8*)cur->next - list_head_offset);
945 /* A consume_data_callback_t implementation that translates raw resource data
946 * into blobs, calling the begin_blob, consume_chunk, and end_blob callback
947 * functions as appropriate. */
949 blobifier_cb(const void *chunk, size_t size, void *_ctx)
951 struct blobifier_context *ctx = _ctx;
954 DEBUG("%zu bytes passed to blobifier", size);
956 wimlib_assert(ctx->cur_blob != NULL);
957 wimlib_assert(size <= ctx->cur_blob->size - ctx->cur_blob_offset);
959 if (ctx->cur_blob_offset == 0) {
961 /* Starting a new blob. */
962 DEBUG("Begin new blob (size=%"PRIu64").", ctx->cur_blob->size);
964 ret = (*ctx->cbs.begin_blob)(ctx->cur_blob,
965 ctx->cbs.begin_blob_ctx);
970 /* Consume the chunk. */
971 ret = (*ctx->cbs.consume_chunk)(chunk, size,
972 ctx->cbs.consume_chunk_ctx);
973 ctx->cur_blob_offset += size;
977 if (ctx->cur_blob_offset == ctx->cur_blob->size) {
978 /* Finished reading all the data for a blob. */
980 ctx->cur_blob_offset = 0;
982 DEBUG("End blob (size=%"PRIu64").", ctx->cur_blob->size);
983 ret = (*ctx->cbs.end_blob)(ctx->cur_blob, 0,
984 ctx->cbs.end_blob_ctx);
988 /* Advance to next blob. */
989 ctx->cur_blob = ctx->next_blob;
990 if (ctx->cur_blob != NULL) {
991 if (ctx->cur_blob != ctx->final_blob)
992 ctx->next_blob = next_blob(ctx->cur_blob,
993 ctx->list_head_offset);
995 ctx->next_blob = NULL;
1001 struct hasher_context {
1004 struct read_blob_list_callbacks cbs;
1007 /* Callback for starting to read a blob while calculating its SHA-1 message
1010 hasher_begin_blob(struct blob_descriptor *blob, void *_ctx)
1012 struct hasher_context *ctx = _ctx;
1014 sha1_init(&ctx->sha_ctx);
1016 if (ctx->cbs.begin_blob == NULL)
1019 return (*ctx->cbs.begin_blob)(blob, ctx->cbs.begin_blob_ctx);
1022 /* A consume_data_callback_t implementation that continues calculating the SHA-1
1023 * message digest of the blob being read, then optionally passes the data on to
1024 * another consume_data_callback_t implementation. This allows checking the
1025 * SHA-1 message digest of a blob being extracted, for example. */
1027 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1029 struct hasher_context *ctx = _ctx;
1031 sha1_update(&ctx->sha_ctx, chunk, size);
1032 if (ctx->cbs.consume_chunk == NULL)
1035 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1038 /* Callback for finishing reading a blob while calculating its SHA-1 message
1041 hasher_end_blob(struct blob_descriptor *blob, int status, void *_ctx)
1043 struct hasher_context *ctx = _ctx;
1044 u8 hash[SHA1_HASH_SIZE];
1048 /* Error occurred; the full blob may not have been read. */
1053 /* Retrieve the final SHA-1 message digest. */
1054 sha1_final(hash, &ctx->sha_ctx);
1056 if (blob->unhashed) {
1057 if (ctx->flags & COMPUTE_MISSING_BLOB_HASHES) {
1058 /* No SHA-1 message digest was previously present for the
1059 * blob. Set it to the one just calculated. */
1060 DEBUG("Set SHA-1 message digest for blob "
1061 "(size=%"PRIu64").", blob->size);
1062 copy_hash(blob->hash, hash);
1065 if (ctx->flags & VERIFY_BLOB_HASHES) {
1066 /* The blob already had a SHA-1 message digest present.
1067 * Verify that it is the same as the calculated value.
1069 if (!hashes_equal(hash, blob->hash)) {
1070 if (wimlib_print_errors) {
1071 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1072 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1073 sprint_hash(blob->hash, expected_hashstr);
1074 sprint_hash(hash, actual_hashstr);
1075 ERROR("The data is corrupted!\n"
1076 " (Expected SHA-1=%"TS",\n"
1077 " got SHA-1=%"TS")",
1078 expected_hashstr, actual_hashstr);
1080 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1084 DEBUG("SHA-1 message digest okay for "
1085 "blob (size=%"PRIu64").", blob->size);
1090 if (ctx->cbs.end_blob == NULL)
1093 return (*ctx->cbs.end_blob)(blob, ret, ctx->cbs.end_blob_ctx);
1097 read_full_blob_with_cbs(struct blob_descriptor *blob,
1098 const struct read_blob_list_callbacks *cbs)
1102 ret = (*cbs->begin_blob)(blob, cbs->begin_blob_ctx);
1106 ret = read_blob_prefix(blob, blob->size, cbs->consume_chunk,
1107 cbs->consume_chunk_ctx);
1109 return (*cbs->end_blob)(blob, ret, cbs->end_blob_ctx);
1112 /* Read the full data of the specified blob, passing the data into the specified
1113 * callbacks (all of which are optional) and either checking or computing the
1114 * SHA-1 message digest of the blob. */
1116 read_full_blob_with_sha1(struct blob_descriptor *blob,
1117 const struct read_blob_list_callbacks *cbs)
1119 struct hasher_context hasher_ctx = {
1120 .flags = VERIFY_BLOB_HASHES | COMPUTE_MISSING_BLOB_HASHES,
1123 struct read_blob_list_callbacks hasher_cbs = {
1124 .begin_blob = hasher_begin_blob,
1125 .begin_blob_ctx = &hasher_ctx,
1126 .consume_chunk = hasher_consume_chunk,
1127 .consume_chunk_ctx = &hasher_ctx,
1128 .end_blob = hasher_end_blob,
1129 .end_blob_ctx = &hasher_ctx,
1131 return read_full_blob_with_cbs(blob, &hasher_cbs);
1135 read_blobs_in_solid_resource(struct blob_descriptor *first_blob,
1136 struct blob_descriptor *last_blob,
1138 size_t list_head_offset,
1139 const struct read_blob_list_callbacks *sink_cbs)
1141 struct data_range *ranges;
1142 bool ranges_malloced;
1143 struct blob_descriptor *cur_blob;
1146 u64 ranges_alloc_size;
1148 DEBUG("Reading %"PRIu64" blobs combined in same WIM resource",
1151 /* Setup data ranges array (one range per blob to read); this way
1152 * read_compressed_wim_resource() does not need to be aware of blobs.
1155 ranges_alloc_size = blob_count * sizeof(ranges[0]);
1157 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1158 ERROR("Too many blobs in one resource!");
1159 return WIMLIB_ERR_NOMEM;
1161 if (likely(ranges_alloc_size <= STACK_MAX)) {
1162 ranges = alloca(ranges_alloc_size);
1163 ranges_malloced = false;
1165 ranges = MALLOC(ranges_alloc_size);
1166 if (ranges == NULL) {
1167 ERROR("Too many blobs in one resource!");
1168 return WIMLIB_ERR_NOMEM;
1170 ranges_malloced = true;
1173 for (i = 0, cur_blob = first_blob;
1175 i++, cur_blob = next_blob(cur_blob, list_head_offset))
1177 ranges[i].offset = cur_blob->offset_in_res;
1178 ranges[i].size = cur_blob->size;
1181 struct blobifier_context blobifier_ctx = {
1183 .cur_blob = first_blob,
1184 .next_blob = next_blob(first_blob, list_head_offset),
1185 .cur_blob_offset = 0,
1186 .final_blob = last_blob,
1187 .list_head_offset = list_head_offset,
1190 ret = read_compressed_wim_resource(first_blob->rdesc,
1196 if (ranges_malloced)
1200 if (blobifier_ctx.cur_blob_offset != 0) {
1201 ret = (*blobifier_ctx.cbs.end_blob)
1202 (blobifier_ctx.cur_blob,
1204 blobifier_ctx.cbs.end_blob_ctx);
1211 * Read a list of blobs, each of which may be in any supported location (e.g.
1212 * in a WIM or in an external file). This function optimizes the case where
1213 * multiple blobs are combined into a single solid compressed WIM resource by
1214 * reading the blobs in sequential order, only decompressing the solid resource
1218 * List of blobs to read.
1220 * Offset of the `struct list_head' within each `struct blob_descriptor' that makes up
1223 * Callback functions to accept the blob data.
1225 * Bitwise OR of zero or more of the following flags:
1227 * VERIFY_BLOB_HASHES:
1228 * For all blobs being read that have already had SHA-1 message
1229 * digests computed, calculate the SHA-1 message digest of the read
1230 * data and compare it with the previously computed value. If they
1231 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1233 * COMPUTE_MISSING_BLOB_HASHES
1234 * For all blobs being read that have not yet had their SHA-1
1235 * message digests computed, calculate and save their SHA-1 message
1238 * BLOB_LIST_ALREADY_SORTED
1239 * @blob_list is already sorted in sequential order for reading.
1241 * The callback functions are allowed to delete the current blob from the list
1244 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1245 * to an error reading the data or due to an error status being returned by any
1246 * of the callback functions.
1249 read_blob_list(struct list_head *blob_list,
1250 size_t list_head_offset,
1251 const struct read_blob_list_callbacks *cbs,
1255 struct list_head *cur, *next;
1256 struct blob_descriptor *blob;
1257 struct hasher_context *hasher_ctx;
1258 struct read_blob_list_callbacks *sink_cbs;
1260 if (!(flags & BLOB_LIST_ALREADY_SORTED)) {
1261 ret = sort_blob_list_by_sequential_order(blob_list, list_head_offset);
1266 if (flags & (VERIFY_BLOB_HASHES | COMPUTE_MISSING_BLOB_HASHES)) {
1267 hasher_ctx = alloca(sizeof(*hasher_ctx));
1268 *hasher_ctx = (struct hasher_context) {
1272 sink_cbs = alloca(sizeof(*sink_cbs));
1273 *sink_cbs = (struct read_blob_list_callbacks) {
1274 .begin_blob = hasher_begin_blob,
1275 .begin_blob_ctx = hasher_ctx,
1276 .consume_chunk = hasher_consume_chunk,
1277 .consume_chunk_ctx = hasher_ctx,
1278 .end_blob = hasher_end_blob,
1279 .end_blob_ctx = hasher_ctx,
1282 sink_cbs = (struct read_blob_list_callbacks*)cbs;
1285 for (cur = blob_list->next, next = cur->next;
1287 cur = next, next = cur->next)
1289 blob = (struct blob_descriptor*)((u8*)cur - list_head_offset);
1291 if (blob->blob_location == BLOB_IN_WIM &&
1292 blob->size != blob->rdesc->uncompressed_size)
1294 struct blob_descriptor *blob_next, *blob_last;
1295 struct list_head *next2;
1298 /* The next blob is a proper sub-sequence of a WIM
1299 * resource. See if there are other blobs in the same
1300 * resource that need to be read. Since
1301 * sort_blob_list_by_sequential_order() sorted the blobs
1302 * by offset in the WIM, this can be determined by
1303 * simply scanning forward in the list. */
1309 && (blob_next = (struct blob_descriptor*)
1310 ((u8*)next2 - list_head_offset),
1311 blob_next->blob_location == BLOB_IN_WIM
1312 && blob_next->rdesc == blob->rdesc);
1313 next2 = next2->next)
1315 blob_last = blob_next;
1318 if (blob_count > 1) {
1319 /* Reading multiple blobs combined into a single
1320 * WIM resource. They are in the blob list,
1321 * sorted by offset; @blob specifies the first
1322 * blob in the resource that needs to be read
1323 * and @blob_last specifies the last blob in the
1324 * resource that needs to be read. */
1326 ret = read_blobs_in_solid_resource(blob, blob_last,
1336 ret = read_full_blob_with_cbs(blob, sink_cbs);
1337 if (ret && ret != BEGIN_BLOB_STATUS_SKIP_BLOB)
1344 * Extract the first @size bytes of the specified blob.
1346 * If @size specifies the full uncompressed size of the blob, then the SHA-1
1347 * message digest of the uncompressed blob is checked while being extracted.
1349 * The uncompressed data of the blob is passed in chunks of unspecified size to
1350 * the @extract_chunk function, passing it @extract_chunk_arg.
1353 extract_blob(struct blob_descriptor *blob, u64 size,
1354 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1356 wimlib_assert(size <= blob->size);
1357 if (size == blob->size) {
1359 struct read_blob_list_callbacks cbs = {
1360 .consume_chunk = extract_chunk,
1361 .consume_chunk_ctx = extract_chunk_arg,
1363 return read_full_blob_with_sha1(blob, &cbs);
1365 /* Don't do SHA-1. */
1366 return read_blob_prefix(blob, size, extract_chunk,
1371 /* A consume_data_callback_t implementation that writes the chunk of data to a
1372 * file descriptor. */
1374 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1376 struct filedes *fd = _fd_p;
1378 int ret = full_write(fd, chunk, size);
1380 ERROR_WITH_ERRNO("Error writing to file descriptor");
1386 /* Extract the first @size bytes of the specified blob to the specified file
1389 extract_blob_to_fd(struct blob_descriptor *blob, struct filedes *fd, u64 size)
1391 return extract_blob(blob, size, extract_chunk_to_fd, fd);
1394 /* Extract the full uncompressed contents of the specified blob to the specified
1395 * file descriptor. */
1397 extract_full_blob_to_fd(struct blob_descriptor *blob, struct filedes *fd)
1399 return extract_blob_to_fd(blob, fd, blob->size);
1402 /* Calculate the SHA-1 message digest of a blob and store it in @blob->hash. */
1404 sha1_blob(struct blob_descriptor *blob)
1406 wimlib_assert(blob->unhashed);
1407 struct read_blob_list_callbacks cbs = {
1409 return read_full_blob_with_sha1(blob, &cbs);
1413 * Convert a short WIM resource header to a stand-alone WIM resource descriptor.
1415 * Note: for solid resources some fields still need to be overridden.
1418 wim_res_hdr_to_desc(const struct wim_reshdr *reshdr, WIMStruct *wim,
1419 struct wim_resource_descriptor *rdesc)
1422 rdesc->offset_in_wim = reshdr->offset_in_wim;
1423 rdesc->size_in_wim = reshdr->size_in_wim;
1424 rdesc->uncompressed_size = reshdr->uncompressed_size;
1425 INIT_LIST_HEAD(&rdesc->blob_list);
1426 rdesc->flags = reshdr->flags;
1427 rdesc->is_pipable = wim_is_pipable(wim);
1428 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1429 rdesc->compression_type = wim->compression_type;
1430 rdesc->chunk_size = wim->chunk_size;
1432 rdesc->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1433 rdesc->chunk_size = 0;
1437 /* Convert a stand-alone resource descriptor to a WIM resource header. */
1439 wim_res_desc_to_hdr(const struct wim_resource_descriptor *rdesc,
1440 struct wim_reshdr *reshdr)
1442 reshdr->offset_in_wim = rdesc->offset_in_wim;
1443 reshdr->size_in_wim = rdesc->size_in_wim;
1444 reshdr->flags = rdesc->flags;
1445 reshdr->uncompressed_size = rdesc->uncompressed_size;
1448 /* Translates a WIM resource header from the on-disk format into an in-memory
1451 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1452 struct wim_reshdr *reshdr)
1454 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1455 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1456 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1457 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1458 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1459 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1460 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1461 ((u64)disk_reshdr->size_in_wim[6] << 48));
1462 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1463 reshdr->flags = disk_reshdr->flags;
1466 /* Translates a WIM resource header from an in-memory format into the on-disk
1469 put_wim_reshdr(const struct wim_reshdr *reshdr,
1470 struct wim_reshdr_disk *disk_reshdr)
1472 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1473 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1474 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1475 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1476 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1477 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1478 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1479 disk_reshdr->flags = reshdr->flags;
1480 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1481 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);