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/.
29 #include "wimlib/assert.h"
30 #include "wimlib/endianness.h"
31 #include "wimlib/error.h"
32 #include "wimlib/file_io.h"
33 #include "wimlib/lookup_table.h"
34 #include "wimlib/resource.h"
35 #include "wimlib/sha1.h"
36 #include "wimlib/wim.h"
39 /* for read_winnt_file_prefix(), read_win32_encrypted_file_prefix() */
40 # include "wimlib/win32.h"
44 /* for read_ntfs_file_prefix() */
45 # include "wimlib/ntfs_3g.h"
57 * Compressed WIM resources
59 * A compressed resource in a WIM consists of a number of compressed chunks,
60 * each of which decompresses to a fixed chunk size (given in the WIM header;
61 * usually 32768) except possibly the last, which always decompresses to any
62 * remaining bytes. In addition, immediately before the chunks, a table (the
63 * "chunk table") provides the offset, in bytes relative to the end of the chunk
64 * table, of the start of each compressed chunk, except for the first chunk
65 * which is omitted as it always has an offset of 0. Therefore, a compressed
66 * resource with N chunks will have a chunk table with N - 1 entries.
68 * Additional information:
70 * - Entries in the chunk table are 4 bytes each, except if the uncompressed
71 * size of the resource is greater than 4 GiB, in which case the entries in
72 * the chunk table are 8 bytes each. In either case, the entries are unsigned
73 * little-endian integers.
75 * - The chunk table is included in the compressed size of the resource provided
76 * in the corresponding entry in the WIM's stream lookup table.
78 * - The compressed size of a chunk is never greater than the uncompressed size.
79 * From the compressor's point of view, chunks that would have compressed to a
80 * size greater than or equal to their original size are in fact stored
81 * uncompressed. From the decompresser's point of view, chunks with
82 * compressed size equal to their uncompressed size are in fact uncompressed.
84 * Furthermore, wimlib supports its own "pipable" WIM format, and for this the
85 * structure of compressed resources was modified to allow piped reading and
86 * writing. To make sequential writing possible, the chunk table is placed
87 * after the chunks rather than before the chunks, and to make sequential
88 * reading possible, each chunk is prefixed with a 4-byte header giving its
89 * compressed size as a 32-bit, unsigned, little-endian integer. Otherwise the
90 * details are the same.
100 * read_compressed_wim_resource() -
102 * Read data from a compressed WIM resource.
105 * Specification of the compressed WIM resource to read from.
107 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
108 * read, sorted by increasing offset.
110 * Number of ranges in @ranges; must be at least 1.
112 * Callback function to feed the data being read. Each call provides the
113 * next chunk of the requested data, uncompressed. Each chunk will be of
114 * nonzero size and will not cross range boundaries, but otherwise will be
115 * of unspecified size.
117 * Parameter to pass to @cb_ctx.
119 * Possible return values:
121 * WIMLIB_ERR_SUCCESS (0)
122 * WIMLIB_ERR_READ (errno set)
123 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
124 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
125 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
127 * or other error code returned by the @cb function.
130 read_compressed_wim_resource(const struct wim_resource_spec * const rspec,
131 const struct data_range * const ranges,
132 const size_t num_ranges,
133 const consume_data_callback_t cb,
139 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 = (rspec->is_pipable && !filedes_is_seekable(in_fd));
174 /* Determine if the chunk table is in an alternate 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,
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 + 15);
373 _ubuf = MALLOC(chunk_size + 15);
376 ubuf_malloced = true;
378 ubuf = (u8 *)(((uintptr_t)_ubuf + 15) & ~15);
380 /* Allocate a temporary buffer for reading compressed chunks, each of
381 * which can be at most @chunk_size - 1 bytes. This excludes compressed
382 * chunks that are a full @chunk_size bytes, which are actually stored
384 if (chunk_size - 1 <= STACK_MAX) {
385 cbuf = alloca(chunk_size - 1);
387 cbuf = MALLOC(chunk_size - 1);
390 cbuf_malloced = true;
393 /* Set current data range. */
394 const struct data_range *cur_range = ranges;
395 const struct data_range * const end_range = &ranges[num_ranges];
396 u64 cur_range_pos = cur_range->offset;
397 u64 cur_range_end = cur_range->offset + cur_range->size;
399 /* Read and process each needed chunk. */
400 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
402 /* Calculate uncompressed size of next chunk. */
404 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
405 chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
407 chunk_usize = chunk_size;
409 /* Calculate compressed size of next chunk. */
412 struct pwm_chunk_hdr chunk_hdr;
414 ret = full_pread(in_fd, &chunk_hdr,
415 sizeof(chunk_hdr), cur_read_offset);
418 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
420 if (i == num_chunks - 1) {
421 chunk_csize = rspec->size_in_wim -
422 chunk_table_full_size -
423 chunk_offsets[i - read_start_chunk];
424 if (rspec->is_pipable)
425 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
427 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
428 chunk_offsets[i - read_start_chunk];
431 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
432 ERROR("Invalid chunk size in compressed resource!");
434 ret = WIMLIB_ERR_DECOMPRESSION;
435 goto out_free_memory;
437 if (rspec->is_pipable)
438 cur_read_offset += sizeof(struct pwm_chunk_hdr);
440 /* Offsets in the uncompressed resource at which this chunk
441 * starts and ends. */
442 const u64 chunk_start_offset = i << chunk_order;
443 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
445 if (chunk_end_offset <= cur_range_pos) {
447 /* The next range does not require data in this chunk,
449 cur_read_offset += chunk_csize;
453 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
459 /* Read the chunk and feed data to the callback
463 if (chunk_csize == chunk_usize)
468 ret = full_pread(in_fd,
475 if (read_buf == cbuf) {
476 DEBUG("Decompressing chunk %"PRIu64" "
477 "(csize=%"PRIu32" usize=%"PRIu32")",
478 i, chunk_csize, chunk_usize);
479 ret = wimlib_decompress(cbuf,
485 ERROR("Failed to decompress data!");
486 ret = WIMLIB_ERR_DECOMPRESSION;
488 goto out_free_memory;
491 cur_read_offset += chunk_csize;
493 /* At least one range requires data in this chunk. */
495 size_t start, end, size;
497 /* Calculate how many bytes of data should be
498 * sent to the callback function, taking into
499 * account that data sent to the callback
500 * function must not overlap range boundaries.
502 start = cur_range_pos - chunk_start_offset;
503 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
506 ret = (*cb)(&ubuf[start], size, cb_ctx);
509 goto out_free_memory;
511 cur_range_pos += size;
512 if (cur_range_pos == cur_range_end) {
513 /* Advance to next range. */
514 if (++cur_range == end_range) {
515 cur_range_pos = ~0ULL;
517 cur_range_pos = cur_range->offset;
518 cur_range_end = cur_range->offset + cur_range->size;
521 } while (cur_range_pos < chunk_end_offset);
526 last_offset == rspec->uncompressed_size - 1 &&
530 /* If reading a pipable resource from a pipe and the full data
531 * was requested, skip the chunk table at the end so that the
532 * file descriptor is fully clear of the resource after this
534 cur_read_offset += chunk_table_size;
535 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
544 wimlib_free_decompressor(rspec->wim->decompressor);
545 rspec->wim->decompressor = decompressor;
546 rspec->wim->decompressor_ctype = ctype;
547 rspec->wim->decompressor_max_block_size = chunk_size;
549 if (chunk_offsets_malloced)
559 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
560 "from compressed WIM resource!", last_offset - first_offset + 1);
562 ret = WIMLIB_ERR_NOMEM;
563 goto out_free_memory;
566 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
567 goto out_free_memory;
571 fill_zeroes(u64 size, consume_data_callback_t cb, void *cb_ctx)
573 if (unlikely(size)) {
574 u8 buf[min(size, BUFFER_SIZE)];
576 memset(buf, 0, sizeof(buf));
582 len = min(size, BUFFER_SIZE);
583 ret = cb(buf, len, cb_ctx);
592 /* Read raw data from a file descriptor at the specified offset, feeding the
593 * data it in chunks into the specified callback function. */
595 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
596 consume_data_callback_t cb, void *cb_ctx)
599 size_t bytes_to_read;
603 bytes_to_read = min(sizeof(buf), size);
604 ret = full_pread(in_fd, buf, bytes_to_read, offset);
606 ERROR_WITH_ERRNO("Read error");
609 ret = cb(buf, bytes_to_read, cb_ctx);
612 size -= bytes_to_read;
613 offset += bytes_to_read;
618 /* A consume_data_callback_t implementation that simply concatenates all chunks
621 bufferer_cb(const void *chunk, size_t size, void *_ctx)
625 *buf_p = mempcpy(*buf_p, chunk, size);
630 * read_partial_wim_resource()-
632 * Read a range of data from an uncompressed or compressed resource in a WIM
636 * Specification of the WIM resource to read from.
638 * Offset within the uncompressed resource at which to start reading.
640 * Number of bytes to read.
642 * Callback function to feed the data being read. Each call provides the
643 * next chunk of the requested data, uncompressed. Each chunk will be of
644 * nonzero size and will not cross range boundaries, but otherwise will be
645 * of unspecified size.
647 * Parameter to pass to @cb_ctx.
650 * WIMLIB_ERR_SUCCESS (0)
651 * WIMLIB_ERR_READ (errno set)
652 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
653 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
654 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
656 * or other error code returned by the @cb function.
659 read_partial_wim_resource(const struct wim_resource_spec *rspec,
660 u64 offset, u64 size,
661 consume_data_callback_t cb, void *cb_ctx)
664 wimlib_assert(offset + size >= offset);
665 wimlib_assert(offset + size <= rspec->uncompressed_size);
667 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
668 "%"PRIu64" => %"PRIu64" @ %"PRIu64,
669 size, offset, rspec->uncompressed_size,
670 rspec->size_in_wim, rspec->offset_in_wim);
676 if (resource_is_compressed(rspec)) {
677 struct data_range range = {
681 return read_compressed_wim_resource(rspec, &range, 1,
684 /* Reading uncompressed resource. For completeness, handle the
685 * weird case where size_in_wim < uncompressed_size. */
691 if (likely(offset + size <= rspec->size_in_wim) ||
697 if (offset >= rspec->size_in_wim) {
701 read_size = rspec->size_in_wim - offset;
702 zeroes_size = offset + size - rspec->size_in_wim;
706 ret = read_raw_file_data(&rspec->wim->in_fd,
707 rspec->offset_in_wim + offset,
714 return fill_zeroes(zeroes_size, cb, cb_ctx);
718 /* Read the specified range of uncompressed data from the specified stream,
719 * which must be located into a WIM file, into the specified buffer. */
721 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
722 size_t size, u64 offset, void *_buf)
726 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
728 return read_partial_wim_resource(lte->rspec,
729 lte->offset_in_res + offset,
735 /* A consume_data_callback_t implementation that simply ignores the data
738 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
743 /* Skip over the data of the specified stream, which must correspond to a full
746 skip_wim_stream(struct wim_lookup_table_entry *lte)
748 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
749 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
750 DEBUG("Skipping stream (size=%"PRIu64")", lte->size);
751 return read_partial_wim_resource(lte->rspec,
753 lte->rspec->uncompressed_size,
759 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
760 consume_data_callback_t cb, void *cb_ctx)
762 return read_partial_wim_resource(lte->rspec, lte->offset_in_res, size,
766 /* This function handles reading stream data that is located in an external
767 * file, such as a file that has been added to the WIM image through execution
768 * of a wimlib_add_command.
770 * This assumes the file can be accessed using the standard POSIX open(),
771 * read(), and close(). On Windows this will not necessarily be the case (since
772 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
773 * encrypted), so Windows uses its own code for its equivalent case. */
775 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
776 consume_data_callback_t cb, void *cb_ctx)
782 wimlib_assert(size <= lte->size);
784 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
786 raw_fd = topen(lte->file_on_disk, O_BINARY | O_RDONLY);
788 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
789 return WIMLIB_ERR_OPEN;
791 filedes_init(&fd, raw_fd);
792 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
799 read_staging_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
800 consume_data_callback_t cb, void *cb_ctx)
806 wimlib_assert(size <= lte->size);
808 DEBUG("Reading %"PRIu64" bytes from staging file \"%s\"",
809 size, lte->staging_file_name);
811 raw_fd = openat(lte->staging_dir_fd, lte->staging_file_name,
812 O_RDONLY | O_NOFOLLOW);
814 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
815 lte->staging_file_name);
816 return WIMLIB_ERR_OPEN;
818 filedes_init(&fd, raw_fd);
819 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
825 /* This function handles the trivial case of reading stream data that is, in
826 * fact, already located in an in-memory buffer. */
828 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
829 u64 size, consume_data_callback_t cb, void *cb_ctx)
831 wimlib_assert(size <= lte->size);
832 return (*cb)(lte->attached_buffer, size, cb_ctx);
835 typedef int (*read_stream_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
837 consume_data_callback_t cb,
841 * read_stream_prefix()-
843 * Reads the first @size bytes from a generic "stream", which may be located in
844 * any one of several locations, such as in a WIM file (compressed or
845 * uncompressed), in an external file, or directly in an in-memory buffer.
847 * This function feeds the data to a callback function @cb in chunks of
850 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
851 * the stream data cannot be successfully read (for a number of different
852 * reasons, depending on the stream location), or if @cb returned nonzero in
853 * which case that error code will be returned.
856 read_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
857 consume_data_callback_t cb, void *cb_ctx)
859 static const read_stream_prefix_handler_t handlers[] = {
860 [RESOURCE_IN_WIM] = read_wim_stream_prefix,
861 [RESOURCE_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
862 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
864 [RESOURCE_IN_STAGING_FILE] = read_staging_file_prefix,
867 [RESOURCE_IN_NTFS_VOLUME] = read_ntfs_file_prefix,
870 [RESOURCE_IN_WINNT_FILE_ON_DISK] = read_winnt_file_prefix,
871 [RESOURCE_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
874 wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
875 && handlers[lte->resource_location] != NULL);
876 return handlers[lte->resource_location](lte, size, cb, cb_ctx);
879 /* Read the full uncompressed data of the specified stream into the specified
880 * buffer, which must have space for at least lte->size bytes. */
882 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
885 return read_stream_prefix(lte, lte->size, bufferer_cb, &buf);
888 /* Retrieve the full uncompressed data of the specified stream. A buffer large
889 * enough hold the data is allocated and returned in @buf_ret. */
891 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
897 if ((size_t)lte->size != lte->size) {
898 ERROR("Can't read %"PRIu64" byte stream into "
899 "memory", lte->size);
900 return WIMLIB_ERR_NOMEM;
903 buf = MALLOC(lte->size);
905 return WIMLIB_ERR_NOMEM;
907 ret = read_full_stream_into_buf(lte, buf);
917 /* Retrieve the full uncompressed data of the specified WIM resource. A buffer
918 * large enough hold the data is allocated and returned in @buf_ret. */
920 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
923 struct wim_lookup_table_entry *lte;
925 lte = new_lookup_table_entry();
927 return WIMLIB_ERR_NOMEM;
929 lte_bind_wim_resource_spec(lte, rspec);
930 lte->flags = rspec->flags;
931 lte->size = rspec->uncompressed_size;
932 lte->offset_in_res = 0;
934 ret = read_full_stream_into_alloc_buf(lte, buf_ret);
936 lte_unbind_wim_resource_spec(lte);
937 free_lookup_table_entry(lte);
941 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
942 * `wim_reshdr' and the corresponding WIM file. A large enough hold the data is
943 * allocated and returned in @buf_ret. */
945 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
947 DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
948 "uncompressed_size=%"PRIu64,
949 reshdr->offset_in_wim, reshdr->size_in_wim,
950 reshdr->uncompressed_size);
952 struct wim_resource_spec rspec;
953 wim_res_hdr_to_spec(reshdr, wim, &rspec);
954 return wim_resource_spec_to_data(&rspec, buf_ret);
958 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
959 u8 hash[SHA1_HASH_SIZE])
961 struct wim_resource_spec rspec;
963 struct wim_lookup_table_entry *lte;
965 wim_res_hdr_to_spec(reshdr, wim, &rspec);
967 lte = new_lookup_table_entry();
969 return WIMLIB_ERR_NOMEM;
971 lte_bind_wim_resource_spec(lte, &rspec);
972 lte->flags = rspec.flags;
973 lte->size = rspec.uncompressed_size;
974 lte->offset_in_res = 0;
977 ret = sha1_stream(lte);
979 lte_unbind_wim_resource_spec(lte);
980 copy_hash(hash, lte->hash);
981 free_lookup_table_entry(lte);
985 struct streamifier_context {
986 struct read_stream_list_callbacks cbs;
987 struct wim_lookup_table_entry *cur_stream;
988 struct wim_lookup_table_entry *next_stream;
989 u64 cur_stream_offset;
990 struct wim_lookup_table_entry *final_stream;
991 size_t list_head_offset;
994 static struct wim_lookup_table_entry *
995 next_stream(struct wim_lookup_table_entry *lte, size_t list_head_offset)
997 struct list_head *cur;
999 cur = (struct list_head*)((u8*)lte + list_head_offset);
1001 return (struct wim_lookup_table_entry*)((u8*)cur->next - list_head_offset);
1004 /* A consume_data_callback_t implementation that translates raw resource data
1005 * into streams, calling the begin_stream, consume_chunk, and end_stream
1006 * callback functions as appropriate. */
1008 streamifier_cb(const void *chunk, size_t size, void *_ctx)
1010 struct streamifier_context *ctx = _ctx;
1013 DEBUG("%zu bytes passed to streamifier", size);
1015 wimlib_assert(ctx->cur_stream != NULL);
1016 wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
1018 if (ctx->cur_stream_offset == 0) {
1020 /* Starting a new stream. */
1021 DEBUG("Begin new stream (size=%"PRIu64").",
1022 ctx->cur_stream->size);
1024 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream,
1025 ctx->cbs.begin_stream_ctx);
1030 /* Consume the chunk. */
1031 ret = (*ctx->cbs.consume_chunk)(chunk, size,
1032 ctx->cbs.consume_chunk_ctx);
1033 ctx->cur_stream_offset += size;
1037 if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1038 /* Finished reading all the data for a stream. */
1040 ctx->cur_stream_offset = 0;
1042 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1043 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1044 ctx->cbs.end_stream_ctx);
1048 /* Advance to next stream. */
1049 ctx->cur_stream = ctx->next_stream;
1050 if (ctx->cur_stream != NULL) {
1051 if (ctx->cur_stream != ctx->final_stream)
1052 ctx->next_stream = next_stream(ctx->cur_stream,
1053 ctx->list_head_offset);
1055 ctx->next_stream = NULL;
1061 struct hasher_context {
1064 struct read_stream_list_callbacks cbs;
1067 /* Callback for starting to read a stream while calculating its SHA1 message
1070 hasher_begin_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1072 struct hasher_context *ctx = _ctx;
1074 sha1_init(&ctx->sha_ctx);
1076 if (ctx->cbs.begin_stream == NULL)
1079 return (*ctx->cbs.begin_stream)(lte, ctx->cbs.begin_stream_ctx);
1082 /* A consume_data_callback_t implementation that continues calculating the SHA1
1083 * message digest of the stream being read, then optionally passes the data on
1084 * to another consume_data_callback_t implementation. This allows checking the
1085 * SHA1 message digest of a stream being extracted, for example. */
1087 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1089 struct hasher_context *ctx = _ctx;
1091 sha1_update(&ctx->sha_ctx, chunk, size);
1092 if (ctx->cbs.consume_chunk == NULL)
1095 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1099 get_sha1_string(const u8 md[SHA1_HASH_SIZE], tchar *str)
1101 for (size_t i = 0; i < SHA1_HASH_SIZE; i++)
1102 str += tsprintf(str, T("%02x"), md[i]);
1105 /* Callback for finishing reading a stream while calculating its SHA1 message
1108 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1110 struct hasher_context *ctx = _ctx;
1111 u8 hash[SHA1_HASH_SIZE];
1115 /* Error occurred; the full stream may not have been read. */
1120 /* Retrieve the final SHA1 message digest. */
1121 sha1_final(hash, &ctx->sha_ctx);
1123 if (lte->unhashed) {
1124 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1125 /* No SHA1 message digest was previously present for the
1126 * stream. Set it to the one just calculated. */
1127 DEBUG("Set SHA1 message digest for stream "
1128 "(size=%"PRIu64").", lte->size);
1129 copy_hash(lte->hash, hash);
1132 if (ctx->flags & VERIFY_STREAM_HASHES) {
1133 /* The stream already had a SHA1 message digest present. Verify
1134 * that it is the same as the calculated value. */
1135 if (!hashes_equal(hash, lte->hash)) {
1136 if (wimlib_print_errors) {
1137 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1138 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1139 get_sha1_string(lte->hash, expected_hashstr);
1140 get_sha1_string(hash, actual_hashstr);
1141 ERROR("The stream is corrupted!\n"
1142 " (Expected SHA1=%"TS",\n"
1144 expected_hashstr, actual_hashstr);
1146 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1150 DEBUG("SHA1 message digest okay for "
1151 "stream (size=%"PRIu64").", lte->size);
1156 if (ctx->cbs.end_stream == NULL)
1159 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1163 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1164 const struct read_stream_list_callbacks *cbs)
1168 ret = (*cbs->begin_stream)(lte, cbs->begin_stream_ctx);
1172 ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1173 cbs->consume_chunk_ctx);
1175 return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1178 /* Read the full data of the specified stream, passing the data into the
1179 * specified callbacks (all of which are optional) and either checking or
1180 * computing the SHA1 message digest of the stream. */
1182 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1183 const struct read_stream_list_callbacks *cbs)
1185 struct hasher_context hasher_ctx = {
1186 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1189 struct read_stream_list_callbacks hasher_cbs = {
1190 .begin_stream = hasher_begin_stream,
1191 .begin_stream_ctx = &hasher_ctx,
1192 .consume_chunk = hasher_consume_chunk,
1193 .consume_chunk_ctx = &hasher_ctx,
1194 .end_stream = hasher_end_stream,
1195 .end_stream_ctx = &hasher_ctx,
1197 return read_full_stream_with_cbs(lte, &hasher_cbs);
1201 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1202 struct wim_lookup_table_entry *last_stream,
1204 size_t list_head_offset,
1205 const struct read_stream_list_callbacks *sink_cbs)
1207 struct data_range *ranges;
1208 bool ranges_malloced;
1209 struct wim_lookup_table_entry *cur_stream;
1212 u64 ranges_alloc_size;
1214 DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1217 /* Setup data ranges array (one range per stream to read); this way
1218 * read_compressed_wim_resource() does not need to be aware of streams.
1221 ranges_alloc_size = stream_count * sizeof(ranges[0]);
1223 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1224 ERROR("Too many streams in one resource!");
1225 return WIMLIB_ERR_NOMEM;
1227 if (likely(ranges_alloc_size <= STACK_MAX)) {
1228 ranges = alloca(ranges_alloc_size);
1229 ranges_malloced = false;
1231 ranges = MALLOC(ranges_alloc_size);
1232 if (ranges == NULL) {
1233 ERROR("Too many streams in one resource!");
1234 return WIMLIB_ERR_NOMEM;
1236 ranges_malloced = true;
1239 for (i = 0, cur_stream = first_stream;
1241 i++, cur_stream = next_stream(cur_stream, list_head_offset))
1243 ranges[i].offset = cur_stream->offset_in_res;
1244 ranges[i].size = cur_stream->size;
1247 struct streamifier_context streamifier_ctx = {
1249 .cur_stream = first_stream,
1250 .next_stream = next_stream(first_stream, list_head_offset),
1251 .cur_stream_offset = 0,
1252 .final_stream = last_stream,
1253 .list_head_offset = list_head_offset,
1256 ret = read_compressed_wim_resource(first_stream->rspec,
1262 if (ranges_malloced)
1266 if (streamifier_ctx.cur_stream_offset != 0) {
1267 ret = (*streamifier_ctx.cbs.end_stream)
1268 (streamifier_ctx.cur_stream,
1270 streamifier_ctx.cbs.end_stream_ctx);
1277 * Read a list of streams, each of which may be in any supported location (e.g.
1278 * in a WIM or in an external file). Unlike read_stream_prefix() or the
1279 * functions which call it, this function optimizes the case where multiple
1280 * streams are packed into a single compressed WIM resource and reads them all
1281 * consecutively, only decompressing the data one time.
1284 * List of streams (represented as `struct wim_lookup_table_entry's) to
1287 * Offset of the `struct list_head' within each `struct
1288 * wim_lookup_table_entry' that makes up the @stream_list.
1290 * Callback functions to accept the stream data.
1292 * Bitwise OR of zero or more of the following flags:
1294 * VERIFY_STREAM_HASHES:
1295 * For all streams being read that have already had SHA1 message
1296 * digests computed, calculate the SHA1 message digest of the read
1297 * data and compare it with the previously computed value. If they
1298 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1300 * COMPUTE_MISSING_STREAM_HASHES
1301 * For all streams being read that have not yet had their SHA1
1302 * message digests computed, calculate and save their SHA1 message
1305 * STREAM_LIST_ALREADY_SORTED
1306 * @stream_list is already sorted in sequential order for reading.
1308 * The callback functions are allowed to delete the current stream from the list
1311 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1312 * to an error reading the data or due to an error status being returned by any
1313 * of the callback functions.
1316 read_stream_list(struct list_head *stream_list,
1317 size_t list_head_offset,
1318 const struct read_stream_list_callbacks *cbs,
1322 struct list_head *cur, *next;
1323 struct wim_lookup_table_entry *lte;
1324 struct hasher_context *hasher_ctx;
1325 struct read_stream_list_callbacks *sink_cbs;
1327 if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1328 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1333 if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1334 hasher_ctx = alloca(sizeof(*hasher_ctx));
1335 *hasher_ctx = (struct hasher_context) {
1339 sink_cbs = alloca(sizeof(*sink_cbs));
1340 *sink_cbs = (struct read_stream_list_callbacks) {
1341 .begin_stream = hasher_begin_stream,
1342 .begin_stream_ctx = hasher_ctx,
1343 .consume_chunk = hasher_consume_chunk,
1344 .consume_chunk_ctx = hasher_ctx,
1345 .end_stream = hasher_end_stream,
1346 .end_stream_ctx = hasher_ctx,
1349 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1352 for (cur = stream_list->next, next = cur->next;
1354 cur = next, next = cur->next)
1356 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1358 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1359 lte->size != lte->rspec->uncompressed_size)
1362 struct wim_lookup_table_entry *lte_next, *lte_last;
1363 struct list_head *next2;
1366 /* The next stream is a proper sub-sequence of a WIM
1367 * resource. See if there are other streams in the same
1368 * resource that need to be read. Since
1369 * sort_stream_list_by_sequential_order() sorted the
1370 * streams by offset in the WIM, this can be determined
1371 * by simply scanning forward in the list. */
1376 next2 != stream_list
1377 && (lte_next = (struct wim_lookup_table_entry*)
1378 ((u8*)next2 - list_head_offset),
1379 lte_next->resource_location == RESOURCE_IN_WIM
1380 && lte_next->rspec == lte->rspec);
1381 next2 = next2->next)
1383 lte_last = lte_next;
1386 if (stream_count > 1) {
1387 /* Reading multiple streams combined into a
1388 * single WIM resource. They are in the stream
1389 * list, sorted by offset; @lte specifies the
1390 * first stream in the resource that needs to be
1391 * read and @lte_last specifies the last stream
1392 * in the resource that needs to be read. */
1394 ret = read_packed_streams(lte, lte_last,
1404 ret = read_full_stream_with_cbs(lte, sink_cbs);
1405 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1411 /* Extract the first @size bytes of the specified stream.
1413 * If @size specifies the full uncompressed size of the stream, then the SHA1
1414 * message digest of the uncompressed stream is checked while being extracted.
1416 * The uncompressed data of the resource is passed in chunks of unspecified size
1417 * to the @extract_chunk function, passing it @extract_chunk_arg. */
1419 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1420 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1422 wimlib_assert(size <= lte->size);
1423 if (size == lte->size) {
1425 struct read_stream_list_callbacks cbs = {
1426 .consume_chunk = extract_chunk,
1427 .consume_chunk_ctx = extract_chunk_arg,
1429 return read_full_stream_with_sha1(lte, &cbs);
1431 /* Don't do SHA1. */
1432 return read_stream_prefix(lte, size, extract_chunk,
1437 /* A consume_data_callback_t implementation that writes the chunk of data to a
1438 * file descriptor. */
1440 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1442 struct filedes *fd = _fd_p;
1444 int ret = full_write(fd, chunk, size);
1446 ERROR_WITH_ERRNO("Error writing to file descriptor");
1452 /* Extract the first @size bytes of the specified stream to the specified file
1455 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1456 struct filedes *fd, u64 size)
1458 return extract_stream(lte, size, extract_chunk_to_fd, fd);
1461 /* Extract the full uncompressed contents of the specified stream to the
1462 * specified file descriptor. */
1464 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1467 return extract_stream_to_fd(lte, fd, lte->size);
1470 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash. */
1472 sha1_stream(struct wim_lookup_table_entry *lte)
1474 wimlib_assert(lte->unhashed);
1475 struct read_stream_list_callbacks cbs = {
1477 return read_full_stream_with_sha1(lte, &cbs);
1480 /* Convert a short WIM resource header to a stand-alone WIM resource
1483 * Note: for packed resources some fields still need to be overridden.
1486 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1487 struct wim_resource_spec *rspec)
1490 rspec->offset_in_wim = reshdr->offset_in_wim;
1491 rspec->size_in_wim = reshdr->size_in_wim;
1492 rspec->uncompressed_size = reshdr->uncompressed_size;
1493 INIT_LIST_HEAD(&rspec->stream_list);
1494 rspec->flags = reshdr->flags;
1495 rspec->is_pipable = wim_is_pipable(wim);
1496 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1497 rspec->compression_type = wim->compression_type;
1498 rspec->chunk_size = wim->chunk_size;
1500 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1501 rspec->chunk_size = 0;
1505 /* Convert a stand-alone resource specification to a WIM resource header. */
1507 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1508 struct wim_reshdr *reshdr)
1510 reshdr->offset_in_wim = rspec->offset_in_wim;
1511 reshdr->size_in_wim = rspec->size_in_wim;
1512 reshdr->flags = rspec->flags;
1513 reshdr->uncompressed_size = rspec->uncompressed_size;
1516 /* Translates a WIM resource header from the on-disk format into an in-memory
1519 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1520 struct wim_reshdr *reshdr)
1522 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1523 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1524 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1525 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1526 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1527 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1528 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1529 ((u64)disk_reshdr->size_in_wim[6] << 48));
1530 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1531 reshdr->flags = disk_reshdr->flags;
1534 /* Translates a WIM resource header from an in-memory format into the on-disk
1537 put_wim_reshdr(const struct wim_reshdr *reshdr,
1538 struct wim_reshdr_disk *disk_reshdr)
1540 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1541 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1542 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1543 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1544 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1545 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1546 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1547 disk_reshdr->flags = reshdr->flags;
1548 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1549 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);