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