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