]> wimlib.net Git - wimlib/blob - src/lookup_table.c
Use read_stream_list() for extraction
[wimlib] / src / lookup_table.c
1 /*
2  * lookup_table.c
3  *
4  * Lookup table, implemented as a hash table, that maps SHA1 message digests to
5  * data streams; plus code to read and write the corresponding on-disk data.
6  */
7
8 /*
9  * Copyright (C) 2012, 2013 Eric Biggers
10  *
11  * This file is part of wimlib, a library for working with WIM files.
12  *
13  * wimlib is free software; you can redistribute it and/or modify it under the
14  * terms of the GNU General Public License as published by the Free
15  * Software Foundation; either version 3 of the License, or (at your option)
16  * any later version.
17  *
18  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
19  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
20  * A PARTICULAR PURPOSE. See the GNU General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #ifdef HAVE_CONFIG_H
28 #  include "config.h"
29 #endif
30
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/glob.h"
35 #include "wimlib/lookup_table.h"
36 #include "wimlib/metadata.h"
37 #include "wimlib/paths.h"
38 #include "wimlib/resource.h"
39 #include "wimlib/util.h"
40 #include "wimlib/write.h"
41
42 #include <errno.h>
43 #include <stdlib.h>
44 #ifdef WITH_FUSE
45 #  include <unistd.h> /* for unlink() */
46 #endif
47
48 struct wim_lookup_table *
49 new_lookup_table(size_t capacity)
50 {
51         struct wim_lookup_table *table;
52         struct hlist_head *array;
53
54         table = CALLOC(1, sizeof(struct wim_lookup_table));
55         if (table) {
56                 array = CALLOC(capacity, sizeof(array[0]));
57                 if (array) {
58                         table->num_entries = 0;
59                         table->capacity = capacity;
60                         table->array = array;
61                 } else {
62                         FREE(table);
63                         table = NULL;
64                         ERROR("Failed to allocate memory for lookup table "
65                               "with capacity %zu", capacity);
66                 }
67         }
68         return table;
69 }
70
71 struct wim_lookup_table_entry *
72 new_lookup_table_entry(void)
73 {
74         struct wim_lookup_table_entry *lte;
75
76         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
77         if (lte == NULL) {
78                 ERROR("Out of memory (tried to allocate %zu bytes for "
79                       "lookup table entry)",
80                       sizeof(struct wim_lookup_table_entry));
81                 return NULL;
82         }
83         lte->refcnt = 1;
84         BUILD_BUG_ON(RESOURCE_NONEXISTENT != 0);
85         return lte;
86 }
87
88 struct wim_lookup_table_entry *
89 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
90 {
91         struct wim_lookup_table_entry *new;
92
93         new = memdup(old, sizeof(struct wim_lookup_table_entry));
94         if (!new)
95                 return NULL;
96
97         new->extracted_file = NULL;
98         switch (new->resource_location) {
99         case RESOURCE_IN_WIM:
100                 list_add(&new->wim_resource_list, &new->rspec->lte_list);
101                 break;
102
103         case RESOURCE_IN_FILE_ON_DISK:
104 #ifdef __WIN32__
105         case RESOURCE_WIN32_ENCRYPTED:
106 #endif
107 #ifdef WITH_FUSE
108         case RESOURCE_IN_STAGING_FILE:
109                 BUILD_BUG_ON((void*)&old->file_on_disk !=
110                              (void*)&old->staging_file_name);
111 #endif
112                 new->file_on_disk = TSTRDUP(old->file_on_disk);
113                 if (!new->file_on_disk)
114                         goto out_free;
115                 break;
116         case RESOURCE_IN_ATTACHED_BUFFER:
117                 new->attached_buffer = memdup(old->attached_buffer, old->size);
118                 if (!new->attached_buffer)
119                         goto out_free;
120                 break;
121 #ifdef WITH_NTFS_3G
122         case RESOURCE_IN_NTFS_VOLUME:
123                 if (old->ntfs_loc) {
124                         struct ntfs_location *loc;
125                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
126                         if (!loc)
127                                 goto out_free;
128                         loc->path = NULL;
129                         loc->stream_name = NULL;
130                         new->ntfs_loc = loc;
131                         loc->path = STRDUP(old->ntfs_loc->path);
132                         if (!loc->path)
133                                 goto out_free;
134                         if (loc->stream_name_nchars) {
135                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
136                                                           loc->stream_name_nchars * 2);
137                                 if (!loc->stream_name)
138                                         goto out_free;
139                         }
140                 }
141                 break;
142 #endif
143         default:
144                 break;
145         }
146         return new;
147 out_free:
148         free_lookup_table_entry(new);
149         return NULL;
150 }
151
152 void
153 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
154 {
155         if (lte) {
156                 switch (lte->resource_location) {
157                 case RESOURCE_IN_WIM:
158                         list_del(&lte->wim_resource_list);
159                         if (list_empty(&lte->rspec->lte_list))
160                                 FREE(lte->rspec);
161                         break;
162                 case RESOURCE_IN_FILE_ON_DISK:
163         #ifdef __WIN32__
164                 case RESOURCE_WIN32_ENCRYPTED:
165         #endif
166         #ifdef WITH_FUSE
167                 case RESOURCE_IN_STAGING_FILE:
168                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
169                                      (void*)&lte->staging_file_name);
170         #endif
171                 case RESOURCE_IN_ATTACHED_BUFFER:
172                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
173                                      (void*)&lte->attached_buffer);
174                         FREE(lte->file_on_disk);
175                         break;
176 #ifdef WITH_NTFS_3G
177                 case RESOURCE_IN_NTFS_VOLUME:
178                         if (lte->ntfs_loc) {
179                                 FREE(lte->ntfs_loc->path);
180                                 FREE(lte->ntfs_loc->stream_name);
181                                 FREE(lte->ntfs_loc);
182                         }
183                         break;
184 #endif
185                 default:
186                         break;
187                 }
188                 FREE(lte);
189         }
190 }
191
192 static int
193 do_free_lookup_table_entry(struct wim_lookup_table_entry *entry, void *ignore)
194 {
195         free_lookup_table_entry(entry);
196         return 0;
197 }
198
199
200 void
201 free_lookup_table(struct wim_lookup_table *table)
202 {
203         DEBUG2("Freeing lookup table");
204         if (table) {
205                 if (table->array) {
206                         for_lookup_table_entry(table,
207                                                do_free_lookup_table_entry,
208                                                NULL);
209                         FREE(table->array);
210                 }
211                 FREE(table);
212         }
213 }
214
215 /*
216  * Inserts an entry into the lookup table.
217  *
218  * @table:      A pointer to the lookup table.
219  * @lte:        A pointer to the entry to insert.
220  */
221 void
222 lookup_table_insert(struct wim_lookup_table *table,
223                     struct wim_lookup_table_entry *lte)
224 {
225         size_t i = lte->hash_short % table->capacity;
226         hlist_add_head(&lte->hash_list, &table->array[i]);
227
228         /* XXX Make the table grow when too many entries have been inserted. */
229         table->num_entries++;
230 }
231
232 static void
233 finalize_lte(struct wim_lookup_table_entry *lte)
234 {
235         #ifdef WITH_FUSE
236         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
237                 unlink(lte->staging_file_name);
238                 list_del(&lte->unhashed_list);
239         }
240         #endif
241         free_lookup_table_entry(lte);
242 }
243
244 /* Decrements the reference count for the lookup table entry @lte.  If its
245  * reference count reaches 0, it is unlinked from the lookup table.  If,
246  * furthermore, the entry has no opened file descriptors associated with it, the
247  * entry is freed.  */
248 void
249 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
250                      struct wim_lookup_table *table)
251 {
252         wimlib_assert(lte != NULL);
253         wimlib_assert(lte->refcnt != 0);
254         if (--lte->refcnt == 0) {
255                 if (lte->unhashed)
256                         list_del(&lte->unhashed_list);
257                 else
258                         lookup_table_unlink(table, lte);
259         #ifdef WITH_FUSE
260                 if (lte->num_opened_fds == 0)
261         #endif
262                         finalize_lte(lte);
263         }
264 }
265
266 #ifdef WITH_FUSE
267 void
268 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
269 {
270         if (lte->num_opened_fds != 0)
271                 if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
272                         finalize_lte(lte);
273 }
274 #endif
275
276 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
277  * return nonzero if any call to the function returns nonzero. */
278 int
279 for_lookup_table_entry(struct wim_lookup_table *table,
280                        int (*visitor)(struct wim_lookup_table_entry *, void *),
281                        void *arg)
282 {
283         struct wim_lookup_table_entry *lte;
284         struct hlist_node *pos, *tmp;
285         int ret;
286
287         for (size_t i = 0; i < table->capacity; i++) {
288                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
289                                           hash_list)
290                 {
291                         wimlib_assert2(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
292                         ret = visitor(lte, arg);
293                         if (ret)
294                                 return ret;
295                 }
296         }
297         return 0;
298 }
299
300 /* qsort() callback that sorts streams (represented by `struct
301  * wim_lookup_table_entry's) into an order optimized for reading and writing.
302  *
303  * Sorting is done primarily by resource location, then secondarily by a
304  * per-resource location order.  For example, resources in WIM files are sorted
305  * primarily by part number, then secondarily by offset, as to implement optimal
306  * reading of either a standalone or split WIM.  */
307 static int
308 cmp_streams_by_sequential_order(const void *p1, const void *p2)
309 {
310         const struct wim_lookup_table_entry *lte1, *lte2;
311         int v;
312         WIMStruct *wim1, *wim2;
313         u64 offset1, offset2;
314
315         lte1 = *(const struct wim_lookup_table_entry**)p1;
316         lte2 = *(const struct wim_lookup_table_entry**)p2;
317
318         v = (int)lte1->resource_location - (int)lte2->resource_location;
319
320         /* Different resource locations?  */
321         if (v)
322                 return v;
323
324         switch (lte1->resource_location) {
325         case RESOURCE_IN_WIM:
326                 wim1 = lte1->rspec->wim;
327                 wim2 = lte2->rspec->wim;
328
329                 /* Different (possibly split) WIMs?  */
330                 if (wim1 != wim2) {
331                         v = memcmp(wim1->hdr.guid, wim2->hdr.guid, WIM_GID_LEN);
332                         if (v)
333                                 return v;
334                 }
335
336                 /* Different part numbers in the same WIM?  */
337                 v = (int)wim1->hdr.part_number - (int)wim2->hdr.part_number;
338                 if (v)
339                         return v;
340
341                 /* Compare by offset.  */
342                 offset1 = lte1->rspec->offset_in_wim + lte1->offset_in_res;
343                 offset2 = lte2->rspec->offset_in_wim + lte2->offset_in_res;
344
345                 if (offset1 < offset2)
346                         return -1;
347                 if (offset1 > offset2)
348                         return 1;
349                 return 0;
350         case RESOURCE_IN_FILE_ON_DISK:
351 #ifdef WITH_FUSE
352         case RESOURCE_IN_STAGING_FILE:
353 #endif
354 #ifdef __WIN32__
355         case RESOURCE_WIN32_ENCRYPTED:
356 #endif
357                 /* Compare files by path: just a heuristic that will place files
358                  * in the same directory next to each other.  */
359                 return tstrcmp(lte1->file_on_disk, lte2->file_on_disk);
360 #ifdef WITH_NTFS_3G
361         case RESOURCE_IN_NTFS_VOLUME:
362                 return tstrcmp(lte1->ntfs_loc->path, lte2->ntfs_loc->path);
363 #endif
364         default:
365                 /* No additional sorting order defined for this resource
366                  * location (e.g. RESOURCE_IN_ATTACHED_BUFFER); simply compare
367                  * everything equal to each other.  */
368                 return 0;
369         }
370 }
371
372 int
373 sort_stream_list_by_sequential_order(struct list_head *stream_list,
374                                      size_t list_head_offset)
375 {
376         struct list_head *cur;
377         struct wim_lookup_table_entry **array;
378         size_t i;
379         size_t array_size;
380         size_t num_streams = 0;
381
382         list_for_each(cur, stream_list)
383                 num_streams++;
384
385         array_size = num_streams * sizeof(array[0]);
386         array = MALLOC(array_size);
387         if (array == NULL)
388                 return WIMLIB_ERR_NOMEM;
389         cur = stream_list->next;
390         for (i = 0; i < num_streams; i++) {
391                 array[i] = (struct wim_lookup_table_entry*)((u8*)cur -
392                                                             list_head_offset);
393                 cur = cur->next;
394         }
395
396         qsort(array, num_streams, sizeof(array[0]),
397               cmp_streams_by_sequential_order);
398
399         INIT_LIST_HEAD(stream_list);
400         for (i = 0; i < num_streams; i++) {
401                 list_add_tail((struct list_head*)
402                                ((u8*)array[i] + list_head_offset),
403                               stream_list);
404         }
405         FREE(array);
406         return 0;
407 }
408
409
410 static int
411 add_lte_to_array(struct wim_lookup_table_entry *lte,
412                  void *_pp)
413 {
414         struct wim_lookup_table_entry ***pp = _pp;
415         *(*pp)++ = lte;
416         return 0;
417 }
418
419 /* Iterate through the lookup table entries, but first sort them by stream
420  * offset in the WIM.  Caution: this is intended to be used when the stream
421  * offset field has actually been set. */
422 int
423 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
424                                   int (*visitor)(struct wim_lookup_table_entry *,
425                                                  void *),
426                                   void *arg)
427 {
428         struct wim_lookup_table_entry **lte_array, **p;
429         size_t num_streams = table->num_entries;
430         int ret;
431
432         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
433         if (!lte_array)
434                 return WIMLIB_ERR_NOMEM;
435         p = lte_array;
436         for_lookup_table_entry(table, add_lte_to_array, &p);
437
438         wimlib_assert(p == lte_array + num_streams);
439
440         qsort(lte_array, num_streams, sizeof(lte_array[0]),
441               cmp_streams_by_sequential_order);
442         ret = 0;
443         for (size_t i = 0; i < num_streams; i++) {
444                 ret = visitor(lte_array[i], arg);
445                 if (ret)
446                         break;
447         }
448         FREE(lte_array);
449         return ret;
450 }
451
452 /* On-disk format of a WIM lookup table entry (stream entry). */
453 struct wim_lookup_table_entry_disk {
454         /* Size, offset, and flags of the stream.  */
455         struct wim_reshdr_disk reshdr;
456
457         /* Which part of the split WIM this stream is in; indexed from 1. */
458         le16 part_number;
459
460         /* Reference count of this stream over all WIM images. */
461         le32 refcnt;
462
463         /* SHA1 message digest of the uncompressed data of this stream, or
464          * optionally all zeroes if this stream is of zero length. */
465         u8 hash[SHA1_HASH_SIZE];
466 } _packed_attribute;
467
468 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
469
470 static int
471 validate_resource(const struct wim_resource_spec *rspec)
472 {
473         struct wim_lookup_table_entry *lte;
474         if (!list_is_singular(&rspec->lte_list)) {
475                 list_for_each_entry(lte, &rspec->lte_list, wim_resource_list) {
476                         if (rspec->flags & WIM_RESHDR_FLAG_COMPRESSED)
477                                 lte->flags |= WIM_RESHDR_FLAG_COMPRESSED;
478                         else
479                                 lte->flags &= ~WIM_RESHDR_FLAG_COMPRESSED;
480
481                         if (lte->offset_in_res + lte->size < lte->size ||
482                             lte->offset_in_res + lte->size > rspec->uncompressed_size)
483                         {
484                                 return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
485                         }
486                 }
487         }
488         return 0;
489 }
490
491 /*
492  * Reads the lookup table from a WIM file.
493  *
494  * Saves lookup table entries for non-metadata streams in a hash table, and
495  * saves the metadata entry for each image in a special per-image location (the
496  * image_metadata array).
497  *
498  * Return values:
499  *      WIMLIB_ERR_SUCCESS (0)
500  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
501  *      WIMLIB_ERR_RESOURCE_NOT_FOUND
502  */
503 int
504 read_wim_lookup_table(WIMStruct *wim)
505 {
506         int ret;
507         size_t i;
508         size_t num_entries;
509         struct wim_lookup_table *table;
510         struct wim_lookup_table_entry *cur_entry, *duplicate_entry;
511         struct wim_resource_spec *cur_rspec;
512         void *buf;
513
514         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
515                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
516
517         DEBUG("Reading lookup table.");
518
519         /* Calculate number of entries in the lookup table.  */
520         num_entries = wim->hdr.lookup_table_reshdr.uncompressed_size /
521                       sizeof(struct wim_lookup_table_entry_disk);
522
523         /* Read the lookup table into a buffer.  */
524         ret = wim_reshdr_to_data(&wim->hdr.lookup_table_reshdr, wim, &buf);
525         if (ret)
526                 goto out;
527
528         /* Allocate hash table.  */
529         table = new_lookup_table(num_entries * 2 + 1);
530         if (table == NULL) {
531                 ERROR("Not enough memory to read lookup table.");
532                 ret = WIMLIB_ERR_NOMEM;
533                 goto out_free_buf;
534         }
535
536         /* Allocate and initalize `struct wim_lookup_table_entry's from the
537          * on-disk lookup table.  */
538         wim->current_image = 0;
539         cur_rspec = NULL;
540         for (i = 0; i < num_entries; i++) {
541                 const struct wim_lookup_table_entry_disk *disk_entry =
542                         &((const struct wim_lookup_table_entry_disk*)buf)[i];
543                 u16 part_number;
544                 struct wim_reshdr reshdr;
545
546                 ret = get_wim_reshdr(&disk_entry->reshdr, &reshdr);
547                 if (ret) {
548                         ERROR("Resource header is invalid!");
549                         goto out_free_lookup_table;
550                 }
551
552                 DEBUG("reshdr: size_in_wim=%"PRIu64", "
553                       "uncompressed_size=%"PRIu64", "
554                       "offset_in_wim=%"PRIu64", "
555                       "flags=0x%02x",
556                       reshdr.size_in_wim, reshdr.uncompressed_size,
557                       reshdr.offset_in_wim, reshdr.flags);
558
559                 cur_entry = new_lookup_table_entry();
560                 if (cur_entry == NULL) {
561                         ERROR("Not enough memory to read lookup table!");
562                         ret = WIMLIB_ERR_NOMEM;
563                         goto out_free_lookup_table;
564                 }
565
566                 part_number = le16_to_cpu(disk_entry->part_number);
567                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
568                 copy_hash(cur_entry->hash, disk_entry->hash);
569
570                 if (part_number != wim->hdr.part_number) {
571                         WARNING("A lookup table entry in part %hu of the WIM "
572                                 "points to part %hu (ignoring it)",
573                                 wim->hdr.part_number, part_number);
574                         free_lookup_table_entry(cur_entry);
575                         continue;
576                 }
577
578                 if (cur_rspec == NULL ||
579                     !(reshdr.flags & WIM_RESHDR_FLAG_CONCAT))
580                 {
581                         /* Starting new run of stream entries that all share the
582                          * same WIM resource (streams concatenated together); or
583                          * simply a single normal entry by itself.  */
584
585                         if (cur_rspec != NULL) {
586                                 ret = validate_resource(cur_rspec);
587                                 if (ret)
588                                         goto out_free_cur_entry;
589                         }
590
591                         cur_rspec = MALLOC(sizeof(struct wim_resource_spec));
592                         if (cur_rspec == NULL) {
593                                 ERROR("Not enough memory to read lookup table!");
594                                 ret = WIMLIB_ERR_NOMEM;
595                                 goto out_free_cur_entry;
596                         }
597                         wim_res_hdr_to_spec(&reshdr, wim, cur_rspec);
598                         if (reshdr.flags & WIM_RESHDR_FLAG_CONCAT) {
599                                 cur_rspec->size_in_wim = 0;
600                                 cur_rspec->uncompressed_size = 0;
601                         }
602                 } else if (is_zero_hash(cur_entry->hash)) {
603                         /* Found the resource specification for the run.  */
604                         cur_rspec->offset_in_wim = reshdr.offset_in_wim;
605                         cur_rspec->size_in_wim = reshdr.size_in_wim;
606                         cur_rspec->flags = reshdr.flags;
607                         DEBUG("Full run is %"PRIu64" compressed bytes "
608                               "at file offset %"PRIu64" (flags 0x%02x)",
609                               cur_rspec->size_in_wim,
610                               cur_rspec->offset_in_wim,
611                               cur_rspec->flags);
612                         free_lookup_table_entry(cur_entry);
613                         continue;
614                 }
615
616                 if (reshdr.flags & WIM_RESHDR_FLAG_CONCAT) {
617                         /* Continuing the run with another stream.  */
618                         DEBUG("Continuing concat run with stream: "
619                               "%"PRIu64" uncompressed bytes @ resource offset %"PRIu64")",
620                               reshdr.size_in_wim, reshdr.offset_in_wim);
621                         cur_rspec->uncompressed_size += reshdr.size_in_wim;
622                 }
623
624                 lte_bind_wim_resource_spec(cur_entry, cur_rspec);
625                 if (reshdr.flags & WIM_RESHDR_FLAG_CONCAT) {
626                         /* In concatenation runs, the offset field is used for
627                          * in-resource offset, not the in-WIM offset, and the
628                          * size field is used for the uncompressed size, not the
629                          * compressed size.  */
630                         cur_entry->offset_in_res = reshdr.offset_in_wim;
631                         cur_entry->size = reshdr.size_in_wim;
632                         cur_entry->flags = reshdr.flags;
633                 } else {
634                         cur_entry->offset_in_res = 0;
635                         cur_entry->size = reshdr.uncompressed_size;
636                         cur_entry->flags = reshdr.flags;
637                         cur_rspec = NULL;
638                 }
639
640                 if (is_zero_hash(cur_entry->hash)) {
641                         WARNING("The WIM lookup table contains an entry with a "
642                                 "SHA1 message digest of all 0's (ignoring it)");
643                         free_lookup_table_entry(cur_entry);
644                         continue;
645                 }
646
647                 if (cur_entry->flags & WIM_RESHDR_FLAG_METADATA) {
648                         /* Lookup table entry for a metadata resource */
649                         if (cur_entry->refcnt != 1) {
650                                 /* Metadata entries with no references must be
651                                  * ignored.  See for example the WinPE WIMs from
652                                  * WAIK v2.1.  */
653                                 if (cur_entry->refcnt == 0) {
654                                         free_lookup_table_entry(cur_entry);
655                                         continue;
656                                 }
657                                 if (wimlib_print_errors) {
658                                         ERROR("Found metadata resource with refcnt != 1:");
659                                         print_lookup_table_entry(cur_entry, stderr);
660                                 }
661                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
662                                 goto out_free_cur_entry;
663                         }
664
665                         if (wim->hdr.part_number != 1) {
666                                 WARNING("Ignoring metadata resource found in a "
667                                         "non-first part of the split WIM");
668                                 free_lookup_table_entry(cur_entry);
669                                 continue;
670                         }
671                         if (wim->current_image == wim->hdr.image_count) {
672                                 WARNING("The WIM header says there are %u images "
673                                         "in the WIM, but we found more metadata "
674                                         "resources than this (ignoring the extra)",
675                                         wim->hdr.image_count);
676                                 free_lookup_table_entry(cur_entry);
677                                 continue;
678                         }
679
680                         /* Notice very carefully:  We are assigning the metadata
681                          * resources in the exact order mirrored by their lookup
682                          * table entries on disk, which is the behavior of
683                          * Microsoft's software.  In particular, this overrides
684                          * the actual locations of the metadata resources
685                          * themselves in the WIM file as well as any information
686                          * written in the XML data. */
687                         DEBUG("Found metadata resource for image %u at "
688                               "offset %"PRIu64".",
689                               wim->current_image + 1,
690                               cur_entry->rspec->offset_in_wim);
691                         wim->image_metadata[
692                                 wim->current_image++]->metadata_lte = cur_entry;
693                 } else {
694                         /* Lookup table entry for a stream that is not a
695                          * metadata resource */
696                         duplicate_entry = lookup_resource(table, cur_entry->hash);
697                         if (duplicate_entry) {
698                                 if (wimlib_print_errors) {
699                                         WARNING("The WIM lookup table contains two entries with the "
700                                               "same SHA1 message digest!");
701                                         WARNING("The first entry is:");
702                                         print_lookup_table_entry(duplicate_entry, stderr);
703                                         WARNING("The second entry is:");
704                                         print_lookup_table_entry(cur_entry, stderr);
705                                 }
706                                 free_lookup_table_entry(cur_entry);
707                                 continue;
708                         } else {
709                                 lookup_table_insert(table, cur_entry);
710                         }
711                 }
712         }
713
714         if (cur_rspec != NULL) {
715                 ret = validate_resource(cur_rspec);
716                 if (ret)
717                         goto out_free_cur_entry;
718         }
719
720         if (wim->hdr.part_number == 1 && wim->current_image != wim->hdr.image_count) {
721                 WARNING("The header of \"%"TS"\" says there are %u images in\n"
722                         "          the WIM, but we only found %d metadata resources!  Acting as if\n"
723                         "          the header specified only %d images instead.",
724                         wim->filename, wim->hdr.image_count,
725                         wim->current_image, wim->current_image);
726                 for (int i = wim->current_image; i < wim->hdr.image_count; i++)
727                         put_image_metadata(wim->image_metadata[i], NULL);
728                 wim->hdr.image_count = wim->current_image;
729         }
730         DEBUG("Done reading lookup table.");
731         wim->lookup_table = table;
732         ret = 0;
733         goto out_free_buf;
734
735 out_free_cur_entry:
736         FREE(cur_entry);
737 out_free_lookup_table:
738         free_lookup_table(table);
739 out_free_buf:
740         FREE(buf);
741 out:
742         wim->current_image = 0;
743         return ret;
744 }
745
746
747 static void
748 write_wim_lookup_table_entry(const struct wim_lookup_table_entry *lte,
749                              struct wim_lookup_table_entry_disk *disk_entry,
750                              u16 part_number)
751 {
752         put_wim_reshdr(&lte->out_reshdr, &disk_entry->reshdr);
753         disk_entry->part_number = cpu_to_le16(part_number);
754         disk_entry->refcnt = cpu_to_le32(lte->out_refcnt);
755         copy_hash(disk_entry->hash, lte->hash);
756 }
757
758 static int
759 write_wim_lookup_table_from_stream_list(struct list_head *stream_list,
760                                         struct filedes *out_fd,
761                                         u16 part_number,
762                                         struct wim_reshdr *out_reshdr,
763                                         int write_resource_flags,
764                                         struct wimlib_lzx_context **comp_ctx)
765 {
766         size_t table_size;
767         struct wim_lookup_table_entry *lte;
768         struct wim_lookup_table_entry_disk *table_buf;
769         struct wim_lookup_table_entry_disk *table_buf_ptr;
770         int ret;
771
772         table_size = 0;
773         list_for_each_entry(lte, stream_list, lookup_table_list)
774                 table_size += sizeof(struct wim_lookup_table_entry_disk);
775
776         DEBUG("Writing WIM lookup table (size=%zu, offset=%"PRIu64")",
777               table_size, out_fd->offset);
778
779         table_buf = MALLOC(table_size);
780         if (!table_buf) {
781                 ERROR("Failed to allocate %zu bytes for temporary lookup table",
782                       table_size);
783                 return WIMLIB_ERR_NOMEM;
784         }
785         table_buf_ptr = table_buf;
786         list_for_each_entry(lte, stream_list, lookup_table_list)
787                 write_wim_lookup_table_entry(lte, table_buf_ptr++, part_number);
788
789         /* Write the lookup table uncompressed.  Although wimlib can handle a
790          * compressed lookup table, MS software cannot.  */
791         ret = write_wim_resource_from_buffer(table_buf,
792                                              table_size,
793                                              WIM_RESHDR_FLAG_METADATA,
794                                              out_fd,
795                                              WIMLIB_COMPRESSION_TYPE_NONE,
796                                              0,
797                                              out_reshdr,
798                                              NULL,
799                                              write_resource_flags,
800                                              comp_ctx);
801         FREE(table_buf);
802         DEBUG("ret=%d", ret);
803         return ret;
804 }
805
806 static int
807 append_lookup_table_entry(struct wim_lookup_table_entry *lte, void *_list)
808 {
809         /* Lookup table entries with 'out_refcnt' == 0 correspond to streams not
810          * written and not present in the resulting WIM file, and should not be
811          * included in the lookup table.
812          *
813          * Lookup table entries marked as filtered (EXTERNAL_WIM) with
814          * 'out_refcnt != 0' were referenced as part of the logical write but
815          * correspond to streams that were not in fact written, and should not
816          * be included in the lookup table.
817          *
818          * Lookup table entries marked as filtered (SAME_WIM) with 'out_refcnt
819          * != 0' were referenced as part of the logical write but correspond to
820          * streams that were not in fact written, but nevertheless were already
821          * present in the WIM being overwritten in-place.  These entries must be
822          * included in the lookup table, and the resource information to write
823          * needs to be copied from the resource information read originally.
824          */
825         if (lte->out_refcnt != 0 && !(lte->filtered & FILTERED_EXTERNAL_WIM)) {
826                 if (lte->filtered & FILTERED_SAME_WIM)
827                         wim_res_spec_to_hdr(lte->rspec, &lte->out_reshdr);
828                 list_add_tail(&lte->lookup_table_list, (struct list_head*)_list);
829         }
830         return 0;
831 }
832
833 int
834 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
835                        struct wim_reshdr *out_reshdr,
836                        struct list_head *stream_list_override)
837 {
838         int write_resource_flags;
839         struct list_head _stream_list;
840         struct list_head *stream_list;
841
842         if (stream_list_override) {
843                 stream_list = stream_list_override;
844         } else {
845                 stream_list = &_stream_list;
846                 INIT_LIST_HEAD(stream_list);
847         }
848
849         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
850                 int start_image;
851                 int end_image;
852
853                 if (image == WIMLIB_ALL_IMAGES) {
854                         start_image = 1;
855                         end_image = wim->hdr.image_count;
856                 } else {
857                         start_image = image;
858                         end_image = image;
859                 }
860
861                 /* Push metadata resource lookup table entries onto the front of
862                  * the list in reverse order, so that they're written in order.
863                  */
864                 for (int i = end_image; i >= start_image; i--) {
865                         struct wim_lookup_table_entry *metadata_lte;
866
867                         metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
868                         metadata_lte->out_refcnt = 1;
869                         metadata_lte->out_reshdr.flags |= WIM_RESHDR_FLAG_METADATA;
870                         list_add(&metadata_lte->lookup_table_list, stream_list);
871                 }
872         }
873
874         /* Append additional lookup table entries that need to be written, with
875          * some special handling for streams that have been marked as filtered.
876          */
877         if (!stream_list_override) {
878                 for_lookup_table_entry(wim->lookup_table,
879                                        append_lookup_table_entry, stream_list);
880         }
881
882         write_resource_flags = 0;
883         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
884                 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
885         return write_wim_lookup_table_from_stream_list(stream_list,
886                                                        &wim->out_fd,
887                                                        wim->hdr.part_number,
888                                                        out_reshdr,
889                                                        write_resource_flags,
890                                                        &wim->lzx_context);
891 }
892
893
894 int
895 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
896 {
897         lte->real_refcnt = 0;
898         return 0;
899 }
900
901 int
902 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
903 {
904         lte->out_refcnt = 0;
905         return 0;
906 }
907
908 int
909 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
910 {
911         if (lte->extracted_file != NULL) {
912                 FREE(lte->extracted_file);
913                 lte->extracted_file = NULL;
914         }
915         return 0;
916 }
917
918 void
919 print_lookup_table_entry(const struct wim_lookup_table_entry *lte, FILE *out)
920 {
921         if (lte == NULL) {
922                 tputc(T('\n'), out);
923                 return;
924         }
925
926
927         tprintf(T("Uncompressed size     = %"PRIu64" bytes\n"),
928                 lte->size);
929         if (lte_is_partial(lte)) {
930                 tprintf(T("Offset                = %"PRIu64" bytes\n"),
931                         lte->offset_in_res);
932
933                 tprintf(T("Raw uncompressed size = %"PRIu64" bytes\n"),
934                         lte->rspec->uncompressed_size);
935
936                 tprintf(T("Raw compressed size   = %"PRIu64" bytes\n"),
937                         lte->rspec->size_in_wim);
938
939                 tprintf(T("Raw offset            = %"PRIu64" bytes\n"),
940                         lte->rspec->offset_in_wim);
941         } else if (lte->resource_location == RESOURCE_IN_WIM) {
942                 tprintf(T("Compressed size       = %"PRIu64" bytes\n"),
943                         lte->rspec->size_in_wim);
944
945                 tprintf(T("Offset                = %"PRIu64" bytes\n"),
946                         lte->rspec->offset_in_wim);
947         }
948
949         tfprintf(out, T("Reference Count       = %u\n"), lte->refcnt);
950
951         if (lte->unhashed) {
952                 tfprintf(out, T("(Unhashed: inode %p, stream_id = %u)\n"),
953                          lte->back_inode, lte->back_stream_id);
954         } else {
955                 tfprintf(out, T("Hash                  = 0x"));
956                 print_hash(lte->hash, out);
957                 tputc(T('\n'), out);
958         }
959
960         tfprintf(out, T("Flags                 = "));
961         u8 flags = lte->flags;
962         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
963                 tfputs(T("WIM_RESHDR_FLAG_COMPRESSED, "), out);
964         if (flags & WIM_RESHDR_FLAG_FREE)
965                 tfputs(T("WIM_RESHDR_FLAG_FREE, "), out);
966         if (flags & WIM_RESHDR_FLAG_METADATA)
967                 tfputs(T("WIM_RESHDR_FLAG_METADATA, "), out);
968         if (flags & WIM_RESHDR_FLAG_SPANNED)
969                 tfputs(T("WIM_RESHDR_FLAG_SPANNED, "), out);
970         if (flags & WIM_RESHDR_FLAG_CONCAT)
971                 tfputs(T("WIM_RESHDR_FLAG_CONCAT, "), out);
972         tputc(T('\n'), out);
973         switch (lte->resource_location) {
974         case RESOURCE_IN_WIM:
975                 if (lte->rspec->wim->filename) {
976                         tfprintf(out, T("WIM file              = `%"TS"'\n"),
977                                  lte->rspec->wim->filename);
978                 }
979                 break;
980 #ifdef __WIN32__
981         case RESOURCE_WIN32_ENCRYPTED:
982 #endif
983         case RESOURCE_IN_FILE_ON_DISK:
984                 tfprintf(out, T("File on Disk          = `%"TS"'\n"),
985                          lte->file_on_disk);
986                 break;
987 #ifdef WITH_FUSE
988         case RESOURCE_IN_STAGING_FILE:
989                 tfprintf(out, T("Staging File          = `%"TS"'\n"),
990                                 lte->staging_file_name);
991                 break;
992 #endif
993         default:
994                 break;
995         }
996         tputc(T('\n'), out);
997 }
998
999 void
1000 lte_to_wimlib_resource_entry(const struct wim_lookup_table_entry *lte,
1001                              struct wimlib_resource_entry *wentry)
1002 {
1003         memset(wentry, 0, sizeof(*wentry));
1004
1005         wentry->uncompressed_size = lte->size;
1006         if (lte->resource_location == RESOURCE_IN_WIM) {
1007                 wentry->part_number = lte->rspec->wim->hdr.part_number;
1008                 if (lte_is_partial(lte)) {
1009                         wentry->compressed_size = 0;
1010                         wentry->offset = lte->offset_in_res;
1011                 } else {
1012                         wentry->compressed_size = lte->rspec->size_in_wim;
1013                         wentry->offset = lte->rspec->offset_in_wim;
1014                 }
1015                 wentry->raw_resource_offset_in_wim = lte->rspec->offset_in_wim;
1016                 wentry->raw_resource_uncompressed_size = lte->rspec->uncompressed_size;
1017                 wentry->raw_resource_compressed_size = lte->rspec->size_in_wim;
1018         }
1019         copy_hash(wentry->sha1_hash, lte->hash);
1020         wentry->reference_count = lte->refcnt;
1021         wentry->is_compressed = (lte->flags & WIM_RESHDR_FLAG_COMPRESSED) != 0;
1022         wentry->is_metadata = (lte->flags & WIM_RESHDR_FLAG_METADATA) != 0;
1023         wentry->is_free = (lte->flags & WIM_RESHDR_FLAG_FREE) != 0;
1024         wentry->is_spanned = (lte->flags & WIM_RESHDR_FLAG_SPANNED) != 0;
1025         wentry->is_partial = lte_is_partial(lte);
1026 }
1027
1028 struct iterate_lte_context {
1029         wimlib_iterate_lookup_table_callback_t cb;
1030         void *user_ctx;
1031 };
1032
1033 static int
1034 do_iterate_lte(struct wim_lookup_table_entry *lte, void *_ctx)
1035 {
1036         struct iterate_lte_context *ctx = _ctx;
1037         struct wimlib_resource_entry entry;
1038
1039         lte_to_wimlib_resource_entry(lte, &entry);
1040         return (*ctx->cb)(&entry, ctx->user_ctx);
1041 }
1042
1043 /* API function documented in wimlib.h  */
1044 WIMLIBAPI int
1045 wimlib_iterate_lookup_table(WIMStruct *wim, int flags,
1046                             wimlib_iterate_lookup_table_callback_t cb,
1047                             void *user_ctx)
1048 {
1049         struct iterate_lte_context ctx = {
1050                 .cb = cb,
1051                 .user_ctx = user_ctx,
1052         };
1053         if (wim->hdr.part_number == 1) {
1054                 int ret;
1055                 for (int i = 0; i < wim->hdr.image_count; i++) {
1056                         ret = do_iterate_lte(wim->image_metadata[i]->metadata_lte,
1057                                              &ctx);
1058                         if (ret)
1059                                 return ret;
1060                 }
1061         }
1062         return for_lookup_table_entry(wim->lookup_table, do_iterate_lte, &ctx);
1063 }
1064
1065 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
1066  * lookup table, or NULL if there is none.  */
1067 struct wim_lookup_table_entry *
1068 lookup_resource(const struct wim_lookup_table *table, const u8 hash[])
1069 {
1070         size_t i;
1071         struct wim_lookup_table_entry *lte;
1072         struct hlist_node *pos;
1073
1074         wimlib_assert(table != NULL);
1075         wimlib_assert(hash != NULL);
1076
1077         i = *(size_t*)hash % table->capacity;
1078         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
1079                 if (hashes_equal(hash, lte->hash))
1080                         return lte;
1081         return NULL;
1082 }
1083
1084 #ifdef WITH_FUSE
1085 /*
1086  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
1087  * given a path name.
1088  *
1089  * This is only for pre-resolved inodes.
1090  */
1091 int
1092 wim_pathname_to_stream(WIMStruct *wim,
1093                        const tchar *path,
1094                        int lookup_flags,
1095                        struct wim_dentry **dentry_ret,
1096                        struct wim_lookup_table_entry **lte_ret,
1097                        u16 *stream_idx_ret)
1098 {
1099         struct wim_dentry *dentry;
1100         struct wim_lookup_table_entry *lte;
1101         u16 stream_idx;
1102         const tchar *stream_name = NULL;
1103         struct wim_inode *inode;
1104         tchar *p = NULL;
1105
1106         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
1107                 stream_name = path_stream_name(path);
1108                 if (stream_name) {
1109                         p = (tchar*)stream_name - 1;
1110                         *p = T('\0');
1111                 }
1112         }
1113
1114         dentry = get_dentry(wim, path);
1115         if (p)
1116                 *p = T(':');
1117         if (!dentry)
1118                 return -errno;
1119
1120         inode = dentry->d_inode;
1121
1122         if (!inode->i_resolved)
1123                 if (inode_resolve_ltes(inode, wim->lookup_table, false))
1124                         return -EIO;
1125
1126         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
1127               && inode_is_directory(inode))
1128                 return -EISDIR;
1129
1130         if (stream_name) {
1131                 struct wim_ads_entry *ads_entry;
1132                 u16 ads_idx;
1133                 ads_entry = inode_get_ads_entry(inode, stream_name,
1134                                                 &ads_idx);
1135                 if (ads_entry) {
1136                         stream_idx = ads_idx + 1;
1137                         lte = ads_entry->lte;
1138                         goto out;
1139                 } else {
1140                         return -ENOENT;
1141                 }
1142         } else {
1143                 lte = inode_unnamed_stream_resolved(inode, &stream_idx);
1144         }
1145 out:
1146         if (dentry_ret)
1147                 *dentry_ret = dentry;
1148         if (lte_ret)
1149                 *lte_ret = lte;
1150         if (stream_idx_ret)
1151                 *stream_idx_ret = stream_idx;
1152         return 0;
1153 }
1154 #endif
1155
1156 int
1157 resource_not_found_error(const struct wim_inode *inode, const u8 *hash)
1158 {
1159         if (wimlib_print_errors) {
1160                 ERROR("\"%"TS"\": resource not found", inode_first_full_path(inode));
1161                 tfprintf(stderr, T("        SHA-1 message digest of missing resource:\n        "));
1162                 print_hash(hash, stderr);
1163                 tputc(T('\n'), stderr);
1164         }
1165         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1166 }
1167
1168 /*
1169  * Resolve an inode's lookup table entries.
1170  *
1171  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
1172  * lookup table) with pointers directly to the lookup table entries.
1173  *
1174  * If @force is %false:
1175  *      If any needed SHA1 message digests are not found in the lookup table,
1176  *      WIMLIB_ERR_RESOURCE_NOT_FOUND is returned and the inode is left
1177  *      unmodified.
1178  * If @force is %true:
1179  *      If any needed SHA1 message digests are not found in the lookup table,
1180  *      new entries are allocated and inserted into the lookup table.
1181  */
1182 int
1183 inode_resolve_ltes(struct wim_inode *inode, struct wim_lookup_table *table,
1184                    bool force)
1185 {
1186         const u8 *hash;
1187
1188         if (!inode->i_resolved) {
1189                 struct wim_lookup_table_entry *lte, *ads_lte;
1190
1191                 /* Resolve the default file stream */
1192                 lte = NULL;
1193                 hash = inode->i_hash;
1194                 if (!is_zero_hash(hash)) {
1195                         lte = lookup_resource(table, hash);
1196                         if (!lte) {
1197                                 if (force) {
1198                                         lte = new_lookup_table_entry();
1199                                         if (!lte)
1200                                                 return WIMLIB_ERR_NOMEM;
1201                                         copy_hash(lte->hash, hash);
1202                                         lookup_table_insert(table, lte);
1203                                 } else {
1204                                         goto resource_not_found;
1205                                 }
1206                         }
1207                 }
1208
1209                 /* Resolve the alternate data streams */
1210                 struct wim_lookup_table_entry *ads_ltes[inode->i_num_ads];
1211                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1212                         struct wim_ads_entry *cur_entry;
1213
1214                         ads_lte = NULL;
1215                         cur_entry = &inode->i_ads_entries[i];
1216                         hash = cur_entry->hash;
1217                         if (!is_zero_hash(hash)) {
1218                                 ads_lte = lookup_resource(table, hash);
1219                                 if (!ads_lte) {
1220                                         if (force) {
1221                                                 ads_lte = new_lookup_table_entry();
1222                                                 if (!ads_lte)
1223                                                         return WIMLIB_ERR_NOMEM;
1224                                                 copy_hash(ads_lte->hash, hash);
1225                                                 lookup_table_insert(table, ads_lte);
1226                                         } else {
1227                                                 goto resource_not_found;
1228                                         }
1229                                 }
1230                         }
1231                         ads_ltes[i] = ads_lte;
1232                 }
1233                 inode->i_lte = lte;
1234                 for (u16 i = 0; i < inode->i_num_ads; i++)
1235                         inode->i_ads_entries[i].lte = ads_ltes[i];
1236                 inode->i_resolved = 1;
1237         }
1238         return 0;
1239
1240 resource_not_found:
1241         return resource_not_found_error(inode, hash);
1242 }
1243
1244 void
1245 inode_unresolve_ltes(struct wim_inode *inode)
1246 {
1247         if (inode->i_resolved) {
1248                 if (inode->i_lte)
1249                         copy_hash(inode->i_hash, inode->i_lte->hash);
1250                 else
1251                         zero_out_hash(inode->i_hash);
1252
1253                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1254                         if (inode->i_ads_entries[i].lte)
1255                                 copy_hash(inode->i_ads_entries[i].hash,
1256                                           inode->i_ads_entries[i].lte->hash);
1257                         else
1258                                 zero_out_hash(inode->i_ads_entries[i].hash);
1259                 }
1260                 inode->i_resolved = 0;
1261         }
1262 }
1263
1264 /*
1265  * Returns the lookup table entry for stream @stream_idx of the inode, where
1266  * stream_idx = 0 means the default un-named file stream, and stream_idx >= 1
1267  * corresponds to an alternate data stream.
1268  *
1269  * This works for both resolved and un-resolved inodes.
1270  */
1271 struct wim_lookup_table_entry *
1272 inode_stream_lte(const struct wim_inode *inode, unsigned stream_idx,
1273                  const struct wim_lookup_table *table)
1274 {
1275         if (inode->i_resolved)
1276                 return inode_stream_lte_resolved(inode, stream_idx);
1277         else
1278                 return inode_stream_lte_unresolved(inode, stream_idx, table);
1279 }
1280
1281 struct wim_lookup_table_entry *
1282 inode_unnamed_stream_resolved(const struct wim_inode *inode, u16 *stream_idx_ret)
1283 {
1284         wimlib_assert(inode->i_resolved);
1285         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1286                 if (inode_stream_name_nbytes(inode, i) == 0 &&
1287                     !is_zero_hash(inode_stream_hash_resolved(inode, i)))
1288                 {
1289                         *stream_idx_ret = i;
1290                         return inode_stream_lte_resolved(inode, i);
1291                 }
1292         }
1293         *stream_idx_ret = 0;
1294         return NULL;
1295 }
1296
1297 struct wim_lookup_table_entry *
1298 inode_unnamed_lte_resolved(const struct wim_inode *inode)
1299 {
1300         u16 stream_idx;
1301         return inode_unnamed_stream_resolved(inode, &stream_idx);
1302 }
1303
1304 struct wim_lookup_table_entry *
1305 inode_unnamed_lte_unresolved(const struct wim_inode *inode,
1306                              const struct wim_lookup_table *table)
1307 {
1308         wimlib_assert(!inode->i_resolved);
1309         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1310                 if (inode_stream_name_nbytes(inode, i) == 0 &&
1311                     !is_zero_hash(inode_stream_hash_unresolved(inode, i)))
1312                 {
1313                         return inode_stream_lte_unresolved(inode, i, table);
1314                 }
1315         }
1316         return NULL;
1317 }
1318
1319 /* Return the lookup table entry for the unnamed data stream of an inode, or
1320  * NULL if there is none.
1321  *
1322  * You'd think this would be easier than it actually is, since the unnamed data
1323  * stream should be the one referenced from the inode itself.  Alas, if there
1324  * are named data streams, Microsoft's "imagex.exe" program will put the unnamed
1325  * data stream in one of the alternate data streams instead of inside the WIM
1326  * dentry itself.  So we need to check the alternate data streams too.
1327  *
1328  * Also, note that a dentry may appear to have more than one unnamed stream, but
1329  * if the SHA1 message digest is all 0's then the corresponding stream does not
1330  * really "count" (this is the case for the inode's own file stream when the
1331  * file stream that should be there is actually in one of the alternate stream
1332  * entries.).  This is despite the fact that we may need to extract such a
1333  * missing entry as an empty file or empty named data stream.
1334  */
1335 struct wim_lookup_table_entry *
1336 inode_unnamed_lte(const struct wim_inode *inode,
1337                   const struct wim_lookup_table *table)
1338 {
1339         if (inode->i_resolved)
1340                 return inode_unnamed_lte_resolved(inode);
1341         else
1342                 return inode_unnamed_lte_unresolved(inode, table);
1343 }
1344
1345 /* Returns the SHA1 message digest of the unnamed data stream of a WIM inode, or
1346  * 'zero_hash' if the unnamed data stream is missing has all zeroes in its SHA1
1347  * message digest field.  */
1348 const u8 *
1349 inode_unnamed_stream_hash(const struct wim_inode *inode)
1350 {
1351         const u8 *hash;
1352
1353         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1354                 if (inode_stream_name_nbytes(inode, i) == 0) {
1355                         hash = inode_stream_hash(inode, i);
1356                         if (!is_zero_hash(hash))
1357                                 return hash;
1358                 }
1359         }
1360         return zero_hash;
1361 }
1362
1363 struct wim_lookup_table_entry **
1364 retrieve_lte_pointer(struct wim_lookup_table_entry *lte)
1365 {
1366         wimlib_assert(lte->unhashed);
1367         struct wim_inode *inode = lte->back_inode;
1368         u32 stream_id = lte->back_stream_id;
1369         if (stream_id == 0)
1370                 return &inode->i_lte;
1371         else
1372                 for (u16 i = 0; i < inode->i_num_ads; i++)
1373                         if (inode->i_ads_entries[i].stream_id == stream_id)
1374                                 return &inode->i_ads_entries[i].lte;
1375         wimlib_assert(0);
1376         return NULL;
1377 }
1378
1379 /* Calculate the SHA1 message digest of a stream and move it from the list of
1380  * unhashed streams to the stream lookup table, possibly joining it with an
1381  * existing lookup table entry for an identical stream.
1382  *
1383  * @lte:  An unhashed lookup table entry.
1384  * @lookup_table:  Lookup table for the WIM.
1385  * @lte_ret:  On success, write a pointer to the resulting lookup table
1386  *            entry to this location.  This will be the same as @lte
1387  *            if it was inserted into the lookup table, or different if
1388  *            a duplicate stream was found.
1389  *
1390  * Returns 0 on success; nonzero if there is an error reading the stream.
1391  */
1392 int
1393 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1394                      struct wim_lookup_table *lookup_table,
1395                      struct wim_lookup_table_entry **lte_ret)
1396 {
1397         int ret;
1398         struct wim_lookup_table_entry *duplicate_lte;
1399         struct wim_lookup_table_entry **back_ptr;
1400
1401         wimlib_assert(lte->unhashed);
1402
1403         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1404          * union with the SHA1 message digest and will no longer be valid once
1405          * the SHA1 has been calculated. */
1406         back_ptr = retrieve_lte_pointer(lte);
1407
1408         ret = sha1_stream(lte);
1409         if (ret)
1410                 return ret;
1411
1412         /* Look for a duplicate stream */
1413         duplicate_lte = lookup_resource(lookup_table, lte->hash);
1414         list_del(&lte->unhashed_list);
1415         if (duplicate_lte) {
1416                 /* We have a duplicate stream.  Transfer the reference counts
1417                  * from this stream to the duplicate, update the reference to
1418                  * this stream (in an inode or ads_entry) to point to the
1419                  * duplicate, then free this stream. */
1420                 wimlib_assert(!(duplicate_lte->unhashed));
1421                 duplicate_lte->refcnt += lte->refcnt;
1422                 duplicate_lte->out_refcnt += lte->out_refcnt;
1423                 *back_ptr = duplicate_lte;
1424                 free_lookup_table_entry(lte);
1425                 lte = duplicate_lte;
1426         } else {
1427                 /* No duplicate stream, so we need to insert
1428                  * this stream into the lookup table and treat
1429                  * it as a hashed stream. */
1430                 lookup_table_insert(lookup_table, lte);
1431                 lte->unhashed = 0;
1432         }
1433         if (lte_ret)
1434                 *lte_ret = lte;
1435         return 0;
1436 }
1437
1438 static int
1439 lte_clone_if_new(struct wim_lookup_table_entry *lte, void *_lookup_table)
1440 {
1441         struct wim_lookup_table *lookup_table = _lookup_table;
1442
1443         if (lookup_resource(lookup_table, lte->hash))
1444                 return 0;  /*  Resource already present.  */
1445
1446         lte = clone_lookup_table_entry(lte);
1447         if (!lte)
1448                 return WIMLIB_ERR_NOMEM;
1449         lte->out_refcnt = 1;
1450         lookup_table_insert(lookup_table, lte);
1451         return 0;
1452 }
1453
1454 static int
1455 lte_delete_if_new(struct wim_lookup_table_entry *lte, void *_lookup_table)
1456 {
1457         struct wim_lookup_table *lookup_table = _lookup_table;
1458
1459         if (lte->out_refcnt) {
1460                 lookup_table_unlink(lookup_table, lte);
1461                 free_lookup_table_entry(lte);
1462         }
1463         return 0;
1464 }
1465
1466 /* API function documented in wimlib.h  */
1467 WIMLIBAPI int
1468 wimlib_reference_resources(WIMStruct *wim,
1469                            WIMStruct **resource_wims, unsigned num_resource_wims,
1470                            int ref_flags)
1471 {
1472         int ret;
1473         unsigned i;
1474
1475         if (wim == NULL)
1476                 return WIMLIB_ERR_INVALID_PARAM;
1477
1478         if (num_resource_wims != 0 && resource_wims == NULL)
1479                 return WIMLIB_ERR_INVALID_PARAM;
1480
1481         for (i = 0; i < num_resource_wims; i++)
1482                 if (resource_wims[i] == NULL)
1483                         return WIMLIB_ERR_INVALID_PARAM;
1484
1485         for_lookup_table_entry(wim->lookup_table, lte_zero_out_refcnt, NULL);
1486
1487         for (i = 0; i < num_resource_wims; i++) {
1488                 ret = for_lookup_table_entry(resource_wims[i]->lookup_table,
1489                                              lte_clone_if_new,
1490                                              wim->lookup_table);
1491                 if (ret)
1492                         goto out_rollback;
1493         }
1494         return 0;
1495
1496 out_rollback:
1497         for_lookup_table_entry(wim->lookup_table, lte_delete_if_new,
1498                                wim->lookup_table);
1499         return ret;
1500 }
1501
1502 static int
1503 reference_resource_paths(WIMStruct *wim,
1504                          const tchar * const *resource_wimfiles,
1505                          unsigned num_resource_wimfiles,
1506                          int ref_flags,
1507                          int open_flags,
1508                          wimlib_progress_func_t progress_func)
1509 {
1510         WIMStruct **resource_wims;
1511         unsigned i;
1512         int ret;
1513
1514         resource_wims = CALLOC(num_resource_wimfiles, sizeof(resource_wims[0]));
1515         if (!resource_wims)
1516                 return WIMLIB_ERR_NOMEM;
1517
1518         for (i = 0; i < num_resource_wimfiles; i++) {
1519                 DEBUG("Referencing resources from path \"%"TS"\"",
1520                       resource_wimfiles[i]);
1521                 ret = wimlib_open_wim(resource_wimfiles[i], open_flags,
1522                                       &resource_wims[i], progress_func);
1523                 if (ret)
1524                         goto out_free_resource_wims;
1525         }
1526
1527         ret = wimlib_reference_resources(wim, resource_wims,
1528                                          num_resource_wimfiles, ref_flags);
1529         if (ret)
1530                 goto out_free_resource_wims;
1531
1532         for (i = 0; i < num_resource_wimfiles; i++)
1533                 list_add_tail(&resource_wims[i]->subwim_node, &wim->subwims);
1534
1535         ret = 0;
1536         goto out_free_array;
1537
1538 out_free_resource_wims:
1539         for (i = 0; i < num_resource_wimfiles; i++)
1540                 wimlib_free(resource_wims[i]);
1541 out_free_array:
1542         FREE(resource_wims);
1543         return ret;
1544 }
1545
1546 static int
1547 reference_resource_glob(WIMStruct *wim, const tchar *refglob,
1548                         int ref_flags, int open_flags,
1549                         wimlib_progress_func_t progress_func)
1550 {
1551         glob_t globbuf;
1552         int ret;
1553
1554         /* Note: glob() is replaced in Windows native builds.  */
1555         ret = tglob(refglob, GLOB_ERR | GLOB_NOSORT, NULL, &globbuf);
1556         if (ret) {
1557                 if (ret == GLOB_NOMATCH) {
1558                         if (ref_flags & WIMLIB_REF_FLAG_GLOB_ERR_ON_NOMATCH) {
1559                                 ERROR("Found no files for glob \"%"TS"\"", refglob);
1560                                 return WIMLIB_ERR_GLOB_HAD_NO_MATCHES;
1561                         } else {
1562                                 return reference_resource_paths(wim,
1563                                                                 &refglob,
1564                                                                 1,
1565                                                                 ref_flags,
1566                                                                 open_flags,
1567                                                                 progress_func);
1568                         }
1569                 } else {
1570                         ERROR_WITH_ERRNO("Failed to process glob \"%"TS"\"", refglob);
1571                         if (ret == GLOB_NOSPACE)
1572                                 return WIMLIB_ERR_NOMEM;
1573                         else
1574                                 return WIMLIB_ERR_READ;
1575                 }
1576         }
1577
1578         ret = reference_resource_paths(wim,
1579                                        (const tchar * const *)globbuf.gl_pathv,
1580                                        globbuf.gl_pathc,
1581                                        ref_flags,
1582                                        open_flags,
1583                                        progress_func);
1584         globfree(&globbuf);
1585         return ret;
1586 }
1587
1588 /* API function documented in wimlib.h  */
1589 WIMLIBAPI int
1590 wimlib_reference_resource_files(WIMStruct *wim,
1591                                 const tchar * const * resource_wimfiles_or_globs,
1592                                 unsigned count,
1593                                 int ref_flags,
1594                                 int open_flags,
1595                                 wimlib_progress_func_t progress_func)
1596 {
1597         unsigned i;
1598         int ret;
1599
1600         if (ref_flags & WIMLIB_REF_FLAG_GLOB_ENABLE) {
1601                 for (i = 0; i < count; i++) {
1602                         ret = reference_resource_glob(wim,
1603                                                       resource_wimfiles_or_globs[i],
1604                                                       ref_flags,
1605                                                       open_flags,
1606                                                       progress_func);
1607                         if (ret)
1608                                 return ret;
1609                 }
1610                 return 0;
1611         } else {
1612                 return reference_resource_paths(wim, resource_wimfiles_or_globs,
1613                                                 count, ref_flags,
1614                                                 open_flags, progress_func);
1615         }
1616 }