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