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