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