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