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