Consistently use the name "solid resource"
[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 SOLID flag
593  * set, count how many specify resources (as opposed to streams within those
594  * resources).
595  *
596  * Returns the resulting count.  */
597 static size_t
598 count_solid_resources(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_SOLID)) {
607                         /* Run was terminated by a stand-alone stream entry.  */
608                         break;
609                 }
610
611                 if (reshdr.uncompressed_size == SOLID_RESOURCE_MAGIC_NUMBER) {
612                         /* This is a resource entry.  */
613                         count++;
614                 }
615         } while (--max);
616         return count;
617 }
618
619 /*
620  * Given a run of consecutive lookup table entries with the SOLID flag set and
621  * having @num_rspecs resource entries, load resource information from them into
622  * the resource specifications in the @rspecs array.
623  *
624  * Returns 0 on success, or a nonzero error code on failure.
625  */
626 static int
627 do_load_solid_info(WIMStruct *wim, struct wim_resource_spec **rspecs,
628                    size_t num_rspecs,
629                    const struct wim_lookup_table_entry_disk *entries)
630 {
631         for (size_t i = 0; i < num_rspecs; i++) {
632                 struct wim_reshdr reshdr;
633                 struct alt_chunk_table_header_disk hdr;
634                 struct wim_resource_spec *rspec;
635                 int ret;
636
637                 /* Advance to next resource entry.  */
638
639                 do {
640                         get_wim_reshdr(&(entries++)->reshdr, &reshdr);
641                 } while (reshdr.uncompressed_size != SOLID_RESOURCE_MAGIC_NUMBER);
642
643                 rspec = rspecs[i];
644
645                 wim_res_hdr_to_spec(&reshdr, wim, rspec);
646
647                 /* For solid resources, the uncompressed size, compression type,
648                  * and chunk size are stored in the resource itself, not in the
649                  * lookup table.  */
650
651                 ret = full_pread(&wim->in_fd, &hdr,
652                                  sizeof(hdr), reshdr.offset_in_wim);
653                 if (ret) {
654                         ERROR("Failed to read header of solid resource "
655                               "(offset_in_wim=%"PRIu64")",
656                               reshdr.offset_in_wim);
657                         return ret;
658                 }
659
660                 rspec->uncompressed_size = le64_to_cpu(hdr.res_usize);
661
662                 /* Compression format numbers must be the same as in
663                  * WIMGAPI to be compatible here.  */
664                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_NONE != 0);
665                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_XPRESS != 1);
666                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZX != 2);
667                 BUILD_BUG_ON(WIMLIB_COMPRESSION_TYPE_LZMS != 3);
668                 rspec->compression_type = le32_to_cpu(hdr.compression_format);
669
670                 rspec->chunk_size = le32_to_cpu(hdr.chunk_size);
671
672                 DEBUG("Solid resource %zu/%zu: %"PRIu64" => %"PRIu64" "
673                       "(%"TS"/%"PRIu32") @ +%"PRIu64"",
674                       i + 1, num_rspecs,
675                       rspec->uncompressed_size,
676                       rspec->size_in_wim,
677                       wimlib_get_compression_type_string(rspec->compression_type),
678                       rspec->chunk_size,
679                       rspec->offset_in_wim);
680
681         }
682         return 0;
683 }
684
685 /*
686  * Given a nonempty run of consecutive lookup table entries with the SOLID flag
687  * set, allocate a 'struct wim_resource_spec' for each resource within that run.
688  *
689  * Returns 0 on success, or a nonzero error code on failure.
690  * Returns the pointers and count in *rspecs_ret and *num_rspecs_ret.
691  */
692 static int
693 load_solid_info(WIMStruct *wim,
694                 const struct wim_lookup_table_entry_disk *entries,
695                 size_t num_remaining_entries,
696                 struct wim_resource_spec ***rspecs_ret,
697                 size_t *num_rspecs_ret)
698 {
699         size_t num_rspecs;
700         struct wim_resource_spec **rspecs;
701         size_t i;
702         int ret;
703
704         num_rspecs = count_solid_resources(entries, num_remaining_entries);
705         rspecs = CALLOC(num_rspecs, sizeof(rspecs[0]));
706         if (!rspecs)
707                 return WIMLIB_ERR_NOMEM;
708
709         for (i = 0; i < num_rspecs; i++) {
710                 rspecs[i] = MALLOC(sizeof(struct wim_resource_spec));
711                 if (!rspecs[i]) {
712                         ret = WIMLIB_ERR_NOMEM;
713                         goto out_free_rspecs;
714                 }
715         }
716
717         ret = do_load_solid_info(wim, rspecs, num_rspecs, entries);
718         if (ret)
719                 goto out_free_rspecs;
720
721         *rspecs_ret = rspecs;
722         *num_rspecs_ret = num_rspecs;
723         return 0;
724
725 out_free_rspecs:
726         for (i = 0; i < num_rspecs; i++)
727                 FREE(rspecs[i]);
728         FREE(rspecs);
729         return ret;
730 }
731
732 /* Given a 'struct wim_lookup_table_entry' allocated for a stream entry with the
733  * SOLID flag set, try to bind it to resource in the current solid run.  */
734 static int
735 bind_stream_to_solid_resource(const struct wim_reshdr *reshdr,
736                               struct wim_lookup_table_entry *stream,
737                               struct wim_resource_spec **rspecs,
738                               size_t num_rspecs)
739 {
740         u64 offset = reshdr->offset_in_wim;
741
742         /* XXX: This linear search will be slow in the degenerate case where the
743          * number of solid resources in the run is huge.  */
744         stream->size = reshdr->size_in_wim;
745         stream->flags = reshdr->flags;
746         for (size_t i = 0; i < num_rspecs; i++) {
747                 if (offset + stream->size <= rspecs[i]->uncompressed_size) {
748                         stream->offset_in_res = offset;
749                         lte_bind_wim_resource_spec(stream, rspecs[i]);
750                         return 0;
751                 }
752                 offset -= rspecs[i]->uncompressed_size;
753         }
754         ERROR("Stream could not be assigned to a solid resource");
755         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
756 }
757
758 static void
759 free_solid_rspecs(struct wim_resource_spec **rspecs, size_t num_rspecs)
760 {
761         if (rspecs) {
762                 for (size_t i = 0; i < num_rspecs; i++)
763                         if (list_empty(&rspecs[i]->stream_list))
764                                 FREE(rspecs[i]);
765                 FREE(rspecs);
766         }
767 }
768
769 static int
770 cmp_streams_by_offset_in_res(const void *p1, const void *p2)
771 {
772         const struct wim_lookup_table_entry *lte1, *lte2;
773
774         lte1 = *(const struct wim_lookup_table_entry**)p1;
775         lte2 = *(const struct wim_lookup_table_entry**)p2;
776
777         return cmp_u64(lte1->offset_in_res, lte2->offset_in_res);
778 }
779
780 /* Validate the size and location of a WIM resource.  */
781 static int
782 validate_resource(struct wim_resource_spec *rspec)
783 {
784         struct wim_lookup_table_entry *lte;
785         bool out_of_order;
786         u64 expected_next_offset;
787         int ret;
788
789         /* Verify that the resource itself has a valid offset and size.  */
790         if (rspec->offset_in_wim + rspec->size_in_wim < rspec->size_in_wim)
791                 goto invalid_due_to_overflow;
792
793         /* Verify that each stream in the resource has a valid offset and size.
794          */
795         expected_next_offset = 0;
796         out_of_order = false;
797         list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
798                 if (lte->offset_in_res + lte->size < lte->size ||
799                     lte->offset_in_res + lte->size > rspec->uncompressed_size)
800                         goto invalid_due_to_overflow;
801
802                 if (lte->offset_in_res >= expected_next_offset)
803                         expected_next_offset = lte->offset_in_res + lte->size;
804                 else
805                         out_of_order = true;
806         }
807
808         /* If the streams were not located at strictly increasing positions (not
809          * allowing for overlap), sort them.  Then make sure that none overlap.
810          */
811         if (out_of_order) {
812                 ret = sort_stream_list(&rspec->stream_list,
813                                        offsetof(struct wim_lookup_table_entry,
814                                                 rspec_node),
815                                        cmp_streams_by_offset_in_res);
816                 if (ret)
817                         return ret;
818
819                 expected_next_offset = 0;
820                 list_for_each_entry(lte, &rspec->stream_list, rspec_node) {
821                         if (lte->offset_in_res >= expected_next_offset)
822                                 expected_next_offset = lte->offset_in_res + lte->size;
823                         else
824                                 goto invalid_due_to_overlap;
825                 }
826         }
827
828         return 0;
829
830 invalid_due_to_overflow:
831         ERROR("Invalid resource entry (offset overflow)");
832         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
833
834 invalid_due_to_overlap:
835         ERROR("Invalid resource entry (streams in solid resource overlap)");
836         return WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
837 }
838
839 static int
840 finish_solid_rspecs(struct wim_resource_spec **rspecs, size_t num_rspecs)
841 {
842         int ret = 0;
843         for (size_t i = 0; i < num_rspecs; i++) {
844                 ret = validate_resource(rspecs[i]);
845                 if (ret)
846                         break;
847         }
848         free_solid_rspecs(rspecs, num_rspecs);
849         return ret;
850 }
851
852 /*
853  * Reads the lookup table from a WIM file.  Usually, each entry specifies a
854  * stream that the WIM file contains, along with its location and SHA1 message
855  * digest.
856  *
857  * Saves lookup table entries for non-metadata streams in a hash table (set to
858  * wim->lookup_table), and saves the metadata entry for each image in a special
859  * per-image location (the wim->image_metadata array).
860  *
861  * This works for both version WIM_VERSION_DEFAULT (68864) and version
862  * WIM_VERSION_SOLID (3584) WIMs.  In the latter, a consecutive run of lookup
863  * table entries that all have flag WIM_RESHDR_FLAG_SOLID (0x10) set is a "solid
864  * run".  A solid run logically contains zero or more resources, each of which
865  * logically contains zero or more streams.  Physically, in such a run, a
866  * "lookup table entry" with uncompressed size SOLID_RESOURCE_MAGIC_NUMBER
867  * (0x100000000) specifies a resource, whereas any other entry specifies a
868  * stream.  Within such a run, stream entries and resource entries need not be
869  * in any particular order, except that the order of the resource entries is
870  * important, as it affects how streams are assigned to resources.  See the code
871  * for details.
872  *
873  * Possible return values:
874  *      WIMLIB_ERR_SUCCESS (0)
875  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
876  *      WIMLIB_ERR_NOMEM
877  *
878  *      Or an error code caused by failure to read the lookup table from the WIM
879  *      file.
880  */
881 int
882 read_wim_lookup_table(WIMStruct *wim)
883 {
884         int ret;
885         size_t num_entries;
886         void *buf = NULL;
887         struct wim_lookup_table *table = NULL;
888         struct wim_lookup_table_entry *cur_entry = NULL;
889         size_t num_duplicate_entries = 0;
890         size_t num_wrong_part_entries = 0;
891         u32 image_index = 0;
892         struct wim_resource_spec **cur_solid_rspecs = NULL;
893         size_t cur_num_solid_rspecs = 0;
894
895         DEBUG("Reading lookup table.");
896
897         /* Sanity check: lookup table entries are 50 bytes each.  */
898         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
899                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
900
901         /* Calculate the number of entries in the lookup table.  */
902         num_entries = wim->hdr.lookup_table_reshdr.uncompressed_size /
903                       sizeof(struct wim_lookup_table_entry_disk);
904
905         /* Read the lookup table into a buffer.  */
906         ret = wim_reshdr_to_data(&wim->hdr.lookup_table_reshdr, wim, &buf);
907         if (ret)
908                 goto out;
909
910         /* Allocate a hash table to map SHA1 message digests into stream
911          * specifications.  This is the in-memory "lookup table".  */
912         table = new_lookup_table(num_entries * 2 + 1);
913         if (!table)
914                 goto oom;
915
916         /* Allocate and initalize stream entries ('struct
917          * wim_lookup_table_entry's) from the raw lookup table buffer.  Each of
918          * these entries will point to a 'struct wim_resource_spec' that
919          * describes the underlying resource.  In WIMs with version number
920          * WIM_VERSION_SOLID, a resource may contain multiple streams.
921          */
922         for (size_t i = 0; i < num_entries; i++) {
923                 const struct wim_lookup_table_entry_disk *disk_entry =
924                         &((const struct wim_lookup_table_entry_disk*)buf)[i];
925                 struct wim_reshdr reshdr;
926                 u16 part_number;
927
928                 /* Get the resource header  */
929                 get_wim_reshdr(&disk_entry->reshdr, &reshdr);
930
931                 DEBUG("reshdr: size_in_wim=%"PRIu64", "
932                       "uncompressed_size=%"PRIu64", "
933                       "offset_in_wim=%"PRIu64", "
934                       "flags=0x%02x",
935                       reshdr.size_in_wim, reshdr.uncompressed_size,
936                       reshdr.offset_in_wim, reshdr.flags);
937
938                 /* Ignore SOLID flag if it isn't supposed to be used in this WIM
939                  * version.  */
940                 if (wim->hdr.wim_version == WIM_VERSION_DEFAULT)
941                         reshdr.flags &= ~WIM_RESHDR_FLAG_SOLID;
942
943                 /* Allocate a new 'struct wim_lookup_table_entry'.  */
944                 cur_entry = new_lookup_table_entry();
945                 if (!cur_entry)
946                         goto oom;
947
948                 /* Get the part number, reference count, and hash.  */
949                 part_number = le16_to_cpu(disk_entry->part_number);
950                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
951                 copy_hash(cur_entry->hash, disk_entry->hash);
952
953                 if (reshdr.flags & WIM_RESHDR_FLAG_SOLID) {
954
955                         /* SOLID entry  */
956
957                         if (!cur_solid_rspecs) {
958                                 /* Starting new run  */
959                                 ret = load_solid_info(wim, disk_entry,
960                                                       num_entries - i,
961                                                       &cur_solid_rspecs,
962                                                       &cur_num_solid_rspecs);
963                                 if (ret)
964                                         goto out;
965                         }
966
967                         if (reshdr.uncompressed_size == SOLID_RESOURCE_MAGIC_NUMBER) {
968                                 /* Resource entry, not stream entry  */
969                                 goto free_cur_entry_and_continue;
970                         }
971
972                         /* Stream entry  */
973
974                         ret = bind_stream_to_solid_resource(&reshdr,
975                                                             cur_entry,
976                                                             cur_solid_rspecs,
977                                                             cur_num_solid_rspecs);
978                         if (ret)
979                                 goto out;
980
981                 } else {
982                         /* Normal stream/resource entry; SOLID not set.  */
983
984                         struct wim_resource_spec *rspec;
985
986                         if (unlikely(cur_solid_rspecs)) {
987                                 /* This entry terminated a solid run.  */
988                                 ret = finish_solid_rspecs(cur_solid_rspecs,
989                                                           cur_num_solid_rspecs);
990                                 cur_solid_rspecs = 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_solid_rspecs &&
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_solid_rspecs) {
1118                 /* End of lookup table terminated a solid run.  */
1119                 ret = finish_solid_rspecs(cur_solid_rspecs, cur_num_solid_rspecs);
1120                 cur_solid_rspecs = 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_solid_rspecs(cur_solid_rspecs, cur_num_solid_rspecs);
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 solid 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_SOLID &&
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_SOLID) {
1218                         struct wim_reshdr tmp_reshdr;
1219
1220                         /* Eww.  When WIMGAPI sees multiple solid resources, it
1221                          * expects the offsets to be adjusted as if there were
1222                          * really only one solid resource.  */
1223
1224                         if (lte->out_res_offset_in_wim != prev_res_offset_in_wim) {
1225                                 /* Put the resource entry for solid resource  */
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 = SOLID_RESOURCE_MAGIC_NUMBER;
1229                                 tmp_reshdr.flags = WIM_RESHDR_FLAG_SOLID;
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_SOLID) {
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_SOLID) != 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 }