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