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