4 * Code for reading streams and resources, including compressed WIM resources.
8 * Copyright (C) 2012, 2013 Eric Biggers
10 * This file is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 3 of the License, or (at your option) any
15 * This file is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this file; if not, see http://www.gnu.org/licenses/.
28 #include "wimlib/assert.h"
29 #include "wimlib/bitops.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;
142 bool chunk_offsets_malloced = false;
143 bool ubuf_malloced = false;
144 bool cbuf_malloced = false;
145 struct wimlib_decompressor *decompressor = NULL;
148 wimlib_assert(rspec != NULL);
149 wimlib_assert(resource_is_compressed(rspec));
150 wimlib_assert(cb != NULL);
151 wimlib_assert(num_ranges != 0);
152 for (size_t i = 0; i < num_ranges; i++) {
153 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
154 i + 1, num_ranges, ranges[i].size, ranges[i].offset,
155 rspec->uncompressed_size);
156 wimlib_assert(ranges[i].size != 0);
157 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
158 wimlib_assert(ranges[i].offset + ranges[i].size <= rspec->uncompressed_size);
160 for (size_t i = 0; i < num_ranges - 1; i++)
161 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
163 /* Get the offsets of the first and last bytes of the read. */
164 const u64 first_offset = ranges[0].offset;
165 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
167 /* Get the file descriptor for the WIM. */
168 struct filedes * const in_fd = &rspec->wim->in_fd;
170 /* Determine if we're reading a pipable resource from a pipe or not. */
171 const bool is_pipe_read = (rspec->is_pipable && !filedes_is_seekable(in_fd));
173 /* Determine if the chunk table is in an alternate format. */
174 const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
177 /* Get the maximum size of uncompressed chunks in this resource, which
178 * we require be a power of 2. */
179 u64 cur_read_offset = rspec->offset_in_wim;
180 int ctype = rspec->compression_type;
181 u32 chunk_size = rspec->chunk_size;
182 if (alt_chunk_table) {
183 /* Alternate chunk table format. Its header specifies the chunk
184 * size and compression format. Note: it could be read here;
185 * however, the relevant data was already loaded into @rspec by
186 * read_wim_lookup_table(). */
187 cur_read_offset += sizeof(struct alt_chunk_table_header_disk);
190 if (!is_power_of_2(chunk_size)) {
191 ERROR("Invalid compressed resource: "
192 "expected power-of-2 chunk size (got %"PRIu32")",
194 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
196 goto out_free_memory;
199 /* Get valid decompressor. */
200 if (ctype == rspec->wim->decompressor_ctype &&
201 chunk_size == rspec->wim->decompressor_max_block_size)
203 /* Cached decompressor. */
204 decompressor = rspec->wim->decompressor;
205 rspec->wim->decompressor_ctype = WIMLIB_COMPRESSION_TYPE_NONE;
206 rspec->wim->decompressor = NULL;
208 ret = wimlib_create_decompressor(ctype, chunk_size,
211 if (ret != WIMLIB_ERR_NOMEM)
213 goto out_free_memory;
217 const u32 chunk_order = fls32(chunk_size);
219 /* Calculate the total number of chunks the resource is divided into. */
220 const u64 num_chunks = (rspec->uncompressed_size + chunk_size - 1) >> chunk_order;
222 /* Calculate the 0-based indices of the first and last chunks containing
223 * data that needs to be passed to the callback. */
224 const u64 first_needed_chunk = first_offset >> chunk_order;
225 const u64 last_needed_chunk = last_offset >> chunk_order;
227 /* Calculate the 0-based index of the first chunk that actually needs to
228 * be read. This is normally first_needed_chunk, but for pipe reads we
229 * must always start from the 0th chunk. */
230 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
232 /* Calculate the number of chunk offsets that are needed for the chunks
234 const u64 num_needed_chunk_offsets =
235 last_needed_chunk - read_start_chunk + 1 +
236 (last_needed_chunk < num_chunks - 1);
238 /* Calculate the number of entries in the chunk table. Normally, it's
239 * one less than the number of chunks, since the first chunk has no
240 * entry. But in the alternate chunk table format, the chunk entries
241 * contain chunk sizes, not offsets, and there is one per chunk. */
242 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
244 /* Set the size of each chunk table entry based on the resource's
245 * uncompressed size. */
246 const u64 chunk_entry_size = get_chunk_entry_size(rspec->uncompressed_size,
249 /* Calculate the size of the chunk table in bytes. */
250 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
252 /* Calculate the size of the chunk table in bytes, including the header
253 * in the case of the alternate chunk table format. */
254 const u64 chunk_table_full_size =
255 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
259 /* Read the needed chunk table entries into memory and use them
260 * to initialize the chunk_offsets array. */
262 u64 first_chunk_entry_to_read;
263 u64 last_chunk_entry_to_read;
265 if (alt_chunk_table) {
266 /* The alternate chunk table contains chunk sizes, not
267 * offsets, so we always must read all preceding entries
268 * in order to determine offsets. */
269 first_chunk_entry_to_read = 0;
270 last_chunk_entry_to_read = last_needed_chunk;
272 /* Here we must account for the fact that the first
273 * chunk has no explicit chunk table entry. */
275 if (read_start_chunk == 0)
276 first_chunk_entry_to_read = 0;
278 first_chunk_entry_to_read = read_start_chunk - 1;
280 if (last_needed_chunk == 0)
281 last_chunk_entry_to_read = 0;
283 last_chunk_entry_to_read = last_needed_chunk - 1;
285 if (last_needed_chunk < num_chunks - 1)
286 last_chunk_entry_to_read++;
289 const u64 num_chunk_entries_to_read =
290 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
292 const u64 chunk_offsets_alloc_size =
293 max(num_chunk_entries_to_read,
294 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
296 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
299 if (chunk_offsets_alloc_size <= STACK_MAX) {
300 chunk_offsets = alloca(chunk_offsets_alloc_size);
302 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
303 if (chunk_offsets == NULL)
305 chunk_offsets_malloced = true;
308 const size_t chunk_table_size_to_read =
309 num_chunk_entries_to_read * chunk_entry_size;
311 const u64 file_offset_of_needed_chunk_entries =
313 + (first_chunk_entry_to_read * chunk_entry_size)
314 + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
316 void * const chunk_table_data =
318 chunk_offsets_alloc_size -
319 chunk_table_size_to_read;
321 ret = full_pread(in_fd, chunk_table_data, chunk_table_size_to_read,
322 file_offset_of_needed_chunk_entries);
326 /* Now fill in chunk_offsets from the entries we have read in
327 * chunk_tab_data. We break aliasing rules here to avoid having
328 * to allocate yet another array. */
329 typedef le64 _may_alias_attribute aliased_le64_t;
330 typedef le32 _may_alias_attribute aliased_le32_t;
331 u64 * chunk_offsets_p = chunk_offsets;
333 if (alt_chunk_table) {
335 aliased_le32_t *raw_entries = chunk_table_data;
337 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
338 u32 entry = le32_to_cpu(raw_entries[i]);
339 if (i >= read_start_chunk)
340 *chunk_offsets_p++ = cur_offset;
343 if (last_needed_chunk < num_chunks - 1)
344 *chunk_offsets_p = cur_offset;
346 if (read_start_chunk == 0)
347 *chunk_offsets_p++ = 0;
349 if (chunk_entry_size == 4) {
350 aliased_le32_t *raw_entries = chunk_table_data;
351 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
352 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
354 aliased_le64_t *raw_entries = chunk_table_data;
355 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
356 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
360 /* Set offset to beginning of first chunk to read. */
361 cur_read_offset += chunk_offsets[0];
362 if (rspec->is_pipable)
363 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
365 cur_read_offset += chunk_table_size;
368 /* Allocate buffer for holding the uncompressed data of each chunk. */
369 if (chunk_size <= STACK_MAX) {
370 ubuf = alloca(chunk_size);
372 ubuf = MALLOC(chunk_size);
375 ubuf_malloced = true;
378 /* Allocate a temporary buffer for reading compressed chunks, each of
379 * which can be at most @chunk_size - 1 bytes. This excludes compressed
380 * chunks that are a full @chunk_size bytes, which are actually stored
382 if (chunk_size - 1 <= STACK_MAX) {
383 cbuf = alloca(chunk_size - 1);
385 cbuf = MALLOC(chunk_size - 1);
388 cbuf_malloced = true;
391 /* Set current data range. */
392 const struct data_range *cur_range = ranges;
393 const struct data_range * const end_range = &ranges[num_ranges];
394 u64 cur_range_pos = cur_range->offset;
395 u64 cur_range_end = cur_range->offset + cur_range->size;
397 /* Read and process each needed chunk. */
398 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
400 /* Calculate uncompressed size of next chunk. */
402 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
403 chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
405 chunk_usize = chunk_size;
407 /* Calculate compressed size of next chunk. */
410 struct pwm_chunk_hdr chunk_hdr;
412 ret = full_pread(in_fd, &chunk_hdr,
413 sizeof(chunk_hdr), cur_read_offset);
416 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
418 if (i == num_chunks - 1) {
419 chunk_csize = rspec->size_in_wim -
420 chunk_table_full_size -
421 chunk_offsets[i - read_start_chunk];
422 if (rspec->is_pipable)
423 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
425 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
426 chunk_offsets[i - read_start_chunk];
429 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
430 ERROR("Invalid chunk size in compressed resource!");
432 ret = WIMLIB_ERR_DECOMPRESSION;
433 goto out_free_memory;
435 if (rspec->is_pipable)
436 cur_read_offset += sizeof(struct pwm_chunk_hdr);
438 /* Offsets in the uncompressed resource at which this chunk
439 * starts and ends. */
440 const u64 chunk_start_offset = i << chunk_order;
441 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
443 if (chunk_end_offset <= cur_range_pos) {
445 /* The next range does not require data in this chunk,
447 cur_read_offset += chunk_csize;
451 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
457 /* Read the chunk and feed data to the callback
461 if (chunk_csize == chunk_usize)
466 ret = full_pread(in_fd,
473 if (read_buf == cbuf) {
474 DEBUG("Decompressing chunk %"PRIu64" "
475 "(csize=%"PRIu32" usize=%"PRIu32")",
476 i, chunk_csize, chunk_usize);
477 ret = wimlib_decompress(cbuf,
483 ERROR("Failed to decompress data!");
484 ret = WIMLIB_ERR_DECOMPRESSION;
486 goto out_free_memory;
489 cur_read_offset += chunk_csize;
491 /* At least one range requires data in this chunk. */
493 size_t start, end, size;
495 /* Calculate how many bytes of data should be
496 * sent to the callback function, taking into
497 * account that data sent to the callback
498 * function must not overlap range boundaries.
500 start = cur_range_pos - chunk_start_offset;
501 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
504 ret = (*cb)(&ubuf[start], size, cb_ctx);
507 goto out_free_memory;
509 cur_range_pos += size;
510 if (cur_range_pos == cur_range_end) {
511 /* Advance to next range. */
512 if (++cur_range == end_range) {
513 cur_range_pos = ~0ULL;
515 cur_range_pos = cur_range->offset;
516 cur_range_end = cur_range->offset + cur_range->size;
519 } while (cur_range_pos < chunk_end_offset);
524 last_offset == rspec->uncompressed_size - 1 &&
528 /* If reading a pipable resource from a pipe and the full data
529 * was requested, skip the chunk table at the end so that the
530 * file descriptor is fully clear of the resource after this
532 cur_read_offset += chunk_table_size;
533 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
542 wimlib_free_decompressor(rspec->wim->decompressor);
543 rspec->wim->decompressor = decompressor;
544 rspec->wim->decompressor_ctype = ctype;
545 rspec->wim->decompressor_max_block_size = chunk_size;
547 if (chunk_offsets_malloced)
557 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
558 "from compressed WIM resource!", last_offset - first_offset + 1);
560 ret = WIMLIB_ERR_NOMEM;
561 goto out_free_memory;
564 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
565 goto out_free_memory;
569 fill_zeroes(u64 size, consume_data_callback_t cb, void *cb_ctx)
571 if (unlikely(size)) {
572 u8 buf[min(size, BUFFER_SIZE)];
574 memset(buf, 0, sizeof(buf));
580 len = min(size, BUFFER_SIZE);
581 ret = cb(buf, len, cb_ctx);
590 /* Read raw data from a file descriptor at the specified offset, feeding the
591 * data it in chunks into the specified callback function. */
593 read_raw_file_data(struct filedes *in_fd, u64 offset, u64 size,
594 consume_data_callback_t cb, void *cb_ctx)
597 size_t bytes_to_read;
601 bytes_to_read = min(sizeof(buf), size);
602 ret = full_pread(in_fd, buf, bytes_to_read, offset);
604 ERROR_WITH_ERRNO("Read error");
607 ret = cb(buf, bytes_to_read, cb_ctx);
610 size -= bytes_to_read;
611 offset += bytes_to_read;
616 /* A consume_data_callback_t implementation that simply concatenates all chunks
619 bufferer_cb(const void *chunk, size_t size, void *_ctx)
623 *buf_p = mempcpy(*buf_p, chunk, size);
628 * read_partial_wim_resource()-
630 * Read a range of data from an uncompressed or compressed resource in a WIM
634 * Specification of the WIM resource to read from.
636 * Offset within the uncompressed resource at which to start reading.
638 * Number of bytes to read.
640 * Callback function to feed the data being read. Each call provides the
641 * next chunk of the requested data, uncompressed. Each chunk will be of
642 * nonzero size and will not cross range boundaries, but otherwise will be
643 * of unspecified size.
645 * Parameter to pass to @cb_ctx.
648 * WIMLIB_ERR_SUCCESS (0)
649 * WIMLIB_ERR_READ (errno set)
650 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
651 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
652 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
654 * or other error code returned by the @cb function.
657 read_partial_wim_resource(const struct wim_resource_spec *rspec,
658 u64 offset, u64 size,
659 consume_data_callback_t cb, void *cb_ctx)
662 wimlib_assert(offset + size >= offset);
663 wimlib_assert(offset + size <= rspec->uncompressed_size);
665 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
666 "%"PRIu64" => %"PRIu64" @ %"PRIu64,
667 size, offset, rspec->uncompressed_size,
668 rspec->size_in_wim, rspec->offset_in_wim);
674 if (resource_is_compressed(rspec)) {
675 struct data_range range = {
679 return read_compressed_wim_resource(rspec, &range, 1,
682 /* Reading uncompressed resource. For completeness, handle the
683 * weird case where size_in_wim < uncompressed_size. */
689 if (likely(offset + size <= rspec->size_in_wim) ||
695 if (offset >= rspec->size_in_wim) {
699 read_size = rspec->size_in_wim - offset;
700 zeroes_size = offset + size - rspec->size_in_wim;
704 ret = read_raw_file_data(&rspec->wim->in_fd,
705 rspec->offset_in_wim + offset,
712 return fill_zeroes(zeroes_size, cb, cb_ctx);
716 /* Read the specified range of uncompressed data from the specified stream,
717 * which must be located into a WIM file, into the specified buffer. */
719 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
720 size_t size, u64 offset, void *_buf)
724 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
726 return read_partial_wim_resource(lte->rspec,
727 lte->offset_in_res + offset,
733 /* A consume_data_callback_t implementation that simply ignores the data
736 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
741 /* Skip over the data of the specified stream, which must correspond to a full
744 skip_wim_stream(struct wim_lookup_table_entry *lte)
746 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
747 wimlib_assert(!(lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS));
748 DEBUG("Skipping stream (size=%"PRIu64")", lte->size);
749 return read_partial_wim_resource(lte->rspec,
751 lte->rspec->uncompressed_size,
757 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
758 consume_data_callback_t cb, void *cb_ctx)
760 return read_partial_wim_resource(lte->rspec, lte->offset_in_res, size,
764 /* This function handles reading stream data that is located in an external
765 * file, such as a file that has been added to the WIM image through execution
766 * of a wimlib_add_command.
768 * This assumes the file can be accessed using the standard POSIX open(),
769 * read(), and close(). On Windows this will not necessarily be the case (since
770 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
771 * encrypted), so Windows uses its own code for its equivalent case. */
773 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
774 consume_data_callback_t cb, void *cb_ctx)
780 wimlib_assert(size <= lte->size);
782 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
784 raw_fd = topen(lte->file_on_disk, O_BINARY | O_RDONLY);
786 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
787 return WIMLIB_ERR_OPEN;
789 filedes_init(&fd, raw_fd);
790 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
797 read_staging_file_prefix(const struct wim_lookup_table_entry *lte, u64 size,
798 consume_data_callback_t cb, void *cb_ctx)
804 wimlib_assert(size <= lte->size);
806 DEBUG("Reading %"PRIu64" bytes from staging file \"%s\"",
807 size, lte->staging_file_name);
809 raw_fd = openat(lte->staging_dir_fd, lte->staging_file_name,
810 O_RDONLY | O_NOFOLLOW);
812 ERROR_WITH_ERRNO("Can't open staging file \"%s\"",
813 lte->staging_file_name);
814 return WIMLIB_ERR_OPEN;
816 filedes_init(&fd, raw_fd);
817 ret = read_raw_file_data(&fd, 0, size, cb, cb_ctx);
823 /* This function handles the trivial case of reading stream data that is, in
824 * fact, already located in an in-memory buffer. */
826 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
827 u64 size, consume_data_callback_t cb, void *cb_ctx)
829 wimlib_assert(size <= lte->size);
830 return (*cb)(lte->attached_buffer, size, cb_ctx);
833 typedef int (*read_stream_prefix_handler_t)(const struct wim_lookup_table_entry *lte,
835 consume_data_callback_t cb,
839 * read_stream_prefix()-
841 * Reads the first @size bytes from a generic "stream", which may be located in
842 * any one of several locations, such as in a WIM file (compressed or
843 * uncompressed), in an external file, or directly in an in-memory buffer.
845 * This function feeds the data to a callback function @cb in chunks of
848 * Returns 0 on success; nonzero on error. A nonzero value will be returned if
849 * the stream data cannot be successfully read (for a number of different
850 * reasons, depending on the stream location), or if @cb returned nonzero in
851 * which case that error code will be returned.
854 read_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
855 consume_data_callback_t cb, void *cb_ctx)
857 static const read_stream_prefix_handler_t handlers[] = {
858 [RESOURCE_IN_WIM] = read_wim_stream_prefix,
859 [RESOURCE_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
860 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
862 [RESOURCE_IN_STAGING_FILE] = read_staging_file_prefix,
865 [RESOURCE_IN_NTFS_VOLUME] = read_ntfs_file_prefix,
868 [RESOURCE_IN_WINNT_FILE_ON_DISK] = read_winnt_file_prefix,
869 [RESOURCE_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
872 wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
873 && handlers[lte->resource_location] != NULL);
874 return handlers[lte->resource_location](lte, size, cb, cb_ctx);
877 /* Read the full uncompressed data of the specified stream into the specified
878 * buffer, which must have space for at least lte->size bytes. */
880 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
883 return read_stream_prefix(lte, lte->size, bufferer_cb, &buf);
886 /* Retrieve the full uncompressed data of the specified stream. A buffer large
887 * enough hold the data is allocated and returned in @buf_ret. */
889 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
895 if ((size_t)lte->size != lte->size) {
896 ERROR("Can't read %"PRIu64" byte stream into "
897 "memory", lte->size);
898 return WIMLIB_ERR_NOMEM;
901 buf = MALLOC(lte->size);
903 return WIMLIB_ERR_NOMEM;
905 ret = read_full_stream_into_buf(lte, buf);
915 /* Retrieve the full uncompressed data of the specified WIM resource. A buffer
916 * large enough hold the data is allocated and returned in @buf_ret. */
918 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
921 struct wim_lookup_table_entry *lte;
923 lte = new_lookup_table_entry();
925 return WIMLIB_ERR_NOMEM;
927 lte_bind_wim_resource_spec(lte, rspec);
928 lte->flags = rspec->flags;
929 lte->size = rspec->uncompressed_size;
930 lte->offset_in_res = 0;
932 ret = read_full_stream_into_alloc_buf(lte, buf_ret);
934 lte_unbind_wim_resource_spec(lte);
935 free_lookup_table_entry(lte);
939 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
940 * `wim_reshdr' and the corresponding WIM file. A large enough hold the data is
941 * allocated and returned in @buf_ret. */
943 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
945 DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
946 "uncompressed_size=%"PRIu64,
947 reshdr->offset_in_wim, reshdr->size_in_wim,
948 reshdr->uncompressed_size);
950 struct wim_resource_spec rspec;
951 wim_res_hdr_to_spec(reshdr, wim, &rspec);
952 return wim_resource_spec_to_data(&rspec, buf_ret);
956 wim_reshdr_to_hash(const struct wim_reshdr *reshdr, WIMStruct *wim,
957 u8 hash[SHA1_HASH_SIZE])
959 struct wim_resource_spec rspec;
961 struct wim_lookup_table_entry *lte;
963 wim_res_hdr_to_spec(reshdr, wim, &rspec);
965 lte = new_lookup_table_entry();
967 return WIMLIB_ERR_NOMEM;
969 lte_bind_wim_resource_spec(lte, &rspec);
970 lte->flags = rspec.flags;
971 lte->size = rspec.uncompressed_size;
972 lte->offset_in_res = 0;
975 ret = sha1_stream(lte);
977 lte_unbind_wim_resource_spec(lte);
978 copy_hash(hash, lte->hash);
979 free_lookup_table_entry(lte);
983 struct streamifier_context {
984 struct read_stream_list_callbacks cbs;
985 struct wim_lookup_table_entry *cur_stream;
986 struct wim_lookup_table_entry *next_stream;
987 u64 cur_stream_offset;
988 struct wim_lookup_table_entry *final_stream;
989 size_t list_head_offset;
992 static struct wim_lookup_table_entry *
993 next_stream(struct wim_lookup_table_entry *lte, size_t list_head_offset)
995 struct list_head *cur;
997 cur = (struct list_head*)((u8*)lte + list_head_offset);
999 return (struct wim_lookup_table_entry*)((u8*)cur->next - list_head_offset);
1002 /* A consume_data_callback_t implementation that translates raw resource data
1003 * into streams, calling the begin_stream, consume_chunk, and end_stream
1004 * callback functions as appropriate. */
1006 streamifier_cb(const void *chunk, size_t size, void *_ctx)
1008 struct streamifier_context *ctx = _ctx;
1011 DEBUG("%zu bytes passed to streamifier", size);
1013 wimlib_assert(ctx->cur_stream != NULL);
1014 wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
1016 if (ctx->cur_stream_offset == 0) {
1018 /* Starting a new stream. */
1019 DEBUG("Begin new stream (size=%"PRIu64").",
1020 ctx->cur_stream->size);
1022 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream,
1023 ctx->cbs.begin_stream_ctx);
1028 /* Consume the chunk. */
1029 ret = (*ctx->cbs.consume_chunk)(chunk, size,
1030 ctx->cbs.consume_chunk_ctx);
1031 ctx->cur_stream_offset += size;
1035 if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1036 /* Finished reading all the data for a stream. */
1038 ctx->cur_stream_offset = 0;
1040 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1041 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1042 ctx->cbs.end_stream_ctx);
1046 /* Advance to next stream. */
1047 ctx->cur_stream = ctx->next_stream;
1048 if (ctx->cur_stream != NULL) {
1049 if (ctx->cur_stream != ctx->final_stream)
1050 ctx->next_stream = next_stream(ctx->cur_stream,
1051 ctx->list_head_offset);
1053 ctx->next_stream = NULL;
1059 struct hasher_context {
1062 struct read_stream_list_callbacks cbs;
1065 /* Callback for starting to read a stream while calculating its SHA1 message
1068 hasher_begin_stream(struct wim_lookup_table_entry *lte, void *_ctx)
1070 struct hasher_context *ctx = _ctx;
1072 sha1_init(&ctx->sha_ctx);
1074 if (ctx->cbs.begin_stream == NULL)
1077 return (*ctx->cbs.begin_stream)(lte, ctx->cbs.begin_stream_ctx);
1080 /* A consume_data_callback_t implementation that continues calculating the SHA1
1081 * message digest of the stream being read, then optionally passes the data on
1082 * to another consume_data_callback_t implementation. This allows checking the
1083 * SHA1 message digest of a stream being extracted, for example. */
1085 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1087 struct hasher_context *ctx = _ctx;
1089 sha1_update(&ctx->sha_ctx, chunk, size);
1090 if (ctx->cbs.consume_chunk == NULL)
1093 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1096 /* Callback for finishing reading a stream while calculating its SHA1 message
1099 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1101 struct hasher_context *ctx = _ctx;
1102 u8 hash[SHA1_HASH_SIZE];
1106 /* Error occurred; the full stream may not have been read. */
1111 /* Retrieve the final SHA1 message digest. */
1112 sha1_final(hash, &ctx->sha_ctx);
1114 if (lte->unhashed) {
1115 if (ctx->flags & COMPUTE_MISSING_STREAM_HASHES) {
1116 /* No SHA1 message digest was previously present for the
1117 * stream. Set it to the one just calculated. */
1118 DEBUG("Set SHA1 message digest for stream "
1119 "(size=%"PRIu64").", lte->size);
1120 copy_hash(lte->hash, hash);
1123 if (ctx->flags & VERIFY_STREAM_HASHES) {
1124 /* The stream already had a SHA1 message digest present. Verify
1125 * that it is the same as the calculated value. */
1126 if (!hashes_equal(hash, lte->hash)) {
1127 if (wimlib_print_errors) {
1128 tchar expected_hashstr[SHA1_HASH_SIZE * 2 + 1];
1129 tchar actual_hashstr[SHA1_HASH_SIZE * 2 + 1];
1130 sprint_hash(lte->hash, expected_hashstr);
1131 sprint_hash(hash, actual_hashstr);
1132 ERROR("The stream is corrupted!\n"
1133 " (Expected SHA1=%"TS",\n"
1135 expected_hashstr, actual_hashstr);
1137 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1141 DEBUG("SHA1 message digest okay for "
1142 "stream (size=%"PRIu64").", lte->size);
1147 if (ctx->cbs.end_stream == NULL)
1150 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1154 read_full_stream_with_cbs(struct wim_lookup_table_entry *lte,
1155 const struct read_stream_list_callbacks *cbs)
1159 ret = (*cbs->begin_stream)(lte, cbs->begin_stream_ctx);
1163 ret = read_stream_prefix(lte, lte->size, cbs->consume_chunk,
1164 cbs->consume_chunk_ctx);
1166 return (*cbs->end_stream)(lte, ret, cbs->end_stream_ctx);
1169 /* Read the full data of the specified stream, passing the data into the
1170 * specified callbacks (all of which are optional) and either checking or
1171 * computing the SHA1 message digest of the stream. */
1173 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1174 const struct read_stream_list_callbacks *cbs)
1176 struct hasher_context hasher_ctx = {
1177 .flags = VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES,
1180 struct read_stream_list_callbacks hasher_cbs = {
1181 .begin_stream = hasher_begin_stream,
1182 .begin_stream_ctx = &hasher_ctx,
1183 .consume_chunk = hasher_consume_chunk,
1184 .consume_chunk_ctx = &hasher_ctx,
1185 .end_stream = hasher_end_stream,
1186 .end_stream_ctx = &hasher_ctx,
1188 return read_full_stream_with_cbs(lte, &hasher_cbs);
1192 read_packed_streams(struct wim_lookup_table_entry *first_stream,
1193 struct wim_lookup_table_entry *last_stream,
1195 size_t list_head_offset,
1196 const struct read_stream_list_callbacks *sink_cbs)
1198 struct data_range *ranges;
1199 bool ranges_malloced;
1200 struct wim_lookup_table_entry *cur_stream;
1203 u64 ranges_alloc_size;
1205 DEBUG("Reading %"PRIu64" streams combined in same WIM resource",
1208 /* Setup data ranges array (one range per stream to read); this way
1209 * read_compressed_wim_resource() does not need to be aware of streams.
1212 ranges_alloc_size = stream_count * sizeof(ranges[0]);
1214 if (unlikely((size_t)ranges_alloc_size != ranges_alloc_size)) {
1215 ERROR("Too many streams in one resource!");
1216 return WIMLIB_ERR_NOMEM;
1218 if (likely(ranges_alloc_size <= STACK_MAX)) {
1219 ranges = alloca(ranges_alloc_size);
1220 ranges_malloced = false;
1222 ranges = MALLOC(ranges_alloc_size);
1223 if (ranges == NULL) {
1224 ERROR("Too many streams in one resource!");
1225 return WIMLIB_ERR_NOMEM;
1227 ranges_malloced = true;
1230 for (i = 0, cur_stream = first_stream;
1232 i++, cur_stream = next_stream(cur_stream, list_head_offset))
1234 ranges[i].offset = cur_stream->offset_in_res;
1235 ranges[i].size = cur_stream->size;
1238 struct streamifier_context streamifier_ctx = {
1240 .cur_stream = first_stream,
1241 .next_stream = next_stream(first_stream, list_head_offset),
1242 .cur_stream_offset = 0,
1243 .final_stream = last_stream,
1244 .list_head_offset = list_head_offset,
1247 ret = read_compressed_wim_resource(first_stream->rspec,
1253 if (ranges_malloced)
1257 if (streamifier_ctx.cur_stream_offset != 0) {
1258 ret = (*streamifier_ctx.cbs.end_stream)
1259 (streamifier_ctx.cur_stream,
1261 streamifier_ctx.cbs.end_stream_ctx);
1268 * Read a list of streams, each of which may be in any supported location (e.g.
1269 * in a WIM or in an external file). Unlike read_stream_prefix() or the
1270 * functions which call it, this function optimizes the case where multiple
1271 * streams are packed into a single compressed WIM resource and reads them all
1272 * consecutively, only decompressing the data one time.
1275 * List of streams (represented as `struct wim_lookup_table_entry's) to
1278 * Offset of the `struct list_head' within each `struct
1279 * wim_lookup_table_entry' that makes up the @stream_list.
1281 * Callback functions to accept the stream data.
1283 * Bitwise OR of zero or more of the following flags:
1285 * VERIFY_STREAM_HASHES:
1286 * For all streams being read that have already had SHA1 message
1287 * digests computed, calculate the SHA1 message digest of the read
1288 * data and compare it with the previously computed value. If they
1289 * do not match, return WIMLIB_ERR_INVALID_RESOURCE_HASH.
1291 * COMPUTE_MISSING_STREAM_HASHES
1292 * For all streams being read that have not yet had their SHA1
1293 * message digests computed, calculate and save their SHA1 message
1296 * STREAM_LIST_ALREADY_SORTED
1297 * @stream_list is already sorted in sequential order for reading.
1299 * The callback functions are allowed to delete the current stream from the list
1302 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1303 * to an error reading the data or due to an error status being returned by any
1304 * of the callback functions.
1307 read_stream_list(struct list_head *stream_list,
1308 size_t list_head_offset,
1309 const struct read_stream_list_callbacks *cbs,
1313 struct list_head *cur, *next;
1314 struct wim_lookup_table_entry *lte;
1315 struct hasher_context *hasher_ctx;
1316 struct read_stream_list_callbacks *sink_cbs;
1318 if (!(flags & STREAM_LIST_ALREADY_SORTED)) {
1319 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1324 if (flags & (VERIFY_STREAM_HASHES | COMPUTE_MISSING_STREAM_HASHES)) {
1325 hasher_ctx = alloca(sizeof(*hasher_ctx));
1326 *hasher_ctx = (struct hasher_context) {
1330 sink_cbs = alloca(sizeof(*sink_cbs));
1331 *sink_cbs = (struct read_stream_list_callbacks) {
1332 .begin_stream = hasher_begin_stream,
1333 .begin_stream_ctx = hasher_ctx,
1334 .consume_chunk = hasher_consume_chunk,
1335 .consume_chunk_ctx = hasher_ctx,
1336 .end_stream = hasher_end_stream,
1337 .end_stream_ctx = hasher_ctx,
1340 sink_cbs = (struct read_stream_list_callbacks*)cbs;
1343 for (cur = stream_list->next, next = cur->next;
1345 cur = next, next = cur->next)
1347 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1349 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1350 lte->size != lte->rspec->uncompressed_size)
1353 struct wim_lookup_table_entry *lte_next, *lte_last;
1354 struct list_head *next2;
1357 /* The next stream is a proper sub-sequence of a WIM
1358 * resource. See if there are other streams in the same
1359 * resource that need to be read. Since
1360 * sort_stream_list_by_sequential_order() sorted the
1361 * streams by offset in the WIM, this can be determined
1362 * by simply scanning forward in the list. */
1367 next2 != stream_list
1368 && (lte_next = (struct wim_lookup_table_entry*)
1369 ((u8*)next2 - list_head_offset),
1370 lte_next->resource_location == RESOURCE_IN_WIM
1371 && lte_next->rspec == lte->rspec);
1372 next2 = next2->next)
1374 lte_last = lte_next;
1377 if (stream_count > 1) {
1378 /* Reading multiple streams combined into a
1379 * single WIM resource. They are in the stream
1380 * list, sorted by offset; @lte specifies the
1381 * first stream in the resource that needs to be
1382 * read and @lte_last specifies the last stream
1383 * in the resource that needs to be read. */
1385 ret = read_packed_streams(lte, lte_last,
1395 ret = read_full_stream_with_cbs(lte, sink_cbs);
1396 if (ret && ret != BEGIN_STREAM_STATUS_SKIP_STREAM)
1402 /* Extract the first @size bytes of the specified stream.
1404 * If @size specifies the full uncompressed size of the stream, then the SHA1
1405 * message digest of the uncompressed stream is checked while being extracted.
1407 * The uncompressed data of the resource is passed in chunks of unspecified size
1408 * to the @extract_chunk function, passing it @extract_chunk_arg. */
1410 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1411 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1413 wimlib_assert(size <= lte->size);
1414 if (size == lte->size) {
1416 struct read_stream_list_callbacks cbs = {
1417 .consume_chunk = extract_chunk,
1418 .consume_chunk_ctx = extract_chunk_arg,
1420 return read_full_stream_with_sha1(lte, &cbs);
1422 /* Don't do SHA1. */
1423 return read_stream_prefix(lte, size, extract_chunk,
1428 /* A consume_data_callback_t implementation that writes the chunk of data to a
1429 * file descriptor. */
1431 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1433 struct filedes *fd = _fd_p;
1435 int ret = full_write(fd, chunk, size);
1437 ERROR_WITH_ERRNO("Error writing to file descriptor");
1443 /* Extract the first @size bytes of the specified stream to the specified file
1446 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1447 struct filedes *fd, u64 size)
1449 return extract_stream(lte, size, extract_chunk_to_fd, fd);
1452 /* Extract the full uncompressed contents of the specified stream to the
1453 * specified file descriptor. */
1455 extract_full_stream_to_fd(struct wim_lookup_table_entry *lte,
1458 return extract_stream_to_fd(lte, fd, lte->size);
1461 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash. */
1463 sha1_stream(struct wim_lookup_table_entry *lte)
1465 wimlib_assert(lte->unhashed);
1466 struct read_stream_list_callbacks cbs = {
1468 return read_full_stream_with_sha1(lte, &cbs);
1471 /* Convert a short WIM resource header to a stand-alone WIM resource
1474 * Note: for packed resources some fields still need to be overridden.
1477 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1478 struct wim_resource_spec *rspec)
1481 rspec->offset_in_wim = reshdr->offset_in_wim;
1482 rspec->size_in_wim = reshdr->size_in_wim;
1483 rspec->uncompressed_size = reshdr->uncompressed_size;
1484 INIT_LIST_HEAD(&rspec->stream_list);
1485 rspec->flags = reshdr->flags;
1486 rspec->is_pipable = wim_is_pipable(wim);
1487 if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED) {
1488 rspec->compression_type = wim->compression_type;
1489 rspec->chunk_size = wim->chunk_size;
1491 rspec->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
1492 rspec->chunk_size = 0;
1496 /* Convert a stand-alone resource specification to a WIM resource header. */
1498 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1499 struct wim_reshdr *reshdr)
1501 reshdr->offset_in_wim = rspec->offset_in_wim;
1502 reshdr->size_in_wim = rspec->size_in_wim;
1503 reshdr->flags = rspec->flags;
1504 reshdr->uncompressed_size = rspec->uncompressed_size;
1507 /* Translates a WIM resource header from the on-disk format into an in-memory
1510 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1511 struct wim_reshdr *reshdr)
1513 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1514 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1515 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1516 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1517 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1518 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1519 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1520 ((u64)disk_reshdr->size_in_wim[6] << 48));
1521 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1522 reshdr->flags = disk_reshdr->flags;
1525 /* Translates a WIM resource header from an in-memory format into the on-disk
1528 put_wim_reshdr(const struct wim_reshdr *reshdr,
1529 struct wim_reshdr_disk *disk_reshdr)
1531 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1532 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1533 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1534 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1535 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1536 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1537 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1538 disk_reshdr->flags = reshdr->flags;
1539 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1540 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);