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