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