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