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