4 * Code for reading streams and resources, including compressed WIM resources.
8 * Copyright (C) 2012, 2013 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/.
30 #include "wimlib/assert.h"
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/resource.h"
36 #include "wimlib/sha1.h"
37 #include "wimlib/wim.h"
40 /* for read_win32_file_prefix(), read_win32_encrypted_file_prefix() */
41 # include "wimlib/win32.h"
45 /* for read_ntfs_file_prefix() */
46 # include "wimlib/ntfs_3g.h"
58 * Compressed WIM resources
60 * A compressed resource in a WIM consists of a number of compressed chunks,
61 * each of which decompresses to a fixed chunk size (given in the WIM header;
62 * usually 32768) except possibly the last, which always decompresses to any
63 * remaining bytes. In addition, immediately before the chunks, a table (the
64 * "chunk table") provides the offset, in bytes relative to the end of the chunk
65 * table, of the start of each compressed chunk, except for the first chunk
66 * which is omitted as it always has an offset of 0. Therefore, a compressed
67 * resource with N chunks will have a chunk table with N - 1 entries.
69 * Additional information:
71 * - Entries in the chunk table are 4 bytes each, except if the uncompressed
72 * size of the resource is greater than 4 GiB, in which case the entries in
73 * the chunk table are 8 bytes each. In either case, the entries are unsigned
74 * little-endian integers.
76 * - The chunk table is included in the compressed size of the resource provided
77 * in the corresponding entry in the WIM's stream lookup table.
79 * - The compressed size of a chunk is never greater than the uncompressed size.
80 * From the compressor's point of view, chunks that would have compressed to a
81 * size greater than or equal to their original size are in fact stored
82 * uncompressed. From the decompresser's point of view, chunks with
83 * compressed size equal to their uncompressed size are in fact uncompressed.
85 * Furthermore, wimlib supports its own "pipable" WIM format, and for this the
86 * structure of compressed resources was modified to allow piped reading and
87 * writing. To make sequential writing possible, the chunk table is placed
88 * after the chunks rather than before the chunks, and to make sequential
89 * reading possible, each chunk is prefixed with a 4-byte header giving its
90 * compressed size as a 32-bit, unsigned, little-endian integer. Otherwise the
91 * details are the same.
101 * read_compressed_wim_resource() -
103 * Read data from a compressed WIM resource.
106 * Specification of the compressed WIM resource to read from.
108 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
109 * read, sorted by increasing offset.
111 * Number of ranges in @ranges; must be at least 1.
113 * Callback function to feed the data being read. Each call provides the
114 * next chunk of the requested data, uncompressed. Each chunk will be of
115 * nonzero size and will not cross range boundaries, but otherwise will be
116 * of unspecified size.
118 * Parameter to pass to @cb_ctx.
120 * Possible return values:
122 * WIMLIB_ERR_SUCCESS (0)
123 * WIMLIB_ERR_READ (errno set)
124 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
125 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
126 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
128 * or other error code returned by the @cb function.
131 read_compressed_wim_resource(const struct wim_resource_spec * const rspec,
132 const struct data_range * const ranges,
133 const size_t num_ranges,
134 const consume_data_callback_t cb,
140 u64 *chunk_offsets = NULL;
143 bool chunk_offsets_malloced = false;
144 bool ubuf_malloced = false;
145 bool cbuf_malloced = false;
146 struct wimlib_decompressor *decompressor = NULL;
149 wimlib_assert(rspec != NULL);
150 wimlib_assert(resource_is_compressed(rspec));
151 wimlib_assert(cb != NULL);
152 wimlib_assert(num_ranges != 0);
153 for (size_t i = 0; i < num_ranges; i++) {
154 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
155 i + 1, num_ranges, ranges[i].size, ranges[i].offset,
156 rspec->uncompressed_size);
157 wimlib_assert(ranges[i].size != 0);
158 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
159 wimlib_assert(ranges[i].offset + ranges[i].size <= rspec->uncompressed_size);
161 for (size_t i = 0; i < num_ranges - 1; i++)
162 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
164 /* Get the offsets of the first and last bytes of the read. */
165 const u64 first_offset = ranges[0].offset;
166 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
168 /* Get the file descriptor for the WIM. */
169 struct filedes * const in_fd = &rspec->wim->in_fd;
171 /* Determine if we're reading a pipable resource from a pipe or not. */
172 const bool is_pipe_read = !filedes_is_seekable(in_fd);
174 /* Determine if the chunk table is in an altenate format. */
175 const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
178 /* Get the maximum size of uncompressed chunks in this resource, which
179 * we require be a power of 2. */
180 u64 cur_read_offset = rspec->offset_in_wim;
181 int ctype = rspec->compression_type;
182 u32 chunk_size = rspec->chunk_size;
183 if (alt_chunk_table) {
184 /* Alternate chunk table format. Its header specifies the chunk
185 * size and compression format. Note: it could be read here;
186 * however, the relevant data was already loaded into @rspec by
187 * read_wim_lookup_table(). */
188 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
191 if (!is_power_of_2(chunk_size)) {
192 ERROR("Invalid compressed resource: "
193 "expected power-of-2 chunk size (got %"PRIu32")",
195 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
197 goto out_free_memory;
200 /* Get valid decompressor. */
201 if (ctype == rspec->wim->decompressor_ctype &&
202 chunk_size == rspec->wim->decompressor_max_block_size)
204 /* Cached decompressor. */
205 decompressor = rspec->wim->decompressor;
206 rspec->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
207 rspec->wim->decompressor = NULL;
209 ret = wimlib_create_decompressor(ctype, chunk_size, NULL,
212 if (ret != WIMLIB_ERR_NOMEM)
214 goto out_free_memory;
218 const u32 chunk_order = bsr32(chunk_size);
220 /* Calculate the total number of chunks the resource is divided into. */
221 const u64 num_chunks = (rspec->uncompressed_size + chunk_size - 1) >> chunk_order;
223 /* Calculate the 0-based indices of the first and last chunks containing
224 * data that needs to be passed to the callback. */
225 const u64 first_needed_chunk = first_offset >> chunk_order;
226 const u64 last_needed_chunk = last_offset >> chunk_order;
228 /* Calculate the 0-based index of the first chunk that actually needs to
229 * be read. This is normally first_needed_chunk, but for pipe reads we
230 * must always start from the 0th chunk. */
231 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
233 /* Calculate the number of chunk offsets that are needed for the chunks
235 const u64 num_needed_chunk_offsets =
236 last_needed_chunk - read_start_chunk + 1 +
237 (last_needed_chunk < num_chunks - 1);
239 /* Calculate the number of entries in the chunk table. Normally, it's
240 * one less than the number of chunks, since the first chunk has no
241 * entry. But in the alternate chunk table format, the chunk entries
242 * contain chunk sizes, not offsets, and there is one per chunk. */
243 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
245 /* Set the size of each chunk table entry based on the resource's
246 * uncompressed size. */
247 const u64 chunk_entry_size = get_chunk_entry_size(rspec->uncompressed_size,
250 /* Calculate the size of the chunk table in bytes. */
251 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
253 /* Calculate the size of the chunk table in bytes, including the header
254 * in the case of the alternate chunk table format. */
255 const u64 chunk_table_full_size =
256 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
260 /* Read the needed chunk table entries into memory and use them
261 * to initialize the chunk_offsets array. */
263 u64 first_chunk_entry_to_read;
264 u64 last_chunk_entry_to_read;
266 if (alt_chunk_table) {
267 /* The alternate chunk table contains chunk sizes, not
268 * offsets, so we always must read all preceding entries
269 * in order to determine offsets. */
270 first_chunk_entry_to_read = 0;
271 last_chunk_entry_to_read = last_needed_chunk;
273 /* Here we must account for the fact that the first
274 * chunk has no explicit chunk table entry. */
276 if (read_start_chunk == 0)
277 first_chunk_entry_to_read = 0;
279 first_chunk_entry_to_read = read_start_chunk - 1;
281 if (last_needed_chunk == 0)
282 last_chunk_entry_to_read = 0;
284 last_chunk_entry_to_read = last_needed_chunk - 1;
286 if (last_needed_chunk < num_chunks - 1)
287 last_chunk_entry_to_read++;
290 const u64 num_chunk_entries_to_read =
291 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
293 const u64 chunk_offsets_alloc_size =
294 max(num_chunk_entries_to_read,
295 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
297 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
300 if (chunk_offsets_alloc_size <= STACK_MAX) {
301 chunk_offsets = alloca(chunk_offsets_alloc_size);
303 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
304 if (chunk_offsets == NULL)
306 chunk_offsets_malloced = true;
309 const size_t chunk_table_size_to_read =
310 num_chunk_entries_to_read * chunk_entry_size;
312 const u64 file_offset_of_needed_chunk_entries =
314 + (first_chunk_entry_to_read * chunk_entry_size)
315 + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
317 void * const chunk_table_data =
319 chunk_offsets_alloc_size -
320 chunk_table_size_to_read;
322 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
323 file_offset_of_needed_chunk_entries);
327 /* Now fill in chunk_offsets from the entries we have read in
328 * chunk_tab_data. We break aliasing rules here to avoid having
329 * to allocate yet another array. */
330 typedef le64 __attribute__((may_alias)) aliased_le64_t;
331 typedef le32 __attribute__((may_alias)) aliased_le32_t;
332 u64 * chunk_offsets_p = chunk_offsets;
334 if (alt_chunk_table) {
336 aliased_le32_t *raw_entries = chunk_table_data;
338 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
339 u32 entry = le32_to_cpu(raw_entries[i]);
340 if (i >= read_start_chunk)
341 *chunk_offsets_p++ = cur_offset;
344 if (last_needed_chunk < num_chunks - 1)
345 *chunk_offsets_p = cur_offset;
347 if (read_start_chunk == 0)
348 *chunk_offsets_p++ = 0;
350 if (chunk_entry_size == 4) {
351 aliased_le32_t *raw_entries = chunk_table_data;
352 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
353 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
355 aliased_le64_t *raw_entries = chunk_table_data;
356 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
357 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
361 /* Set offset to beginning of first chunk to read. */
362 cur_read_offset += chunk_offsets[0];
363 if (rspec->is_pipable)
364 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
366 cur_read_offset += chunk_table_size;
369 /* Allocate buffer for holding the uncompressed data of each chunk. */
370 if (chunk_size <= STACK_MAX) {
371 ubuf = alloca(chunk_size);
373 ubuf = MALLOC(chunk_size);
376 ubuf_malloced = true;
379 /* Allocate a temporary buffer for reading compressed chunks, each of
380 * which can be at most @chunk_size - 1 bytes. This excludes compressed
381 * chunks that are a full @chunk_size bytes, which are actually stored
383 if (chunk_size - 1 <= STACK_MAX) {
384 cbuf = alloca(chunk_size - 1);
386 cbuf = MALLOC(chunk_size - 1);
389 cbuf_malloced = true;
392 /* Set current data range. */
393 const struct data_range *cur_range = ranges;
394 const struct data_range * const end_range = &ranges[num_ranges];
395 u64 cur_range_pos = cur_range->offset;
396 u64 cur_range_end = cur_range->offset + cur_range->size;
398 /* Read and process each needed chunk. */
399 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
401 /* Calculate uncompressed size of next chunk. */
403 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
404 chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
406 chunk_usize = chunk_size;
408 /* Calculate compressed size of next chunk. */
411 struct pwm_chunk_hdr chunk_hdr;
413 ret = full_pread(in_fd, &chunk_hdr,
414 sizeof(chunk_hdr), cur_read_offset);
417 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
419 if (i == num_chunks - 1) {
420 chunk_csize = rspec->size_in_wim -
421 chunk_table_full_size -
422 chunk_offsets[i - read_start_chunk];
423 if (rspec->is_pipable)
424 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
426 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
427 chunk_offsets[i - read_start_chunk];
430 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
431 ERROR("Invalid chunk size in compressed resource!");
433 ret = WIMLIB_ERR_DECOMPRESSION;
434 goto out_free_memory;
436 if (rspec->is_pipable)
437 cur_read_offset += sizeof(struct pwm_chunk_hdr);
439 /* Offsets in the uncompressed resource at which this chunk
440 * starts and ends. */
441 const u64 chunk_start_offset = i << chunk_order;
442 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
444 if (chunk_end_offset <= cur_range_pos) {
446 /* The next range does not require data in this chunk,
448 cur_read_offset += chunk_csize;
452 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
458 /* Read the chunk and feed data to the callback
462 if (chunk_csize == chunk_usize)
467 ret = full_pread(in_fd,
474 if (read_buf == cbuf) {
475 DEBUG("Decompressing chunk %"PRIu64" "
476 "(csize=%"PRIu32" usize=%"PRIu32")",
477 i, chunk_csize, chunk_usize);
478 ret = wimlib_decompress(cbuf,
484 ERROR("Failed to decompress data!");
485 ret = WIMLIB_ERR_DECOMPRESSION;
487 goto out_free_memory;
490 cur_read_offset += chunk_csize;
492 /* At least one range requires data in this chunk. */
494 size_t start, end, size;
496 /* Calculate how many bytes of data should be
497 * sent to the callback function, taking into
498 * account that data sent to the callback
499 * function must not overlap range boundaries.
501 start = cur_range_pos - chunk_start_offset;
502 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
505 ret = (*cb)(&ubuf[start], size, cb_ctx);
508 goto out_free_memory;
510 cur_range_pos += size;
511 if (cur_range_pos == cur_range_end) {
512 /* Advance to next range. */
513 if (++cur_range == end_range) {
514 cur_range_pos = ~0ULL;
516 cur_range_pos = cur_range->offset;
517 cur_range_end = cur_range->offset + cur_range->size;
520 } while (cur_range_pos < chunk_end_offset);
525 last_offset == rspec->uncompressed_size - 1 &&
529 /* If reading a pipable resource from a pipe and the full data
530 * was requested, skip the chunk table at the end so that the
531 * file descriptor is fully clear of the resource after this
533 cur_read_offset += chunk_table_size;
534 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
543 wimlib_free_decompressor(rspec->wim->decompressor);
544 rspec->wim->decompressor = decompressor;
545 rspec->wim->decompressor_ctype = ctype;
546 rspec->wim->decompressor_max_block_size = chunk_size;
548 if (chunk_offsets_malloced)
558 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
559 "from compressed WIM resource!", last_offset - first_offset + 1);
561 ret = WIMLIB_ERR_NOMEM;
562 goto out_free_memory;
565 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
566 goto out_free_memory;
570 fill_zeroes(u64 size, consume_data_callback_t cb, void *cb_ctx)
572 if (unlikely(size)) {
573 u8 buf[min(size, BUFFER_SIZE)];
575 memset(buf, 0, sizeof(buf));
581 len = min(size, BUFFER_SIZE);
582 ret = cb(buf, len, cb_ctx);
591 /* Read raw data from a file descriptor at the specified offset, feeding the
592 * data it in chunks into the specified callback function. */
594 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
595 consume_data_callback_t cb, void *cb_ctx)
598 size_t bytes_to_read;
602 bytes_to_read = min(sizeof(buf), size);
603 ret = full_pread(in_fd, buf, bytes_to_read, offset);
605 ERROR_WITH_ERRNO("Read error");
608 ret = cb(buf, bytes_to_read, cb_ctx);
611 size -= bytes_to_read;
612 offset += bytes_to_read;
617 /* A consume_data_callback_t implementation that simply concatenates all chunks
620 bufferer_cb(const void *chunk, size_t size, void *_ctx)
624 *buf_p = mempcpy(*buf_p, chunk, size);
629 * read_partial_wim_resource()-
631 * Read a range of data from an uncompressed or compressed resource in a WIM
635 * Specification of the WIM resource to read from.
637 * Offset within the uncompressed resource at which to start reading.
639 * Number of bytes to read.
641 * Callback function to feed the data being read. Each call provides the
642 * next chunk of the requested data, uncompressed. Each chunk will be of
643 * nonzero size and will not cross range boundaries, but otherwise will be
644 * of unspecified size.
646 * Parameter to pass to @cb_ctx.
649 * WIMLIB_ERR_SUCCESS (0)
650 * WIMLIB_ERR_READ (errno set)
651 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
652 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
653 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
655 * or other error code returned by the @cb function.
658 read_partial_wim_resource(const struct wim_resource_spec *rspec,
659 u64 offset, u64 size,
660 consume_data_callback_t cb, void *cb_ctx)
663 wimlib_assert(offset + size >= offset);
664 wimlib_assert(offset + size <= rspec->uncompressed_size);
666 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
667 "%"PRIu64" => %"PRIu64" @ %"PRIu64,
668 size, offset, rspec->uncompressed_size,
669 rspec->size_in_wim, rspec->offset_in_wim);
675 if (resource_is_compressed(rspec)) {
676 struct data_range range = {
680 return read_compressed_wim_resource(rspec, &range, 1,
683 /* Reading uncompressed resource. For completeness, handle the
684 * weird case where size_in_wim < uncompressed_size. */
690 if (likely(offset + size <= rspec->size_in_wim) ||
696 if (offset >= rspec->size_in_wim) {
700 read_size = rspec->size_in_wim - offset;
701 zeroes_size = offset + size - rspec->size_in_wim;
705 ret = read_raw_file_data(&rspec->wim->in_fd,
706 rspec->offset_in_wim + offset,
713 return fill_zeroes(zeroes_size, cb, cb_ctx);
717 /* Read the specified range of uncompressed data from the specified stream,
718 * which must be located into a WIM file, into the specified buffer. */
720 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
721 size_t size, u64 offset, void *_buf)
725 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
727 return read_partial_wim_resource(lte->rspec,
728 lte->offset_in_res + offset,
734 /* A consume_data_callback_t implementation that simply ignores the data
737 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
742 /* Skip over the data of the specified stream, which must correspond to a full
745 skip_wim_stream(struct wim_lookup_table_entry *lte)
747 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
748 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
749 DEBUG("Skipping stream (size=%"PRIu64")", lte->size);
750 return read_partial_wim_resource(lte->rspec,
752 lte->rspec->uncompressed_size,
758 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
759 consume_data_callback_t cb, void *cb_ctx)
761 return read_partial_wim_resource(lte->rspec, lte->offset_in_res, size,
765 /* This function handles reading stream data that is located in an external
766 * file, such as a file that has been added to the WIM image through execution
767 * of a wimlib_add_command.
769 * This assumes the file can be accessed using the standard POSIX open(),
770 * read(), and close(). On Windows this will not necessarily be the case (since
771 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
772 * encrypted), so Windows uses its own code for its equivalent case. */
774 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
775 consume_data_callback_t cb, void *cb_ctx)
781 wimlib_assert(size <= lte->size);
783 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
785 raw_fd = topen(lte->file_on_disk, O_BINARY | O_RDONLY);
787 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
788 return WIMLIB_ERR_OPEN;
790 filedes_init(&fd, raw_fd);
791 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
798 read_staging_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
799 consume_data_callback_t cb, void *cb_ctx)
805 wimlib_assert(size <= lte->size);
807 DEBUG("Reading %"PRIu64" bytes from staging file \"%s\"",
808 size, lte->staging_file_name);
810 raw_fd = openat(lte->staging_dir_fd, lte->staging_file_name,
811 O_RDONLY | O_NOFOLLOW);
813 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
814 lte->staging_file_name);
815 return WIMLIB_ERR_OPEN;
817 filedes_init(&fd, raw_fd);
818 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
824 /* This function handles the trivial case of reading stream data that is, in
825 * fact, already located in an in-memory buffer. */
827 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
828 u64 size, consume_data_callback_t cb, void *cb_ctx)
830 wimlib_assert(size <= lte->size);
831 return (*cb)(lte->attached_buffer, size, cb_ctx);
834 typedef int (*read_stream_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
836 consume_data_callback_t cb,
840 * read_stream_prefix()-
842 * Reads the first @size bytes from a generic "stream", which may be located in
843 * any one of several locations, such as in a WIM file (compressed or
844 * uncompressed), in an external file, or directly in an in-memory buffer.
846 * This function feeds the data to a callback function @cb in chunks of
849 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
850 * the stream data cannot be successfully read (for a number of different
851 * reasons, depending on the stream location), or if @cb returned nonzero in
852 * which case that error code will be returned.
855 read_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
856 consume_data_callback_t cb, void *cb_ctx)
858 static const read_stream_prefix_handler_t handlers[] = {
859 [RESOURCE_IN_WIM] = read_wim_stream_prefix,
860 [RESOURCE_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
861 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
863 [RESOURCE_IN_STAGING_FILE] = read_staging_file_prefix,
866 [RESOURCE_IN_NTFS_VOLUME] = read_ntfs_file_prefix,
869 [RESOURCE_IN_WINNT_FILE_ON_DISK] = read_winnt_file_prefix,
870 [RESOURCE_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
873 wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
874 && handlers[lte->resource_location] != NULL);
875 return handlers[lte->resource_location](lte, size, cb, cb_ctx);
878 /* Read the full uncompressed data of the specified stream into the specified
879 * buffer, which must have space for at least lte->size bytes. */
881 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
884 return read_stream_prefix(lte, lte->size, bufferer_cb, &buf);
887 /* Retrieve the full uncompressed data of the specified stream. A buffer large
888 * enough hold the data is allocated and returned in @buf_ret. */
890 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
896 if ((size_t)lte->size != lte->size) {
897 ERROR("Can't read %"PRIu64" byte stream into "
898 "memory", lte->size);
899 return WIMLIB_ERR_NOMEM;
902 buf = MALLOC(lte->size);
904 return WIMLIB_ERR_NOMEM;
906 ret = read_full_stream_into_buf(lte, buf);
916 /* Retrieve the full uncompressed data of the specified WIM resource. A buffer
917 * large enough hold the data is allocated and returned in @buf_ret. */
919 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
922 struct wim_lookup_table_entry *lte;
924 lte = new_lookup_table_entry();
926 return WIMLIB_ERR_NOMEM;
928 lte_bind_wim_resource_spec(lte, rspec);
929 lte->flags = rspec->flags;
930 lte->size = rspec->uncompressed_size;
931 lte->offset_in_res = 0;
933 ret = read_full_stream_into_alloc_buf(lte, buf_ret);
935 lte_unbind_wim_resource_spec(lte);
936 free_lookup_table_entry(lte);
940 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
941 * `wim_reshdr' and the corresponding WIM file. A large enough hold the data is
942 * allocated and returned in @buf_ret. */
944 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
946 DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
947 "uncompressed_size=%"PRIu64,
948 reshdr->offset_in_wim, reshdr->size_in_wim,
949 reshdr->uncompressed_size);
951 struct wim_resource_spec rspec;
952 wim_res_hdr_to_spec(reshdr, wim, &rspec);
953 return wim_resource_spec_to_data(&rspec, buf_ret);
957 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
958 u8 hash[SHA1_HASH_SIZE])
960 struct wim_resource_spec rspec;
962 struct wim_lookup_table_entry *lte;
964 wim_res_hdr_to_spec(reshdr, wim, &rspec);
966 lte = new_lookup_table_entry();
968 return WIMLIB_ERR_NOMEM;
970 lte_bind_wim_resource_spec(lte, &rspec);
971 lte->flags = rspec.flags;
972 lte->size = rspec.uncompressed_size;
973 lte->offset_in_res = 0;
976 ret = sha1_stream(lte);
978 lte_unbind_wim_resource_spec(lte);
979 copy_hash(hash, lte->hash);
980 free_lookup_table_entry(lte);
984 struct streamifier_context {
985 struct read_stream_list_callbacks cbs;
986 struct wim_lookup_table_entry *cur_stream;
987 struct wim_lookup_table_entry *next_stream;
988 u64 cur_stream_offset;
989 struct wim_lookup_table_entry *final_stream;
990 size_t list_head_offset;
993 static struct wim_lookup_table_entry *
994 next_stream(struct wim_lookup_table_entry *lte, size_t list_head_offset)
996 struct list_head *cur;
998 cur = (struct list_head*)((u8*)lte + list_head_offset);
1000 return (struct wim_lookup_table_entry*)((u8*)cur->next - list_head_offset);
1003 /* A consume_data_callback_t implementation that translates raw resource data
1004 * into streams, calling the begin_stream, consume_chunk, and end_stream
1005 * callback functions as appropriate. */
1007 streamifier_cb(const void *chunk, size_t size, void *_ctx)
1009 struct streamifier_context *ctx = _ctx;
1012 DEBUG("%zu bytes passed to streamifier", size);
1014 wimlib_assert(ctx->cur_stream != NULL);
1015 wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
1017 if (ctx->cur_stream_offset == 0) {
1020 /* Starting a new stream. */
1021 DEBUG("Begin new stream (size=%"PRIu64").",
1022 ctx->cur_stream->size);
1024 flags = BEGIN_STREAM_FLAG_PARTIAL_RESOURCE;
1025 if (size == ctx->cur_stream->size)
1026 flags |= BEGIN_STREAM_FLAG_WHOLE_STREAM;
1027 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream,
1029 ctx->cbs.begin_stream_ctx);
1034 /* Consume the chunk. */
1035 ret = (*ctx->cbs.consume_chunk)(chunk, size,
1036 ctx->cbs.consume_chunk_ctx);
1037 ctx->cur_stream_offset += size;
1041 if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1042 /* Finished reading all the data for a stream. */
1044 ctx->cur_stream_offset = 0;
1046 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1047 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1048 ctx->cbs.end_stream_ctx);
1052 /* Advance to next stream. */
1053 ctx->cur_stream = ctx->next_stream;
1054 if (ctx->cur_stream != NULL) {
1055 if (ctx->cur_stream != ctx->final_stream)
1056 ctx->next_stream = next_stream(ctx->cur_stream,
1057 ctx->list_head_offset);
1059 ctx->next_stream = NULL;
1065 struct hasher_context {
1068 struct read_stream_list_callbacks cbs;
1071 /* Callback for starting to read a stream while calculating its SHA1 message
1074 hasher_begin_stream(struct wim_lookup_table_entry *lte, u32 flags,
1077 struct hasher_context *ctx = _ctx;
1079 sha1_init(&ctx->sha_ctx);
1081 if (ctx->cbs.begin_stream == NULL)
1084 return (*ctx->cbs.begin_stream)(lte, flags,
1085 ctx->cbs.begin_stream_ctx);
1088 /* A consume_data_callback_t implementation that continues calculating the SHA1
1089 * message digest of the stream being read, then optionally passes the data on
1090 * to another consume_data_callback_t implementation. This allows checking the
1091 * SHA1 message digest of a stream being extracted, for example. */
1093 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1095 struct hasher_context *ctx = _ctx;
1097 sha1_update(&ctx->sha_ctx, chunk, size);
1098 if (ctx->cbs.consume_chunk == NULL)
1101 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1105 get_sha1_string(const u8 md[SHA1_HASH_SIZE], tchar *str)
1107 for (size_t i = 0; i < SHA1_HASH_SIZE; i++)
1108 str += tsprintf(str, T("%02x"), md[i]);
1111 /* Callback for finishing reading a stream while calculating its SHA1 message
1114 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1116 struct hasher_context *ctx = _ctx;
1117 u8 hash[SHA1_HASH_SIZE];
1121 /* Error occurred; the full stream may not have been read. */
1126 /* Retrieve the final SHA1 message digest. */
1127 sha1_final(hash, &ctx->sha_ctx);
1129 if (lte->unhashed) {
1130 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1131 /* No SHA1 message digest was previously present for the
1132 * stream. Set it to the one just calculated. */
1133 DEBUG("Set SHA1 message digest for stream "
1134 "(size=%"PRIu64").", lte->size);
1135 copy_hash(lte->hash, hash);
1138 if (ctx->flags & VERIFY_STREAM_HASHES) {
1139 /* The stream already had a SHA1 message digest present. Verify
1140 * that it is the same as the calculated value. */
1141 if (!hashes_equal(hash, lte->hash)) {
1142 if (wimlib_print_errors) {
1143 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1144 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1145 get_sha1_string(lte->hash, expected_hashstr);
1146 get_sha1_string(hash, actual_hashstr);
1147 ERROR("The stream is corrupted!\n"
1148 " (Expected SHA1=%"TS",\n"
1150 expected_hashstr, actual_hashstr);
1152 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1156 DEBUG("SHA1 message digest okay for "
1157 "stream (size=%"PRIu64").", lte->size);
1162 if (ctx->cbs.end_stream == NULL)
1165 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1169 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1170 const struct read_stream_list_callbacks *cbs)
1174 ret = (*cbs->begin_stream)(lte, 0, cbs->begin_stream_ctx);
1178 ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1179 cbs->consume_chunk_ctx);
1181 return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1184 /* Read the full data of the specified stream, passing the data into the
1185 * specified callbacks (all of which are optional) and either checking or
1186 * computing the SHA1 message digest of the stream. */
1188 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1189 const struct read_stream_list_callbacks *cbs)
1191 struct hasher_context hasher_ctx = {
1192 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1195 struct read_stream_list_callbacks hasher_cbs = {
1196 .begin_stream = hasher_begin_stream,
1197 .begin_stream_ctx = &hasher_ctx,
1198 .consume_chunk = hasher_consume_chunk,
1199 .consume_chunk_ctx = &hasher_ctx,
1200 .end_stream = hasher_end_stream,
1201 .end_stream_ctx = &hasher_ctx,
1203 return read_full_stream_with_cbs(lte, &hasher_cbs);
1207 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1208 struct wim_lookup_table_entry *last_stream,
1210 size_t list_head_offset,
1211 const struct read_stream_list_callbacks *sink_cbs)
1213 struct data_range *ranges;
1214 bool ranges_malloced;
1215 struct wim_lookup_table_entry *cur_stream;
1218 u64 ranges_alloc_size;
1220 DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1223 /* Setup data ranges array (one range per stream to read); this way
1224 * read_compressed_wim_resource() does not need to be aware of streams.
1227 ranges_alloc_size = stream_count * sizeof(ranges[0]);
1229 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1230 ERROR("Too many streams in one resource!");
1231 return WIMLIB_ERR_NOMEM;
1233 if (likely(ranges_alloc_size <= STACK_MAX)) {
1234 ranges = alloca(ranges_alloc_size);
1235 ranges_malloced = false;
1237 ranges = MALLOC(ranges_alloc_size);
1238 if (ranges == NULL) {
1239 ERROR("Too many streams in one resource!");
1240 return WIMLIB_ERR_NOMEM;
1242 ranges_malloced = true;
1245 for (i = 0, cur_stream = first_stream;
1247 i++, cur_stream = next_stream(cur_stream, list_head_offset))
1249 ranges[i].offset = cur_stream->offset_in_res;
1250 ranges[i].size = cur_stream->size;
1253 struct streamifier_context streamifier_ctx = {
1255 .cur_stream = first_stream,
1256 .next_stream = next_stream(first_stream, list_head_offset),
1257 .cur_stream_offset = 0,
1258 .final_stream = last_stream,
1259 .list_head_offset = list_head_offset,
1262 ret = read_compressed_wim_resource(first_stream->rspec,
1268 if (ranges_malloced)
1272 if (streamifier_ctx.cur_stream_offset != 0) {
1273 ret = (*streamifier_ctx.cbs.end_stream)
1274 (streamifier_ctx.cur_stream,
1276 streamifier_ctx.cbs.end_stream_ctx);
1283 * Read a list of streams, each of which may be in any supported location (e.g.
1284 * in a WIM or in an external file). Unlike read_stream_prefix() or the
1285 * functions which call it, this function optimizes the case where multiple
1286 * streams are packed into a single compressed WIM resource and reads them all
1287 * consecutively, only decompressing the data one time.
1290 * List of streams (represented as `struct wim_lookup_table_entry's) to
1293 * Offset of the `struct list_head' within each `struct
1294 * wim_lookup_table_entry' that makes up the @stream_list.
1296 * Callback functions to accept the stream data.
1298 * Bitwise OR of zero or more of the following flags:
1300 * VERIFY_STREAM_HASHES:
1301 * For all streams being read that have already had SHA1 message
1302 * digests computed, calculate the SHA1 message digest of the read
1303 * data and compare it with the previously computed value. If they
1304 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1306 * COMPUTE_MISSING_STREAM_HASHES
1307 * For all streams being read that have not yet had their SHA1
1308 * message digests computed, calculate and save their SHA1 message
1311 * STREAM_LIST_ALREADY_SORTED
1312 * @stream_list is already sorted in sequential order for reading.
1314 * The callback functions are allowed to delete the current stream from the list
1317 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1318 * to an error reading the data or due to an error status being returned by any
1319 * of the callback functions.
1322 read_stream_list(struct list_head *stream_list,
1323 size_t list_head_offset,
1324 const struct read_stream_list_callbacks *cbs,
1328 struct list_head *cur, *next;
1329 struct wim_lookup_table_entry *lte;
1330 struct hasher_context *hasher_ctx;
1331 struct read_stream_list_callbacks *sink_cbs;
1333 if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1334 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1339 if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1340 hasher_ctx = alloca(sizeof(*hasher_ctx));
1341 *hasher_ctx = (struct hasher_context) {
1345 sink_cbs = alloca(sizeof(*sink_cbs));
1346 *sink_cbs = (struct read_stream_list_callbacks) {
1347 .begin_stream = hasher_begin_stream,
1348 .begin_stream_ctx = hasher_ctx,
1349 .consume_chunk = hasher_consume_chunk,
1350 .consume_chunk_ctx = hasher_ctx,
1351 .end_stream = hasher_end_stream,
1352 .end_stream_ctx = hasher_ctx,
1355 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1358 for (cur = stream_list->next, next = cur->next;
1360 cur = next, next = cur->next)
1362 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1364 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1365 lte->size != lte->rspec->uncompressed_size)
1368 struct wim_lookup_table_entry *lte_next, *lte_last;
1369 struct list_head *next2;
1372 /* The next stream is a proper sub-sequence of a WIM
1373 * resource. See if there are other streams in the same
1374 * resource that need to be read. Since
1375 * sort_stream_list_by_sequential_order() sorted the
1376 * streams by offset in the WIM, this can be determined
1377 * by simply scanning forward in the list. */
1382 next2 != stream_list
1383 && (lte_next = (struct wim_lookup_table_entry*)
1384 ((u8*)next2 - list_head_offset),
1385 lte_next->resource_location == RESOURCE_IN_WIM
1386 && lte_next->rspec == lte->rspec);
1387 next2 = next2->next)
1389 lte_last = lte_next;
1392 if (stream_count > 1) {
1393 /* Reading multiple streams combined into a
1394 * single WIM resource. They are in the stream
1395 * list, sorted by offset; @lte specifies the
1396 * first stream in the resource that needs to be
1397 * read and @lte_last specifies the last stream
1398 * in the resource that needs to be read. */
1400 ret = read_packed_streams(lte, lte_last,
1410 ret = read_full_stream_with_cbs(lte, sink_cbs);
1411 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1417 /* Extract the first @size bytes of the specified stream.
1419 * If @size specifies the full uncompressed size of the stream, then the SHA1
1420 * message digest of the uncompressed stream is checked while being extracted.
1422 * The uncompressed data of the resource is passed in chunks of unspecified size
1423 * to the @extract_chunk function, passing it @extract_chunk_arg. */
1425 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1426 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1428 wimlib_assert(size <= lte->size);
1429 if (size == lte->size) {
1431 struct read_stream_list_callbacks cbs = {
1432 .consume_chunk = extract_chunk,
1433 .consume_chunk_ctx = extract_chunk_arg,
1435 return read_full_stream_with_sha1(lte, &cbs);
1437 /* Don't do SHA1. */
1438 return read_stream_prefix(lte, size, extract_chunk,
1443 /* A consume_data_callback_t implementation that writes the chunk of data to a
1444 * file descriptor. */
1446 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1448 struct filedes *fd = _fd_p;
1450 int ret = full_write(fd, chunk, size);
1452 ERROR_WITH_ERRNO("Error writing to file descriptor");
1458 /* Extract the first @size bytes of the specified stream to the specified file
1461 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1462 struct filedes *fd, u64 size)
1464 return extract_stream(lte, size, extract_chunk_to_fd, fd);
1467 /* Extract the full uncompressed contents of the specified stream to the
1468 * specified file descriptor. */
1470 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1473 return extract_stream_to_fd(lte, fd, lte->size);
1476 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash. */
1478 sha1_stream(struct wim_lookup_table_entry *lte)
1480 wimlib_assert(lte->unhashed);
1481 struct read_stream_list_callbacks cbs = {
1483 return read_full_stream_with_sha1(lte, &cbs);
1486 /* Convert a short WIM resource header to a stand-alone WIM resource
1489 * Note: for packed resources some fields still need to be overridden.
1492 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1493 struct wim_resource_spec *rspec)
1496 rspec->offset_in_wim = reshdr->offset_in_wim;
1497 rspec->size_in_wim = reshdr->size_in_wim;
1498 rspec->uncompressed_size = reshdr->uncompressed_size;
1499 INIT_LIST_HEAD(&rspec->stream_list);
1500 rspec->flags = reshdr->flags;
1501 rspec->is_pipable = wim_is_pipable(wim);
1502 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1503 rspec->compression_type = wim->compression_type;
1504 rspec->chunk_size = wim->chunk_size;
1506 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1507 rspec->chunk_size = 0;
1511 /* Convert a stand-alone resource specification to a WIM resource header. */
1513 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1514 struct wim_reshdr *reshdr)
1516 reshdr->offset_in_wim = rspec->offset_in_wim;
1517 reshdr->size_in_wim = rspec->size_in_wim;
1518 reshdr->flags = rspec->flags;
1519 reshdr->uncompressed_size = rspec->uncompressed_size;
1522 /* Translates a WIM resource header from the on-disk format into an in-memory
1525 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1526 struct wim_reshdr *reshdr)
1528 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1529 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1530 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1531 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1532 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1533 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1534 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1535 ((u64)disk_reshdr->size_in_wim[6] << 48));
1536 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1537 reshdr->flags = disk_reshdr->flags;
1540 /* Translates a WIM resource header from an in-memory format into the on-disk
1543 put_wim_reshdr(const struct wim_reshdr *reshdr,
1544 struct wim_reshdr_disk *disk_reshdr)
1546 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1547 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1548 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1549 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1550 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1551 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1552 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1553 disk_reshdr->flags = reshdr->flags;
1554 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1555 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);