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