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/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"
38 /* for read_win32_file_prefix(), read_win32_encrypted_file_prefix() */
39 # include "wimlib/win32.h"
43 /* for read_ntfs_file_prefix() */
44 # include "wimlib/ntfs_3g.h"
56 * Compressed WIM resources
58 * A compressed resource in a WIM consists of a number of compressed chunks,
59 * each of which decompresses to a fixed chunk size (given in the WIM header;
60 * usually 32768) except possibly the last, which always decompresses to any
61 * remaining bytes. In addition, immediately before the chunks, a table (the
62 * "chunk table") provides the offset, in bytes relative to the end of the chunk
63 * table, of the start of each compressed chunk, except for the first chunk
64 * which is omitted as it always has an offset of 0. Therefore, a compressed
65 * resource with N chunks will have a chunk table with N - 1 entries.
67 * Additional information:
69 * - Entries in the chunk table are 4 bytes each, except if the uncompressed
70 * size of the resource is greater than 4 GiB, in which case the entries in
71 * the chunk table are 8 bytes each. In either case, the entries are unsigned
72 * little-endian integers.
74 * - The chunk table is included in the compressed size of the resource provided
75 * in the corresponding entry in the WIM's stream lookup table.
77 * - The compressed size of a chunk is never greater than the uncompressed size.
78 * From the compressor's point of view, chunks that would have compressed to a
79 * size greater than or equal to their original size are in fact stored
80 * uncompressed. From the decompresser's point of view, chunks with
81 * compressed size equal to their uncompressed size are in fact uncompressed.
83 * Furthermore, wimlib supports its own "pipable" WIM format, and for this the
84 * structure of compressed resources was modified to allow piped reading and
85 * writing. To make sequential writing possible, the chunk table is placed
86 * after the chunks rather than before the chunks, and to make sequential
87 * reading possible, each chunk is prefixed with a 4-byte header giving its
88 * compressed size as a 32-bit, unsigned, little-endian integer. Otherwise the
89 * details are the same.
93 /* Decompress the specified chunk that uses the specified compression type
94 * @ctype, part of a WIM with default chunk size @wim_chunk_size. For LZX the
95 * separate @wim_chunk_size is needed because it determines the window size used
96 * for LZX compression. */
98 decompress(const void *cchunk, unsigned clen, void *uchunk, unsigned ulen,
99 int ctype, u32 wim_chunk_size)
102 case WIMLIB_COMPRESSION_TYPE_LZX:
103 return wimlib_lzx_decompress2(cchunk, clen,
104 uchunk, ulen, wim_chunk_size);
105 case WIMLIB_COMPRESSION_TYPE_XPRESS:
106 return wimlib_xpress_decompress(cchunk, clen,
108 case WIMLIB_COMPRESSION_TYPE_LZMS:
109 return wimlib_lzms_decompress(cchunk, clen, uchunk, ulen);
111 ERROR("Invalid compression format (%d)", ctype);
121 /* Alternate chunk table format for resources with
122 * WIM_RESHDR_FLAG_PACKED_STREAMS set. */
123 struct alt_chunk_table_header_disk {
124 /* Uncompressed size of the resource in bytes. */
127 /* Number of bytes each compressed chunk decompresses into, except
128 * possibly the last which decompresses into the remainder. */
131 /* Compression format used for compressed chunks:
136 le32 compression_format;
138 /* This header is directly followed by a table of compressed sizes of
143 * read_compressed_wim_resource() -
145 * Read data from a compressed WIM resource.
148 * Specification of the compressed WIM resource to read from.
150 * Nonoverlapping, nonempty ranges of the uncompressed resource data to
151 * read, sorted by increasing offset.
153 * Number of ranges in @ranges; must be at least 1.
155 * Callback function to feed the data being read. Each call provides the
156 * next chunk of the requested data. Each chunk will be of nonzero size
157 * and will not cross range boundaries, but otherwise is of unspecified
160 * Parameter to pass to @cb_ctx.
162 * If %true, this function will provide the raw compressed chunks of the
163 * resource rather than the uncompressed data. In this mode, only a single
164 * data range can be requested, and it must cover the entire uncompressed
167 * Possible return values:
169 * WIMLIB_ERR_SUCCESS (0)
170 * WIMLIB_ERR_READ (errno set)
171 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
172 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
173 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
175 * or other error code returned by the @cb function.
178 read_compressed_wim_resource(const struct wim_resource_spec * const rspec,
179 const struct data_range * const ranges,
180 const size_t num_ranges,
181 const consume_data_callback_t cb,
183 const bool raw_chunks_mode)
188 u64 *chunk_offsets = NULL;
191 bool chunk_offsets_malloced = false;
192 bool ubuf_malloced = false;
193 bool cbuf_malloced = false;
196 wimlib_assert(rspec != NULL);
197 wimlib_assert(resource_is_compressed(rspec));
198 wimlib_assert(cb != NULL);
199 wimlib_assert(num_ranges != 0);
200 for (size_t i = 0; i < num_ranges; i++) {
201 DEBUG("Range %zu/%zu: %"PRIu64"@+%"PRIu64" / %"PRIu64,
202 i + 1, num_ranges, ranges[i].size, ranges[i].offset,
203 rspec->uncompressed_size);
204 wimlib_assert(ranges[i].size != 0);
205 wimlib_assert(ranges[i].offset + ranges[i].size >= ranges[i].size);
206 wimlib_assert(ranges[i].offset + ranges[i].size <= rspec->uncompressed_size);
208 for (size_t i = 0; i < num_ranges - 1; i++)
209 wimlib_assert(ranges[i].offset + ranges[i].size <= ranges[i + 1].offset);
211 if (raw_chunks_mode) {
212 wimlib_assert(num_ranges == 1);
213 wimlib_assert(ranges[0].offset == 0);
214 wimlib_assert(ranges[0].size == rspec->uncompressed_size);
217 /* Get the offsets of the first and last bytes of the read. */
218 const u64 first_offset = ranges[0].offset;
219 const u64 last_offset = ranges[num_ranges - 1].offset + ranges[num_ranges - 1].size - 1;
221 /* Get the file descriptor for the WIM. */
222 struct filedes * const in_fd = &rspec->wim->in_fd;
224 /* Determine if we're reading a pipable resource from a pipe or not. */
225 const bool is_pipe_read = !filedes_is_seekable(in_fd);
227 /* Determine if the chunk table is in an altenate format. */
228 const bool alt_chunk_table = (rspec->flags & WIM_RESHDR_FLAG_PACKED_STREAMS)
231 /* Get the maximum size of uncompressed chunks in this resource, which
232 * we require be a power of 2. */
234 u64 cur_read_offset = rspec->offset_in_wim;
236 if (alt_chunk_table) {
237 /* Alternate chunk table format. Its header specifies the chunk
238 * size and compression format. */
239 struct alt_chunk_table_header_disk hdr;
241 ret = full_pread(in_fd, &hdr, sizeof(hdr), cur_read_offset);
244 cur_read_offset += sizeof(hdr);
246 chunk_size = le32_to_cpu(hdr.chunk_size);
247 ctype = le32_to_cpu(hdr.compression_format);
249 /* Format numbers must be the same as in WIMGAPI to be
251 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_NONE != 0);
252 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 1);
253 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 2);
254 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
256 /* "Normal" format: the maximum uncompressed chunk size and the
257 * compression format default to those of the WIM itself. */
258 chunk_size = rspec->wim->chunk_size;
259 ctype = rspec->wim->compression_type;
261 if (!is_power_of_2(chunk_size)) {
262 ERROR("Invalid compressed resource: "
263 "expected power-of-2 chunk size (got %u)", chunk_size);
264 ret = WIMLIB_ERR_INVALID_CHUNK_SIZE;
265 goto out_free_memory;
268 const u32 chunk_order = bsr32(chunk_size);
270 /* Calculate the total number of chunks the resource is divided into. */
271 const u64 num_chunks = (rspec->uncompressed_size + chunk_size - 1) >> chunk_order;
273 /* Calculate the 0-based indices of the first and last chunks containing
274 * data that needs to be passed to the callback. */
275 const u64 first_needed_chunk = first_offset >> chunk_order;
276 const u64 last_needed_chunk = last_offset >> chunk_order;
278 /* Calculate the 0-based index of the first chunk that actually needs to
279 * be read. This is normally first_needed_chunk, but for pipe reads we
280 * must always start from the 0th chunk. */
281 const u64 read_start_chunk = (is_pipe_read ? 0 : first_needed_chunk);
283 /* Calculate the number of chunk offsets that are needed for the chunks
285 const u64 num_needed_chunk_offsets =
286 last_needed_chunk - read_start_chunk + 1 +
287 (last_needed_chunk < num_chunks - 1);
289 /* Calculate the number of entries in the chunk table. Normally, it's
290 * one less than the number of chunks, since the first chunk has no
291 * entry. But in the alternate chunk table format, the chunk entries
292 * contain chunk sizes, not offsets, and there is one per chunk. */
293 const u64 num_chunk_entries = (alt_chunk_table ? num_chunks : num_chunks - 1);
295 /* Set the size of each chunk table entry based on the resource's
296 * uncompressed size. XXX: Does the alternate chunk table really
297 * always have 4-byte entries? */
298 const u64 chunk_entry_size =
299 (rspec->uncompressed_size > (1ULL << 32) && !alt_chunk_table)
302 /* Calculate the size of the chunk table in bytes. */
303 const u64 chunk_table_size = num_chunk_entries * chunk_entry_size;
305 /* Calculate the size of the chunk table in bytes, including the header
306 * in the case of the alternate chunk table format. */
307 const u64 chunk_table_full_size =
308 (alt_chunk_table) ? chunk_table_size + sizeof(struct alt_chunk_table_header_disk)
312 /* Read the needed chunk table entries into memory and use them
313 * to initialize the chunk_offsets array. */
315 u64 first_chunk_entry_to_read;
316 u64 last_chunk_entry_to_read;
318 if (alt_chunk_table) {
319 /* The alternate chunk table contains chunk sizes, not
320 * offsets, so we always must read all preceding entries
321 * in order to determine offsets. */
322 first_chunk_entry_to_read = 0;
323 last_chunk_entry_to_read = last_needed_chunk;
325 /* Here we must account for the fact that the first
326 * chunk has no explicit chunk table entry. */
328 if (read_start_chunk == 0)
329 first_chunk_entry_to_read = 0;
331 first_chunk_entry_to_read = read_start_chunk - 1;
333 if (last_needed_chunk == 0)
334 last_chunk_entry_to_read = 0;
336 last_chunk_entry_to_read = last_needed_chunk - 1;
338 if (last_needed_chunk < num_chunks - 1)
339 last_chunk_entry_to_read++;
342 const u64 num_chunk_entries_to_read =
343 last_chunk_entry_to_read - first_chunk_entry_to_read + 1;
345 const u64 chunk_offsets_alloc_size =
346 max(num_chunk_entries_to_read,
347 num_needed_chunk_offsets) * sizeof(chunk_offsets[0]);
349 if ((size_t)chunk_offsets_alloc_size != chunk_offsets_alloc_size)
352 if (chunk_offsets_alloc_size <= STACK_MAX) {
353 chunk_offsets = alloca(chunk_offsets_alloc_size);
355 chunk_offsets = MALLOC(chunk_offsets_alloc_size);
356 if (chunk_offsets == NULL)
358 chunk_offsets_malloced = true;
361 const size_t chunk_table_size_to_read =
362 num_chunk_entries_to_read * chunk_entry_size;
364 const u64 file_offset_of_needed_chunk_entries =
366 + (first_chunk_entry_to_read * chunk_entry_size)
367 + (rspec->is_pipable ? (rspec->size_in_wim - chunk_table_size) : 0);
369 void * const chunk_table_data =
371 chunk_offsets_alloc_size -
372 chunk_table_size_to_read;
374 ret = full_pread(in_fd, chunk_table_data, chunk_table_size,
375 file_offset_of_needed_chunk_entries);
379 /* Now fill in chunk_offsets from the entries we have read in
380 * chunk_tab_data. We break aliasing rules here to avoid having
381 * to allocate yet another array. */
382 typedef le64 __attribute__((may_alias)) aliased_le64_t;
383 typedef le32 __attribute__((may_alias)) aliased_le32_t;
384 u64 * chunk_offsets_p = chunk_offsets;
386 if (alt_chunk_table) {
388 aliased_le32_t *raw_entries = chunk_table_data;
390 for (size_t i = 0; i < num_chunk_entries_to_read; i++) {
391 u32 entry = le32_to_cpu(raw_entries[i]);
392 if (i >= read_start_chunk)
393 *chunk_offsets_p++ = cur_offset;
396 if (last_needed_chunk < num_chunks - 1)
397 *chunk_offsets_p = cur_offset;
399 if (read_start_chunk == 0)
400 *chunk_offsets_p++ = 0;
402 if (chunk_entry_size == 4) {
403 aliased_le32_t *raw_entries = chunk_table_data;
404 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
405 *chunk_offsets_p++ = le32_to_cpu(raw_entries[i]);
407 aliased_le64_t *raw_entries = chunk_table_data;
408 for (size_t i = 0; i < num_chunk_entries_to_read; i++)
409 *chunk_offsets_p++ = le64_to_cpu(raw_entries[i]);
413 /* Set offset to beginning of first chunk to read. */
414 cur_read_offset += chunk_offsets[0];
415 if (rspec->is_pipable)
416 cur_read_offset += read_start_chunk * sizeof(struct pwm_chunk_hdr);
418 cur_read_offset += chunk_table_size;
421 /* Allocate buffer for holding the uncompressed data of each chunk. */
422 if (chunk_size <= STACK_MAX) {
423 ubuf = alloca(chunk_size);
425 ubuf = MALLOC(chunk_size);
428 ubuf_malloced = true;
431 /* Unless the raw compressed data was requested, allocate a temporary
432 * buffer for reading compressed chunks, each of which can be at most
433 * @chunk_size - 1 bytes. This excludes compressed chunks that are a
434 * full @chunk_size bytes, which are actually stored uncompressed. */
435 if (!raw_chunks_mode) {
436 if (chunk_size - 1 <= STACK_MAX) {
437 cbuf = alloca(chunk_size - 1);
439 cbuf = MALLOC(chunk_size - 1);
442 cbuf_malloced = true;
446 /* Set current data range. */
447 const struct data_range *cur_range = ranges;
448 const struct data_range * const end_range = &ranges[num_ranges];
449 u64 cur_range_pos = cur_range->offset;
450 u64 cur_range_end = cur_range->offset + cur_range->size;
452 /* Read and process each needed chunk. */
453 for (u64 i = read_start_chunk; i <= last_needed_chunk; i++) {
455 /* Calculate uncompressed size of next chunk. */
457 if ((i == num_chunks - 1) && (rspec->uncompressed_size & (chunk_size - 1)))
458 chunk_usize = (rspec->uncompressed_size & (chunk_size - 1));
460 chunk_usize = chunk_size;
462 /* Calculate compressed size of next chunk. */
465 struct pwm_chunk_hdr chunk_hdr;
467 ret = full_pread(in_fd, &chunk_hdr,
468 sizeof(chunk_hdr), cur_read_offset);
471 chunk_csize = le32_to_cpu(chunk_hdr.compressed_size);
473 if (i == num_chunks - 1) {
474 chunk_csize = rspec->size_in_wim -
475 chunk_table_full_size -
476 chunk_offsets[i - read_start_chunk];
477 if (rspec->is_pipable)
478 chunk_csize -= num_chunks * sizeof(struct pwm_chunk_hdr);
480 chunk_csize = chunk_offsets[i + 1 - read_start_chunk] -
481 chunk_offsets[i - read_start_chunk];
484 if (chunk_csize == 0 || chunk_csize > chunk_usize) {
485 ERROR("Invalid chunk size in compressed resource!");
487 ret = WIMLIB_ERR_DECOMPRESSION;
488 goto out_free_memory;
490 if (rspec->is_pipable)
491 cur_read_offset += sizeof(struct pwm_chunk_hdr);
493 /* Offsets in the uncompressed resource at which this chunk
494 * starts and ends. */
495 const u64 chunk_start_offset = i << chunk_order;
496 const u64 chunk_end_offset = chunk_start_offset + chunk_usize;
498 if (chunk_end_offset <= cur_range_pos) {
500 /* The next range does not require data in this chunk,
502 cur_read_offset += chunk_csize;
506 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
512 /* Read the chunk and feed data to the callback
516 ret = full_pread(in_fd,
523 if (chunk_csize != chunk_usize && !raw_chunks_mode) {
524 DEBUG("Decompressing chunk %"PRIu64" "
525 "(csize=%"PRIu64" usize=%"PRIu64"",
526 i, chunk_csize, chunk_usize);
527 ret = decompress(cbuf,
534 ERROR("Failed to decompress data!");
535 ret = WIMLIB_ERR_DECOMPRESSION;
537 goto out_free_memory;
541 /* Raw chunks requested, or data stored
545 cur_read_offset += chunk_csize;
547 /* At least one range requires data in this chunk. */
549 size_t start, end, size;
551 /* Calculate how many bytes of data should be
552 * sent to the callback function, taking into
553 * account that data sent to the callback
554 * function must not overlap range boundaries.
556 start = cur_range_pos - chunk_start_offset;
557 end = min(cur_range_end, chunk_end_offset) - chunk_start_offset;
561 ret = (*cb)(&cb_buf[0], chunk_csize, cb_ctx);
563 ret = (*cb)(&cb_buf[start], size, cb_ctx);
566 goto out_free_memory;
568 cur_range_pos += size;
569 if (cur_range_pos == cur_range_end) {
570 /* Advance to next range. */
571 if (++cur_range == end_range) {
572 cur_range_pos = ~0ULL;
574 cur_range_pos = cur_range->offset;
575 cur_range_end = cur_range->offset + cur_range->size;
578 } while (cur_range_pos < chunk_end_offset);
583 last_offset == rspec->uncompressed_size - 1 &&
587 /* If reading a pipable resource from a pipe and the full data
588 * was requested, skip the chunk table at the end so that the
589 * file descriptor is fully clear of the resource after this
591 cur_read_offset += chunk_table_size;
592 ret = full_pread(in_fd, &dummy, 1, cur_read_offset - 1);
599 if (chunk_offsets_malloced)
609 ERROR("Not enough memory available to read size=%"PRIu64" bytes "
610 "from compressed WIM resource!", last_offset - first_offset + 1);
612 ret = WIMLIB_ERR_NOMEM;
613 goto out_free_memory;
616 ERROR_WITH_ERRNO("Error reading compressed WIM resource!");
617 goto out_free_memory;
620 /* Read raw data from a file descriptor at the specified offset, feeding the
621 * data it in chunks into the specified callback function. */
623 read_raw_file_data(struct filedes *in_fd, u64 size,
624 consume_data_callback_t cb, void *cb_ctx, u64 offset)
627 size_t bytes_to_read;
631 bytes_to_read = min(sizeof(buf), size);
632 ret = full_pread(in_fd, buf, bytes_to_read, offset);
634 ERROR_WITH_ERRNO("Read error");
637 ret = cb(buf, bytes_to_read, cb_ctx);
640 size -= bytes_to_read;
641 offset += bytes_to_read;
646 /* A consume_data_callback_t implementation that simply concatenates all chunks
649 bufferer_cb(const void *chunk, size_t size, void *_ctx)
653 *buf_p = mempcpy(*buf_p, chunk, size);
658 * read_partial_wim_resource()-
660 * Read a range of data from an uncompressed or compressed resource in a WIM
661 * file. Data is fed chunk-by-chunk into the callback function @cb, passing it
662 * the argument @cb_ctx. The chunks are of unspecified size unless the
663 * RAW_CHUNKS mode is requested.
665 * By default, this function provides the uncompressed data of the resource, and
666 * @offset and @size and interpreted relative to the uncompressed contents of
667 * the resource. This behavior can be modified by either of the following
670 * WIMLIB_READ_RESOURCE_FLAG_RAW_FULL:
671 * Read @size bytes at @offset of the raw contents of the compressed
672 * resource. In the case of pipable resources, this excludes the stream
673 * header. Exclusive with WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS.
675 * WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS:
676 * Read the raw compressed chunks of the compressed resource. @size must
677 * be the full uncompressed size, @offset must be 0, and @cb_chunk_size
678 * must be the resource chunk size.
681 * WIMLIB_ERR_SUCCESS (0)
682 * WIMLIB_ERR_READ (errno set)
683 * WIMLIB_ERR_UNEXPECTED_END_OF_FILE (errno set to 0)
684 * WIMLIB_ERR_NOMEM (errno set to ENOMEM)
685 * WIMLIB_ERR_DECOMPRESSION (errno set to EINVAL)
687 * or other error code returned by the @cb function.
690 read_partial_wim_resource(const struct wim_resource_spec *rspec,
691 u64 offset, u64 size, consume_data_callback_t cb,
692 void *cb_ctx, int flags)
695 if (flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL) {
696 wimlib_assert(!(flags & WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS));
697 wimlib_assert(offset + size >= offset);
698 wimlib_assert(offset + size <= rspec->size_in_wim);
699 } else if (flags & WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS) {
700 wimlib_assert(offset == 0);
701 wimlib_assert(offset == rspec->uncompressed_size);
703 wimlib_assert(offset + size >= offset);
704 wimlib_assert(offset + size <= rspec->uncompressed_size);
707 DEBUG("Reading %"PRIu64" @ %"PRIu64" from WIM resource "
708 "%"PRIu64" => %"PRIu64" @ %"PRIu64" (flags 0x%08x)",
709 size, offset, rspec->uncompressed_size,
710 rspec->size_in_wim, rspec->offset_in_wim, flags);
716 if ((flags & WIMLIB_READ_RESOURCE_FLAG_RAW_FULL) ||
717 !resource_is_compressed(rspec))
719 return read_raw_file_data(&rspec->wim->in_fd,
723 rspec->offset_in_wim + offset);
725 bool raw_chunks = (flags & WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS);
726 struct data_range range = {
730 return read_compressed_wim_resource(rspec, &range, 1,
731 cb, cb_ctx, raw_chunks);
735 /* Read the specified range of uncompressed data from the specified stream,
736 * which must be located into a WIM file, into the specified buffer. */
738 read_partial_wim_stream_into_buf(const struct wim_lookup_table_entry *lte,
739 size_t size, u64 offset, void *_buf)
743 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
745 return read_partial_wim_resource(lte->rspec,
746 lte->offset_in_res + offset,
753 /* A consume_data_callback_t implementation that simply ignores the data
756 skip_chunk_cb(const void *chunk, size_t size, void *_ctx)
761 /* Skip over the data of the specified stream, which must correspond to a full
764 skip_wim_stream(struct wim_lookup_table_entry *lte)
766 wimlib_assert(lte->resource_location == RESOURCE_IN_WIM);
767 wimlib_assert(!lte_is_partial(lte));
768 return read_partial_wim_resource(lte->rspec,
770 lte->rspec->uncompressed_size,
773 WIMLIB_READ_RESOURCE_FLAG_RAW_CHUNKS);
777 read_wim_stream_prefix(const struct wim_lookup_table_entry *lte, u64 size,
778 consume_data_callback_t cb, void *cb_ctx, int flags)
780 return read_partial_wim_resource(lte->rspec,
789 /* This function handles reading stream data that is located in an external
790 * file, such as a file that has been added to the WIM image through execution
791 * of a wimlib_add_command.
793 * This assumes the file can be accessed using the standard POSIX open(),
794 * read(), and close(). On Windows this will not necessarily be the case (since
795 * the file may need FILE_FLAG_BACKUP_SEMANTICS to be opened, or the file may be
796 * encrypted), so Windows uses its own code for its equivalent case. */
798 read_file_on_disk_prefix(const struct wim_lookup_table_entry *lte, u64 size,
799 consume_data_callback_t cb, void *cb_ctx,
806 wimlib_assert(size <= lte->size);
808 DEBUG("Reading %"PRIu64" bytes from \"%"TS"\"", size, lte->file_on_disk);
810 raw_fd = open(lte->file_on_disk, O_BINARY | O_RDONLY);
812 ERROR_WITH_ERRNO("Can't open \"%"TS"\"", lte->file_on_disk);
813 return WIMLIB_ERR_OPEN;
815 filedes_init(&fd, raw_fd);
816 ret = read_raw_file_data(&fd, size, cb, cb_ctx, 0);
820 #endif /* !__WIN32__ */
822 /* This function handles the trivial case of reading stream data that is, in
823 * fact, already located in an in-memory buffer. */
825 read_buffer_prefix(const struct wim_lookup_table_entry *lte,
826 u64 size, consume_data_callback_t cb,
827 void *cb_ctx, int _ignored_flags)
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,
836 void *cb_ctx, int flags);
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 * If the stream is located in a WIM file, @flags can be set as documented in
849 * read_partial_wim_resource(). Otherwise @flags are ignored.
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, int flags)
860 static const read_stream_prefix_handler_t handlers[] = {
861 [RESOURCE_IN_WIM] = read_wim_stream_prefix,
863 [RESOURCE_IN_FILE_ON_DISK] = read_win32_file_prefix,
865 [RESOURCE_IN_FILE_ON_DISK] = read_file_on_disk_prefix,
867 [RESOURCE_IN_ATTACHED_BUFFER] = read_buffer_prefix,
869 [RESOURCE_IN_STAGING_FILE] = read_file_on_disk_prefix,
872 [RESOURCE_IN_NTFS_VOLUME] = read_ntfs_file_prefix,
875 [RESOURCE_WIN32_ENCRYPTED] = read_win32_encrypted_file_prefix,
878 wimlib_assert(lte->resource_location < ARRAY_LEN(handlers)
879 && handlers[lte->resource_location] != NULL);
880 return handlers[lte->resource_location](lte, size, cb, cb_ctx, flags);
883 /* Read the full uncompressed data of the specified stream into the specified
884 * buffer, which must have space for at least lte->size bytes. */
886 read_full_stream_into_buf(const struct wim_lookup_table_entry *lte, void *_buf)
889 return read_stream_prefix(lte, lte->size, bufferer_cb, &buf, 0);
892 /* Retrieve the full uncompressed data of the specified stream. A buffer large
893 * enough hold the data is allocated and returned in @buf_ret. */
895 read_full_stream_into_alloc_buf(const struct wim_lookup_table_entry *lte,
901 if ((size_t)lte->size != lte->size) {
902 ERROR("Can't read %"PRIu64" byte stream into "
903 "memory", lte->size);
904 return WIMLIB_ERR_NOMEM;
907 buf = MALLOC(lte->size);
909 return WIMLIB_ERR_NOMEM;
911 ret = read_full_stream_into_buf(lte, buf);
921 /* Retrieve the full uncompressed data of the specified WIM resource. A buffer
922 * large enough hold the data is allocated and returned in @buf_ret. */
924 wim_resource_spec_to_data(struct wim_resource_spec *rspec, void **buf_ret)
927 struct wim_lookup_table_entry *lte;
929 lte = new_lookup_table_entry();
931 return WIMLIB_ERR_NOMEM;
934 lte_bind_wim_resource_spec(lte, rspec);
935 lte->flags = rspec->flags;
936 lte->size = rspec->uncompressed_size;
937 lte->offset_in_res = 0;
939 ret = read_full_stream_into_alloc_buf(lte, buf_ret);
941 lte_unbind_wim_resource_spec(lte);
942 free_lookup_table_entry(lte);
946 /* Retrieve the full uncompressed data of a WIM resource specified as a raw
947 * `wim_reshdr' and the corresponding WIM file. A large enough hold the data is
948 * allocated and returned in @buf_ret. */
950 wim_reshdr_to_data(const struct wim_reshdr *reshdr, WIMStruct *wim, void **buf_ret)
952 DEBUG("offset_in_wim=%"PRIu64", size_in_wim=%"PRIu64", "
953 "uncompressed_size=%"PRIu64,
954 reshdr->offset_in_wim, reshdr->size_in_wim,
955 reshdr->uncompressed_size);
957 struct wim_resource_spec rspec;
958 wim_res_hdr_to_spec(reshdr, wim, &rspec);
959 return wim_resource_spec_to_data(&rspec, buf_ret);
962 struct streamifier_context {
963 struct read_stream_list_callbacks cbs;
964 struct wim_lookup_table_entry *cur_stream;
965 u64 cur_stream_offset;
966 struct wim_lookup_table_entry *final_stream;
967 size_t list_head_offset;
970 /* A consume_data_callback_t implementation that translates raw resource data
971 * into streams, calling the begin_stream, consume_chunk, and end_stream
972 * callback functions as appropriate. */
974 streamifier_cb(const void *chunk, size_t size, void *_ctx)
976 struct streamifier_context *ctx = _ctx;
979 DEBUG("%zu bytes passed to streamifier", size);
981 wimlib_assert(ctx->cur_stream != NULL);
982 wimlib_assert(size <= ctx->cur_stream->size - ctx->cur_stream_offset);
984 if (ctx->cur_stream_offset == 0) {
985 /* Starting a new stream. */
986 DEBUG("Begin new stream (size=%"PRIu64").",
987 ctx->cur_stream->size);
988 ret = (*ctx->cbs.begin_stream)(ctx->cur_stream, true,
989 ctx->cbs.begin_stream_ctx);
994 /* Consume the chunk. */
995 ret = (*ctx->cbs.consume_chunk)(chunk, size,
996 ctx->cbs.consume_chunk_ctx);
999 ctx->cur_stream_offset += size;
1001 if (ctx->cur_stream_offset == ctx->cur_stream->size) {
1002 /* Finished reading all the data for a stream. */
1003 DEBUG("End stream (size=%"PRIu64").", ctx->cur_stream->size);
1004 ret = (*ctx->cbs.end_stream)(ctx->cur_stream, 0,
1005 ctx->cbs.end_stream_ctx);
1009 if (ctx->cur_stream != ctx->final_stream) {
1010 /* Advance to next stream. */
1011 struct list_head *cur, *next;
1013 cur = (struct list_head *)
1014 ((u8*)ctx->cur_stream + ctx->list_head_offset);
1017 ctx->cur_stream = (struct wim_lookup_table_entry *)
1018 ((u8*)next - ctx->list_head_offset);
1020 ctx->cur_stream_offset = 0;
1022 /* No more streams. */
1023 ctx->cur_stream = NULL;
1029 struct hasher_context {
1031 struct read_stream_list_callbacks cbs;
1034 /* Callback for starting to read a stream while calculating its SHA1 message
1037 hasher_begin_stream(struct wim_lookup_table_entry *lte, bool is_partial_res,
1040 struct hasher_context *ctx = _ctx;
1042 sha1_init(&ctx->sha_ctx);
1044 if (ctx->cbs.begin_stream == NULL)
1047 return (*ctx->cbs.begin_stream)(lte, is_partial_res,
1048 ctx->cbs.begin_stream_ctx);
1051 /* A consume_data_callback_t implementation that continues calculating the SHA1
1052 * message digest of the stream being read, then optionally passes the data on
1053 * to another consume_data_callback_t implementation. This allows checking the
1054 * SHA1 message digest of a stream being extracted, for example. */
1056 hasher_consume_chunk(const void *chunk, size_t size, void *_ctx)
1058 struct hasher_context *ctx = _ctx;
1060 sha1_update(&ctx->sha_ctx, chunk, size);
1061 if (ctx->cbs.consume_chunk == NULL)
1064 return (*ctx->cbs.consume_chunk)(chunk, size, ctx->cbs.consume_chunk_ctx);
1067 /* Callback for finishing reading a stream while calculating its SHA1 message
1070 hasher_end_stream(struct wim_lookup_table_entry *lte, int status, void *_ctx)
1072 struct hasher_context *ctx = _ctx;
1073 u8 hash[SHA1_HASH_SIZE];
1077 /* Error occurred; the full stream may not have been read. */
1082 /* Retrieve the final SHA1 message digest. */
1083 sha1_final(hash, &ctx->sha_ctx);
1085 if (lte->unhashed) {
1086 /* No SHA1 message digest was previously present for the stream.
1087 * Set it to the one just calculated. */
1088 DEBUG("Set SHA1 message digest for stream (size=%"PRIu64").", lte->size);
1089 copy_hash(lte->hash, hash);
1091 /* The stream already had a SHA1 message digest present. Verify
1092 * that it is the same as the calculated value. */
1093 if (!hashes_equal(hash, lte->hash)) {
1094 if (wimlib_print_errors) {
1095 ERROR("Invalid SHA1 message digest "
1096 "on the following WIM stream:");
1097 print_lookup_table_entry(lte, stderr);
1098 if (lte->resource_location == RESOURCE_IN_WIM)
1099 ERROR("The WIM file appears to be corrupt!");
1101 ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
1105 DEBUG("SHA1 message digest okay for stream (size=%"PRIu64").", lte->size);
1109 if (ctx->cbs.end_stream == NULL)
1112 return (*ctx->cbs.end_stream)(lte, ret, ctx->cbs.end_stream_ctx);
1115 /* Read the full data of the specified stream, passing the data into the
1116 * specified callbacks (all of which are optional) and either checking or
1117 * computing the SHA1 message digest of the stream. */
1119 read_full_stream_with_sha1(struct wim_lookup_table_entry *lte,
1120 const struct read_stream_list_callbacks *cbs)
1124 struct hasher_context hasher_ctx = {
1128 ret = hasher_begin_stream(lte, false, &hasher_ctx);
1132 ret = read_stream_prefix(lte, lte->size, hasher_consume_chunk,
1135 return hasher_end_stream(lte, ret, &hasher_ctx);
1138 struct rechunkifier_context {
1143 const struct data_range *ranges;
1146 u64 range_bytes_remaining;
1148 consume_data_callback_t cb;
1152 /* Wrapper callback for adjusting the data chunk size. */
1154 rechunkifier_cb(const void *chunk, size_t size, void *_ctx)
1156 struct rechunkifier_context *ctx = _ctx;
1157 const u8 *chunkptr = chunk;
1158 size_t bytes_to_copy;
1161 wimlib_assert(ctx->cur_range != ctx->num_ranges);
1165 /* Append more data to the buffer. */
1166 bytes_to_copy = size;
1168 if (bytes_to_copy > ctx->cb_chunk_size - ctx->buffer_filled)
1169 bytes_to_copy = ctx->cb_chunk_size - ctx->buffer_filled;
1171 if (bytes_to_copy > ctx->range_bytes_remaining - ctx->buffer_filled)
1172 bytes_to_copy = ctx->range_bytes_remaining - ctx->buffer_filled;
1174 memcpy(&ctx->buffer[ctx->buffer_filled], chunkptr, bytes_to_copy);
1176 ctx->buffer_filled += bytes_to_copy;
1177 chunkptr += bytes_to_copy;
1178 size -= bytes_to_copy;
1179 ctx->range_bytes_remaining -= bytes_to_copy;
1181 if (ctx->buffer_filled == ctx->cb_chunk_size ||
1182 ctx->range_bytes_remaining == 0)
1184 /* Maximum chunk size reached, or current range ended.
1185 * Call the next consume_data_callback_t and empty the
1187 ret = (*ctx->cb)(ctx->buffer, ctx->buffer_filled, ctx->cb_ctx);
1190 ctx->buffer_filled = 0;
1192 if (ctx->range_bytes_remaining == 0 &&
1193 ++ctx->cur_range != ctx->num_ranges)
1194 ctx->range_bytes_remaining = ctx->ranges[ctx->cur_range].size;
1201 * Read a list of streams, each of which may be in any supported location (e.g.
1202 * in a WIM or in an external file). Unlike read_stream_prefix() or the
1203 * functions which call it, this function optimizes the case where multiple
1204 * streams are packed into a single compressed WIM resource and reads them all
1205 * consecutively, only decompressing the data one time.
1208 * List of streams (represented as `struct wim_lookup_table_entry's) to
1211 * Offset of the `struct list_head' within each `struct
1212 * wim_lookup_table_entry' that makes up the @stream_list.
1214 * Size of chunks to provide to @consume_chunk. For a given stream, all
1215 * the chunks will be this size, except possibly the last which will be the
1219 * Returns 0 on success; a nonzero error code on failure. Failure can occur due
1220 * to an error reading the data or due to an error status being returned by any
1221 * of the callback functions.
1224 read_stream_list(struct list_head *stream_list,
1225 size_t list_head_offset,
1227 const struct read_stream_list_callbacks *cbs)
1230 struct list_head *cur, *next;
1231 struct wim_lookup_table_entry *lte;
1233 ret = sort_stream_list_by_sequential_order(stream_list, list_head_offset);
1237 for (cur = stream_list->next, next = cur->next;
1239 cur = next, next = cur->next)
1241 lte = (struct wim_lookup_table_entry*)((u8*)cur - list_head_offset);
1243 if (lte_is_partial(lte)) {
1245 struct wim_lookup_table_entry *lte_next, *lte_last;
1246 struct list_head *next2;
1247 size_t stream_count;
1249 /* The next stream is a proper sub-sequence of a WIM
1250 * resource. See if there are other streams in the same
1251 * resource that need to be read. Since
1252 * sort_stream_list_by_sequential_order() sorted the
1253 * streams by offset in the WIM, this can be determined
1254 * by simply scanning forward in the list. */
1259 next2 != stream_list
1260 && (lte_next = (struct wim_lookup_table_entry*)
1261 ((u8*)next2 - list_head_offset),
1262 lte_next->resource_location == RESOURCE_IN_WIM
1263 && lte_next->rspec == lte->rspec);
1264 next2 = next2->next)
1266 lte_last = lte_next;
1269 if (stream_count > 1) {
1270 /* Reading multiple streams combined into a
1271 * single WIM resource. They are in the stream
1272 * list, sorted by offset; @lte specifies the
1273 * first stream in the resource that needs to be
1274 * read and @lte_last specifies the last stream
1275 * in the resource that needs to be read. */
1277 DEBUG("Reading %zu streams combined in same "
1278 "WIM resource", stream_count);
1282 struct data_range ranges[stream_count];
1285 struct list_head *next3;
1287 struct wim_lookup_table_entry *lte_cur;
1290 for (i = 0; i < stream_count; i++) {
1291 lte_cur = (struct wim_lookup_table_entry*)
1292 ((u8*)next3 - list_head_offset);
1293 ranges[i].offset = lte_cur->offset_in_res;
1294 ranges[i].size = lte_cur->size;
1295 next3 = next3->next;
1299 /* Set up a chain of callbacks.
1301 * The first level is the
1303 * which takes in chunks of data and divides
1304 * them into the constituent streams.
1306 * The second level are the SHA1 message digest
1307 * callbacks, which checksum each stream.
1309 * rechunkifier_cb handles dividing the read
1310 * data into chunks of maximum size
1311 * @cb_chunk_size. If @cb_chunk_size is 0, then
1312 * this callback is not needed.
1314 * Finally, the last level of callbacks are
1315 * @cbs, passed as arguments to this function.
1318 struct rechunkifier_context *rechunkifier_ctx = NULL;
1319 consume_data_callback_t last_cb;
1322 if (cb_chunk_size != 0) {
1323 rechunkifier_ctx = alloca(sizeof(*rechunkifier_ctx));
1324 *rechunkifier_ctx = (struct rechunkifier_context) {
1325 .buffer = MALLOC(cb_chunk_size),
1327 .cb_chunk_size = cb_chunk_size,
1329 .num_ranges = stream_count,
1331 .range_bytes_remaining = ranges[0].size,
1332 .cb = cbs->consume_chunk,
1333 .cb_ctx = cbs->consume_chunk_ctx,
1336 if (rechunkifier_ctx->buffer == NULL)
1337 return WIMLIB_ERR_NOMEM;
1338 last_cb = rechunkifier_cb;
1339 last_cb_ctx = rechunkifier_ctx;
1341 rechunkifier_ctx = NULL;
1342 last_cb = cbs->consume_chunk;
1343 last_cb_ctx = cbs->consume_chunk_ctx;
1346 struct hasher_context hasher_ctx = {
1348 .begin_stream = cbs->begin_stream,
1349 .begin_stream_ctx = cbs->begin_stream_ctx,
1350 .consume_chunk = last_cb,
1351 .consume_chunk_ctx = last_cb_ctx,
1352 .end_stream = cbs->end_stream,
1353 .end_stream_ctx = cbs->end_stream_ctx,
1357 struct streamifier_context streamifier_ctx = {
1359 .begin_stream = hasher_begin_stream,
1360 .begin_stream_ctx = &hasher_ctx,
1361 .consume_chunk = hasher_consume_chunk,
1362 .consume_chunk_ctx = &hasher_ctx,
1363 .end_stream = hasher_end_stream,
1364 .end_stream_ctx = &hasher_ctx,
1367 .cur_stream_offset = 0,
1368 .final_stream = lte_last,
1369 .list_head_offset = list_head_offset,
1372 ret = read_compressed_wim_resource(lte->rspec,
1378 if (rechunkifier_ctx != NULL)
1379 FREE(rechunkifier_ctx->buffer);
1382 if (streamifier_ctx.cur_stream_offset != 0) {
1383 ret = (*streamifier_ctx.cbs.end_stream)
1384 (streamifier_ctx.cur_stream,
1386 streamifier_ctx.cbs.end_stream_ctx);
1394 ret = read_full_stream_with_sha1(lte, cbs);
1401 /* Extract the first @size bytes of the specified stream.
1403 * If @size specifies the full uncompressed size of the stream, then the SHA1
1404 * message digest of the uncompressed stream is checked while being extracted.
1406 * The uncompressed data of the resource is passed in chunks of unspecified size
1407 * to the @extract_chunk function, passing it @extract_chunk_arg. */
1409 extract_stream(struct wim_lookup_table_entry *lte, u64 size,
1410 consume_data_callback_t extract_chunk, void *extract_chunk_arg)
1412 if (size == lte->size) {
1414 struct read_stream_list_callbacks cbs = {
1415 .consume_chunk = extract_chunk,
1416 .consume_chunk_ctx = extract_chunk_arg,
1418 return read_full_stream_with_sha1(lte, &cbs);
1420 /* Don't do SHA1. */
1421 return read_stream_prefix(lte, size, extract_chunk,
1422 extract_chunk_arg, 0);
1426 /* A consume_data_callback_t implementation that writes the chunk of data to a
1427 * file descriptor. */
1429 extract_chunk_to_fd(const void *chunk, size_t size, void *_fd_p)
1431 struct filedes *fd = _fd_p;
1433 int ret = full_write(fd, chunk, size);
1435 ERROR_WITH_ERRNO("Error writing to file descriptor");
1441 /* Extract the first @size bytes of the specified stream to the specified file
1444 extract_stream_to_fd(struct wim_lookup_table_entry *lte,
1445 struct filedes *fd, u64 size)
1447 return extract_stream(lte, size, extract_chunk_to_fd, fd);
1450 /* Calculate the SHA1 message digest of a stream and store it in @lte->hash. */
1452 sha1_stream(struct wim_lookup_table_entry *lte)
1454 wimlib_assert(lte->unhashed);
1455 struct read_stream_list_callbacks cbs = {
1457 return read_full_stream_with_sha1(lte, &cbs);
1460 /* Convert a short WIM resource header to a stand-alone WIM resource
1463 wim_res_hdr_to_spec(const struct wim_reshdr *reshdr, WIMStruct *wim,
1464 struct wim_resource_spec *spec)
1467 spec->offset_in_wim = reshdr->offset_in_wim;
1468 spec->size_in_wim = reshdr->size_in_wim;
1469 spec->uncompressed_size = reshdr->uncompressed_size;
1470 INIT_LIST_HEAD(&spec->stream_list);
1471 spec->flags = reshdr->flags;
1472 spec->is_pipable = wim_is_pipable(wim);
1475 /* Convert a stand-alone resource specification to a WIM resource header. */
1477 wim_res_spec_to_hdr(const struct wim_resource_spec *rspec,
1478 struct wim_reshdr *reshdr)
1480 reshdr->offset_in_wim = rspec->offset_in_wim;
1481 reshdr->size_in_wim = rspec->size_in_wim;
1482 reshdr->flags = rspec->flags;
1483 reshdr->uncompressed_size = rspec->uncompressed_size;
1486 /* Translates a WIM resource header from the on-disk format into an in-memory
1489 get_wim_reshdr(const struct wim_reshdr_disk *disk_reshdr,
1490 struct wim_reshdr *reshdr)
1492 reshdr->offset_in_wim = le64_to_cpu(disk_reshdr->offset_in_wim);
1493 reshdr->size_in_wim = (((u64)disk_reshdr->size_in_wim[0] << 0) |
1494 ((u64)disk_reshdr->size_in_wim[1] << 8) |
1495 ((u64)disk_reshdr->size_in_wim[2] << 16) |
1496 ((u64)disk_reshdr->size_in_wim[3] << 24) |
1497 ((u64)disk_reshdr->size_in_wim[4] << 32) |
1498 ((u64)disk_reshdr->size_in_wim[5] << 40) |
1499 ((u64)disk_reshdr->size_in_wim[6] << 48));
1500 reshdr->uncompressed_size = le64_to_cpu(disk_reshdr->uncompressed_size);
1501 reshdr->flags = disk_reshdr->flags;
1503 /* Avoid possible overflows. */
1504 if (reshdr->offset_in_wim & 0xc000000000000000ULL)
1505 return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
1507 if (reshdr->uncompressed_size & 0xc000000000000000ULL)
1508 return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
1513 /* Translates a WIM resource header from an in-memory format into the on-disk
1516 put_wim_reshdr(const struct wim_reshdr *reshdr,
1517 struct wim_reshdr_disk *disk_reshdr)
1519 disk_reshdr->size_in_wim[0] = reshdr->size_in_wim >> 0;
1520 disk_reshdr->size_in_wim[1] = reshdr->size_in_wim >> 8;
1521 disk_reshdr->size_in_wim[2] = reshdr->size_in_wim >> 16;
1522 disk_reshdr->size_in_wim[3] = reshdr->size_in_wim >> 24;
1523 disk_reshdr->size_in_wim[4] = reshdr->size_in_wim >> 32;
1524 disk_reshdr->size_in_wim[5] = reshdr->size_in_wim >> 40;
1525 disk_reshdr->size_in_wim[6] = reshdr->size_in_wim >> 48;
1526 disk_reshdr->flags = reshdr->flags;
1527 disk_reshdr->offset_in_wim = cpu_to_le64(reshdr->offset_in_wim);
1528 disk_reshdr->uncompressed_size = cpu_to_le64(reshdr->uncompressed_size);