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 sequence of chunks. Each chunk
49 * decompresses to the same size except possibly for the last, which
50 * decompresses to the remaining size. Chunks that did not compress to less
51 * than their original size are stored uncompressed.
53 * We support three variations on this resource format, independently of the
54 * compression type and chunk size which can vary as well:
56 * - Original resource format: immediately before the compressed chunks, the
57 * "chunk table" provides the offset, in bytes relative to the end of the
58 * chunk table, of the start of each compressed chunk, except for the first
59 * chunk which is omitted as it always has an offset of 0. Chunk table
60 * entries are 32-bit for resources <= 4 GiB uncompressed and 64-bit for
61 * resources > 4 GiB uncompressed.
63 * - Solid resource format (distinguished by the use of WIM_RESHDR_FLAG_SOLID
64 * instead of WIM_RESHDR_FLAG_COMPRESSED): similar to the original format, but
65 * the resource begins with a 16-byte header which specifies the uncompressed
66 * size of the resource, the compression type, and the chunk size. (In the
67 * original format, these values were instead determined from outside the
68 * resource itself, from the blob table and the WIM file header.) In addition,
69 * in this format the entries in the chunk table contain compressed chunk
70 * sizes rather than offsets. As a consequence of this, the chunk table
71 * entries are always 32-bit and there is an entry for chunk 0.
73 * - Pipable resource format (wimlib extension; all resources in a pipable WIM
74 * have this format): similar to the original format, but the chunk table is
75 * at the end of the resource rather than the beginning, and each compressed
76 * chunk is prefixed with its compressed size as a 32-bit integer. This
77 * format allows a resource to be written without rewinding.
87 * Read data from a compressed WIM resource.
90 * Description of the compressed WIM resource to read from.
92 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
93 * read, sorted by increasing offset.
95 * Number of ranges in @ranges; must be at least 1.
97 * Structure which provides the consume_chunk() callback to feed the data
98 * being read. Each call provides the next chunk of the requested data,
99 * uncompressed. Each chunk will be nonempty and will not cross range
100 * boundaries but otherwise will be of unspecified size.
102 * Possible return values:
104 * WIMLIB_ERR_SUCCESS (0)
105 * WIMLIB_ERR_READ (errno set)
106 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to EINVAL)
107 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
108 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
109 * WIMLIB_ERR_INVALID_CHUNK_SIZE (errno set to EINVAL)
111 * or other error code returned by the cbs->consume_chunk() function.
114 read_compressed_wim_resource(const struct wim_resource_descriptor * const rdesc,
115 const struct data_range * const ranges,
116 const size_t num_ranges,
117 const struct read_blob_callbacks *cbs)
120 u64 *chunk_offsets = NULL;
123 bool chunk_offsets_malloced = false;
124 bool ubuf_malloced = false;
125 bool cbuf_malloced = false;
126 struct wimlib_decompressor *decompressor = NULL;
129 wimlib_assert(num_ranges != 0);
130 for (size_t i = 0; i < num_ranges; i++) {
131 wimlib_assert(ranges[i].offset + ranges[i].size > ranges[i].offset &&
132 ranges[i].offset + ranges[i].size <= rdesc->uncompressed_size);
134 for (size_t i = 0; i < num_ranges - 1; i++)
135 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
137 /* Get the offsets of the first and last bytes of the read. */
138 const u64 first_offset = ranges[0].offset;
139 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
141 /* Get the file descriptor for the WIM. */
142 struct filedes * const in_fd = &rdesc->wim->in_fd;
144 /* Determine if we're reading a pipable resource from a pipe or not. */
145 const bool is_pipe_read = (rdesc->is_pipable && !filedes_is_seekable(in_fd));
147 /* Determine if the chunk table is in an alternate format. */
148 const bool alt_chunk_table = (rdesc->flags & WIM_RESHDR_FLAG_SOLID)
151 /* Get the maximum size of uncompressed chunks in this resource, which
152 * we require be a power of 2. */
153 u64 cur_read_offset = rdesc->offset_in_wim;
154 int ctype = rdesc->compression_type;
155 u32 chunk_size = rdesc->chunk_size;
156 if (alt_chunk_table) {
157 /* Alternate chunk table format. Its header specifies the chunk
158 * size and compression format. Note: it could be read here;
159 * however, the relevant data was already loaded into @rdesc by
160 * read_blob_table(). */
161 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
164 if (unlikely(!is_power_of_2(chunk_size))) {
165 ERROR("Invalid compressed resource: "
166 "expected power-of-2 chunk size (got %"PRIu32")",
168 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
173 /* Get valid decompressor. */
174 if (likely(ctype == rdesc->wim->decompressor_ctype &&
175 chunk_size == rdesc->wim->decompressor_max_block_size))
177 /* Cached decompressor. */
178 decompressor = rdesc->wim->decompressor;
179 rdesc->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
180 rdesc->wim->decompressor = NULL;
182 ret = wimlib_create_decompressor(ctype, chunk_size,
185 if (ret != WIMLIB_ERR_NOMEM)
191 const u32 chunk_order = fls32(chunk_size);
193 /* Calculate the total number of chunks the resource is divided into. */
194 const u64 num_chunks = (rdesc->uncompressed_size + chunk_size - 1) >> chunk_order;
196 /* Calculate the 0-based indices of the first and last chunks containing
197 * data that needs to be passed to the callback. */
198 const u64 first_needed_chunk = first_offset >> chunk_order;
199 const u64 last_needed_chunk = last_offset >> chunk_order;
201 /* Calculate the 0-based index of the first chunk that actually needs to
202 * be read. This is normally first_needed_chunk, but for pipe reads we
203 * must always start from the 0th chunk. */
204 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
206 /* Calculate the number of chunk offsets that are needed for the chunks
208 const u64 num_needed_chunk_offsets =
209 last_needed_chunk - read_start_chunk + 1 +
210 (last_needed_chunk < num_chunks - 1);
212 /* Calculate the number of entries in the chunk table. Normally, it's
213 * one less than the number of chunks, since the first chunk has no
214 * entry. But in the alternate chunk table format, the chunk entries
215 * contain chunk sizes, not offsets, and there is one per chunk. */
216 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
218 /* Set the size of each chunk table entry based on the resource's
219 * uncompressed size. */
220 const u64 chunk_entry_size = get_chunk_entry_size(rdesc->uncompressed_size,
223 /* Calculate the size of the chunk table in bytes. */
224 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
226 /* Calculate the size of the chunk table in bytes, including the header
227 * in the case of the alternate chunk table format. */
228 const u64 chunk_table_full_size =
229 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
233 /* Read the needed chunk table entries into memory and use them
234 * to initialize the chunk_offsets array. */
236 u64 first_chunk_entry_to_read;
237 u64 last_chunk_entry_to_read;
239 if (alt_chunk_table) {
240 /* The alternate chunk table contains chunk sizes, not
241 * offsets, so we always must read all preceding entries
242 * in order to determine offsets. */
243 first_chunk_entry_to_read = 0;
244 last_chunk_entry_to_read = last_needed_chunk;
246 /* Here we must account for the fact that the first
247 * chunk has no explicit chunk table entry. */
249 if (read_start_chunk == 0)
250 first_chunk_entry_to_read = 0;
252 first_chunk_entry_to_read = read_start_chunk - 1;
254 if (last_needed_chunk == 0)
255 last_chunk_entry_to_read = 0;
257 last_chunk_entry_to_read = last_needed_chunk - 1;
259 if (last_needed_chunk < num_chunks - 1)
260 last_chunk_entry_to_read++;
263 const u64 num_chunk_entries_to_read =
264 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
266 const u64 chunk_offsets_alloc_size =
267 max(num_chunk_entries_to_read,
268 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
270 if (unlikely((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)) {
275 if (likely(chunk_offsets_alloc_size <= STACK_MAX)) {
276 chunk_offsets = alloca(chunk_offsets_alloc_size);
278 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
279 if (unlikely(!chunk_offsets))
281 chunk_offsets_malloced = true;
284 const size_t chunk_table_size_to_read =
285 num_chunk_entries_to_read * chunk_entry_size;
287 const u64 file_offset_of_needed_chunk_entries =
289 + (first_chunk_entry_to_read * chunk_entry_size)
290 + (rdesc->is_pipable ? (rdesc->size_in_wim - chunk_table_size) : 0);
292 void * const chunk_table_data =
294 chunk_offsets_alloc_size -
295 chunk_table_size_to_read;
297 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
298 file_offset_of_needed_chunk_entries);
302 /* Now fill in chunk_offsets from the entries we have read in
303 * chunk_tab_data. We break aliasing rules here to avoid having
304 * to allocate yet another array. */
305 typedef le64 _may_alias_attribute aliased_le64_t;
306 typedef le32 _may_alias_attribute aliased_le32_t;
307 u64 * chunk_offsets_p = chunk_offsets;
309 if (alt_chunk_table) {
311 aliased_le32_t *raw_entries = chunk_table_data;
313 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
314 u32 entry = le32_to_cpu(raw_entries[i]);
315 if (i >= read_start_chunk)
316 *chunk_offsets_p++ = cur_offset;
319 if (last_needed_chunk < num_chunks - 1)
320 *chunk_offsets_p = cur_offset;
322 if (read_start_chunk == 0)
323 *chunk_offsets_p++ = 0;
325 if (chunk_entry_size == 4) {
326 aliased_le32_t *raw_entries = chunk_table_data;
327 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
328 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
330 aliased_le64_t *raw_entries = chunk_table_data;
331 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
332 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
336 /* Set offset to beginning of first chunk to read. */
337 cur_read_offset += chunk_offsets[0];
338 if (rdesc->is_pipable)
339 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
341 cur_read_offset += chunk_table_size;
344 /* Allocate buffer for holding the uncompressed data of each chunk. */
345 if (chunk_size <= STACK_MAX) {
346 ubuf = alloca(chunk_size);
348 ubuf = MALLOC(chunk_size);
351 ubuf_malloced = true;
354 /* Allocate a temporary buffer for reading compressed chunks, each of
355 * which can be at most @chunk_size - 1 bytes. This excludes compressed
356 * chunks that are a full @chunk_size bytes, which are actually stored
358 if (chunk_size - 1 <= STACK_MAX) {
359 cbuf = alloca(chunk_size - 1);
361 cbuf = MALLOC(chunk_size - 1);
364 cbuf_malloced = true;
367 /* Set current data range. */
368 const struct data_range *cur_range = ranges;
369 const struct data_range * const end_range = &ranges[num_ranges];
370 u64 cur_range_pos = cur_range->offset;
371 u64 cur_range_end = cur_range->offset + cur_range->size;
373 /* Read and process each needed chunk. */
374 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
376 /* Calculate uncompressed size of next chunk. */
378 if ((i == num_chunks - 1) && (rdesc->uncompressed_size & (chunk_size - 1)))
379 chunk_usize = (rdesc->uncompressed_size & (chunk_size - 1));
381 chunk_usize = chunk_size;
383 /* Calculate compressed size of next chunk. */
386 struct pwm_chunk_hdr chunk_hdr;
388 ret = full_pread(in_fd, &chunk_hdr,
389 sizeof(chunk_hdr), cur_read_offset);
392 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
394 if (i == num_chunks - 1) {
395 chunk_csize = rdesc->size_in_wim -
396 chunk_table_full_size -
397 chunk_offsets[i - read_start_chunk];
398 if (rdesc->is_pipable)
399 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
401 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
402 chunk_offsets[i - read_start_chunk];
405 if (unlikely(chunk_csize == 0 || chunk_csize > chunk_usize)) {
406 ERROR("Invalid chunk size in compressed resource!");
408 ret = WIMLIB_ERR_DECOMPRESSION;
411 if (rdesc->is_pipable)
412 cur_read_offset += sizeof(struct pwm_chunk_hdr);
414 /* Offsets in the uncompressed resource at which this chunk
415 * starts and ends. */
416 const u64 chunk_start_offset = i << chunk_order;
417 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
419 if (chunk_end_offset <= cur_range_pos) {
421 /* The next range does not require data in this chunk,
423 cur_read_offset += chunk_csize;
427 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
433 /* Read the chunk and feed data to the callback
437 if (chunk_csize == chunk_usize)
442 ret = full_pread(in_fd,
449 if (read_buf == cbuf) {
450 ret = wimlib_decompress(cbuf,
456 ERROR("Failed to decompress data!");
457 ret = WIMLIB_ERR_DECOMPRESSION;
462 cur_read_offset += chunk_csize;
464 /* At least one range requires data in this chunk. */
466 size_t start, end, size;
468 /* Calculate how many bytes of data should be
469 * sent to the callback function, taking into
470 * account that data sent to the callback
471 * function must not overlap range boundaries.
473 start = cur_range_pos - chunk_start_offset;
474 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
477 ret = call_consume_chunk(&ubuf[start], size, cbs);
481 cur_range_pos += size;
482 if (cur_range_pos == cur_range_end) {
483 /* Advance to next range. */
484 if (++cur_range == end_range) {
485 cur_range_pos = ~0ULL;
487 cur_range_pos = cur_range->offset;
488 cur_range_end = cur_range->offset + cur_range->size;
491 } while (cur_range_pos < chunk_end_offset);
496 last_offset == rdesc->uncompressed_size - 1 &&
500 /* If reading a pipable resource from a pipe and the full data
501 * was requested, skip the chunk table at the end so that the
502 * file descriptor is fully clear of the resource after this
504 cur_read_offset += chunk_table_size;
505 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
513 wimlib_free_decompressor(rdesc->wim->decompressor);
514 rdesc->wim->decompressor = decompressor;
515 rdesc->wim->decompressor_ctype = ctype;
516 rdesc->wim->decompressor_max_block_size = chunk_size;
518 if (chunk_offsets_malloced)
527 ERROR("Out of memory while reading compressed WIM resource");
528 ret = WIMLIB_ERR_NOMEM;
532 ERROR_WITH_ERRNO("Error reading data from WIM file");
536 /* Read raw data from a file descriptor at the specified offset, feeding the
537 * data in nonempty chunks into the cbs->consume_chunk() function. */
539 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
540 const struct read_blob_callbacks *cbs)
543 size_t bytes_to_read;
547 bytes_to_read = min(sizeof(buf), size);
548 ret = full_pread(in_fd, buf, bytes_to_read, offset);
550 ERROR_WITH_ERRNO("Read error");
553 ret = call_consume_chunk(buf, bytes_to_read, cbs);
556 size -= bytes_to_read;
557 offset += bytes_to_read;
562 /* A consume_chunk() implementation that simply concatenates all chunks into an
563 * in-memory buffer. */
565 bufferer_cb(const void *chunk, size_t size, void *_ctx)
569 *buf_p = mempcpy(*buf_p, chunk, size);
574 * Read @size bytes at @offset in the WIM resource described by @rdesc and feed
575 * the data into the @cbs->consume_chunk callback function.
577 * @offset and @size are assumed to have already been validated against the
578 * resource's uncompressed size.
580 * Returns 0 on success; or the first nonzero value returned by the callback
581 * function; or a nonzero wimlib error code with errno set as well.
584 read_partial_wim_resource(const struct wim_resource_descriptor *rdesc,
585 const u64 offset, const u64 size,
586 const struct read_blob_callbacks *cbs)
588 if (rdesc->flags & (WIM_RESHDR_FLAG_COMPRESSED |
589 WIM_RESHDR_FLAG_SOLID))
591 /* Compressed resource */
594 struct data_range range = {
598 return read_compressed_wim_resource(rdesc, &range, 1, cbs);
601 /* Uncompressed resource */
602 return read_raw_file_data(&rdesc->wim->in_fd,
603 rdesc->offset_in_wim + offset,
607 /* Read the specified range of uncompressed data from the specified blob, which
608 * must be located in a WIM file, into the specified buffer. */
610 read_partial_wim_blob_into_buf(const struct blob_descriptor *blob,
611 u64 offset, size_t size, void *buf)
613 struct read_blob_callbacks cbs = {
614 .consume_chunk = bufferer_cb,
617 return read_partial_wim_resource(blob->rdesc,
618 blob->offset_in_res + offset,
623 /* Skip over the data of the specified WIM resource. */
625 skip_wim_resource(const struct wim_resource_descriptor *rdesc)
627 struct read_blob_callbacks cbs = {
629 return read_partial_wim_resource(rdesc, 0,
630 rdesc->uncompressed_size, &cbs);
634 read_wim_blob_prefix(const struct blob_descriptor *blob, u64 size,
635 const struct read_blob_callbacks *cbs)
637 return read_partial_wim_resource(blob->rdesc, blob->offset_in_res,
641 /* This function handles reading blob data that is located in an external file,
642 * such as a file that has been added to the WIM image through execution of a
643 * wimlib_add_command.
645 * This assumes the file can be accessed using the standard POSIX open(),
646 * read(), and close(). On Windows this will not necessarily be the case (since
647 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
648 * encrypted), so Windows uses its own code for its equivalent case. */
650 read_file_on_disk_prefix(const struct blob_descriptor *blob, u64 size,
651 const struct read_blob_callbacks *cbs)
657 raw_fd = topen(blob->file_on_disk, O_BINARY | O_RDONLY);
658 if (unlikely(raw_fd < 0)) {
659 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", blob->file_on_disk);
660 return WIMLIB_ERR_OPEN;
662 filedes_init(&fd, raw_fd);
663 ret = read_raw_file_data(&fd, 0, size, cbs);
670 read_staging_file_prefix(const struct blob_descriptor *blob, u64 size,
671 const struct read_blob_callbacks *cbs)
677 raw_fd = openat(blob->staging_dir_fd, blob->staging_file_name,
678 O_RDONLY | O_NOFOLLOW);
679 if (unlikely(raw_fd < 0)) {
680 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
681 blob->staging_file_name);
682 return WIMLIB_ERR_OPEN;
684 filedes_init(&fd, raw_fd);
685 ret = read_raw_file_data(&fd, 0, size, cbs);
691 /* This function handles the trivial case of reading blob data that is, in fact,
692 * already located in an in-memory buffer. */
694 read_buffer_prefix(const struct blob_descriptor *blob,
695 u64 size, const struct read_blob_callbacks *cbs)
699 return call_consume_chunk(blob->attached_buffer, size, cbs);
702 typedef int (*read_blob_prefix_handler_t)(const struct blob_descriptor *blob,
704 const struct read_blob_callbacks *cbs);
707 * Read the first @size bytes from a generic "blob", which may be located in any
708 * one of several locations, such as in a WIM resource (possibly compressed), in
709 * an external file, or directly in an in-memory buffer. The blob data will be
710 * fed to the cbs->consume_chunk() callback function in chunks that are nonempty
711 * but otherwise are of unspecified size.
713 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
714 * the blob data cannot be successfully read (for a number of different reasons,
715 * depending on the blob location), or if cbs->consume_chunk() returned nonzero
716 * in which case that error code will be returned.
719 read_blob_prefix(const struct blob_descriptor *blob, u64 size,
720 const struct read_blob_callbacks *cbs)
722 static const read_blob_prefix_handler_t handlers[] = {
723 [BLOB_IN_WIM] = read_wim_blob_prefix,
724 [BLOB_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
725 [BLOB_IN_ATTACHED_BUFFER] = read_buffer_prefix,
727 [BLOB_IN_STAGING_FILE] = read_staging_file_prefix,
730 [BLOB_IN_NTFS_VOLUME] = read_ntfs_attribute_prefix,
733 [BLOB_IN_WINNT_FILE_ON_DISK] = read_winnt_stream_prefix,
734 [BLOB_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
737 wimlib_assert(blob->blob_location < ARRAY_LEN(handlers)
738 && handlers[blob->blob_location] != NULL);
739 wimlib_assert(size <= blob->size);
740 return handlers[blob->blob_location](blob, size, cbs);
743 /* Read the full data of the specified blob, passing the data into the specified
744 * callbacks (all of which are optional). */
746 read_blob_with_cbs(struct blob_descriptor *blob,
747 const struct read_blob_callbacks *cbs)
751 ret = call_begin_blob(blob, cbs);
755 ret = read_blob_prefix(blob, blob->size, cbs);
757 return call_end_blob(blob, ret, cbs);
760 /* Read the full uncompressed data of the specified blob into the specified
761 * buffer, which must have space for at least blob->size bytes. The SHA-1
762 * message digest is *not* checked. */
764 read_blob_into_buf(const struct blob_descriptor *blob, void *buf)
766 struct read_blob_callbacks cbs = {
767 .consume_chunk = bufferer_cb,
770 return read_blob_prefix(blob, blob->size, &cbs);
773 /* Retrieve the full uncompressed data of the specified blob. A buffer large
774 * enough hold the data is allocated and returned in @buf_ret. The SHA-1
775 * message digest is *not* checked. */
777 read_blob_into_alloc_buf(const struct blob_descriptor *blob, void **buf_ret)
782 if (unlikely((size_t)blob->size != blob->size)) {
783 ERROR("Can't read %"PRIu64" byte blob into memory", blob->size);
784 return WIMLIB_ERR_NOMEM;
787 buf = MALLOC(blob->size);
789 return WIMLIB_ERR_NOMEM;
791 ret = read_blob_into_buf(blob, buf);
801 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
802 * `wim_reshdr' and the corresponding WIM file. A buffer large enough hold the
803 * data is allocated and returned in @buf_ret. */
805 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim,
808 struct wim_resource_descriptor rdesc;
809 struct blob_descriptor blob;
811 wim_reshdr_to_desc_and_blob(reshdr, wim, &rdesc, &blob);
813 return read_blob_into_alloc_buf(&blob, buf_ret);
816 /* Calculate the SHA-1 message digest of the uncompressed data of the specified
819 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
820 u8 hash[SHA1_HASH_SIZE])
822 struct wim_resource_descriptor rdesc;
823 struct blob_descriptor blob;
826 wim_reshdr_to_desc_and_blob(reshdr, wim, &rdesc, &blob);
829 ret = sha1_blob(&blob);
833 copy_hash(hash, blob.hash);
837 struct blobifier_context {
838 struct read_blob_callbacks cbs;
839 struct blob_descriptor *cur_blob;
840 struct blob_descriptor *next_blob;
842 struct blob_descriptor *final_blob;
843 size_t list_head_offset;
846 static struct blob_descriptor *
847 next_blob(struct blob_descriptor *blob, size_t list_head_offset)
849 struct list_head *cur;
851 cur = (struct list_head*)((u8*)blob + list_head_offset);
853 return (struct blob_descriptor*)((u8*)cur->next - list_head_offset);
856 /* A consume_chunk() implementation that translates raw resource data into
857 * blobs, calling the begin_blob, consume_chunk, and end_blob callbacks as
860 blobifier_cb(const void *chunk, size_t size, void *_ctx)
862 struct blobifier_context *ctx = _ctx;
865 wimlib_assert(ctx->cur_blob != NULL);
866 wimlib_assert(size <= ctx->cur_blob->size - ctx->cur_blob_offset);
868 if (ctx->cur_blob_offset == 0) {
869 /* Starting a new blob. */
870 ret = call_begin_blob(ctx->cur_blob, &ctx->cbs);
875 ctx->cur_blob_offset += size;
877 ret = call_consume_chunk(chunk, size, &ctx->cbs);
881 if (ctx->cur_blob_offset == ctx->cur_blob->size) {
882 /* Finished reading all the data for a blob. */
884 ctx->cur_blob_offset = 0;
886 ret = call_end_blob(ctx->cur_blob, 0, &ctx->cbs);
890 /* Advance to next blob. */
891 ctx->cur_blob = ctx->next_blob;
892 if (ctx->cur_blob != NULL) {
893 if (ctx->cur_blob != ctx->final_blob)
894 ctx->next_blob = next_blob(ctx->cur_blob,
895 ctx->list_head_offset);
897 ctx->next_blob = NULL;
903 struct hasher_context {
906 struct read_blob_callbacks cbs;
909 /* Callback for starting to read a blob while calculating its SHA-1 message
912 hasher_begin_blob(struct blob_descriptor *blob, void *_ctx)
914 struct hasher_context *ctx = _ctx;
916 sha1_init(&ctx->sha_ctx);
918 return call_begin_blob(blob, &ctx->cbs);
921 /* A consume_chunk() implementation that continues calculating the SHA-1 message
922 * digest of the blob being read, then optionally passes the data on to another
923 * consume_chunk() implementation. This allows checking the SHA-1 message
924 * digest of a blob being extracted, for example. */
926 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
928 struct hasher_context *ctx = _ctx;
930 sha1_update(&ctx->sha_ctx, chunk, size);
932 return call_consume_chunk(chunk, size, &ctx->cbs);
935 /* Callback for finishing reading a blob while calculating its SHA-1 message
938 hasher_end_blob(struct blob_descriptor *blob, int status, void *_ctx)
940 struct hasher_context *ctx = _ctx;
941 u8 hash[SHA1_HASH_SIZE];
944 if (unlikely(status)) {
945 /* Error occurred; the full blob may not have been read. */
950 /* Retrieve the final SHA-1 message digest. */
951 sha1_final(hash, &ctx->sha_ctx);
953 /* Set the SHA-1 message digest of the blob, or compare the calculated
954 * value with stored value. */
955 if (blob->unhashed) {
956 if (ctx->flags & COMPUTE_MISSING_BLOB_HASHES)
957 copy_hash(blob->hash, hash);
958 } else if ((ctx->flags & VERIFY_BLOB_HASHES) &&
959 unlikely(!hashes_equal(hash, blob->hash)))
961 if (wimlib_print_errors) {
962 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
963 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
964 sprint_hash(blob->hash, expected_hashstr);
965 sprint_hash(hash, actual_hashstr);
966 ERROR("The data is corrupted!\n"
967 " (Expected SHA-1=%"TS", got SHA-1=%"TS")",
968 expected_hashstr, actual_hashstr);
970 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
975 return call_end_blob(blob, ret, &ctx->cbs);
978 /* Read the full data of the specified blob, passing the data into the specified
979 * callbacks (all of which are optional) and either checking or computing the
980 * SHA-1 message digest of the blob. */
982 read_blob_with_sha1(struct blob_descriptor *blob,
983 const struct read_blob_callbacks *cbs)
985 struct hasher_context hasher_ctx = {
986 .flags = VERIFY_BLOB_HASHES | COMPUTE_MISSING_BLOB_HASHES,
989 struct read_blob_callbacks hasher_cbs = {
990 .begin_blob = hasher_begin_blob,
991 .consume_chunk = hasher_consume_chunk,
992 .end_blob = hasher_end_blob,
995 return read_blob_with_cbs(blob, &hasher_cbs);
999 read_blobs_in_solid_resource(struct blob_descriptor *first_blob,
1000 struct blob_descriptor *last_blob,
1002 size_t list_head_offset,
1003 const struct read_blob_callbacks *sink_cbs)
1005 struct data_range *ranges;
1006 bool ranges_malloced;
1007 struct blob_descriptor *cur_blob;
1010 u64 ranges_alloc_size;
1012 /* Setup data ranges array (one range per blob to read); this way
1013 * read_compressed_wim_resource() does not need to be aware of blobs.
1016 ranges_alloc_size = (u64)blob_count * sizeof(ranges[0]);
1018 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size))
1021 if (ranges_alloc_size <= STACK_MAX) {
1022 ranges = alloca(ranges_alloc_size);
1023 ranges_malloced = false;
1025 ranges = MALLOC(ranges_alloc_size);
1026 if (unlikely(!ranges))
1028 ranges_malloced = true;
1031 for (i = 0, cur_blob = first_blob;
1033 i++, cur_blob = next_blob(cur_blob, list_head_offset))
1035 ranges[i].offset = cur_blob->offset_in_res;
1036 ranges[i].size = cur_blob->size;
1039 struct blobifier_context blobifier_ctx = {
1041 .cur_blob = first_blob,
1042 .next_blob = next_blob(first_blob, list_head_offset),
1043 .cur_blob_offset = 0,
1044 .final_blob = last_blob,
1045 .list_head_offset = list_head_offset,
1047 struct read_blob_callbacks cbs = {
1048 .consume_chunk = blobifier_cb,
1049 .ctx = &blobifier_ctx,
1052 ret = read_compressed_wim_resource(first_blob->rdesc, ranges,
1055 if (ranges_malloced)
1058 if (unlikely(ret && blobifier_ctx.cur_blob_offset != 0)) {
1059 ret = call_end_blob(blobifier_ctx.cur_blob, ret,
1060 &blobifier_ctx.cbs);
1065 ERROR("Too many blobs in one resource!");
1066 return WIMLIB_ERR_NOMEM;
1070 * Read a list of blobs, each of which may be in any supported location (e.g.
1071 * in a WIM or in an external file). This function optimizes the case where
1072 * multiple blobs are combined into a single solid compressed WIM resource by
1073 * reading the blobs in sequential order, only decompressing the solid resource
1077 * List of blobs to read.
1079 * Offset of the `struct list_head' within each `struct blob_descriptor'
1080 * that makes up the @blob_list.
1082 * Callback functions to accept the blob data.
1084 * Bitwise OR of zero or more of the following flags:
1086 * VERIFY_BLOB_HASHES:
1087 * For all blobs being read that have already had SHA-1 message
1088 * digests computed, calculate the SHA-1 message digest of the read
1089 * data and compare it with the previously computed value. If they
1090 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1092 * COMPUTE_MISSING_BLOB_HASHES
1093 * For all blobs being read that have not yet had their SHA-1
1094 * message digests computed, calculate and save their SHA-1 message
1097 * BLOB_LIST_ALREADY_SORTED
1098 * @blob_list is already sorted in sequential order for reading.
1100 * The callback functions are allowed to delete the current blob from the list
1103 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1104 * to an error reading the data or due to an error status being returned by any
1105 * of the callback functions.
1108 read_blob_list(struct list_head *blob_list, size_t list_head_offset,
1109 const struct read_blob_callbacks *cbs, int flags)
1112 struct list_head *cur, *next;
1113 struct blob_descriptor *blob;
1114 struct hasher_context *hasher_ctx;
1115 struct read_blob_callbacks *sink_cbs;
1117 if (!(flags & BLOB_LIST_ALREADY_SORTED)) {
1118 ret = sort_blob_list_by_sequential_order(blob_list,
1124 if (flags & (VERIFY_BLOB_HASHES | COMPUTE_MISSING_BLOB_HASHES)) {
1125 hasher_ctx = alloca(sizeof(*hasher_ctx));
1126 *hasher_ctx = (struct hasher_context) {
1130 sink_cbs = alloca(sizeof(*sink_cbs));
1131 *sink_cbs = (struct read_blob_callbacks) {
1132 .begin_blob = hasher_begin_blob,
1133 .consume_chunk = hasher_consume_chunk,
1134 .end_blob = hasher_end_blob,
1138 sink_cbs = (struct read_blob_callbacks *)cbs;
1141 for (cur = blob_list->next, next = cur->next;
1143 cur = next, next = cur->next)
1145 blob = (struct blob_descriptor*)((u8*)cur - list_head_offset);
1147 if (blob->blob_location == BLOB_IN_WIM &&
1148 blob->size != blob->rdesc->uncompressed_size)
1150 struct blob_descriptor *blob_next, *blob_last;
1151 struct list_head *next2;
1154 /* The next blob is a proper sub-sequence of a WIM
1155 * resource. See if there are other blobs in the same
1156 * resource that need to be read. Since
1157 * sort_blob_list_by_sequential_order() sorted the blobs
1158 * by offset in the WIM, this can be determined by
1159 * simply scanning forward in the list. */
1165 && (blob_next = (struct blob_descriptor*)
1166 ((u8*)next2 - list_head_offset),
1167 blob_next->blob_location == BLOB_IN_WIM
1168 && blob_next->rdesc == blob->rdesc);
1169 next2 = next2->next)
1171 blob_last = blob_next;
1174 if (blob_count > 1) {
1175 /* Reading multiple blobs combined into a single
1176 * WIM resource. They are in the blob list,
1177 * sorted by offset; @blob specifies the first
1178 * blob in the resource that needs to be read
1179 * and @blob_last specifies the last blob in the
1180 * resource that needs to be read. */
1182 ret = read_blobs_in_solid_resource(blob, blob_last,
1192 ret = read_blob_with_cbs(blob, sink_cbs);
1193 if (unlikely(ret && ret != BEGIN_BLOB_STATUS_SKIP_BLOB))
1200 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd)
1202 struct filedes *fd = _fd;
1203 int ret = full_write(fd, chunk, size);
1205 ERROR_WITH_ERRNO("Error writing to file descriptor");
1209 /* Extract the first @size bytes of the specified blob to the specified file
1210 * descriptor. This does *not* check the SHA-1 message digest. */
1212 extract_blob_prefix_to_fd(struct blob_descriptor *blob, u64 size,
1215 struct read_blob_callbacks cbs = {
1216 .consume_chunk = extract_chunk_to_fd,
1219 return read_blob_prefix(blob, size, &cbs);
1222 /* Extract the full uncompressed contents of the specified blob to the specified
1223 * file descriptor. This checks the SHA-1 message digest. */
1225 extract_blob_to_fd(struct blob_descriptor *blob, struct filedes *fd)
1227 struct read_blob_callbacks cbs = {
1228 .consume_chunk = extract_chunk_to_fd,
1231 return read_blob_with_sha1(blob, &cbs);
1234 /* Calculate the SHA-1 message digest of a blob and store it in @blob->hash. */
1236 sha1_blob(struct blob_descriptor *blob)
1238 struct read_blob_callbacks cbs = {
1240 return read_blob_with_sha1(blob, &cbs);
1244 * Convert a short WIM resource header to a stand-alone WIM resource descriptor.
1246 * Note: for solid resources some fields still need to be overridden.
1249 wim_reshdr_to_desc(const struct wim_reshdr *reshdr, WIMStruct *wim,
1250 struct wim_resource_descriptor *rdesc)
1253 rdesc->offset_in_wim = reshdr->offset_in_wim;
1254 rdesc->size_in_wim = reshdr->size_in_wim;
1255 rdesc->uncompressed_size = reshdr->uncompressed_size;
1256 INIT_LIST_HEAD(&rdesc->blob_list);
1257 rdesc->flags = reshdr->flags;
1258 rdesc->is_pipable = wim_is_pipable(wim);
1259 if (rdesc->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1260 rdesc->compression_type = wim->compression_type;
1261 rdesc->chunk_size = wim->chunk_size;
1263 rdesc->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1264 rdesc->chunk_size = 0;
1269 * Convert the short WIM resource header @reshdr to a stand-alone WIM resource
1270 * descriptor @rdesc, then set @blob to consist of that entire resource. This
1271 * should only be used for non-solid resources!
1274 wim_reshdr_to_desc_and_blob(const struct wim_reshdr *reshdr, WIMStruct *wim,
1275 struct wim_resource_descriptor *rdesc,
1276 struct blob_descriptor *blob)
1278 wim_reshdr_to_desc(reshdr, wim, rdesc);
1279 blob->size = rdesc->uncompressed_size;
1280 blob_set_is_located_in_wim_resource(blob, rdesc, 0);
1283 /* Import a WIM resource header from the on-disk format. */
1285 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1286 struct wim_reshdr *reshdr)
1288 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1289 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1290 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1291 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1292 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1293 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1294 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1295 ((u64)disk_reshdr->size_in_wim[6] << 48));
1296 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1297 reshdr->flags = disk_reshdr->flags;
1300 /* Export a WIM resource header to the on-disk format. */
1302 put_wim_reshdr(const struct wim_reshdr *reshdr,
1303 struct wim_reshdr_disk *disk_reshdr)
1305 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1306 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1307 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1308 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1309 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1310 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1311 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1312 disk_reshdr->flags = reshdr->flags;
1313 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1314 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);