]> wimlib.net Git - wimlib/blob - src/resource.c
c6da07a29ed6b709dbf493acc03ed3ec0a499435
[wimlib] / src / resource.c
1 /*
2  * resource.c
3  *
4  * Read uncompressed and compressed metadata and file resources.
5  */
6
7 /*
8  * Copyright (C) 2012 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
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
15  * version.
16  *
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.
20  *
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/.
23  */
24
25 #include "config.h"
26
27 #include <stdlib.h>
28 #include <stdarg.h>
29
30 #ifdef WITH_NTFS_3G
31 #include <ntfs-3g/attrib.h>
32 #include <ntfs-3g/inode.h>
33 #include <ntfs-3g/dir.h>
34 #endif
35
36 #include "wimlib_internal.h"
37 #include "lookup_table.h"
38 #include "io.h"
39 #include "lzx.h"
40 #include "xpress.h"
41 #include "sha1.h"
42 #include "dentry.h"
43 #include <unistd.h>
44 #include <errno.h>
45 #ifdef HAVE_ALLOCA_H
46 #include <alloca.h>
47 #endif
48
49
50 /*
51  * Reads all or part of a compressed resource into an in-memory buffer.
52  *
53  * @fp:                 The FILE* for the WIM file.
54  * @resource_compressed_size:    The compressed size of the resource.
55  * @resource_uncompressed_size:  The uncompressed size of the resource.
56  * @resource_offset:             The offset of the start of the resource from
57  *                                      the start of the stream @fp.
58  * @resource_ctype:     The compression type of the resource.
59  * @len:                The number of bytes of uncompressed data to read from
60  *                              the resource.
61  * @offset:             The offset of the bytes to read within the uncompressed
62  *                              resource.
63  * @contents_len:       An array into which the uncompressed data is written.
64  *                              It must be at least @len bytes long.
65  *
66  * Returns zero on success, nonzero on failure.
67  */
68 static int read_compressed_resource(FILE *fp, u64 resource_compressed_size,
69                                     u64 resource_uncompressed_size,
70                                     u64 resource_offset, int resource_ctype,
71                                     u64 len, u64 offset, u8  contents_ret[])
72 {
73
74         DEBUG2("comp size = %"PRIu64", uncomp size = %"PRIu64", "
75                "res offset = %"PRIu64"",
76                resource_compressed_size,
77                resource_uncompressed_size,
78                resource_offset);
79         DEBUG2("resource_ctype = %s, len = %"PRIu64", offset = %"PRIu64"",
80                wimlib_get_compression_type_string(resource_ctype), len, offset);
81         /* Trivial case */
82         if (len == 0)
83                 return 0;
84
85         int (*decompress)(const void *, uint, void *, uint);
86         /* Set the appropriate decompress function. */
87         if (resource_ctype == WIM_COMPRESSION_TYPE_LZX)
88                 decompress = lzx_decompress;
89         else
90                 decompress = xpress_decompress;
91
92         /* The structure of a compressed resource consists of a table of chunk
93          * offsets followed by the chunks themselves.  Each chunk consists of
94          * compressed data, and there is one chunk for each WIM_CHUNK_SIZE =
95          * 32768 bytes of the uncompressed file, with the last chunk having any
96          * remaining bytes.
97          *
98          * The chunk offsets are measured relative to the end of the chunk
99          * table.  The first chunk is omitted from the table in the WIM file
100          * because its offset is implicitly given by the fact that it directly
101          * follows the chunk table and therefore must have an offset of 0.
102          */
103
104         /* Calculate how many chunks the resource conists of in its entirety. */
105         u64 num_chunks = (resource_uncompressed_size + WIM_CHUNK_SIZE - 1) /
106                                                                 WIM_CHUNK_SIZE;
107         /* As mentioned, the first chunk has no entry in the chunk table. */
108         u64 num_chunk_entries = num_chunks - 1;
109
110
111         /* The index of the chunk that the read starts at. */
112         u64 start_chunk = offset / WIM_CHUNK_SIZE;
113         /* The byte offset at which the read starts, within the start chunk. */
114         u64 start_chunk_offset = offset % WIM_CHUNK_SIZE;
115
116         /* The index of the chunk that contains the last byte of the read. */
117         u64 end_chunk   = (offset + len - 1) / WIM_CHUNK_SIZE;
118         /* The byte offset of the last byte of the read, within the end chunk */
119         u64 end_chunk_offset = (offset + len - 1) % WIM_CHUNK_SIZE;
120
121         /* Number of chunks that are actually needed to read the requested part
122          * of the file. */
123         u64 num_needed_chunks = end_chunk - start_chunk + 1;
124
125         /* If the end chunk is not the last chunk, an extra chunk entry is
126          * needed because we need to know the offset of the chunk after the last
127          * chunk read to figure out the size of the last read chunk. */
128         if (end_chunk != num_chunks - 1)
129                 num_needed_chunks++;
130
131         /* Declare the chunk table.  It will only contain offsets for the chunks
132          * that are actually needed for this read. */
133         u64 chunk_offsets[num_needed_chunks];
134
135         /* Set the implicit offset of the first chunk if it is included in the
136          * needed chunks.
137          *
138          * Note: M$'s documentation includes a picture that shows the first
139          * chunk starting right after the chunk entry table, labeled as offset
140          * 0x10.  However, in the actual file format, the offset is measured
141          * from the end of the chunk entry table, so the first chunk has an
142          * offset of 0. */
143         if (start_chunk == 0)
144                 chunk_offsets[0] = 0;
145
146         /* According to M$'s documentation, if the uncompressed size of
147          * the file is greater than 4 GB, the chunk entries are 8-byte
148          * integers.  Otherwise, they are 4-byte integers. */
149         u64 chunk_entry_size = (resource_uncompressed_size >= (u64)1 << 32) ?
150                                                                         8 : 4;
151
152         /* Size of the full chunk table in the WIM file. */
153         u64 chunk_table_size = chunk_entry_size * num_chunk_entries;
154
155         /* Read the needed chunk offsets from the table in the WIM file. */
156
157         /* Index, in the WIM file, of the first needed entry in the
158          * chunk table. */
159         u64 start_table_idx = (start_chunk == 0) ? 0 : start_chunk - 1;
160
161         /* Number of entries we need to actually read from the chunk
162          * table (excludes the implicit first chunk). */
163         u64 num_needed_chunk_entries = (start_chunk == 0) ?
164                                 num_needed_chunks - 1 : num_needed_chunks;
165
166         /* Skip over unneeded chunk table entries. */
167         u64 file_offset_of_needed_chunk_entries = resource_offset +
168                                 start_table_idx * chunk_entry_size;
169         if (fseeko(fp, file_offset_of_needed_chunk_entries, SEEK_SET) != 0) {
170                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
171                                  "chunk table of compressed resource",
172                                  file_offset_of_needed_chunk_entries);
173                 return WIMLIB_ERR_READ;
174         }
175
176         /* Number of bytes we need to read from the chunk table. */
177         size_t size = num_needed_chunk_entries * chunk_entry_size;
178
179         u8 chunk_tab_buf[size];
180
181         if (fread(chunk_tab_buf, 1, size, fp) != size)
182                 goto err;
183
184         /* Now fill in chunk_offsets from the entries we have read in
185          * chunk_tab_buf. */
186
187         u64 *chunk_tab_p = chunk_offsets;
188         if (start_chunk == 0)
189                 chunk_tab_p++;
190
191         if (chunk_entry_size == 4) {
192                 u32 *entries = (u32*)chunk_tab_buf;
193                 while (num_needed_chunk_entries--)
194                         *chunk_tab_p++ = le32_to_cpu(*entries++);
195         } else {
196                 u64 *entries = (u64*)chunk_tab_buf;
197                 while (num_needed_chunk_entries--)
198                         *chunk_tab_p++ = le64_to_cpu(*entries++);
199         }
200
201         /* Done with the chunk table now.  We must now seek to the first chunk
202          * that is needed for the read. */
203
204         u64 file_offset_of_first_needed_chunk = resource_offset +
205                                 chunk_table_size + chunk_offsets[0];
206         if (fseeko(fp, file_offset_of_first_needed_chunk, SEEK_SET) != 0) {
207                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
208                                  "first chunk of compressed resource",
209                                  file_offset_of_first_needed_chunk);
210                 return WIMLIB_ERR_READ;
211         }
212
213         /* Pointer to current position in the output buffer for uncompressed
214          * data. */
215         u8 *out_p = (u8*)contents_ret;
216
217         /* Buffer for compressed data.  While most compressed chunks will have a
218          * size much less than WIM_CHUNK_SIZE, WIM_CHUNK_SIZE - 1 is the maximum
219          * size in the worst-case.  This assumption is valid only if chunks that
220          * happen to compress to more than the uncompressed size (i.e. a
221          * sequence of random bytes) are always stored uncompressed. But this seems
222          * to be the case in M$'s WIM files, even though it is undocumented. */
223         u8 compressed_buf[WIM_CHUNK_SIZE - 1];
224
225
226         /* Decompress all the chunks. */
227         for (u64 i = start_chunk; i <= end_chunk; i++) {
228
229                 DEBUG2("Chunk %"PRIu64" (start %"PRIu64", end %"PRIu64").",
230                        i, start_chunk, end_chunk);
231
232                 /* Calculate the sizes of the compressed chunk and of the
233                  * uncompressed chunk. */
234                 uint compressed_chunk_size, uncompressed_chunk_size;
235                 if (i != num_chunks - 1) {
236                         /* All the chunks except the last one in the resource
237                          * expand to WIM_CHUNK_SIZE uncompressed, and the amount
238                          * of compressed data for the chunk is given by the
239                          * difference of offsets in the chunk offset table. */
240                         compressed_chunk_size = chunk_offsets[i + 1 - start_chunk] -
241                                                 chunk_offsets[i - start_chunk];
242                         uncompressed_chunk_size = WIM_CHUNK_SIZE;
243                 } else {
244                         /* The last compressed chunk consists of the remaining
245                          * bytes in the file resource, and the last uncompressed
246                          * chunk has size equal to however many bytes are left-
247                          * that is, the remainder of the uncompressed size when
248                          * divided by WIM_CHUNK_SIZE.
249                          *
250                          * Note that the resource_compressed_size includes the
251                          * chunk table, so the size of it must be subtracted. */
252                         compressed_chunk_size = resource_compressed_size -
253                                                 chunk_table_size -
254                                                 chunk_offsets[i - start_chunk];
255
256                         uncompressed_chunk_size = resource_uncompressed_size %
257                                                                 WIM_CHUNK_SIZE;
258
259                         /* If the remainder is 0, the last chunk actually
260                          * uncompresses to a full WIM_CHUNK_SIZE bytes. */
261                         if (uncompressed_chunk_size == 0)
262                                 uncompressed_chunk_size = WIM_CHUNK_SIZE;
263                 }
264
265                 DEBUG2("compressed_chunk_size = %u, "
266                        "uncompressed_chunk_size = %u",
267                        compressed_chunk_size, uncompressed_chunk_size);
268
269
270                 /* Figure out how much of this chunk we actually need to read */
271                 u64 start_offset;
272                 if (i == start_chunk)
273                         start_offset = start_chunk_offset;
274                 else
275                         start_offset = 0;
276                 u64 end_offset;
277                 if (i == end_chunk)
278                         end_offset = end_chunk_offset;
279                 else
280                         end_offset = WIM_CHUNK_SIZE - 1;
281
282                 u64 partial_chunk_size = end_offset + 1 - start_offset;
283                 bool is_partial_chunk = (partial_chunk_size !=
284                                                 uncompressed_chunk_size);
285
286                 DEBUG2("start_offset = %u, end_offset = %u", start_offset,
287                                         end_offset);
288                 DEBUG2("partial_chunk_size = %u", partial_chunk_size);
289
290                 /* This is undocumented, but chunks can be uncompressed.  This
291                  * appears to always be the case when the compressed chunk size
292                  * is equal to the uncompressed chunk size. */
293                 if (compressed_chunk_size == uncompressed_chunk_size) {
294                         /* Probably an uncompressed chunk */
295
296                         if (start_offset != 0) {
297                                 if (fseeko(fp, start_offset, SEEK_CUR) != 0) {
298                                         ERROR_WITH_ERRNO("Uncompressed partial "
299                                                          "chunk fseek() error");
300                                         return WIMLIB_ERR_READ;
301                                 }
302                         }
303                         if (fread(out_p, 1, partial_chunk_size, fp) !=
304                                         partial_chunk_size)
305                                 goto err;
306                 } else {
307                         /* Compressed chunk */
308                         int ret;
309
310                         /* Read the compressed data into compressed_buf. */
311                         if (fread(compressed_buf, 1, compressed_chunk_size,
312                                                 fp) != compressed_chunk_size)
313                                 goto err;
314
315                         /* For partial chunks we must buffer the uncompressed
316                          * data because we don't need all of it. */
317                         if (is_partial_chunk) {
318                                 u8 uncompressed_buf[uncompressed_chunk_size];
319
320                                 ret = decompress(compressed_buf,
321                                                 compressed_chunk_size,
322                                                 uncompressed_buf,
323                                                 uncompressed_chunk_size);
324                                 if (ret != 0)
325                                         return WIMLIB_ERR_DECOMPRESSION;
326                                 memcpy(out_p, uncompressed_buf + start_offset,
327                                                 partial_chunk_size);
328                         } else {
329                                 ret = decompress(compressed_buf,
330                                                 compressed_chunk_size,
331                                                 out_p,
332                                                 uncompressed_chunk_size);
333                                 if (ret != 0)
334                                         return WIMLIB_ERR_DECOMPRESSION;
335                         }
336                 }
337
338                 /* Advance the pointer into the uncompressed output data by the
339                  * number of uncompressed bytes that were written.  */
340                 out_p += partial_chunk_size;
341         }
342
343         return 0;
344
345 err:
346         if (feof(fp))
347                 ERROR("Unexpected EOF in compressed file resource");
348         else
349                 ERROR_WITH_ERRNO("Error reading compressed file resource");
350         return WIMLIB_ERR_READ;
351 }
352
353 /*
354  * Reads uncompressed data from an open file stream.
355  */
356 int read_uncompressed_resource(FILE *fp, u64 offset, u64 len,
357                                u8 contents_ret[])
358 {
359         if (fseeko(fp, offset, SEEK_SET) != 0) {
360                 ERROR("Failed to seek to byte %"PRIu64" of input file "
361                       "to read uncompressed resource (len = %"PRIu64")",
362                       offset, len);
363                 return WIMLIB_ERR_READ;
364         }
365         if (fread(contents_ret, 1, len, fp) != len) {
366                 if (feof(fp)) {
367                         ERROR("Unexpected EOF in uncompressed file resource");
368                 } else {
369                         ERROR("Failed to read %"PRIu64" bytes from "
370                               "uncompressed resource at offset %"PRIu64,
371                               len, offset);
372                 }
373                 return WIMLIB_ERR_READ;
374         }
375         return 0;
376 }
377
378
379
380
381 /* Reads the contents of a struct resource_entry, as represented in the on-disk
382  * format, from the memory pointed to by @p, and fills in the fields of @entry.
383  * A pointer to the byte after the memory read at @p is returned. */
384 const u8 *get_resource_entry(const u8 *p, struct resource_entry *entry)
385 {
386         u64 size;
387         u8 flags;
388
389         p = get_u56(p, &size);
390         p = get_u8(p, &flags);
391         entry->size = size;
392         entry->flags = flags;
393
394         /* offset and original_size are truncated to 62 bits to avoid possible
395          * overflows, when converting to a signed 64-bit integer (off_t) or when
396          * adding size or original_size.  This is okay since no one would ever
397          * actually have a WIM bigger than 4611686018427387903 bytes... */
398         p = get_u64(p, &entry->offset);
399         if (entry->offset & 0xc000000000000000ULL) {
400                 WARNING("Truncating offset in resource entry");
401                 entry->offset &= 0x3fffffffffffffffULL;
402         }
403         p = get_u64(p, &entry->original_size);
404         if (entry->original_size & 0xc000000000000000ULL) {
405                 WARNING("Truncating original_size in resource entry");
406                 entry->original_size &= 0x3fffffffffffffffULL;
407         }
408         return p;
409 }
410
411 /* Copies the struct resource_entry @entry to the memory pointed to by @p in the
412  * on-disk format.  A pointer to the byte after the memory written at @p is
413  * returned. */
414 u8 *put_resource_entry(u8 *p, const struct resource_entry *entry)
415 {
416         p = put_u56(p, entry->size);
417         p = put_u8(p, entry->flags);
418         p = put_u64(p, entry->offset);
419         p = put_u64(p, entry->original_size);
420         return p;
421 }
422
423 /*
424  * Reads some data from the resource corresponding to a WIM lookup table entry.
425  *
426  * @lte:        The WIM lookup table entry for the resource.
427  * @buf:        Buffer into which to write the data.
428  * @size:       Number of bytes to read.
429  * @offset:     Offset at which to start reading the resource.
430  * @raw:        If %true, compressed data is read literally rather than being
431  *                      decompressed first.
432  *
433  * Returns zero on success, nonzero on failure.
434  */
435 int read_wim_resource(const struct lookup_table_entry *lte, u8 buf[],
436                       size_t size, u64 offset, bool raw)
437 {
438         int ctype;
439         int ret = 0;
440         FILE *fp;
441
442         /* We shouldn't be allowing read over-runs in any part of the library.
443          * */
444         if (raw)
445                 wimlib_assert(offset + size <= lte->resource_entry.size);
446         else
447                 wimlib_assert(offset + size <= lte->resource_entry.original_size);
448
449         switch (lte->resource_location) {
450         case RESOURCE_IN_WIM:
451                 /* The resource is in a WIM file, and its WIMStruct is given by
452                  * the lte->wim member.  The resource may be either compressed
453                  * or uncompressed. */
454                 wimlib_assert(lte->wim != NULL);
455                 wimlib_assert(lte->wim->fp != NULL);
456                 ctype = wim_resource_compression_type(lte);
457
458                 wimlib_assert(ctype != WIM_COMPRESSION_TYPE_NONE ||
459                               (lte->resource_entry.original_size ==
460                                lte->resource_entry.size));
461
462                 if (raw || ctype == WIM_COMPRESSION_TYPE_NONE)
463                         ret = read_uncompressed_resource(lte->wim->fp,
464                                                          lte->resource_entry.offset + offset,
465                                                          size, buf);
466                 else
467                         ret = read_compressed_resource(lte->wim->fp,
468                                                        lte->resource_entry.size,
469                                                        lte->resource_entry.original_size,
470                                                        lte->resource_entry.offset,
471                                                        ctype, size, offset, buf);
472                 break;
473         case RESOURCE_IN_STAGING_FILE:
474         case RESOURCE_IN_FILE_ON_DISK:
475                 /* The resource is in some file on the external filesystem and
476                  * needs to be read uncompressed */
477                 wimlib_assert(lte->file_on_disk);
478                 wimlib_assert(&lte->file_on_disk == &lte->staging_file_name);
479                 /* Use existing file pointer if available; otherwise open one
480                  * temporarily */
481                 if (lte->file_on_disk_fp) {
482                         fp = lte->file_on_disk_fp;
483                 } else {
484                         fp = fopen(lte->file_on_disk, "rb");
485                         if (!fp) {
486                                 ERROR_WITH_ERRNO("Failed to open the file "
487                                                  "`%s'", lte->file_on_disk);
488                                 ret = WIMLIB_ERR_OPEN;
489                                 break;
490                         }
491                 }
492                 ret = read_uncompressed_resource(fp, offset, size, buf);
493                 if (fp != lte->file_on_disk_fp)
494                         fclose(fp);
495                 break;
496         case RESOURCE_IN_ATTACHED_BUFFER:
497                 /* The resource is directly attached uncompressed in an
498                  * in-memory buffer. */
499                 wimlib_assert(lte->attached_buffer != NULL);
500                 memcpy(buf, lte->attached_buffer + offset, size);
501                 break;
502 #ifdef WITH_NTFS_3G
503         case RESOURCE_IN_NTFS_VOLUME:
504                 wimlib_assert(lte->ntfs_loc != NULL);
505                 wimlib_assert(lte->attr != NULL);
506                 {
507                         if (lte->ntfs_loc->is_reparse_point)
508                                 offset += 8;
509                         if (ntfs_attr_pread(lte->attr, offset, size, buf) != size) {
510                                 ERROR_WITH_ERRNO("Error reading NTFS attribute "
511                                                  "at `%s'",
512                                                  lte->ntfs_loc->path_utf8);
513                                 ret = WIMLIB_ERR_NTFS_3G;
514                         }
515                         break;
516                 }
517 #endif
518         default:
519                 wimlib_assert(0);
520                 ret = -1;
521                 break;
522         }
523         return ret;
524 }
525
526 /*
527  * Reads all the data from the resource corresponding to a WIM lookup table
528  * entry.
529  *
530  * @lte:        The WIM lookup table entry for the resource.
531  * @buf:        Buffer into which to write the data.  It must be at least
532  *              wim_resource_size(lte) bytes long.
533  *
534  * Returns 0 on success; nonzero on failure.
535  */
536 int read_full_wim_resource(const struct lookup_table_entry *lte, u8 buf[])
537 {
538         return read_wim_resource(lte, buf, wim_resource_size(lte), 0, false);
539 }
540
541 /* Chunk table that's located at the beginning of each compressed resource in
542  * the WIM.  (This is not the on-disk format; the on-disk format just has an
543  * array of offsets.) */
544 struct chunk_table {
545         off_t file_offset;
546         u64 num_chunks;
547         u64 original_resource_size;
548         u64 bytes_per_chunk_entry;
549         u64 table_disk_size;
550         u64 cur_offset;
551         u64 *cur_offset_p;
552         u64 offsets[0];
553 };
554
555 /*
556  * Allocates and initializes a chunk table, and reserves space for it in the
557  * output file.
558  */
559 static int
560 begin_wim_resource_chunk_tab(const struct lookup_table_entry *lte,
561                              FILE *out_fp,
562                              off_t file_offset,
563                              struct chunk_table **chunk_tab_ret)
564 {
565         u64 size = wim_resource_size(lte);
566         u64 num_chunks = (size + WIM_CHUNK_SIZE - 1) / WIM_CHUNK_SIZE;
567         size_t alloc_size = sizeof(struct chunk_table) + num_chunks * sizeof(u64);
568         struct chunk_table *chunk_tab = CALLOC(1, alloc_size);
569         int ret;
570
571         if (!chunk_tab) {
572                 ERROR("Failed to allocate chunk table for %"PRIu64" byte "
573                       "resource", size);
574                 ret = WIMLIB_ERR_NOMEM;
575                 goto out;
576         }
577         chunk_tab->file_offset = file_offset;
578         chunk_tab->num_chunks = num_chunks;
579         chunk_tab->original_resource_size = size;
580         chunk_tab->bytes_per_chunk_entry = (size >= (1ULL << 32)) ? 8 : 4;
581         chunk_tab->table_disk_size = chunk_tab->bytes_per_chunk_entry *
582                                      (num_chunks - 1);
583         chunk_tab->cur_offset = 0;
584         chunk_tab->cur_offset_p = chunk_tab->offsets;
585
586         if (fwrite(chunk_tab, 1, chunk_tab->table_disk_size, out_fp) !=
587                    chunk_tab->table_disk_size) {
588                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
589                                  "file resource");
590                 ret = WIMLIB_ERR_WRITE;
591                 goto out;
592         }
593
594         ret = 0;
595 out:
596         *chunk_tab_ret = chunk_tab;
597         return ret;
598 }
599
600 /*
601  * Compresses a chunk of a WIM resource.
602  *
603  * @chunk:              Uncompressed data of the chunk.
604  * @chunk_size:         Size of the uncompressed chunk in bytes.
605  * @compressed_chunk:   Pointer to output buffer of size at least
606  *                              (@chunk_size - 1) bytes.
607  * @compressed_chunk_len_ret:   Pointer to an unsigned int into which the size
608  *                                      of the compressed chunk will be
609  *                                      returned.
610  * @ctype:      Type of compression to use.  Must be WIM_COMPRESSION_TYPE_LZX
611  *              or WIM_COMPRESSION_TYPE_XPRESS.
612  *
613  * Returns zero if compressed succeeded, and nonzero if the chunk could not be
614  * compressed to any smaller than @chunk_size.  This function cannot fail for
615  * any other reasons.
616  */
617 static int compress_chunk(const u8 chunk[], unsigned chunk_size,
618                           u8 compressed_chunk[],
619                           unsigned *compressed_chunk_len_ret,
620                           int ctype)
621 {
622         int (*compress)(const void *, unsigned, void *, unsigned *);
623         switch (ctype) {
624         case WIM_COMPRESSION_TYPE_LZX:
625                 compress = lzx_compress;
626                 break;
627         case WIM_COMPRESSION_TYPE_XPRESS:
628                 compress = xpress_compress;
629                 break;
630         default:
631                 wimlib_assert(0);
632                 break;
633         }
634         return (*compress)(chunk, chunk_size, compressed_chunk,
635                            compressed_chunk_len_ret);
636 }
637
638 /*
639  * Writes a chunk of a WIM resource to an output file.
640  *
641  * @chunk:        Uncompressed data of the chunk.
642  * @chunk_size:   Size of the chunk (<= WIM_CHUNK_SIZE)
643  * @out_fp:       FILE * to write tho chunk to.
644  * @out_ctype:    Compression type to use when writing the chunk (ignored if no
645  *                      chunk table provided)
646  * @chunk_tab:    Pointer to chunk table being created.  It is updated with the
647  *                      offset of the chunk we write.
648  *
649  * Returns 0 on success; nonzero on failure.
650  */
651 static int write_wim_resource_chunk(const u8 chunk[], unsigned chunk_size,
652                                     FILE *out_fp, int out_ctype,
653                                     struct chunk_table *chunk_tab)
654 {
655         const u8 *out_chunk;
656         unsigned out_chunk_size;
657
658         wimlib_assert(chunk_size <= WIM_CHUNK_SIZE);
659
660         if (!chunk_tab) {
661                 out_chunk = chunk;
662                 out_chunk_size = chunk_size;
663         } else {
664                 u8 *compressed_chunk = alloca(chunk_size);
665                 int ret;
666
667                 ret = compress_chunk(chunk, chunk_size, compressed_chunk,
668                                      &out_chunk_size, out_ctype);
669                 if (ret == 0) {
670                         out_chunk = compressed_chunk;
671                 } else {
672                         out_chunk = chunk;
673                         out_chunk_size = chunk_size;
674                 }
675                 *chunk_tab->cur_offset_p++ = chunk_tab->cur_offset;
676                 chunk_tab->cur_offset += out_chunk_size;
677         }
678
679         if (fwrite(out_chunk, 1, out_chunk_size, out_fp) != out_chunk_size) {
680                 ERROR_WITH_ERRNO("Failed to write WIM resource chunk");
681                 return WIMLIB_ERR_WRITE;
682         }
683         return 0;
684 }
685
686 /*
687  * Finishes a WIM chunk tale and writes it to the output file at the correct
688  * offset.
689  *
690  * The final size of the full compressed resource is returned in the
691  * @compressed_size_p.
692  */
693 static int
694 finish_wim_resource_chunk_tab(struct chunk_table *chunk_tab,
695                               FILE *out_fp, u64 *compressed_size_p)
696 {
697         size_t bytes_written;
698         if (fseeko(out_fp, chunk_tab->file_offset, SEEK_SET) != 0) {
699                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" of output "
700                                  "WIM file", chunk_tab->file_offset);
701                 return WIMLIB_ERR_WRITE;
702         }
703
704         if (chunk_tab->bytes_per_chunk_entry == 8) {
705                 array_cpu_to_le64(chunk_tab->offsets, chunk_tab->num_chunks);
706         } else {
707                 for (u64 i = 0; i < chunk_tab->num_chunks; i++)
708                         ((u32*)chunk_tab->offsets)[i] =
709                                 cpu_to_le32(chunk_tab->offsets[i]);
710         }
711         bytes_written = fwrite((u8*)chunk_tab->offsets +
712                                         chunk_tab->bytes_per_chunk_entry,
713                                1, chunk_tab->table_disk_size, out_fp);
714         if (bytes_written != chunk_tab->table_disk_size) {
715                 ERROR_WITH_ERRNO("Failed to write chunk table in compressed "
716                                  "file resource");
717                 return WIMLIB_ERR_WRITE;
718         }
719         if (fseeko(out_fp, 0, SEEK_END) != 0) {
720                 ERROR_WITH_ERRNO("Failed to seek to end of output WIM file");
721                 return WIMLIB_ERR_WRITE;
722         }
723         *compressed_size_p = chunk_tab->cur_offset + chunk_tab->table_disk_size;
724         return 0;
725 }
726
727 /*
728  * Writes a WIM resource to a FILE * opened for writing.  The resource may be
729  * written uncompressed or compressed depending on the @out_ctype parameter.
730  *
731  * If by chance the resource compresses to more than the original size (this may
732  * happen with random data or files than are pre-compressed), the resource is
733  * instead written uncompressed (and this is reflected in the @out_res_entry by
734  * removing the WIM_RESHDR_FLAG_COMPRESSED flag).
735  *
736  * @lte:        The lookup table entry for the WIM resource.
737  * @out_fp:     The FILE * to write the resource to.
738  * @out_ctype:  The compression type of the resource to write.  Note: if this is
739  *                      the same as the compression type of the WIM resource we
740  *                      need to read, we simply copy the data (i.e. we do not
741  *                      uncompress it, then compress it again).
742  * @out_res_entry:  If non-NULL, a resource entry that is filled in with the
743  *                  offset, original size, compressed size, and compression flag
744  *                  of the output resource.
745  *
746  * Returns 0 on success; nonzero on failure.
747  */
748 static int write_wim_resource(struct lookup_table_entry *lte,
749                               FILE *out_fp, int out_ctype,
750                               struct resource_entry *out_res_entry)
751 {
752         u64 bytes_remaining;
753         u64 original_size;
754         u64 old_compressed_size;
755         u64 new_compressed_size;
756         u64 offset;
757         int ret;
758         struct chunk_table *chunk_tab = NULL;
759         bool raw;
760         off_t file_offset;
761 #ifdef WITH_NTFS_3G
762         ntfs_inode *ni = NULL;
763 #endif
764
765         wimlib_assert(lte);
766
767         /* Original size of the resource */
768         original_size = wim_resource_size(lte);
769
770         /* Compressed size of the resource (as it exists now) */
771         old_compressed_size = wim_resource_compressed_size(lte);
772
773         /* Current offset in output file */
774         file_offset = ftello(out_fp);
775         if (file_offset == -1) {
776                 ERROR_WITH_ERRNO("Failed to get offset in output "
777                                  "stream");
778                 return WIMLIB_ERR_WRITE;
779         }
780
781         /* Are the compression types the same?  If so, do a raw copy (copy
782          * without decompressing and recompressing the data). */
783         raw = (wim_resource_compression_type(lte) == out_ctype
784                && out_ctype != WIM_COMPRESSION_TYPE_NONE);
785         if (raw)
786                 bytes_remaining = old_compressed_size;
787         else
788                 bytes_remaining = original_size;
789
790         /* Empty resource; nothing needs to be done, so just return success. */
791         if (bytes_remaining == 0)
792                 return 0;
793
794         /* Buffer for reading chunks for the resource */
795         u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
796
797         /* If we are writing a compressed resource and not doing a raw copy, we
798          * need to initialize the chunk table */
799         if (out_ctype != WIM_COMPRESSION_TYPE_NONE && !raw) {
800                 ret = begin_wim_resource_chunk_tab(lte, out_fp, file_offset,
801                                                    &chunk_tab);
802                 if (ret != 0)
803                         goto out;
804         }
805
806         /* If the WIM resource is in an external file, open a FILE * to it so we
807          * don't have to open a temporary one in read_wim_resource() for each
808          * chunk. */
809         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
810              && !lte->file_on_disk_fp)
811         {
812                 wimlib_assert(lte->file_on_disk);
813                 lte->file_on_disk_fp = fopen(lte->file_on_disk, "rb");
814                 if (!lte->file_on_disk_fp) {
815                         ERROR_WITH_ERRNO("Failed to open the file `%s' for "
816                                          "reading", lte->file_on_disk);
817                         ret = WIMLIB_ERR_OPEN;
818                         goto out;
819                 }
820         }
821 #ifdef WITH_NTFS_3G
822         else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME
823                   && !lte->attr)
824         {
825                 struct ntfs_location *loc = lte->ntfs_loc;
826                 wimlib_assert(loc);
827                 ni = ntfs_pathname_to_inode(*loc->ntfs_vol_p, NULL, loc->path_utf8);
828                 if (!ni) {
829                         ERROR_WITH_ERRNO("Failed to open inode `%s' in NTFS "
830                                          "volume", loc->path_utf8);
831                         ret = WIMLIB_ERR_NTFS_3G;
832                         goto out;
833                 }
834                 lte->attr = ntfs_attr_open(ni,
835                                            loc->is_reparse_point ? AT_REPARSE_POINT : AT_DATA,
836                                            (ntfschar*)loc->stream_name_utf16,
837                                            loc->stream_name_utf16_num_chars);
838                 if (!lte->attr) {
839                         ERROR_WITH_ERRNO("Failed to open attribute of `%s' in "
840                                          "NTFS volume", loc->path_utf8);
841                         ret = WIMLIB_ERR_NTFS_3G;
842                         goto out_fclose;
843                 }
844         }
845 #endif
846
847         /* If we aren't doing a raw copy, we will compute the SHA1 message
848          * digest of the resource as we read it, and verify it's the same as the
849          * hash given in the lookup table entry once we've finished reading the
850          * resource. */
851         SHA_CTX ctx;
852         if (!raw)
853                 sha1_init(&ctx);
854
855         /* While there are still bytes remaining in the WIM resource, read a
856          * chunk of the resource, update SHA1, then write that chunk using the
857          * desired compression type. */
858         offset = 0;
859         do {
860                 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
861                 ret = read_wim_resource(lte, buf, to_read, offset, raw);
862                 if (ret != 0)
863                         goto out_fclose;
864                 if (!raw)
865                         sha1_update(&ctx, buf, to_read);
866                 ret = write_wim_resource_chunk(buf, to_read, out_fp,
867                                                out_ctype, chunk_tab);
868                 if (ret != 0)
869                         goto out_fclose;
870                 bytes_remaining -= to_read;
871                 offset += to_read;
872         } while (bytes_remaining);
873
874         /* Raw copy:  The new compressed size is the same as the old compressed
875          * size
876          *
877          * Using WIM_COMPRESSION_TYPE_NONE:  The new compressed size is the
878          * original size
879          *
880          * Using a different compression type:  Call
881          * finish_wim_resource_chunk_tab() and it will provide the new
882          * compressed size.
883          */
884         if (raw) {
885                 new_compressed_size = old_compressed_size;
886         } else {
887                 if (out_ctype == WIM_COMPRESSION_TYPE_NONE)
888                         new_compressed_size = original_size;
889                 else {
890                         ret = finish_wim_resource_chunk_tab(chunk_tab, out_fp,
891                                                             &new_compressed_size);
892                         if (ret != 0)
893                                 goto out_fclose;
894                 }
895         }
896
897         /* Verify SHA1 message digest of the resource, unless we are doing a raw
898          * write (in which case we never even saw the uncompressed data).  Or,
899          * if the hash we had before is all 0's, just re-set it to be the new
900          * hash. */
901         if (!raw) {
902                 u8 md[SHA1_HASH_SIZE];
903                 sha1_final(md, &ctx);
904                 if (is_zero_hash(lte->hash)) {
905                         copy_hash(lte->hash, md);
906                 } else if (!hashes_equal(md, lte->hash)) {
907                         ERROR("WIM resource has incorrect hash!");
908                         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK) {
909                                 ERROR("We were reading it from `%s'; maybe it changed "
910                                       "while we were reading it.",
911                                       lte->file_on_disk);
912                         }
913                         ret = WIMLIB_ERR_INVALID_RESOURCE_HASH;
914                         goto out_fclose;
915                 }
916         }
917
918         if (!raw && new_compressed_size >= original_size &&
919             out_ctype != WIM_COMPRESSION_TYPE_NONE)
920         {
921                 /* Oops!  We compressed the resource to larger than the original
922                  * size.  Write the resource uncompressed instead. */
923                 if (fseeko(out_fp, file_offset, SEEK_SET) != 0) {
924                         ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" "
925                                          "of output WIM file", file_offset);
926                         ret = WIMLIB_ERR_WRITE;
927                         goto out_fclose;
928                 }
929                 ret = write_wim_resource(lte, out_fp, WIM_COMPRESSION_TYPE_NONE,
930                                          out_res_entry);
931                 if (ret != 0)
932                         goto out_fclose;
933                 if (fflush(out_fp) != 0) {
934                         ERROR_WITH_ERRNO("Failed to flush output WIM file");
935                         ret = WIMLIB_ERR_WRITE;
936                         goto out_fclose;
937                 }
938                 if (ftruncate(fileno(out_fp), file_offset + out_res_entry->size) != 0) {
939                         ERROR_WITH_ERRNO("Failed to truncate output WIM file");
940                         ret = WIMLIB_ERR_WRITE;
941                         goto out_fclose;
942                 }
943         } else {
944                 if (out_res_entry) {
945                         out_res_entry->size          = new_compressed_size;
946                         out_res_entry->original_size = original_size;
947                         out_res_entry->offset        = file_offset;
948                         out_res_entry->flags         = lte->resource_entry.flags
949                                                         & ~WIM_RESHDR_FLAG_COMPRESSED;
950                         if (out_ctype != WIM_COMPRESSION_TYPE_NONE)
951                                 out_res_entry->flags |= WIM_RESHDR_FLAG_COMPRESSED;
952                 }
953         }
954         ret = 0;
955 out_fclose:
956         if (lte->resource_location == RESOURCE_IN_FILE_ON_DISK
957             && lte->file_on_disk_fp) {
958                 fclose(lte->file_on_disk_fp);
959                 lte->file_on_disk_fp = NULL;
960         }
961 #ifdef WITH_NTFS_3G
962         else if (lte->resource_location == RESOURCE_IN_NTFS_VOLUME) {
963                 if (lte->attr) {
964                         ntfs_attr_close(lte->attr);
965                         lte->attr = NULL;
966                 }
967                 if (ni)
968                         ntfs_inode_close(ni);
969         }
970 #endif
971 out:
972         FREE(chunk_tab);
973         return ret;
974 }
975
976 /* Like write_wim_resource(), but the resource is specified by a buffer of
977  * uncompressed data rather a lookup table entry; also writes the SHA1 hash of
978  * the buffer to @hash.  */
979 static int write_wim_resource_from_buffer(const u8 *buf, u64 buf_size,
980                                           FILE *out_fp, int out_ctype,
981                                           struct resource_entry *out_res_entry,
982                                           u8 hash[SHA1_HASH_SIZE])
983 {
984         /* Set up a temporary lookup table entry to provide to
985          * write_wim_resource(). */
986         struct lookup_table_entry lte;
987         int ret;
988         lte.resource_entry.flags         = 0;
989         lte.resource_entry.original_size = buf_size;
990         lte.resource_entry.size          = buf_size;
991         lte.resource_entry.offset        = 0;
992         lte.resource_location            = RESOURCE_IN_ATTACHED_BUFFER;
993         lte.attached_buffer              = (u8*)buf;
994
995         zero_out_hash(lte.hash);
996         ret = write_wim_resource(&lte, out_fp, out_ctype, out_res_entry);
997         if (ret != 0)
998                 return ret;
999         copy_hash(hash, lte.hash);
1000         return 0;
1001 }
1002
1003 /*
1004  * Extracts the first @size bytes of the WIM resource specified by @lte to the
1005  * open file descriptor @fd.
1006  *
1007  * Returns 0 on success; nonzero on failure.
1008  */
1009 int extract_wim_resource_to_fd(const struct lookup_table_entry *lte, int fd,
1010                                u64 size)
1011 {
1012         u64 bytes_remaining = size;
1013         u8 buf[min(WIM_CHUNK_SIZE, bytes_remaining)];
1014         u64 offset = 0;
1015         int ret = 0;
1016         u8 hash[SHA1_HASH_SIZE];
1017
1018         SHA_CTX ctx;
1019         sha1_init(&ctx);
1020
1021         while (bytes_remaining) {
1022                 u64 to_read = min(bytes_remaining, WIM_CHUNK_SIZE);
1023                 ret = read_wim_resource(lte, buf, to_read, offset, false);
1024                 if (ret != 0)
1025                         break;
1026                 sha1_update(&ctx, buf, to_read);
1027                 if (full_write(fd, buf, to_read) < to_read) {
1028                         ERROR_WITH_ERRNO("Error extracting WIM resource");
1029                         return WIMLIB_ERR_WRITE;
1030                 }
1031                 bytes_remaining -= to_read;
1032                 offset += to_read;
1033         }
1034         sha1_final(hash, &ctx);
1035         if (!hashes_equal(hash, lte->hash)) {
1036                 ERROR("Invalid checksum on a WIM resource "
1037                       "(detected when extracting to external file)");
1038                 ERROR("The following WIM resource is invalid:");
1039                 print_lookup_table_entry(lte);
1040                 return WIMLIB_ERR_INVALID_RESOURCE_HASH;
1041         }
1042         return 0;
1043 }
1044
1045 /*
1046  * Extracts the WIM resource specified by @lte to the open file descriptor @fd.
1047  *
1048  * Returns 0 on success; nonzero on failure.
1049  */
1050 int extract_full_wim_resource_to_fd(const struct lookup_table_entry *lte, int fd)
1051 {
1052         return extract_wim_resource_to_fd(lte, fd, wim_resource_size(lte));
1053 }
1054
1055 /*
1056  * Copies the file resource specified by the lookup table entry @lte from the
1057  * input WIM to the output WIM that has its FILE * given by
1058  * ((WIMStruct*)wim)->out_fp.
1059  *
1060  * The output_resource_entry, out_refcnt, and part_number fields of @lte are
1061  * updated.
1062  *
1063  * Metadata resources are not copied (they are handled elsewhere for joining and
1064  * splitting).
1065  */
1066 int copy_resource(struct lookup_table_entry *lte, void *wim)
1067 {
1068         WIMStruct *w = wim;
1069         int ret;
1070
1071         if ((lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) &&
1072             !w->write_metadata)
1073                 return 0;
1074
1075         ret = write_wim_resource(lte, w->out_fp,
1076                                  wim_resource_compression_type(lte),
1077                                  &lte->output_resource_entry);
1078         if (ret != 0)
1079                 return ret;
1080         lte->out_refcnt = lte->refcnt;
1081         lte->part_number = w->hdr.part_number;
1082         return 0;
1083 }
1084
1085 /*
1086  * Writes a dentry's resources, including the main file resource as well as all
1087  * alternate data streams, to the output file.
1088  *
1089  * @dentry:  The dentry for the file.
1090  * @wim_p:   A pointer to the WIMStruct containing @dentry.
1091  *
1092  * @return zero on success, nonzero on failure.
1093  */
1094 int write_dentry_resources(struct dentry *dentry, void *wim_p)
1095 {
1096         WIMStruct *w = wim_p;
1097         int ret = 0;
1098         struct lookup_table_entry *lte;
1099         int ctype = wimlib_get_compression_type(w);
1100
1101         if (w->write_flags & WIMLIB_WRITE_FLAG_VERBOSE) {
1102                 wimlib_assert(dentry->full_path_utf8);
1103                 printf("Writing streams for `%s'\n", dentry->full_path_utf8);
1104         }
1105
1106         for (unsigned i = 0; i <= dentry->d_inode->num_ads; i++) {
1107                 lte = inode_stream_lte(dentry->d_inode, i, w->lookup_table);
1108                 if (lte && ++lte->out_refcnt == 1) {
1109                         ret = write_wim_resource(lte, w->out_fp, ctype,
1110                                                  &lte->output_resource_entry);
1111                         if (ret != 0)
1112                                 break;
1113                 }
1114         }
1115         return ret;
1116 }
1117
1118 /*
1119  * Reads the metadata metadata resource from the WIM file.  The metadata
1120  * resource consists of the security data, followed by the directory entry for
1121  * the root directory, followed by all the other directory entries in the
1122  * filesystem.  The subdir_offset field of each directory entry gives the start
1123  * of its child entries from the beginning of the metadata resource.  An
1124  * end-of-directory is signaled by a directory entry of length '0', really of
1125  * length 8, because that's how long the 'length' field is.
1126  *
1127  * @fp:         The FILE* for the input WIM file.
1128  * @wim_ctype:  The compression type of the WIM file.
1129  * @imd:        Pointer to the image metadata structure.  Its `metadata_lte'
1130  *              member specifies the lookup table entry for the metadata
1131  *              resource.  The rest of the image metadata entry will be filled
1132  *              in by this function.
1133  *
1134  * @return:     Zero on success, nonzero on failure.
1135  */
1136 int read_metadata_resource(WIMStruct *w, struct image_metadata *imd)
1137 {
1138         u8 *buf;
1139         u32 dentry_offset;
1140         int ret;
1141         struct dentry *dentry;
1142         struct inode_table inode_tab;
1143         const struct lookup_table_entry *metadata_lte;
1144         u64 metadata_len;
1145         u64 metadata_offset;
1146         struct hlist_head inode_list;
1147
1148         metadata_lte = imd->metadata_lte;
1149         metadata_len = wim_resource_size(metadata_lte);
1150         metadata_offset = metadata_lte->resource_entry.offset;
1151
1152         DEBUG("Reading metadata resource: length = %"PRIu64", "
1153               "offset = %"PRIu64"", metadata_len, metadata_offset);
1154
1155         /* There is no way the metadata resource could possibly be less than (8
1156          * + WIM_DENTRY_DISK_SIZE) bytes, where the 8 is for security data (with
1157          * no security descriptors) and WIM_DENTRY_DISK_SIZE is for the root
1158          * dentry. */
1159         if (metadata_len < 8 + WIM_DENTRY_DISK_SIZE) {
1160                 ERROR("Expected at least %u bytes for the metadata resource",
1161                       8 + WIM_DENTRY_DISK_SIZE);
1162                 return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
1163         }
1164
1165         if (sizeof(size_t) < 8 && metadata_len > 0xffffffff) {
1166                 ERROR("Metadata resource is too large (%"PRIu64" bytes",
1167                       metadata_len);
1168                 return WIMLIB_ERR_INVALID_RESOURCE_SIZE;
1169         }
1170
1171         /* Allocate memory for the uncompressed metadata resource. */
1172         buf = MALLOC(metadata_len);
1173
1174         if (!buf) {
1175                 ERROR("Failed to allocate %"PRIu64" bytes for uncompressed "
1176                       "metadata resource", metadata_len);
1177                 return WIMLIB_ERR_NOMEM;
1178         }
1179
1180         /* Read the metadata resource into memory.  (It may be compressed.) */
1181         ret = read_full_wim_resource(metadata_lte, buf);
1182         if (ret != 0)
1183                 goto out_free_buf;
1184
1185         DEBUG("Finished reading metadata resource into memory.");
1186
1187         /* The root directory entry starts after security data, aligned on an
1188          * 8-byte boundary within the metadata resource.
1189          *
1190          * The security data starts with a 4-byte integer giving its total
1191          * length, so if we round that up to an 8-byte boundary that gives us
1192          * the offset of the root dentry.
1193          *
1194          * Here we read the security data into a wim_security_data structure,
1195          * and if successful, go ahead and calculate the offset in the metadata
1196          * resource of the root dentry. */
1197
1198         wimlib_assert(imd->security_data == NULL);
1199         ret = read_security_data(buf, metadata_len, &imd->security_data);
1200         if (ret != 0)
1201                 goto out_free_buf;
1202
1203         dentry_offset = (imd->security_data->total_length + 7) & ~7;
1204
1205         if (dentry_offset == 0) {
1206                 ERROR("Integer overflow while reading metadata resource");
1207                 ret = WIMLIB_ERR_INVALID_SECURITY_DATA;
1208                 goto out_free_security_data;
1209         }
1210
1211         /* Allocate memory for the root dentry and read it into memory */
1212         dentry = MALLOC(sizeof(struct dentry));
1213         if (!dentry) {
1214                 ERROR("Failed to allocate %zu bytes for root dentry",
1215                       sizeof(struct dentry));
1216                 ret = WIMLIB_ERR_NOMEM;
1217                 goto out_free_security_data;
1218         }
1219
1220         ret = read_dentry(buf, metadata_len, dentry_offset, dentry);
1221
1222         /* This is the root dentry, so set its pointers correctly. */
1223         dentry->parent = dentry;
1224         dentry->next   = dentry;
1225         dentry->prev   = dentry;
1226         if (ret != 0)
1227                 goto out_free_dentry_tree;
1228         inode_add_dentry(dentry, dentry->d_inode);
1229
1230         /* Now read the entire directory entry tree into memory. */
1231         DEBUG("Reading dentry tree");
1232         ret = read_dentry_tree(buf, metadata_len, dentry);
1233         if (ret != 0)
1234                 goto out_free_dentry_tree;
1235
1236         /* Calculate the full paths in the dentry tree. */
1237         DEBUG("Calculating dentry full paths");
1238         ret = for_dentry_in_tree(dentry, calculate_dentry_full_path, NULL);
1239         if (ret != 0)
1240                 goto out_free_dentry_tree;
1241
1242         /* Build hash table that maps hard link group IDs to dentry sets */
1243         DEBUG("Building link group table");
1244         ret = init_inode_table(&inode_tab, 9001);
1245         if (ret != 0)
1246                 goto out_free_dentry_tree;
1247
1248         for_dentry_in_tree(dentry, inode_table_insert, &inode_tab);
1249
1250         DEBUG("Fixing inconsistencies in the hard link groups");
1251         ret = fix_inodes(&inode_tab, &inode_list);
1252         destroy_inode_table(&inode_tab);
1253         if (ret != 0)
1254                 goto out_free_dentry_tree;
1255
1256         DEBUG("Running miscellaneous verifications on the dentry tree");
1257         for_lookup_table_entry(w->lookup_table, lte_zero_real_refcnt, NULL);
1258         ret = for_dentry_in_tree(dentry, verify_dentry, w);
1259         if (ret != 0)
1260                 goto out_free_dentry_tree;
1261
1262         DEBUG("Done reading image metadata");
1263
1264         imd->root_dentry = dentry;
1265         imd->inode_list  = inode_list;
1266         goto out_free_buf;
1267 out_free_dentry_tree:
1268         free_dentry_tree(dentry, NULL);
1269 out_free_security_data:
1270         free_security_data(imd->security_data);
1271         imd->security_data = NULL;
1272 out_free_buf:
1273         FREE(buf);
1274         return ret;
1275 }
1276
1277 /* Write the metadata resource for the current WIM image. */
1278 int write_metadata_resource(WIMStruct *w)
1279 {
1280         u8 *buf;
1281         u8 *p;
1282         int ret;
1283         u64 subdir_offset;
1284         struct dentry *root;
1285         struct lookup_table_entry *lte;
1286         u64 metadata_original_size;
1287         const struct wim_security_data *sd;
1288
1289         DEBUG("Writing metadata resource for image %d", w->current_image);
1290
1291         root = wim_root_dentry(w);
1292         sd = wim_security_data(w);
1293
1294         /* We do not allow the security data pointer to be NULL, although it may
1295          * point to an empty security data with no entries. */
1296         wimlib_assert(root != NULL);
1297         wimlib_assert(sd != NULL);
1298
1299         /* Offset of first child of the root dentry.  It's equal to:
1300          * - The total length of the security data, rounded to the next 8-byte
1301          *   boundary,
1302          * - plus the total length of the root dentry,
1303          * - plus 8 bytes for an end-of-directory entry following the root
1304          *   dentry (shouldn't really be needed, but just in case...)
1305          */
1306         subdir_offset = ((sd->total_length + 7) & ~7) +
1307                         dentry_correct_total_length(root) + 8;
1308
1309         /* Calculate the subdirectory offsets for the entire dentry tree. */
1310         calculate_subdir_offsets(root, &subdir_offset);
1311
1312         /* Total length of the metadata resource (uncompressed) */
1313         metadata_original_size = subdir_offset;
1314
1315         /* Allocate a buffer to contain the uncompressed metadata resource */
1316         buf = MALLOC(metadata_original_size);
1317         if (!buf) {
1318                 ERROR("Failed to allocate %"PRIu64" bytes for "
1319                       "metadata resource", metadata_original_size);
1320                 return WIMLIB_ERR_NOMEM;
1321         }
1322
1323         /* Write the security data into the resource buffer */
1324         p = write_security_data(sd, buf);
1325
1326         /* Write the dentry tree into the resource buffer */
1327         p = write_dentry_tree(root, p);
1328
1329         /* We MUST have exactly filled the buffer; otherwise we calculated its
1330          * size incorrectly or wrote the data incorrectly. */
1331         wimlib_assert(p - buf == metadata_original_size);
1332
1333         /* Get the lookup table entry for the metadata resource so we can update
1334          * it. */
1335         lte = wim_metadata_lookup_table_entry(w);
1336
1337         wimlib_assert(lte != NULL);
1338
1339         /* Write the metadata resource to the output WIM using the proper
1340          * compression type.  The lookup table entry for the metadata resource
1341          * is updated. */
1342         ret = write_wim_resource_from_buffer(buf, metadata_original_size,
1343                                              w->out_fp,
1344                                              wimlib_get_compression_type(w),
1345                                              &lte->output_resource_entry,
1346                                              lte->hash);
1347         if (ret != 0)
1348                 goto out;
1349
1350         /* It's very likely the SHA1 message digest of the metadata resource
1351          * changed, so re-insert the lookup table entry into the lookup table.
1352          *
1353          * We do not check for other lookup table entries having the same SHA1
1354          * message digest.  It's possible for 2 absolutely identical images to
1355          * be added, therefore causing 2 identical metadata resources to be in
1356          * the WIM.  However, in this case, it's expected for 2 separate lookup
1357          * table entries to be created, even though this doesn't make a whole
1358          * lot of sense since they will share the same SHA1 message digest.
1359          * */
1360         lookup_table_unlink(w->lookup_table, lte);
1361         lookup_table_insert(w->lookup_table, lte);
1362
1363         wimlib_assert(lte->out_refcnt == 0);
1364         lte->out_refcnt = 1;
1365
1366         /* Make sure that the resource entry is written marked with the metadata
1367          * flag. */
1368         lte->output_resource_entry.flags |= WIM_RESHDR_FLAG_METADATA;
1369 out:
1370         /* All the data has been written to the new WIM; no need for the buffer
1371          * anymore */
1372         FREE(buf);
1373         return ret;
1374 }