]> wimlib.net Git - wimlib/blob - src/lookup_table.c
1950ab21a89bbbefb75fc56473ce64936d12753c
[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, 2014 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/assert.h"
32 #include "wimlib/endianness.h"
33 #include "wimlib/error.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/ntfs_3g.h"
37 #include "wimlib/resource.h"
38 #include "wimlib/util.h"
39 #include "wimlib/write.h"
40
41 #include <stdlib.h>
42 #include <string.h>
43 #include <unistd.h> /* for unlink()  */
44
45 /* WIM lookup table:
46  *
47  * This is a logical mapping from SHA1 message digests to the data streams
48  * contained in a WIM.
49  *
50  * Here it is implemented as a hash table.
51  *
52  * Note: Everything will break horribly if there is a SHA1 collision.
53  */
54 struct wim_lookup_table {
55         struct hlist_head *array;
56         size_t num_entries;
57         size_t capacity;
58 };
59
60 struct wim_lookup_table *
61 new_lookup_table(size_t capacity)
62 {
63         struct wim_lookup_table *table;
64         struct hlist_head *array;
65
66         table = MALLOC(sizeof(struct wim_lookup_table));
67         if (table == NULL)
68                 goto oom;
69
70         array = CALLOC(capacity, sizeof(array[0]));
71         if (array == NULL) {
72                 FREE(table);
73                 goto oom;
74         }
75
76         table->num_entries = 0;
77         table->capacity = capacity;
78         table->array = array;
79         return table;
80
81 oom:
82         ERROR("Failed to allocate memory for lookup table "
83               "with capacity %zu", capacity);
84         return NULL;
85 }
86
87 static int
88 do_free_lookup_table_entry(struct wim_lookup_table_entry *entry, void *ignore)
89 {
90         free_lookup_table_entry(entry);
91         return 0;
92 }
93
94 void
95 free_lookup_table(struct wim_lookup_table *table)
96 {
97         if (table) {
98                 for_lookup_table_entry(table, do_free_lookup_table_entry, NULL);
99                 FREE(table->array);
100                 FREE(table);
101         }
102 }
103
104 struct wim_lookup_table_entry *
105 new_lookup_table_entry(void)
106 {
107         struct wim_lookup_table_entry *lte;
108
109         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
110         if (lte == NULL)
111                 return NULL;
112
113         lte->refcnt = 1;
114
115         /* lte->resource_location = RESOURCE_NONEXISTENT  */
116         BUILD_BUG_ON(RESOURCE_NONEXISTENT != 0);
117
118         return lte;
119 }
120
121 struct wim_lookup_table_entry *
122 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
123 {
124         struct wim_lookup_table_entry *new;
125
126         new = memdup(old, sizeof(struct wim_lookup_table_entry));
127         if (new == NULL)
128                 return NULL;
129
130         switch (new->resource_location) {
131         case RESOURCE_IN_WIM:
132                 list_add(&new->rspec_node, &new->rspec->stream_list);
133                 break;
134
135         case RESOURCE_IN_FILE_ON_DISK:
136 #ifdef __WIN32__
137         case RESOURCE_IN_WINNT_FILE_ON_DISK:
138         case RESOURCE_WIN32_ENCRYPTED:
139 #endif
140 #ifdef WITH_FUSE
141         case RESOURCE_IN_STAGING_FILE:
142                 BUILD_BUG_ON((void*)&old->file_on_disk !=
143                              (void*)&old->staging_file_name);
144 #endif
145                 new->file_on_disk = TSTRDUP(old->file_on_disk);
146                 if (new->file_on_disk == NULL)
147                         goto out_free;
148                 break;
149         case RESOURCE_IN_ATTACHED_BUFFER:
150                 new->attached_buffer = memdup(old->attached_buffer, old->size);
151                 if (new->attached_buffer == NULL)
152                         goto out_free;
153                 break;
154 #ifdef WITH_NTFS_3G
155         case RESOURCE_IN_NTFS_VOLUME:
156                 if (old->ntfs_loc) {
157                         struct ntfs_location *loc;
158                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
159                         if (loc == NULL)
160                                 goto out_free;
161                         loc->path = NULL;
162                         loc->stream_name = NULL;
163                         new->ntfs_loc = loc;
164                         loc->path = STRDUP(old->ntfs_loc->path);
165                         if (loc->path == NULL)
166                                 goto out_free;
167                         if (loc->stream_name_nchars != 0) {
168                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
169                                                           loc->stream_name_nchars * 2);
170                                 if (loc->stream_name == NULL)
171                                         goto out_free;
172                         }
173                 }
174                 break;
175 #endif
176         default:
177                 break;
178         }
179         return new;
180
181 out_free:
182         free_lookup_table_entry(new);
183         return NULL;
184 }
185
186 void
187 lte_put_resource(struct wim_lookup_table_entry *lte)
188 {
189         switch (lte->resource_location) {
190         case RESOURCE_IN_WIM:
191                 list_del(&lte->rspec_node);
192                 if (list_empty(&lte->rspec->stream_list))
193                         FREE(lte->rspec);
194                 break;
195         case RESOURCE_IN_FILE_ON_DISK:
196 #ifdef __WIN32__
197         case RESOURCE_IN_WINNT_FILE_ON_DISK:
198         case RESOURCE_WIN32_ENCRYPTED:
199 #endif
200 #ifdef WITH_FUSE
201         case RESOURCE_IN_STAGING_FILE:
202                 BUILD_BUG_ON((void*)&lte->file_on_disk !=
203                              (void*)&lte->staging_file_name);
204 #endif
205         case RESOURCE_IN_ATTACHED_BUFFER:
206                 BUILD_BUG_ON((void*)&lte->file_on_disk !=
207                              (void*)&lte->attached_buffer);
208                 FREE(lte->file_on_disk);
209                 break;
210 #ifdef WITH_NTFS_3G
211         case RESOURCE_IN_NTFS_VOLUME:
212                 if (lte->ntfs_loc) {
213                         FREE(lte->ntfs_loc->path);
214                         FREE(lte->ntfs_loc->stream_name);
215                         FREE(lte->ntfs_loc);
216                 }
217                 break;
218 #endif
219         default:
220                 break;
221         }
222 }
223
224 void
225 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
226 {
227         if (lte) {
228                 lte_put_resource(lte);
229                 FREE(lte);
230         }
231 }
232
233 /* Should this stream be retained even if it has no references?  */
234 static bool
235 should_retain_lte(const struct wim_lookup_table_entry *lte)
236 {
237         return lte->resource_location == RESOURCE_IN_WIM;
238 }
239
240 static void
241 finalize_lte(struct wim_lookup_table_entry *lte)
242 {
243         if (!should_retain_lte(lte))
244                 free_lookup_table_entry(lte);
245 }
246
247 /*
248  * Decrements the reference count for the lookup table entry @lte, which must be
249  * inserted in the stream lookup table @table.
250  *
251  * If the reference count reaches 0, this may cause @lte to be destroyed.
252  * However, we may retain entries with 0 reference count.  This does not affect
253  * correctness, but it prevents the entries for valid streams in a WIM archive,
254  * which will continue to be present after appending to the file, from being
255  * lost merely because we dropped all references to them.
256  */
257 void
258 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
259                      struct wim_lookup_table *table)
260 {
261         wimlib_assert(lte->refcnt != 0);
262
263         if (--lte->refcnt == 0) {
264                 if (lte->unhashed) {
265                         list_del(&lte->unhashed_list);
266                 #ifdef WITH_FUSE
267                         /* If the stream has been extracted to a staging file
268                          * for a FUSE mount, unlink the staging file.  (Note
269                          * that there still may be open file descriptors to it.)
270                          * */
271                         if (lte->resource_location == RESOURCE_IN_STAGING_FILE)
272                                 unlink(lte->staging_file_name);
273                 #endif
274                 } else {
275                         if (!should_retain_lte(lte))
276                                 lookup_table_unlink(table, lte);
277                 }
278
279                 /* If FUSE mounts are enabled, we don't actually free the entry
280                  * until the last file descriptor has been closed by
281                  * lte_decrement_num_opened_fds().  */
282 #ifdef WITH_FUSE
283                 if (lte->num_opened_fds == 0)
284 #endif
285                         finalize_lte(lte);
286         }
287 }
288
289 #ifdef WITH_FUSE
290 void
291 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
292 {
293         wimlib_assert(lte->num_opened_fds != 0);
294
295         if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
296                 finalize_lte(lte);
297 }
298 #endif
299
300 static void
301 lookup_table_insert_raw(struct wim_lookup_table *table,
302                         struct wim_lookup_table_entry *lte)
303 {
304         size_t i = lte->hash_short % table->capacity;
305
306         hlist_add_head(&lte->hash_list, &table->array[i]);
307 }
308
309 static void
310 enlarge_lookup_table(struct wim_lookup_table *table)
311 {
312         size_t old_capacity, new_capacity;
313         struct hlist_head *old_array, *new_array;
314         struct wim_lookup_table_entry *lte;
315         struct hlist_node *cur, *tmp;
316         size_t i;
317
318         old_capacity = table->capacity;
319         new_capacity = old_capacity * 2;
320         new_array = CALLOC(new_capacity, sizeof(struct hlist_head));
321         if (new_array == NULL)
322                 return;
323         old_array = table->array;
324         table->array = new_array;
325         table->capacity = new_capacity;
326
327         for (i = 0; i < old_capacity; i++) {
328                 hlist_for_each_entry_safe(lte, cur, tmp, &old_array[i], hash_list) {
329                         hlist_del(&lte->hash_list);
330                         lookup_table_insert_raw(table, lte);
331                 }
332         }
333         FREE(old_array);
334 }
335
336 /* Inserts an entry into the lookup table.  */
337 void
338 lookup_table_insert(struct wim_lookup_table *table,
339                     struct wim_lookup_table_entry *lte)
340 {
341         lookup_table_insert_raw(table, lte);
342         if (++table->num_entries > table->capacity)
343                 enlarge_lookup_table(table);
344 }
345
346 /* Unlinks a lookup table entry from the table; does not free it.  */
347 void
348 lookup_table_unlink(struct wim_lookup_table *table,
349                     struct wim_lookup_table_entry *lte)
350 {
351         wimlib_assert(!lte->unhashed);
352         wimlib_assert(table->num_entries != 0);
353
354         hlist_del(&lte->hash_list);
355         table->num_entries--;
356 }
357
358 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
359  * lookup table, or NULL if there is none.  */
360 struct wim_lookup_table_entry *
361 lookup_stream(const struct wim_lookup_table *table, const u8 hash[])
362 {
363         size_t i;
364         struct wim_lookup_table_entry *lte;
365         struct hlist_node *pos;
366
367         i = *(size_t*)hash % table->capacity;
368         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
369                 if (hashes_equal(hash, lte->hash))
370                         return lte;
371         return NULL;
372 }
373
374 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
375  * return nonzero if any call to the function returns nonzero. */
376 int
377 for_lookup_table_entry(struct wim_lookup_table *table,
378                        int (*visitor)(struct wim_lookup_table_entry *, void *),
379                        void *arg)
380 {
381         struct wim_lookup_table_entry *lte;
382         struct hlist_node *pos, *tmp;
383         int ret;
384
385         for (size_t i = 0; i < table->capacity; i++) {
386                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
387                                           hash_list)
388                 {
389                         ret = visitor(lte, arg);
390                         if (ret)
391                                 return ret;
392                 }
393         }
394         return 0;
395 }
396
397 /* qsort() callback that sorts streams (represented by `struct
398  * wim_lookup_table_entry's) into an order optimized for reading.
399  *
400  * Sorting is done primarily by resource location, then secondarily by a
401  * per-resource location order.  For example, resources in WIM files are sorted
402  * primarily by part number, then secondarily by offset, as to implement optimal
403  * reading of either a standalone or split WIM.  */
404 static int
405 cmp_streams_by_sequential_order(const void *p1, const void *p2)
406 {
407         const struct wim_lookup_table_entry *lte1, *lte2;
408         int v;
409         WIMStruct *wim1, *wim2;
410
411         lte1 = *(const struct wim_lookup_table_entry**)p1;
412         lte2 = *(const struct wim_lookup_table_entry**)p2;
413
414         v = (int)lte1->resource_location - (int)lte2->resource_location;
415
416         /* Different resource locations?  */
417         if (v)
418                 return v;
419
420         switch (lte1->resource_location) {
421         case RESOURCE_IN_WIM:
422                 wim1 = lte1->rspec->wim;
423                 wim2 = lte2->rspec->wim;
424
425                 /* Different (possibly split) WIMs?  */
426                 if (wim1 != wim2) {
427                         v = memcmp(wim1->hdr.guid, wim2->hdr.guid, WIM_GUID_LEN);
428                         if (v)
429                                 return v;
430                 }
431
432                 /* Different part numbers in the same WIM?  */
433                 v = (int)wim1->hdr.part_number - (int)wim2->hdr.part_number;
434                 if (v)
435                         return v;
436
437                 if (lte1->rspec->offset_in_wim != lte2->rspec->offset_in_wim)
438                         return cmp_u64(lte1->rspec->offset_in_wim,
439                                        lte2->rspec->offset_in_wim);
440
441                 return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
442
443         case RESOURCE_IN_FILE_ON_DISK:
444 #ifdef WITH_FUSE
445         case RESOURCE_IN_STAGING_FILE:
446 #endif
447 #ifdef __WIN32__
448         case RESOURCE_IN_WINNT_FILE_ON_DISK:
449         case RESOURCE_WIN32_ENCRYPTED:
450 #endif
451                 /* Compare files by path: just a heuristic that will place files
452                  * in the same directory next to each other.  */
453                 return tstrcmp(lte1->file_on_disk, lte2->file_on_disk);
454 #ifdef WITH_NTFS_3G
455         case RESOURCE_IN_NTFS_VOLUME:
456                 return tstrcmp(lte1->ntfs_loc->path, lte2->ntfs_loc->path);
457 #endif
458         default:
459                 /* No additional sorting order defined for this resource
460                  * location (e.g. RESOURCE_IN_ATTACHED_BUFFER); simply compare
461                  * everything equal to each other.  */
462                 return 0;
463         }
464 }
465
466 int
467 sort_stream_list(struct list_head *stream_list,
468                  size_t list_head_offset,
469                  int (*compar)(const void *, const void*))
470 {
471         struct list_head *cur;
472         struct wim_lookup_table_entry **array;
473         size_t i;
474         size_t array_size;
475         size_t num_streams = 0;
476
477         list_for_each(cur, stream_list)
478                 num_streams++;
479
480         if (num_streams <= 1)
481                 return 0;
482
483         array_size = num_streams * sizeof(array[0]);
484         array = MALLOC(array_size);
485         if (array == NULL)
486                 return WIMLIB_ERR_NOMEM;
487
488         cur = stream_list->next;
489         for (i = 0; i < num_streams; i++) {
490                 array[i] = (struct wim_lookup_table_entry*)((u8*)cur -
491                                                             list_head_offset);
492                 cur = cur->next;
493         }
494
495         qsort(array, num_streams, sizeof(array[0]), compar);
496
497         INIT_LIST_HEAD(stream_list);
498         for (i = 0; i < num_streams; i++) {
499                 list_add_tail((struct list_head*)
500                                ((u8*)array[i] + list_head_offset),
501                               stream_list);
502         }
503         FREE(array);
504         return 0;
505 }
506
507 /* Sort the specified list of streams in an order optimized for reading.  */
508 int
509 sort_stream_list_by_sequential_order(struct list_head *stream_list,
510                                      size_t list_head_offset)
511 {
512         return sort_stream_list(stream_list, list_head_offset,
513                                 cmp_streams_by_sequential_order);
514 }
515
516
517 static int
518 add_lte_to_array(struct wim_lookup_table_entry *lte,
519                  void *_pp)
520 {
521         struct wim_lookup_table_entry ***pp = _pp;
522         *(*pp)++ = lte;
523         return 0;
524 }
525
526 /* Iterate through the lookup table entries, but first sort them by stream
527  * offset in the WIM.  Caution: this is intended to be used when the stream
528  * offset field has actually been set. */
529 int
530 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
531                                   int (*visitor)(struct wim_lookup_table_entry *,
532                                                  void *),
533                                   void *arg)
534 {
535         struct wim_lookup_table_entry **lte_array, **p;
536         size_t num_streams = table->num_entries;
537         int ret;
538
539         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
540         if (!lte_array)
541                 return WIMLIB_ERR_NOMEM;
542         p = lte_array;
543         for_lookup_table_entry(table, add_lte_to_array, &p);
544
545         wimlib_assert(p == lte_array + num_streams);
546
547         qsort(lte_array, num_streams, sizeof(lte_array[0]),
548               cmp_streams_by_sequential_order);
549         ret = 0;
550         for (size_t i = 0; i < num_streams; i++) {
551                 ret = visitor(lte_array[i], arg);
552                 if (ret)
553                         break;
554         }
555         FREE(lte_array);
556         return ret;
557 }
558
559 /* On-disk format of a WIM lookup table entry (stream entry). */
560 struct wim_lookup_table_entry_disk {
561         /* Size, offset, and flags of the stream.  */
562         struct wim_reshdr_disk reshdr;
563
564         /* Which part of the split WIM this stream is in; indexed from 1. */
565         le16 part_number;
566
567         /* Reference count of this stream over all WIM images. */
568         le32 refcnt;
569
570         /* SHA1 message digest of the uncompressed data of this stream, or
571          * optionally all zeroes if this stream is of zero length. */
572         u8 hash[SHA1_HASH_SIZE];
573 } _packed_attribute;
574
575 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
576
577 /* Given a nonempty run of consecutive lookup table entries with the
578  * PACKED_STREAMS flag set, count how many specify resources (as opposed to
579  * streams within those resources).
580  *
581  * Returns the resulting count.  */
582 static size_t
583 count_subpacks(const struct wim_lookup_table_entry_disk *entries, size_t max)
584 {
585         size_t count = 0;
586         do {
587                 struct wim_reshdr reshdr;
588
589                 get_wim_reshdr(&(entries++)->reshdr, &reshdr);
590
591                 if (!(reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS)) {
592                         /* Run was terminated by a stand-alone stream entry.  */
593                         break;
594                 }
595
596                 if (reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER) {
597                         /* This is a resource entry.  */
598                         count++;
599                 }
600         } while (--max);
601         return count;
602 }
603
604 /* Given a run of consecutive lookup table entries with the PACKED_STREAMS flag
605  * set and having @num_subpacks resource entries, load resource information from
606  * them into the resource specifications in the @subpacks array.
607  *
608  * Returns 0 on success, or a nonzero error code on failure.  */
609 static int
610 do_load_subpack_info(WIMStruct *wim, struct wim_resource_spec **subpacks,
611                      size_t num_subpacks,
612                      const struct wim_lookup_table_entry_disk *entries)
613 {
614         for (size_t i = 0; i < num_subpacks; i++) {
615                 struct wim_reshdr reshdr;
616                 struct alt_chunk_table_header_disk hdr;
617                 struct wim_resource_spec *rspec;
618                 int ret;
619
620                 /* Advance to next resource entry.  */
621
622                 do {
623                         get_wim_reshdr(&(entries++)->reshdr, &reshdr);
624                 } while (reshdr.uncompressed_size != WIM_PACK_MAGIC_NUMBER);
625
626                 rspec = subpacks[i];
627
628                 wim_res_hdr_to_spec(&reshdr, wim, rspec);
629
630                 /* For packed resources, the uncompressed size, compression
631                  * type, and chunk size are stored in the resource itself, not
632                  * in the lookup table.  */
633
634                 ret = full_pread(&wim->in_fd, &hdr,
635                                  sizeof(hdr), reshdr.offset_in_wim);
636                 if (ret) {
637                         ERROR("Failed to read header of packed resource "
638                               "(offset_in_wim=%"PRIu64")",
639                               reshdr.offset_in_wim);
640                         return ret;
641                 }
642
643                 rspec->uncompressed_size = le64_to_cpu(hdr.res_usize);
644
645                 /* Compression format numbers must be the same as in
646                  * WIMGAPI to be compatible here.  */
647                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_NONE != 0);
648                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
649                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
650                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
651                 rspec->compression_type = le32_to_cpu(hdr.compression_format);
652
653                 rspec->chunk_size = le32_to_cpu(hdr.chunk_size);
654
655                 DEBUG("Subpack %zu/%zu: %"PRIu64" => %"PRIu64" "
656                       "(%"TS"/%"PRIu32") @ +%"PRIu64"",
657                       i + 1, num_subpacks,
658                       rspec->uncompressed_size,
659                       rspec->size_in_wim,
660                       wimlib_get_compression_type_string(rspec->compression_type),
661                       rspec->chunk_size,
662                       rspec->offset_in_wim);
663
664         }
665         return 0;
666 }
667
668 /* Given a nonempty run of consecutive lookup table entries with the
669  * PACKED_STREAMS flag set, allocate a 'struct wim_resource_spec' for each
670  * resource within that run.
671  *
672  * Returns 0 on success, or a nonzero error code on failure.
673  * Returns the pointers and count in *subpacks_ret and *num_subpacks_ret.
674  */
675 static int
676 load_subpack_info(WIMStruct *wim,
677                   const struct wim_lookup_table_entry_disk *entries,
678                   size_t num_remaining_entries,
679                   struct wim_resource_spec ***subpacks_ret,
680                   size_t *num_subpacks_ret)
681 {
682         size_t num_subpacks;
683         struct wim_resource_spec **subpacks;
684         size_t i;
685         int ret;
686
687         num_subpacks = count_subpacks(entries, num_remaining_entries);
688         subpacks = CALLOC(num_subpacks, sizeof(subpacks[0]));
689         if (!subpacks)
690                 return WIMLIB_ERR_NOMEM;
691
692         for (i = 0; i < num_subpacks; i++) {
693                 subpacks[i] = MALLOC(sizeof(struct wim_resource_spec));
694                 if (!subpacks[i]) {
695                         ret = WIMLIB_ERR_NOMEM;
696                         goto out_free_subpacks;
697                 }
698         }
699
700         ret = do_load_subpack_info(wim, subpacks, num_subpacks, entries);
701         if (ret)
702                 goto out_free_subpacks;
703
704         *subpacks_ret = subpacks;
705         *num_subpacks_ret = num_subpacks;
706         return 0;
707
708 out_free_subpacks:
709         for (i = 0; i < num_subpacks; i++)
710                 FREE(subpacks[i]);
711         FREE(subpacks);
712         return ret;
713 }
714
715 /* Given a 'struct wim_lookup_table_entry' allocated for a stream entry with
716  * PACKED_STREAMS set, try to bind it to a subpack of the current PACKED_STREAMS
717  * run.  */
718 static int
719 bind_stream_to_subpack(const struct wim_reshdr *reshdr,
720                        struct wim_lookup_table_entry *stream,
721                        struct wim_resource_spec **subpacks,
722                        size_t num_subpacks)
723 {
724         u64 offset = reshdr->offset_in_wim;
725
726         /* XXX: This linear search will be slow in the degenerate case where the
727          * number of subpacks is huge.  */
728         stream->size = reshdr->size_in_wim;
729         stream->flags = reshdr->flags;
730         for (size_t i = 0; i < num_subpacks; i++) {
731                 if (offset + stream->size <= subpacks[i]->uncompressed_size) {
732                         stream->offset_in_res = offset;
733                         lte_bind_wim_resource_spec(stream, subpacks[i]);
734                         return 0;
735                 }
736                 offset -= subpacks[i]->uncompressed_size;
737         }
738         ERROR("Packed stream could not be assigned to any resource");
739         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
740 }
741
742 static void
743 free_subpack_info(struct wim_resource_spec **subpacks, size_t num_subpacks)
744 {
745         if (subpacks) {
746                 for (size_t i = 0; i < num_subpacks; i++)
747                         if (list_empty(&subpacks[i]->stream_list))
748                                 FREE(subpacks[i]);
749                 FREE(subpacks);
750         }
751 }
752
753 static int
754 cmp_streams_by_offset_in_res(const void *p1, const void *p2)
755 {
756         const struct wim_lookup_table_entry *lte1, *lte2;
757
758         lte1 = *(const struct wim_lookup_table_entry**)p1;
759         lte2 = *(const struct wim_lookup_table_entry**)p2;
760
761         return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
762 }
763
764 /* Validate the size and location of a WIM resource.  */
765 static int
766 validate_resource(struct wim_resource_spec *rspec)
767 {
768         struct wim_lookup_table_entry *lte;
769         bool out_of_order;
770         u64 expected_next_offset;
771         int ret;
772
773         /* Verify that the resource itself has a valid offset and size.  */
774         if (rspec->offset_in_wim + rspec->size_in_wim < rspec->size_in_wim)
775                 goto invalid_due_to_overflow;
776
777         /* Verify that each stream in the resource has a valid offset and size.
778          */
779         expected_next_offset = 0;
780         out_of_order = false;
781         list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
782                 if (lte->offset_in_res + lte->size < lte->size ||
783                     lte->offset_in_res + lte->size > rspec->uncompressed_size)
784                         goto invalid_due_to_overflow;
785
786                 if (lte->offset_in_res >= expected_next_offset)
787                         expected_next_offset = lte->offset_in_res + lte->size;
788                 else
789                         out_of_order = true;
790         }
791
792         /* If the streams were not located at strictly increasing positions (not
793          * allowing for overlap), sort them.  Then make sure that none overlap.
794          */
795         if (out_of_order) {
796                 ret = sort_stream_list(&rspec->stream_list,
797                                        offsetof(struct wim_lookup_table_entry,
798                                                 rspec_node),
799                                        cmp_streams_by_offset_in_res);
800                 if (ret)
801                         return ret;
802
803                 expected_next_offset = 0;
804                 list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
805                         if (lte->offset_in_res >= expected_next_offset)
806                                 expected_next_offset = lte->offset_in_res + lte->size;
807                         else
808                                 goto invalid_due_to_overlap;
809                 }
810         }
811
812         return 0;
813
814 invalid_due_to_overflow:
815         ERROR("Invalid resource entry (offset overflow)");
816         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
817
818 invalid_due_to_overlap:
819         ERROR("Invalid resource entry (streams in packed resource overlap)");
820         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
821 }
822
823 static int
824 finish_subpacks(struct wim_resource_spec **subpacks, size_t num_subpacks)
825 {
826         int ret = 0;
827         for (size_t i = 0; i < num_subpacks; i++) {
828                 ret = validate_resource(subpacks[i]);
829                 if (ret)
830                         break;
831         }
832         free_subpack_info(subpacks, num_subpacks);
833         return ret;
834 }
835
836 /*
837  * Reads the lookup table from a WIM file.  Usually, each entry specifies a
838  * stream that the WIM file contains, along with its location and SHA1 message
839  * digest.
840  *
841  * Saves lookup table entries for non-metadata streams in a hash table (set to
842  * wim->lookup_table), and saves the metadata entry for each image in a special
843  * per-image location (the wim->image_metadata array).
844  *
845  * This works for both version WIM_VERSION_DEFAULT (68864) and version
846  * WIM_VERSION_PACKED_STREAMS (3584) WIMs.  In the latter, a consecutive run of
847  * lookup table entries that all have flag WIM_RESHDR_FLAG_PACKED_STREAMS (0x10)
848  * set is a "packed run".  A packed run logically contains zero or more
849  * resources, each of which logically contains zero or more streams.
850  * Physically, in such a run, a "lookup table entry" with uncompressed size
851  * WIM_PACK_MAGIC_NUMBER (0x100000000) specifies a resource, whereas any other
852  * entry specifies a stream.  Within such a run, stream entries and resource
853  * entries need not be in any particular order, except that the order of the
854  * resource entries is important, as it affects how streams are assigned to
855  * resources.  See the code for details.
856  *
857  * Possible return values:
858  *      WIMLIB_ERR_SUCCESS (0)
859  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
860  *      WIMLIB_ERR_NOMEM
861  *
862  *      Or an error code caused by failure to read the lookup table from the WIM
863  *      file.
864  */
865 int
866 read_wim_lookup_table(WIMStruct *wim)
867 {
868         int ret;
869         size_t num_entries;
870         void *buf = NULL;
871         struct wim_lookup_table *table = NULL;
872         struct wim_lookup_table_entry *cur_entry = NULL;
873         size_t num_duplicate_entries = 0;
874         size_t num_wrong_part_entries = 0;
875         u32 image_index = 0;
876         struct wim_resource_spec **cur_subpacks = NULL;
877         size_t cur_num_subpacks = 0;
878
879         DEBUG("Reading lookup table.");
880
881         /* Sanity check: lookup table entries are 50 bytes each.  */
882         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
883                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
884
885         /* Calculate the number of entries in the lookup table.  */
886         num_entries = wim->hdr.lookup_table_reshdr.uncompressed_size /
887                       sizeof(struct wim_lookup_table_entry_disk);
888
889         /* Read the lookup table into a buffer.  */
890         ret = wim_reshdr_to_data(&wim->hdr.lookup_table_reshdr, wim, &buf);
891         if (ret)
892                 goto out;
893
894         /* Allocate a hash table to map SHA1 message digests into stream
895          * specifications.  This is the in-memory "lookup table".  */
896         table = new_lookup_table(num_entries * 2 + 1);
897         if (!table)
898                 goto oom;
899
900         /* Allocate and initalize stream entries ('struct
901          * wim_lookup_table_entry's) from the raw lookup table buffer.  Each of
902          * these entries will point to a 'struct wim_resource_spec' that
903          * describes the underlying resource.  In WIMs with version number
904          * WIM_VERSION_PACKED_STREAMS, a resource may contain multiple streams.
905          */
906         for (size_t i = 0; i < num_entries; i++) {
907                 const struct wim_lookup_table_entry_disk *disk_entry =
908                         &((const struct wim_lookup_table_entry_disk*)buf)[i];
909                 struct wim_reshdr reshdr;
910                 u16 part_number;
911
912                 /* Get the resource header  */
913                 get_wim_reshdr(&disk_entry->reshdr, &reshdr);
914
915                 DEBUG("reshdr: size_in_wim=%"PRIu64", "
916                       "uncompressed_size=%"PRIu64", "
917                       "offset_in_wim=%"PRIu64", "
918                       "flags=0x%02x",
919                       reshdr.size_in_wim, reshdr.uncompressed_size,
920                       reshdr.offset_in_wim, reshdr.flags);
921
922                 /* Ignore PACKED_STREAMS flag if it isn't supposed to be used in
923                  * this WIM version.  */
924                 if (wim->hdr.wim_version == WIM_VERSION_DEFAULT)
925                         reshdr.flags &= ~WIM_RESHDR_FLAG_PACKED_STREAMS;
926
927                 /* Allocate a new 'struct wim_lookup_table_entry'.  */
928                 cur_entry = new_lookup_table_entry();
929                 if (!cur_entry)
930                         goto oom;
931
932                 /* Get the part number, reference count, and hash.  */
933                 part_number = le16_to_cpu(disk_entry->part_number);
934                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
935                 copy_hash(cur_entry->hash, disk_entry->hash);
936
937                 if (reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
938
939                         /* PACKED_STREAMS entry  */
940
941                         if (!cur_subpacks) {
942                                 /* Starting new run  */
943                                 ret = load_subpack_info(wim, disk_entry,
944                                                         num_entries - i,
945                                                         &cur_subpacks,
946                                                         &cur_num_subpacks);
947                                 if (ret)
948                                         goto out;
949                         }
950
951                         if (reshdr.uncompressed_size == WIM_PACK_MAGIC_NUMBER) {
952                                 /* Resource entry, not stream entry  */
953                                 goto free_cur_entry_and_continue;
954                         }
955
956                         /* Stream entry  */
957
958                         ret = bind_stream_to_subpack(&reshdr,
959                                                      cur_entry,
960                                                      cur_subpacks,
961                                                      cur_num_subpacks);
962                         if (ret)
963                                 goto out;
964
965                 } else {
966                         /* Normal stream/resource entry; PACKED_STREAMS not set.
967                          */
968
969                         struct wim_resource_spec *rspec;
970
971                         if (unlikely(cur_subpacks)) {
972                                 /* This entry terminated a packed run.  */
973                                 ret = finish_subpacks(cur_subpacks,
974                                                       cur_num_subpacks);
975                                 cur_subpacks = NULL;
976                                 if (ret)
977                                         goto out;
978                         }
979
980                         /* How to handle an uncompressed resource with its
981                          * uncompressed size different from its compressed size?
982                          *
983                          * Based on a simple test, WIMGAPI seems to handle this
984                          * as follows:
985                          *
986                          * if (size_in_wim > uncompressed_size) {
987                          *      Ignore uncompressed_size; use size_in_wim
988                          *      instead.
989                          * } else {
990                          *      Honor uncompressed_size, but treat the part of
991                          *      the file data above size_in_wim as all zeros.
992                          * }
993                          *
994                          * So we will do the same.  */
995                         if (unlikely(!(reshdr.flags &
996                                        WIM_RESHDR_FLAG_COMPRESSED) &&
997                                      (reshdr.size_in_wim >
998                                       reshdr.uncompressed_size)))
999                         {
1000                                 reshdr.uncompressed_size = reshdr.size_in_wim;
1001                         }
1002
1003                         /* Set up a resource specification for this stream.  */
1004
1005                         rspec = MALLOC(sizeof(struct wim_resource_spec));
1006                         if (!rspec)
1007                                 goto oom;
1008
1009                         wim_res_hdr_to_spec(&reshdr, wim, rspec);
1010
1011                         cur_entry->offset_in_res = 0;
1012                         cur_entry->size = reshdr.uncompressed_size;
1013                         cur_entry->flags = reshdr.flags;
1014
1015                         lte_bind_wim_resource_spec(cur_entry, rspec);
1016                 }
1017
1018                 /* cur_entry is now a stream bound to a resource.  */
1019
1020                 /* Ignore entries with all zeroes in the hash field.  */
1021                 if (is_zero_hash(cur_entry->hash))
1022                         goto free_cur_entry_and_continue;
1023
1024                 /* Verify that the part number matches that of the underlying
1025                  * WIM file.  */
1026                 if (part_number != wim->hdr.part_number) {
1027                         num_wrong_part_entries++;
1028                         goto free_cur_entry_and_continue;
1029                 }
1030
1031                 if (reshdr.flags & WIM_RESHDR_FLAG_METADATA) {
1032
1033                         /* Lookup table entry for a metadata resource.  */
1034
1035                         /* Metadata entries with no references must be ignored.
1036                          * See, for example, the WinPE WIMs from the WAIK v2.1.
1037                          */
1038                         if (cur_entry->refcnt == 0)
1039                                 goto free_cur_entry_and_continue;
1040
1041                         if (cur_entry->refcnt != 1) {
1042                                 /* We don't currently support this case due to
1043                                  * the complications of multiple images sharing
1044                                  * the same metadata resource or a metadata
1045                                  * resource also being referenced by files.  */
1046                                 ERROR("Found metadata resource with refcnt != 1");
1047                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
1048                                 goto out;
1049                         }
1050
1051                         if (wim->hdr.part_number != 1) {
1052                                 WARNING("Ignoring metadata resource found in a "
1053                                         "non-first part of the split WIM");
1054                                 goto free_cur_entry_and_continue;
1055                         }
1056
1057                         /* The number of entries in the lookup table with
1058                          * WIM_RESHDR_FLAG_METADATA set should be the same as
1059                          * the image_count field in the WIM header.  */
1060                         if (image_index == wim->hdr.image_count) {
1061                                 WARNING("Found more metadata resources than images");
1062                                 goto free_cur_entry_and_continue;
1063                         }
1064
1065                         /* Notice very carefully:  We are assigning the metadata
1066                          * resources to images in the same order in which their
1067                          * lookup table entries occur on disk.  (This is also
1068                          * the behavior of Microsoft's software.)  In
1069                          * particular, this overrides the actual locations of
1070                          * the metadata resources themselves in the WIM file as
1071                          * well as any information written in the XML data.  */
1072                         DEBUG("Found metadata resource for image %"PRIu32" at "
1073                               "offset %"PRIu64".",
1074                               image_index + 1,
1075                               reshdr.offset_in_wim);
1076
1077                         wim->image_metadata[image_index++]->metadata_lte = cur_entry;
1078                 } else {
1079                         /* Lookup table entry for a non-metadata stream.  */
1080
1081                         /* Ignore this stream if it's a duplicate.  */
1082                         if (lookup_stream(table, cur_entry->hash)) {
1083                                 num_duplicate_entries++;
1084                                 goto free_cur_entry_and_continue;
1085                         }
1086
1087                         /* Insert the stream into the in-memory lookup table,
1088                          * keyed by its SHA1 message digest.  */
1089                         lookup_table_insert(table, cur_entry);
1090                 }
1091
1092                 continue;
1093
1094         free_cur_entry_and_continue:
1095                 if (cur_subpacks &&
1096                     cur_entry->resource_location == RESOURCE_IN_WIM)
1097                         lte_unbind_wim_resource_spec(cur_entry);
1098                 free_lookup_table_entry(cur_entry);
1099         }
1100         cur_entry = NULL;
1101
1102         if (cur_subpacks) {
1103                 /* End of lookup table terminated a packed run.  */
1104                 ret = finish_subpacks(cur_subpacks, cur_num_subpacks);
1105                 cur_subpacks = NULL;
1106                 if (ret)
1107                         goto out;
1108         }
1109
1110         if (wim->hdr.part_number == 1 && image_index != wim->hdr.image_count) {
1111                 WARNING("Could not find metadata resources for all images");
1112                 for (u32 i = image_index; i < wim->hdr.image_count; i++)
1113                         put_image_metadata(wim->image_metadata[i], NULL);
1114                 wim->hdr.image_count = image_index;
1115         }
1116
1117         if (num_duplicate_entries > 0) {
1118                 WARNING("Ignoring %zu duplicate streams in the WIM lookup table",
1119                         num_duplicate_entries);
1120         }
1121
1122         if (num_wrong_part_entries > 0) {
1123                 WARNING("Ignoring %zu streams with wrong part number",
1124                         num_wrong_part_entries);
1125         }
1126
1127         DEBUG("Done reading lookup table.");
1128         wim->lookup_table = table;
1129         ret = 0;
1130         goto out_free_buf;
1131
1132 oom:
1133         ERROR("Not enough memory to read lookup table!");
1134         ret = WIMLIB_ERR_NOMEM;
1135 out:
1136         free_subpack_info(cur_subpacks, cur_num_subpacks);
1137         free_lookup_table_entry(cur_entry);
1138         free_lookup_table(table);
1139 out_free_buf:
1140         FREE(buf);
1141         return ret;
1142 }
1143
1144 static void
1145 put_wim_lookup_table_entry(struct wim_lookup_table_entry_disk *disk_entry,
1146                            const struct wim_reshdr *out_reshdr,
1147                            u16 part_number, u32 refcnt, const u8 *hash)
1148 {
1149         put_wim_reshdr(out_reshdr, &disk_entry->reshdr);
1150         disk_entry->part_number = cpu_to_le16(part_number);
1151         disk_entry->refcnt = cpu_to_le32(refcnt);
1152         copy_hash(disk_entry->hash, hash);
1153 }
1154
1155 /* Note: the list of stream entries must be sorted so that all entries for the
1156  * same packed resource are consecutive.  In addition, entries with
1157  * WIM_RESHDR_FLAG_METADATA set must be in the same order as the indices of the
1158  * underlying images.  */
1159 int
1160 write_wim_lookup_table_from_stream_list(struct list_head *stream_list,
1161                                         struct filedes *out_fd,
1162                                         u16 part_number,
1163                                         struct wim_reshdr *out_reshdr,
1164                                         int write_resource_flags)
1165 {
1166         size_t table_size;
1167         struct wim_lookup_table_entry *lte;
1168         struct wim_lookup_table_entry_disk *table_buf;
1169         struct wim_lookup_table_entry_disk *table_buf_ptr;
1170         int ret;
1171         u64 prev_res_offset_in_wim = ~0ULL;
1172         u64 prev_uncompressed_size;
1173         u64 logical_offset;
1174
1175         table_size = 0;
1176         list_for_each_entry(lte, stream_list, lookup_table_list) {
1177                 table_size += sizeof(struct wim_lookup_table_entry_disk);
1178
1179                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS &&
1180                     lte->out_res_offset_in_wim != prev_res_offset_in_wim)
1181                 {
1182                         table_size += sizeof(struct wim_lookup_table_entry_disk);
1183                         prev_res_offset_in_wim = lte->out_res_offset_in_wim;
1184                 }
1185         }
1186
1187         DEBUG("Writing WIM lookup table (size=%zu, offset=%"PRIu64")",
1188               table_size, out_fd->offset);
1189
1190         table_buf = MALLOC(table_size);
1191         if (table_buf == NULL) {
1192                 ERROR("Failed to allocate %zu bytes for temporary lookup table",
1193                       table_size);
1194                 return WIMLIB_ERR_NOMEM;
1195         }
1196         table_buf_ptr = table_buf;
1197
1198         prev_res_offset_in_wim = ~0ULL;
1199         prev_uncompressed_size = 0;
1200         logical_offset = 0;
1201         list_for_each_entry(lte, stream_list, lookup_table_list) {
1202                 if (lte->out_reshdr.flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1203                         struct wim_reshdr tmp_reshdr;
1204
1205                         /* Eww.  When WIMGAPI sees multiple resource packs, it
1206                          * expects the offsets to be adjusted as if there were
1207                          * really only one pack.  */
1208
1209                         if (lte->out_res_offset_in_wim != prev_res_offset_in_wim) {
1210                                 /* Put the resource entry for pack  */
1211                                 tmp_reshdr.offset_in_wim = lte->out_res_offset_in_wim;
1212                                 tmp_reshdr.size_in_wim = lte->out_res_size_in_wim;
1213                                 tmp_reshdr.uncompressed_size = WIM_PACK_MAGIC_NUMBER;
1214                                 tmp_reshdr.flags = WIM_RESHDR_FLAG_PACKED_STREAMS;
1215
1216                                 put_wim_lookup_table_entry(table_buf_ptr++,
1217                                                            &tmp_reshdr,
1218                                                            part_number,
1219                                                            1, zero_hash);
1220
1221                                 logical_offset += prev_uncompressed_size;
1222
1223                                 prev_res_offset_in_wim = lte->out_res_offset_in_wim;
1224                                 prev_uncompressed_size = lte->out_res_uncompressed_size;
1225                         }
1226                         tmp_reshdr = lte->out_reshdr;
1227                         tmp_reshdr.offset_in_wim += logical_offset;
1228                         put_wim_lookup_table_entry(table_buf_ptr++,
1229                                                    &tmp_reshdr,
1230                                                    part_number,
1231                                                    lte->out_refcnt,
1232                                                    lte->hash);
1233                 } else {
1234                         put_wim_lookup_table_entry(table_buf_ptr++,
1235                                                    &lte->out_reshdr,
1236                                                    part_number,
1237                                                    lte->out_refcnt,
1238                                                    lte->hash);
1239                 }
1240
1241         }
1242         wimlib_assert((u8*)table_buf_ptr - (u8*)table_buf == table_size);
1243
1244         /* Write the lookup table uncompressed.  Although wimlib can handle a
1245          * compressed lookup table, MS software cannot.  */
1246         ret = write_wim_resource_from_buffer(table_buf,
1247                                              table_size,
1248                                              WIM_RESHDR_FLAG_METADATA,
1249                                              out_fd,
1250                                              WIMLIB_COMPRESSION_TYPE_NONE,
1251                                              0,
1252                                              out_reshdr,
1253                                              NULL,
1254                                              write_resource_flags);
1255         FREE(table_buf);
1256         DEBUG("ret=%d", ret);
1257         return ret;
1258 }
1259
1260 int
1261 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
1262 {
1263         lte->real_refcnt = 0;
1264         return 0;
1265 }
1266
1267 int
1268 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
1269 {
1270         lte->out_refcnt = 0;
1271         return 0;
1272 }
1273
1274 /* Allocate a stream entry for the contents of the buffer, or re-use an existing
1275  * entry in @lookup_table for the same stream.  */
1276 struct wim_lookup_table_entry *
1277 new_stream_from_data_buffer(const void *buffer, size_t size,
1278                             struct wim_lookup_table *lookup_table)
1279 {
1280         u8 hash[SHA1_HASH_SIZE];
1281         struct wim_lookup_table_entry *lte, *existing_lte;
1282
1283         sha1_buffer(buffer, size, hash);
1284         existing_lte = lookup_stream(lookup_table, hash);
1285         if (existing_lte) {
1286                 wimlib_assert(existing_lte->size == size);
1287                 lte = existing_lte;
1288                 lte->refcnt++;
1289         } else {
1290                 void *buffer_copy;
1291                 lte = new_lookup_table_entry();
1292                 if (lte == NULL)
1293                         return NULL;
1294                 buffer_copy = memdup(buffer, size);
1295                 if (buffer_copy == NULL) {
1296                         free_lookup_table_entry(lte);
1297                         return NULL;
1298                 }
1299                 lte->resource_location  = RESOURCE_IN_ATTACHED_BUFFER;
1300                 lte->attached_buffer    = buffer_copy;
1301                 lte->size               = size;
1302                 copy_hash(lte->hash, hash);
1303                 lookup_table_insert(lookup_table, lte);
1304         }
1305         return lte;
1306 }
1307
1308 /* Calculate the SHA1 message digest of a stream and move it from the list of
1309  * unhashed streams to the stream lookup table, possibly joining it with an
1310  * existing lookup table entry for an identical stream.
1311  *
1312  * @lte:  An unhashed lookup table entry.
1313  * @lookup_table:  Lookup table for the WIM.
1314  * @lte_ret:  On success, write a pointer to the resulting lookup table
1315  *            entry to this location.  This will be the same as @lte
1316  *            if it was inserted into the lookup table, or different if
1317  *            a duplicate stream was found.
1318  *
1319  * Returns 0 on success; nonzero if there is an error reading the stream.
1320  */
1321 int
1322 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1323                      struct wim_lookup_table *lookup_table,
1324                      struct wim_lookup_table_entry **lte_ret)
1325 {
1326         int ret;
1327         struct wim_lookup_table_entry *duplicate_lte;
1328         struct wim_lookup_table_entry **back_ptr;
1329
1330         wimlib_assert(lte->unhashed);
1331
1332         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1333          * union with the SHA1 message digest and will no longer be valid once
1334          * the SHA1 has been calculated. */
1335         back_ptr = retrieve_lte_pointer(lte);
1336
1337         ret = sha1_stream(lte);
1338         if (ret)
1339                 return ret;
1340
1341         /* Look for a duplicate stream */
1342         duplicate_lte = lookup_stream(lookup_table, lte->hash);
1343         list_del(&lte->unhashed_list);
1344         if (duplicate_lte) {
1345                 /* We have a duplicate stream.  Transfer the reference counts
1346                  * from this stream to the duplicate and update the reference to
1347                  * this stream (in an inode or ads_entry) to point to the
1348                  * duplicate.  The caller is responsible for freeing @lte if
1349                  * needed.  */
1350                 wimlib_assert(!(duplicate_lte->unhashed));
1351                 wimlib_assert(duplicate_lte->size == lte->size);
1352                 duplicate_lte->refcnt += lte->refcnt;
1353                 lte->refcnt = 0;
1354                 *back_ptr = duplicate_lte;
1355                 lte = duplicate_lte;
1356         } else {
1357                 /* No duplicate stream, so we need to insert this stream into
1358                  * the lookup table and treat it as a hashed stream. */
1359                 lookup_table_insert(lookup_table, lte);
1360                 lte->unhashed = 0;
1361         }
1362         *lte_ret = lte;
1363         return 0;
1364 }
1365
1366 void
1367 lte_to_wimlib_resource_entry(const struct wim_lookup_table_entry *lte,
1368                              struct wimlib_resource_entry *wentry)
1369 {
1370         memset(wentry, 0, sizeof(*wentry));
1371
1372         wentry->uncompressed_size = lte->size;
1373         if (lte->resource_location == RESOURCE_IN_WIM) {
1374                 wentry->part_number = lte->rspec->wim->hdr.part_number;
1375                 if (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) {
1376                         wentry->compressed_size = 0;
1377                         wentry->offset = lte->offset_in_res;
1378                 } else {
1379                         wentry->compressed_size = lte->rspec->size_in_wim;
1380                         wentry->offset = lte->rspec->offset_in_wim;
1381                 }
1382                 wentry->raw_resource_offset_in_wim = lte->rspec->offset_in_wim;
1383                 /*wentry->raw_resource_uncompressed_size = lte->rspec->uncompressed_size;*/
1384                 wentry->raw_resource_compressed_size = lte->rspec->size_in_wim;
1385         }
1386         copy_hash(wentry->sha1_hash, lte->hash);
1387         wentry->reference_count = lte->refcnt;
1388         wentry->is_compressed = (lte->flags & WIM_RESHDR_FLAG_COMPRESSED) != 0;
1389         wentry->is_metadata = (lte->flags & WIM_RESHDR_FLAG_METADATA) != 0;
1390         wentry->is_free = (lte->flags & WIM_RESHDR_FLAG_FREE) != 0;
1391         wentry->is_spanned = (lte->flags & WIM_RESHDR_FLAG_SPANNED) != 0;
1392         wentry->packed = (lte->flags & WIM_RESHDR_FLAG_PACKED_STREAMS) != 0;
1393 }
1394
1395 struct iterate_lte_context {
1396         wimlib_iterate_lookup_table_callback_t cb;
1397         void *user_ctx;
1398 };
1399
1400 static int
1401 do_iterate_lte(struct wim_lookup_table_entry *lte, void *_ctx)
1402 {
1403         struct iterate_lte_context *ctx = _ctx;
1404         struct wimlib_resource_entry entry;
1405
1406         lte_to_wimlib_resource_entry(lte, &entry);
1407         return (*ctx->cb)(&entry, ctx->user_ctx);
1408 }
1409
1410 /* API function documented in wimlib.h  */
1411 WIMLIBAPI int
1412 wimlib_iterate_lookup_table(WIMStruct *wim, int flags,
1413                             wimlib_iterate_lookup_table_callback_t cb,
1414                             void *user_ctx)
1415 {
1416         if (flags != 0)
1417                 return WIMLIB_ERR_INVALID_PARAM;
1418
1419         struct iterate_lte_context ctx = {
1420                 .cb = cb,
1421                 .user_ctx = user_ctx,
1422         };
1423         if (wim_has_metadata(wim)) {
1424                 int ret;
1425                 for (int i = 0; i < wim->hdr.image_count; i++) {
1426                         ret = do_iterate_lte(wim->image_metadata[i]->metadata_lte,
1427                                              &ctx);
1428                         if (ret)
1429                                 return ret;
1430                 }
1431         }
1432         return for_lookup_table_entry(wim->lookup_table, do_iterate_lte, &ctx);
1433 }