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