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