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