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_winnt_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;
144 bool chunk_offsets_malloced = false;
145 bool ubuf_malloced = false;
146 bool cbuf_malloced = false;
147 struct wimlib_decompressor *decompressor = NULL;
150 wimlib_assert(rspec != NULL);
151 wimlib_assert(resource_is_compressed(rspec));
152 wimlib_assert(cb != NULL);
153 wimlib_assert(num_ranges != 0);
154 for (size_t i = 0; i < num_ranges; i++) {
155 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
156 i + 1, num_ranges, ranges[i].size, ranges[i].offset,
157 rspec->uncompressed_size);
158 wimlib_assert(ranges[i].size != 0);
159 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
160 wimlib_assert(ranges[i].offset + ranges[i].size <= rspec->uncompressed_size);
162 for (size_t i = 0; i < num_ranges - 1; i++)
163 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
165 /* Get the offsets of the first and last bytes of the read. */
166 const u64 first_offset = ranges[0].offset;
167 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
169 /* Get the file descriptor for the WIM. */
170 struct filedes * const in_fd = &rspec->wim->in_fd;
172 /* Determine if we're reading a pipable resource from a pipe or not. */
173 const bool is_pipe_read = (rspec->is_pipable && !filedes_is_seekable(in_fd));
175 /* Determine if the chunk table is in an alternate format. */
176 const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
179 /* Get the maximum size of uncompressed chunks in this resource, which
180 * we require be a power of 2. */
181 u64 cur_read_offset = rspec->offset_in_wim;
182 int ctype = rspec->compression_type;
183 u32 chunk_size = rspec->chunk_size;
184 if (alt_chunk_table) {
185 /* Alternate chunk table format. Its header specifies the chunk
186 * size and compression format. Note: it could be read here;
187 * however, the relevant data was already loaded into @rspec by
188 * read_wim_lookup_table(). */
189 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
192 if (!is_power_of_2(chunk_size)) {
193 ERROR("Invalid compressed resource: "
194 "expected power-of-2 chunk size (got %"PRIu32")",
196 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
198 goto out_free_memory;
201 /* Get valid decompressor. */
202 if (ctype == rspec->wim->decompressor_ctype &&
203 chunk_size == rspec->wim->decompressor_max_block_size)
205 /* Cached decompressor. */
206 decompressor = rspec->wim->decompressor;
207 rspec->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
208 rspec->wim->decompressor = NULL;
210 ret = wimlib_create_decompressor(ctype, chunk_size, NULL,
213 if (ret != WIMLIB_ERR_NOMEM)
215 goto out_free_memory;
219 const u32 chunk_order = bsr32(chunk_size);
221 /* Calculate the total number of chunks the resource is divided into. */
222 const u64 num_chunks = (rspec->uncompressed_size + chunk_size - 1) >> chunk_order;
224 /* Calculate the 0-based indices of the first and last chunks containing
225 * data that needs to be passed to the callback. */
226 const u64 first_needed_chunk = first_offset >> chunk_order;
227 const u64 last_needed_chunk = last_offset >> chunk_order;
229 /* Calculate the 0-based index of the first chunk that actually needs to
230 * be read. This is normally first_needed_chunk, but for pipe reads we
231 * must always start from the 0th chunk. */
232 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
234 /* Calculate the number of chunk offsets that are needed for the chunks
236 const u64 num_needed_chunk_offsets =
237 last_needed_chunk - read_start_chunk + 1 +
238 (last_needed_chunk < num_chunks - 1);
240 /* Calculate the number of entries in the chunk table. Normally, it's
241 * one less than the number of chunks, since the first chunk has no
242 * entry. But in the alternate chunk table format, the chunk entries
243 * contain chunk sizes, not offsets, and there is one per chunk. */
244 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
246 /* Set the size of each chunk table entry based on the resource's
247 * uncompressed size. */
248 const u64 chunk_entry_size = get_chunk_entry_size(rspec->uncompressed_size,
251 /* Calculate the size of the chunk table in bytes. */
252 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
254 /* Calculate the size of the chunk table in bytes, including the header
255 * in the case of the alternate chunk table format. */
256 const u64 chunk_table_full_size =
257 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
261 /* Read the needed chunk table entries into memory and use them
262 * to initialize the chunk_offsets array. */
264 u64 first_chunk_entry_to_read;
265 u64 last_chunk_entry_to_read;
267 if (alt_chunk_table) {
268 /* The alternate chunk table contains chunk sizes, not
269 * offsets, so we always must read all preceding entries
270 * in order to determine offsets. */
271 first_chunk_entry_to_read = 0;
272 last_chunk_entry_to_read = last_needed_chunk;
274 /* Here we must account for the fact that the first
275 * chunk has no explicit chunk table entry. */
277 if (read_start_chunk == 0)
278 first_chunk_entry_to_read = 0;
280 first_chunk_entry_to_read = read_start_chunk - 1;
282 if (last_needed_chunk == 0)
283 last_chunk_entry_to_read = 0;
285 last_chunk_entry_to_read = last_needed_chunk - 1;
287 if (last_needed_chunk < num_chunks - 1)
288 last_chunk_entry_to_read++;
291 const u64 num_chunk_entries_to_read =
292 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
294 const u64 chunk_offsets_alloc_size =
295 max(num_chunk_entries_to_read,
296 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
298 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
301 if (chunk_offsets_alloc_size <= STACK_MAX) {
302 chunk_offsets = alloca(chunk_offsets_alloc_size);
304 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
305 if (chunk_offsets == NULL)
307 chunk_offsets_malloced = true;
310 const size_t chunk_table_size_to_read =
311 num_chunk_entries_to_read * chunk_entry_size;
313 const u64 file_offset_of_needed_chunk_entries =
315 + (first_chunk_entry_to_read * chunk_entry_size)
316 + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
318 void * const chunk_table_data =
320 chunk_offsets_alloc_size -
321 chunk_table_size_to_read;
323 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
324 file_offset_of_needed_chunk_entries);
328 /* Now fill in chunk_offsets from the entries we have read in
329 * chunk_tab_data. We break aliasing rules here to avoid having
330 * to allocate yet another array. */
331 typedef le64 __attribute__((may_alias)) aliased_le64_t;
332 typedef le32 __attribute__((may_alias)) aliased_le32_t;
333 u64 * chunk_offsets_p = chunk_offsets;
335 if (alt_chunk_table) {
337 aliased_le32_t *raw_entries = chunk_table_data;
339 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
340 u32 entry = le32_to_cpu(raw_entries[i]);
341 if (i >= read_start_chunk)
342 *chunk_offsets_p++ = cur_offset;
345 if (last_needed_chunk < num_chunks - 1)
346 *chunk_offsets_p = cur_offset;
348 if (read_start_chunk == 0)
349 *chunk_offsets_p++ = 0;
351 if (chunk_entry_size == 4) {
352 aliased_le32_t *raw_entries = chunk_table_data;
353 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
354 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
356 aliased_le64_t *raw_entries = chunk_table_data;
357 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
358 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
362 /* Set offset to beginning of first chunk to read. */
363 cur_read_offset += chunk_offsets[0];
364 if (rspec->is_pipable)
365 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
367 cur_read_offset += chunk_table_size;
370 /* Allocate buffer for holding the uncompressed data of each chunk. */
371 if (chunk_size <= STACK_MAX) {
372 _ubuf = alloca(chunk_size + 15);
374 _ubuf = MALLOC(chunk_size + 15);
377 ubuf_malloced = true;
379 ubuf = (u8 *)(((uintptr_t)_ubuf + 15) & ~15);
381 /* Allocate a temporary buffer for reading compressed chunks, each of
382 * which can be at most @chunk_size - 1 bytes. This excludes compressed
383 * chunks that are a full @chunk_size bytes, which are actually stored
385 if (chunk_size - 1 <= STACK_MAX) {
386 cbuf = alloca(chunk_size - 1);
388 cbuf = MALLOC(chunk_size - 1);
391 cbuf_malloced = true;
394 /* Set current data range. */
395 const struct data_range *cur_range = ranges;
396 const struct data_range * const end_range = &ranges[num_ranges];
397 u64 cur_range_pos = cur_range->offset;
398 u64 cur_range_end = cur_range->offset + cur_range->size;
400 /* Read and process each needed chunk. */
401 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
403 /* Calculate uncompressed size of next chunk. */
405 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
406 chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
408 chunk_usize = chunk_size;
410 /* Calculate compressed size of next chunk. */
413 struct pwm_chunk_hdr chunk_hdr;
415 ret = full_pread(in_fd, &chunk_hdr,
416 sizeof(chunk_hdr), cur_read_offset);
419 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
421 if (i == num_chunks - 1) {
422 chunk_csize = rspec->size_in_wim -
423 chunk_table_full_size -
424 chunk_offsets[i - read_start_chunk];
425 if (rspec->is_pipable)
426 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
428 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
429 chunk_offsets[i - read_start_chunk];
432 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
433 ERROR("Invalid chunk size in compressed resource!");
435 ret = WIMLIB_ERR_DECOMPRESSION;
436 goto out_free_memory;
438 if (rspec->is_pipable)
439 cur_read_offset += sizeof(struct pwm_chunk_hdr);
441 /* Offsets in the uncompressed resource at which this chunk
442 * starts and ends. */
443 const u64 chunk_start_offset = i << chunk_order;
444 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
446 if (chunk_end_offset <= cur_range_pos) {
448 /* The next range does not require data in this chunk,
450 cur_read_offset += chunk_csize;
454 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
460 /* Read the chunk and feed data to the callback
464 if (chunk_csize == chunk_usize)
469 ret = full_pread(in_fd,
476 if (read_buf == cbuf) {
477 DEBUG("Decompressing chunk %"PRIu64" "
478 "(csize=%"PRIu32" usize=%"PRIu32")",
479 i, chunk_csize, chunk_usize);
480 ret = wimlib_decompress(cbuf,
486 ERROR("Failed to decompress data!");
487 ret = WIMLIB_ERR_DECOMPRESSION;
489 goto out_free_memory;
492 cur_read_offset += chunk_csize;
494 /* At least one range requires data in this chunk. */
496 size_t start, end, size;
498 /* Calculate how many bytes of data should be
499 * sent to the callback function, taking into
500 * account that data sent to the callback
501 * function must not overlap range boundaries.
503 start = cur_range_pos - chunk_start_offset;
504 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
507 ret = (*cb)(&ubuf[start], size, cb_ctx);
510 goto out_free_memory;
512 cur_range_pos += size;
513 if (cur_range_pos == cur_range_end) {
514 /* Advance to next range. */
515 if (++cur_range == end_range) {
516 cur_range_pos = ~0ULL;
518 cur_range_pos = cur_range->offset;
519 cur_range_end = cur_range->offset + cur_range->size;
522 } while (cur_range_pos < chunk_end_offset);
527 last_offset == rspec->uncompressed_size - 1 &&
531 /* If reading a pipable resource from a pipe and the full data
532 * was requested, skip the chunk table at the end so that the
533 * file descriptor is fully clear of the resource after this
535 cur_read_offset += chunk_table_size;
536 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
545 wimlib_free_decompressor(rspec->wim->decompressor);
546 rspec->wim->decompressor = decompressor;
547 rspec->wim->decompressor_ctype = ctype;
548 rspec->wim->decompressor_max_block_size = chunk_size;
550 if (chunk_offsets_malloced)
560 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
561 "from compressed WIM resource!", last_offset - first_offset + 1);
563 ret = WIMLIB_ERR_NOMEM;
564 goto out_free_memory;
567 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
568 goto out_free_memory;
572 fill_zeroes(u64 size, consume_data_callback_t cb, void *cb_ctx)
574 if (unlikely(size)) {
575 u8 buf[min(size, BUFFER_SIZE)];
577 memset(buf, 0, sizeof(buf));
583 len = min(size, BUFFER_SIZE);
584 ret = cb(buf, len, cb_ctx);
593 /* Read raw data from a file descriptor at the specified offset, feeding the
594 * data it in chunks into the specified callback function. */
596 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
597 consume_data_callback_t cb, void *cb_ctx)
600 size_t bytes_to_read;
604 bytes_to_read = min(sizeof(buf), size);
605 ret = full_pread(in_fd, buf, bytes_to_read, offset);
607 ERROR_WITH_ERRNO("Read error");
610 ret = cb(buf, bytes_to_read, cb_ctx);
613 size -= bytes_to_read;
614 offset += bytes_to_read;
619 /* A consume_data_callback_t implementation that simply concatenates all chunks
622 bufferer_cb(const void *chunk, size_t size, void *_ctx)
626 *buf_p = mempcpy(*buf_p, chunk, size);
631 * read_partial_wim_resource()-
633 * Read a range of data from an uncompressed or compressed resource in a WIM
637 * Specification of the WIM resource to read from.
639 * Offset within the uncompressed resource at which to start reading.
641 * Number of bytes to read.
643 * Callback function to feed the data being read. Each call provides the
644 * next chunk of the requested data, uncompressed. Each chunk will be of
645 * nonzero size and will not cross range boundaries, but otherwise will be
646 * of unspecified size.
648 * Parameter to pass to @cb_ctx.
651 * WIMLIB_ERR_SUCCESS (0)
652 * WIMLIB_ERR_READ (errno set)
653 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
654 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
655 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
657 * or other error code returned by the @cb function.
660 read_partial_wim_resource(const struct wim_resource_spec *rspec,
661 u64 offset, u64 size,
662 consume_data_callback_t cb, void *cb_ctx)
665 wimlib_assert(offset + size >= offset);
666 wimlib_assert(offset + size <= rspec->uncompressed_size);
668 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
669 "%"PRIu64" => %"PRIu64" @ %"PRIu64,
670 size, offset, rspec->uncompressed_size,
671 rspec->size_in_wim, rspec->offset_in_wim);
677 if (resource_is_compressed(rspec)) {
678 struct data_range range = {
682 return read_compressed_wim_resource(rspec, &range, 1,
685 /* Reading uncompressed resource. For completeness, handle the
686 * weird case where size_in_wim < uncompressed_size. */
692 if (likely(offset + size <= rspec->size_in_wim) ||
698 if (offset >= rspec->size_in_wim) {
702 read_size = rspec->size_in_wim - offset;
703 zeroes_size = offset + size - rspec->size_in_wim;
707 ret = read_raw_file_data(&rspec->wim->in_fd,
708 rspec->offset_in_wim + offset,
715 return fill_zeroes(zeroes_size, cb, cb_ctx);
719 /* Read the specified range of uncompressed data from the specified stream,
720 * which must be located into a WIM file, into the specified buffer. */
722 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
723 size_t size, u64 offset, void *_buf)
727 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
729 return read_partial_wim_resource(lte->rspec,
730 lte->offset_in_res + offset,
736 /* A consume_data_callback_t implementation that simply ignores the data
739 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
744 /* Skip over the data of the specified stream, which must correspond to a full
747 skip_wim_stream(struct wim_lookup_table_entry *lte)
749 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
750 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
751 DEBUG("Skipping stream (size=%"PRIu64")", lte->size);
752 return read_partial_wim_resource(lte->rspec,
754 lte->rspec->uncompressed_size,
760 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
761 consume_data_callback_t cb, void *cb_ctx)
763 return read_partial_wim_resource(lte->rspec, lte->offset_in_res, size,
767 /* This function handles reading stream data that is located in an external
768 * file, such as a file that has been added to the WIM image through execution
769 * of a wimlib_add_command.
771 * This assumes the file can be accessed using the standard POSIX open(),
772 * read(), and close(). On Windows this will not necessarily be the case (since
773 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
774 * encrypted), so Windows uses its own code for its equivalent case. */
776 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
777 consume_data_callback_t cb, void *cb_ctx)
783 wimlib_assert(size <= lte->size);
785 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
787 raw_fd = topen(lte->file_on_disk, O_BINARY | O_RDONLY);
789 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
790 return WIMLIB_ERR_OPEN;
792 filedes_init(&fd, raw_fd);
793 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
800 read_staging_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
801 consume_data_callback_t cb, void *cb_ctx)
807 wimlib_assert(size <= lte->size);
809 DEBUG("Reading %"PRIu64" bytes from staging file \"%s\"",
810 size, lte->staging_file_name);
812 raw_fd = openat(lte->staging_dir_fd, lte->staging_file_name,
813 O_RDONLY | O_NOFOLLOW);
815 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
816 lte->staging_file_name);
817 return WIMLIB_ERR_OPEN;
819 filedes_init(&fd, raw_fd);
820 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
826 /* This function handles the trivial case of reading stream data that is, in
827 * fact, already located in an in-memory buffer. */
829 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
830 u64 size, consume_data_callback_t cb, void *cb_ctx)
832 wimlib_assert(size <= lte->size);
833 return (*cb)(lte->attached_buffer, size, cb_ctx);
836 typedef int (*read_stream_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
838 consume_data_callback_t cb,
842 * read_stream_prefix()-
844 * Reads the first @size bytes from a generic "stream", which may be located in
845 * any one of several locations, such as in a WIM file (compressed or
846 * uncompressed), in an external file, or directly in an in-memory buffer.
848 * This function feeds the data to a callback function @cb in chunks of
851 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
852 * the stream data cannot be successfully read (for a number of different
853 * reasons, depending on the stream location), or if @cb returned nonzero in
854 * which case that error code will be returned.
857 read_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
858 consume_data_callback_t cb, void *cb_ctx)
860 static const read_stream_prefix_handler_t handlers[] = {
861 [RESOURCE_IN_WIM] = read_wim_stream_prefix,
862 [RESOURCE_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
863 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
865 [RESOURCE_IN_STAGING_FILE] = read_staging_file_prefix,
868 [RESOURCE_IN_NTFS_VOLUME] = read_ntfs_file_prefix,
871 [RESOURCE_IN_WINNT_FILE_ON_DISK] = read_winnt_file_prefix,
872 [RESOURCE_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
875 wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
876 && handlers[lte->resource_location] != NULL);
877 return handlers[lte->resource_location](lte, size, cb, cb_ctx);
880 /* Read the full uncompressed data of the specified stream into the specified
881 * buffer, which must have space for at least lte->size bytes. */
883 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
886 return read_stream_prefix(lte, lte->size, bufferer_cb, &buf);
889 /* Retrieve the full uncompressed data of the specified stream. A buffer large
890 * enough hold the data is allocated and returned in @buf_ret. */
892 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
898 if ((size_t)lte->size != lte->size) {
899 ERROR("Can't read %"PRIu64" byte stream into "
900 "memory", lte->size);
901 return WIMLIB_ERR_NOMEM;
904 buf = MALLOC(lte->size);
906 return WIMLIB_ERR_NOMEM;
908 ret = read_full_stream_into_buf(lte, buf);
918 /* Retrieve the full uncompressed data of the specified WIM resource. A buffer
919 * large enough hold the data is allocated and returned in @buf_ret. */
921 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
924 struct wim_lookup_table_entry *lte;
926 lte = new_lookup_table_entry();
928 return WIMLIB_ERR_NOMEM;
930 lte_bind_wim_resource_spec(lte, rspec);
931 lte->flags = rspec->flags;
932 lte->size = rspec->uncompressed_size;
933 lte->offset_in_res = 0;
935 ret = read_full_stream_into_alloc_buf(lte, buf_ret);
937 lte_unbind_wim_resource_spec(lte);
938 free_lookup_table_entry(lte);
942 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
943 * `wim_reshdr' and the corresponding WIM file. A large enough hold the data is
944 * allocated and returned in @buf_ret. */
946 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
948 DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
949 "uncompressed_size=%"PRIu64,
950 reshdr->offset_in_wim, reshdr->size_in_wim,
951 reshdr->uncompressed_size);
953 struct wim_resource_spec rspec;
954 wim_res_hdr_to_spec(reshdr, wim, &rspec);
955 return wim_resource_spec_to_data(&rspec, buf_ret);
959 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
960 u8 hash[SHA1_HASH_SIZE])
962 struct wim_resource_spec rspec;
964 struct wim_lookup_table_entry *lte;
966 wim_res_hdr_to_spec(reshdr, wim, &rspec);
968 lte = new_lookup_table_entry();
970 return WIMLIB_ERR_NOMEM;
972 lte_bind_wim_resource_spec(lte, &rspec);
973 lte->flags = rspec.flags;
974 lte->size = rspec.uncompressed_size;
975 lte->offset_in_res = 0;
978 ret = sha1_stream(lte);
980 lte_unbind_wim_resource_spec(lte);
981 copy_hash(hash, lte->hash);
982 free_lookup_table_entry(lte);
986 struct streamifier_context {
987 struct read_stream_list_callbacks cbs;
988 struct wim_lookup_table_entry *cur_stream;
989 struct wim_lookup_table_entry *next_stream;
990 u64 cur_stream_offset;
991 struct wim_lookup_table_entry *final_stream;
992 size_t list_head_offset;
995 static struct wim_lookup_table_entry *
996 next_stream(struct wim_lookup_table_entry *lte, size_t list_head_offset)
998 struct list_head *cur;
1000 cur = (struct list_head*)((u8*)lte + list_head_offset);
1002 return (struct wim_lookup_table_entry*)((u8*)cur->next - list_head_offset);
1005 /* A consume_data_callback_t implementation that translates raw resource data
1006 * into streams, calling the begin_stream, consume_chunk, and end_stream
1007 * callback functions as appropriate. */
1009 streamifier_cb(const void *chunk, size_t size, void *_ctx)
1011 struct streamifier_context *ctx = _ctx;
1014 DEBUG("%zu bytes passed to streamifier", size);
1016 wimlib_assert(ctx->cur_stream != NULL);
1017 wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
1019 if (ctx->cur_stream_offset == 0) {
1022 /* Starting a new stream. */
1023 DEBUG("Begin new stream (size=%"PRIu64").",
1024 ctx->cur_stream->size);
1026 flags = BEGIN_STREAM_FLAG_PARTIAL_RESOURCE;
1027 if (size == ctx->cur_stream->size)
1028 flags |= BEGIN_STREAM_FLAG_WHOLE_STREAM;
1029 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream,
1031 ctx->cbs.begin_stream_ctx);
1036 /* Consume the chunk. */
1037 ret = (*ctx->cbs.consume_chunk)(chunk, size,
1038 ctx->cbs.consume_chunk_ctx);
1039 ctx->cur_stream_offset += size;
1043 if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1044 /* Finished reading all the data for a stream. */
1046 ctx->cur_stream_offset = 0;
1048 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1049 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1050 ctx->cbs.end_stream_ctx);
1054 /* Advance to next stream. */
1055 ctx->cur_stream = ctx->next_stream;
1056 if (ctx->cur_stream != NULL) {
1057 if (ctx->cur_stream != ctx->final_stream)
1058 ctx->next_stream = next_stream(ctx->cur_stream,
1059 ctx->list_head_offset);
1061 ctx->next_stream = NULL;
1067 struct hasher_context {
1070 struct read_stream_list_callbacks cbs;
1073 /* Callback for starting to read a stream while calculating its SHA1 message
1076 hasher_begin_stream(struct wim_lookup_table_entry *lte, u32 flags,
1079 struct hasher_context *ctx = _ctx;
1081 sha1_init(&ctx->sha_ctx);
1083 if (ctx->cbs.begin_stream == NULL)
1086 return (*ctx->cbs.begin_stream)(lte, flags,
1087 ctx->cbs.begin_stream_ctx);
1090 /* A consume_data_callback_t implementation that continues calculating the SHA1
1091 * message digest of the stream being read, then optionally passes the data on
1092 * to another consume_data_callback_t implementation. This allows checking the
1093 * SHA1 message digest of a stream being extracted, for example. */
1095 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1097 struct hasher_context *ctx = _ctx;
1099 sha1_update(&ctx->sha_ctx, chunk, size);
1100 if (ctx->cbs.consume_chunk == NULL)
1103 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1107 get_sha1_string(const u8 md[SHA1_HASH_SIZE], tchar *str)
1109 for (size_t i = 0; i < SHA1_HASH_SIZE; i++)
1110 str += tsprintf(str, T("%02x"), md[i]);
1113 /* Callback for finishing reading a stream while calculating its SHA1 message
1116 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1118 struct hasher_context *ctx = _ctx;
1119 u8 hash[SHA1_HASH_SIZE];
1123 /* Error occurred; the full stream may not have been read. */
1128 /* Retrieve the final SHA1 message digest. */
1129 sha1_final(hash, &ctx->sha_ctx);
1131 if (lte->unhashed) {
1132 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1133 /* No SHA1 message digest was previously present for the
1134 * stream. Set it to the one just calculated. */
1135 DEBUG("Set SHA1 message digest for stream "
1136 "(size=%"PRIu64").", lte->size);
1137 copy_hash(lte->hash, hash);
1140 if (ctx->flags & VERIFY_STREAM_HASHES) {
1141 /* The stream already had a SHA1 message digest present. Verify
1142 * that it is the same as the calculated value. */
1143 if (!hashes_equal(hash, lte->hash)) {
1144 if (wimlib_print_errors) {
1145 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1146 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1147 get_sha1_string(lte->hash, expected_hashstr);
1148 get_sha1_string(hash, actual_hashstr);
1149 ERROR("The stream is corrupted!\n"
1150 " (Expected SHA1=%"TS",\n"
1152 expected_hashstr, actual_hashstr);
1154 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1158 DEBUG("SHA1 message digest okay for "
1159 "stream (size=%"PRIu64").", lte->size);
1164 if (ctx->cbs.end_stream == NULL)
1167 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1171 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1172 const struct read_stream_list_callbacks *cbs)
1176 ret = (*cbs->begin_stream)(lte, 0, cbs->begin_stream_ctx);
1180 ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1181 cbs->consume_chunk_ctx);
1183 return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1186 /* Read the full data of the specified stream, passing the data into the
1187 * specified callbacks (all of which are optional) and either checking or
1188 * computing the SHA1 message digest of the stream. */
1190 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1191 const struct read_stream_list_callbacks *cbs)
1193 struct hasher_context hasher_ctx = {
1194 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1197 struct read_stream_list_callbacks hasher_cbs = {
1198 .begin_stream = hasher_begin_stream,
1199 .begin_stream_ctx = &hasher_ctx,
1200 .consume_chunk = hasher_consume_chunk,
1201 .consume_chunk_ctx = &hasher_ctx,
1202 .end_stream = hasher_end_stream,
1203 .end_stream_ctx = &hasher_ctx,
1205 return read_full_stream_with_cbs(lte, &hasher_cbs);
1209 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1210 struct wim_lookup_table_entry *last_stream,
1212 size_t list_head_offset,
1213 const struct read_stream_list_callbacks *sink_cbs)
1215 struct data_range *ranges;
1216 bool ranges_malloced;
1217 struct wim_lookup_table_entry *cur_stream;
1220 u64 ranges_alloc_size;
1222 DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1225 /* Setup data ranges array (one range per stream to read); this way
1226 * read_compressed_wim_resource() does not need to be aware of streams.
1229 ranges_alloc_size = stream_count * sizeof(ranges[0]);
1231 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1232 ERROR("Too many streams in one resource!");
1233 return WIMLIB_ERR_NOMEM;
1235 if (likely(ranges_alloc_size <= STACK_MAX)) {
1236 ranges = alloca(ranges_alloc_size);
1237 ranges_malloced = false;
1239 ranges = MALLOC(ranges_alloc_size);
1240 if (ranges == NULL) {
1241 ERROR("Too many streams in one resource!");
1242 return WIMLIB_ERR_NOMEM;
1244 ranges_malloced = true;
1247 for (i = 0, cur_stream = first_stream;
1249 i++, cur_stream = next_stream(cur_stream, list_head_offset))
1251 ranges[i].offset = cur_stream->offset_in_res;
1252 ranges[i].size = cur_stream->size;
1255 struct streamifier_context streamifier_ctx = {
1257 .cur_stream = first_stream,
1258 .next_stream = next_stream(first_stream, list_head_offset),
1259 .cur_stream_offset = 0,
1260 .final_stream = last_stream,
1261 .list_head_offset = list_head_offset,
1264 ret = read_compressed_wim_resource(first_stream->rspec,
1270 if (ranges_malloced)
1274 if (streamifier_ctx.cur_stream_offset != 0) {
1275 ret = (*streamifier_ctx.cbs.end_stream)
1276 (streamifier_ctx.cur_stream,
1278 streamifier_ctx.cbs.end_stream_ctx);
1285 * Read a list of streams, each of which may be in any supported location (e.g.
1286 * in a WIM or in an external file). Unlike read_stream_prefix() or the
1287 * functions which call it, this function optimizes the case where multiple
1288 * streams are packed into a single compressed WIM resource and reads them all
1289 * consecutively, only decompressing the data one time.
1292 * List of streams (represented as `struct wim_lookup_table_entry's) to
1295 * Offset of the `struct list_head' within each `struct
1296 * wim_lookup_table_entry' that makes up the @stream_list.
1298 * Callback functions to accept the stream data.
1300 * Bitwise OR of zero or more of the following flags:
1302 * VERIFY_STREAM_HASHES:
1303 * For all streams being read that have already had SHA1 message
1304 * digests computed, calculate the SHA1 message digest of the read
1305 * data and compare it with the previously computed value. If they
1306 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1308 * COMPUTE_MISSING_STREAM_HASHES
1309 * For all streams being read that have not yet had their SHA1
1310 * message digests computed, calculate and save their SHA1 message
1313 * STREAM_LIST_ALREADY_SORTED
1314 * @stream_list is already sorted in sequential order for reading.
1316 * The callback functions are allowed to delete the current stream from the list
1319 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1320 * to an error reading the data or due to an error status being returned by any
1321 * of the callback functions.
1324 read_stream_list(struct list_head *stream_list,
1325 size_t list_head_offset,
1326 const struct read_stream_list_callbacks *cbs,
1330 struct list_head *cur, *next;
1331 struct wim_lookup_table_entry *lte;
1332 struct hasher_context *hasher_ctx;
1333 struct read_stream_list_callbacks *sink_cbs;
1335 if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1336 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1341 if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1342 hasher_ctx = alloca(sizeof(*hasher_ctx));
1343 *hasher_ctx = (struct hasher_context) {
1347 sink_cbs = alloca(sizeof(*sink_cbs));
1348 *sink_cbs = (struct read_stream_list_callbacks) {
1349 .begin_stream = hasher_begin_stream,
1350 .begin_stream_ctx = hasher_ctx,
1351 .consume_chunk = hasher_consume_chunk,
1352 .consume_chunk_ctx = hasher_ctx,
1353 .end_stream = hasher_end_stream,
1354 .end_stream_ctx = hasher_ctx,
1357 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1360 for (cur = stream_list->next, next = cur->next;
1362 cur = next, next = cur->next)
1364 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1366 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1367 lte->size != lte->rspec->uncompressed_size)
1370 struct wim_lookup_table_entry *lte_next, *lte_last;
1371 struct list_head *next2;
1374 /* The next stream is a proper sub-sequence of a WIM
1375 * resource. See if there are other streams in the same
1376 * resource that need to be read. Since
1377 * sort_stream_list_by_sequential_order() sorted the
1378 * streams by offset in the WIM, this can be determined
1379 * by simply scanning forward in the list. */
1384 next2 != stream_list
1385 && (lte_next = (struct wim_lookup_table_entry*)
1386 ((u8*)next2 - list_head_offset),
1387 lte_next->resource_location == RESOURCE_IN_WIM
1388 && lte_next->rspec == lte->rspec);
1389 next2 = next2->next)
1391 lte_last = lte_next;
1394 if (stream_count > 1) {
1395 /* Reading multiple streams combined into a
1396 * single WIM resource. They are in the stream
1397 * list, sorted by offset; @lte specifies the
1398 * first stream in the resource that needs to be
1399 * read and @lte_last specifies the last stream
1400 * in the resource that needs to be read. */
1402 ret = read_packed_streams(lte, lte_last,
1412 ret = read_full_stream_with_cbs(lte, sink_cbs);
1413 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1419 /* Extract the first @size bytes of the specified stream.
1421 * If @size specifies the full uncompressed size of the stream, then the SHA1
1422 * message digest of the uncompressed stream is checked while being extracted.
1424 * The uncompressed data of the resource is passed in chunks of unspecified size
1425 * to the @extract_chunk function, passing it @extract_chunk_arg. */
1427 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1428 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1430 wimlib_assert(size <= lte->size);
1431 if (size == lte->size) {
1433 struct read_stream_list_callbacks cbs = {
1434 .consume_chunk = extract_chunk,
1435 .consume_chunk_ctx = extract_chunk_arg,
1437 return read_full_stream_with_sha1(lte, &cbs);
1439 /* Don't do SHA1. */
1440 return read_stream_prefix(lte, size, extract_chunk,
1445 /* A consume_data_callback_t implementation that writes the chunk of data to a
1446 * file descriptor. */
1448 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1450 struct filedes *fd = _fd_p;
1452 int ret = full_write(fd, chunk, size);
1454 ERROR_WITH_ERRNO("Error writing to file descriptor");
1460 /* Extract the first @size bytes of the specified stream to the specified file
1463 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1464 struct filedes *fd, u64 size)
1466 return extract_stream(lte, size, extract_chunk_to_fd, fd);
1469 /* Extract the full uncompressed contents of the specified stream to the
1470 * specified file descriptor. */
1472 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1475 return extract_stream_to_fd(lte, fd, lte->size);
1478 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash. */
1480 sha1_stream(struct wim_lookup_table_entry *lte)
1482 wimlib_assert(lte->unhashed);
1483 struct read_stream_list_callbacks cbs = {
1485 return read_full_stream_with_sha1(lte, &cbs);
1488 /* Convert a short WIM resource header to a stand-alone WIM resource
1491 * Note: for packed resources some fields still need to be overridden.
1494 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1495 struct wim_resource_spec *rspec)
1498 rspec->offset_in_wim = reshdr->offset_in_wim;
1499 rspec->size_in_wim = reshdr->size_in_wim;
1500 rspec->uncompressed_size = reshdr->uncompressed_size;
1501 INIT_LIST_HEAD(&rspec->stream_list);
1502 rspec->flags = reshdr->flags;
1503 rspec->is_pipable = wim_is_pipable(wim);
1504 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1505 rspec->compression_type = wim->compression_type;
1506 rspec->chunk_size = wim->chunk_size;
1508 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1509 rspec->chunk_size = 0;
1513 /* Convert a stand-alone resource specification to a WIM resource header. */
1515 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1516 struct wim_reshdr *reshdr)
1518 reshdr->offset_in_wim = rspec->offset_in_wim;
1519 reshdr->size_in_wim = rspec->size_in_wim;
1520 reshdr->flags = rspec->flags;
1521 reshdr->uncompressed_size = rspec->uncompressed_size;
1524 /* Translates a WIM resource header from the on-disk format into an in-memory
1527 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1528 struct wim_reshdr *reshdr)
1530 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1531 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1532 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1533 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1534 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1535 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1536 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1537 ((u64)disk_reshdr->size_in_wim[6] << 48));
1538 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1539 reshdr->flags = disk_reshdr->flags;
1542 /* Translates a WIM resource header from an in-memory format into the on-disk
1545 put_wim_reshdr(const struct wim_reshdr *reshdr,
1546 struct wim_reshdr_disk *disk_reshdr)
1548 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1549 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1550 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1551 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1552 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1553 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1554 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1555 disk_reshdr->flags = reshdr->flags;
1556 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1557 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);