Improve write streams performance and handling of joins
[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/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/paths.h"
37 #include "wimlib/resource.h"
38 #include "wimlib/util.h"
39 #include "wimlib/write.h"
40
41 #include <errno.h>
42 #include <stdlib.h>
43 #ifdef WITH_FUSE
44 #  include <unistd.h> /* for unlink() */
45 #endif
46
47 struct wim_lookup_table *
48 new_lookup_table(size_t capacity)
49 {
50         struct wim_lookup_table *table;
51         struct hlist_head *array;
52
53         table = CALLOC(1, sizeof(struct wim_lookup_table));
54         if (table) {
55                 array = CALLOC(capacity, sizeof(array[0]));
56                 if (array) {
57                         table->num_entries = 0;
58                         table->capacity = capacity;
59                         table->array = array;
60                 } else {
61                         FREE(table);
62                         table = NULL;
63                         ERROR("Failed to allocate memory for lookup table "
64                               "with capacity %zu", capacity);
65                 }
66         }
67         return table;
68 }
69
70 struct wim_lookup_table_entry *
71 new_lookup_table_entry(void)
72 {
73         struct wim_lookup_table_entry *lte;
74
75         lte = CALLOC(1, sizeof(struct wim_lookup_table_entry));
76         if (lte) {
77                 lte->part_number  = 1;
78                 lte->refcnt       = 1;
79         } else {
80                 ERROR("Out of memory (tried to allocate %zu bytes for "
81                       "lookup table entry)",
82                       sizeof(struct wim_lookup_table_entry));
83         }
84         return lte;
85 }
86
87 struct wim_lookup_table_entry *
88 clone_lookup_table_entry(const struct wim_lookup_table_entry *old)
89 {
90         struct wim_lookup_table_entry *new;
91
92         new = memdup(old, sizeof(struct wim_lookup_table_entry));
93         if (!new)
94                 return NULL;
95
96         new->extracted_file = NULL;
97         switch (new->resource_location) {
98         case RESOURCE_IN_FILE_ON_DISK:
99 #ifdef __WIN32__
100         case RESOURCE_WIN32_ENCRYPTED:
101 #endif
102 #ifdef WITH_FUSE
103         case RESOURCE_IN_STAGING_FILE:
104                 BUILD_BUG_ON((void*)&old->file_on_disk !=
105                              (void*)&old->staging_file_name);
106 #endif
107                 new->file_on_disk = TSTRDUP(old->file_on_disk);
108                 if (!new->file_on_disk)
109                         goto out_free;
110                 break;
111         case RESOURCE_IN_ATTACHED_BUFFER:
112                 new->attached_buffer = memdup(old->attached_buffer,
113                                               wim_resource_size(old));
114                 if (!new->attached_buffer)
115                         goto out_free;
116                 break;
117 #ifdef WITH_NTFS_3G
118         case RESOURCE_IN_NTFS_VOLUME:
119                 if (old->ntfs_loc) {
120                         struct ntfs_location *loc;
121                         loc = memdup(old->ntfs_loc, sizeof(struct ntfs_location));
122                         if (!loc)
123                                 goto out_free;
124                         loc->path = NULL;
125                         loc->stream_name = NULL;
126                         new->ntfs_loc = loc;
127                         loc->path = STRDUP(old->ntfs_loc->path);
128                         if (!loc->path)
129                                 goto out_free;
130                         if (loc->stream_name_nchars) {
131                                 loc->stream_name = memdup(old->ntfs_loc->stream_name,
132                                                           loc->stream_name_nchars * 2);
133                                 if (!loc->stream_name)
134                                         goto out_free;
135                         }
136                 }
137                 break;
138 #endif
139         default:
140                 break;
141         }
142         return new;
143 out_free:
144         free_lookup_table_entry(new);
145         return NULL;
146 }
147
148 void
149 free_lookup_table_entry(struct wim_lookup_table_entry *lte)
150 {
151         if (lte) {
152                 switch (lte->resource_location) {
153                 case RESOURCE_IN_FILE_ON_DISK:
154         #ifdef __WIN32__
155                 case RESOURCE_WIN32_ENCRYPTED:
156         #endif
157         #ifdef WITH_FUSE
158                 case RESOURCE_IN_STAGING_FILE:
159                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
160                                      (void*)&lte->staging_file_name);
161         #endif
162                 case RESOURCE_IN_ATTACHED_BUFFER:
163                         BUILD_BUG_ON((void*)&lte->file_on_disk !=
164                                      (void*)&lte->attached_buffer);
165                         FREE(lte->file_on_disk);
166                         break;
167 #ifdef WITH_NTFS_3G
168                 case RESOURCE_IN_NTFS_VOLUME:
169                         if (lte->ntfs_loc) {
170                                 FREE(lte->ntfs_loc->path);
171                                 FREE(lte->ntfs_loc->stream_name);
172                                 FREE(lte->ntfs_loc);
173                         }
174                         break;
175 #endif
176                 default:
177                         break;
178                 }
179                 FREE(lte);
180         }
181 }
182
183 static int
184 do_free_lookup_table_entry(struct wim_lookup_table_entry *entry, void *ignore)
185 {
186         free_lookup_table_entry(entry);
187         return 0;
188 }
189
190
191 void
192 free_lookup_table(struct wim_lookup_table *table)
193 {
194         DEBUG2("Freeing lookup table");
195         if (table) {
196                 if (table->array) {
197                         for_lookup_table_entry(table,
198                                                do_free_lookup_table_entry,
199                                                NULL);
200                         FREE(table->array);
201                 }
202                 FREE(table);
203         }
204 }
205
206 /*
207  * Inserts an entry into the lookup table.
208  *
209  * @table:      A pointer to the lookup table.
210  * @lte:        A pointer to the entry to insert.
211  */
212 void
213 lookup_table_insert(struct wim_lookup_table *table,
214                     struct wim_lookup_table_entry *lte)
215 {
216         size_t i = lte->hash_short % table->capacity;
217         hlist_add_head(&lte->hash_list, &table->array[i]);
218
219         /* XXX Make the table grow when too many entries have been inserted. */
220         table->num_entries++;
221 }
222
223 static void
224 finalize_lte(struct wim_lookup_table_entry *lte)
225 {
226         #ifdef WITH_FUSE
227         if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
228                 unlink(lte->staging_file_name);
229                 list_del(&lte->unhashed_list);
230         }
231         #endif
232         free_lookup_table_entry(lte);
233 }
234
235 /* Decrements the reference count for the lookup table entry @lte.  If its
236  * reference count reaches 0, it is unlinked from the lookup table.  If,
237  * furthermore, the entry has no opened file descriptors associated with it, the
238  * entry is freed.  */
239 void
240 lte_decrement_refcnt(struct wim_lookup_table_entry *lte,
241                      struct wim_lookup_table *table)
242 {
243         wimlib_assert(lte != NULL);
244         wimlib_assert(lte->refcnt != 0);
245         if (--lte->refcnt == 0) {
246                 if (lte->unhashed)
247                         list_del(&lte->unhashed_list);
248                 else
249                         lookup_table_unlink(table, lte);
250         #ifdef WITH_FUSE
251                 if (lte->num_opened_fds == 0)
252         #endif
253                         finalize_lte(lte);
254         }
255 }
256
257 #ifdef WITH_FUSE
258 void
259 lte_decrement_num_opened_fds(struct wim_lookup_table_entry *lte)
260 {
261         if (lte->num_opened_fds != 0)
262                 if (--lte->num_opened_fds == 0 && lte->refcnt == 0)
263                         finalize_lte(lte);
264 }
265 #endif
266
267 /* Calls a function on all the entries in the WIM lookup table.  Stop early and
268  * return nonzero if any call to the function returns nonzero. */
269 int
270 for_lookup_table_entry(struct wim_lookup_table *table,
271                        int (*visitor)(struct wim_lookup_table_entry *, void *),
272                        void *arg)
273 {
274         struct wim_lookup_table_entry *lte;
275         struct hlist_node *pos, *tmp;
276         int ret;
277
278         for (size_t i = 0; i < table->capacity; i++) {
279                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
280                                           hash_list)
281                 {
282                         wimlib_assert2(!(lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA));
283                         ret = visitor(lte, arg);
284                         if (ret)
285                                 return ret;
286                 }
287         }
288         return 0;
289 }
290
291 /* qsort() callback that sorts streams (represented by `struct
292  * wim_lookup_table_entry's) into an order optimized for reading and writing.
293  *
294  * Sorting is done primarily by resource location, then secondarily by a
295  * per-resource location order.  For example, resources in WIM files are sorted
296  * primarily by part number, then secondarily by offset, as to implement optimal
297  * reading of either a standalone or split WIM.  */
298 static int
299 cmp_streams_by_sequential_order(const void *p1, const void *p2)
300 {
301         const struct wim_lookup_table_entry *lte1, *lte2;
302         int v;
303
304         lte1 = *(const struct wim_lookup_table_entry**)p1;
305         lte2 = *(const struct wim_lookup_table_entry**)p2;
306
307         v = (int)lte1->resource_location - (int)lte2->resource_location;
308
309         /* Different resource locations?  */
310         if (v)
311                 return v;
312
313         switch (lte1->resource_location) {
314         case RESOURCE_IN_WIM:
315
316                 /* Different (possibly split) WIMs?  */
317                 if (lte1->wim != lte2->wim) {
318                         v = memcmp(lte1->wim->hdr.guid, lte2->wim->hdr.guid,
319                                    WIM_GID_LEN);
320                         if (v)
321                                 return v;
322                 }
323
324                 /* Different part numbers in the same WIM?  */
325                 v = (int)lte1->wim->hdr.part_number - (int)lte2->wim->hdr.part_number;
326                 if (v)
327                         return v;
328
329                 /* Compare by offset.  */
330                 if (lte1->resource_entry.offset < lte2->resource_entry.offset)
331                         return -1;
332                 else if (lte1->resource_entry.offset > lte2->resource_entry.offset)
333                         return 1;
334                 return 0;
335         case RESOURCE_IN_FILE_ON_DISK:
336 #ifdef __WIN32__
337         case RESOURCE_WIN32_ENCRYPTED:
338 #endif
339                 /* Compare files by path: just a heuristic that will place files
340                  * in the same directory next to each other.  */
341                 return tstrcmp(lte1->file_on_disk, lte2->file_on_disk);
342 #ifdef WITH_NTFS_3G
343         case RESOURCE_IN_NTFS_VOLUME:
344                 return tstrcmp(lte1->ntfs_loc->path, lte2->ntfs_loc->path);
345 #endif
346         default:
347                 /* No additional sorting order defined for this resource
348                  * location (e.g. RESOURCE_IN_ATTACHED_BUFFER); simply compare
349                  * everything equal to each other.  */
350                 return 0;
351         }
352 }
353
354 int
355 sort_stream_list_by_sequential_order(struct list_head *stream_list,
356                                      size_t list_head_offset)
357 {
358         struct list_head *cur;
359         struct wim_lookup_table_entry **array;
360         size_t i;
361         size_t array_size;
362         size_t num_streams = 0;
363
364         list_for_each(cur, stream_list)
365                 num_streams++;
366
367         array_size = num_streams * sizeof(array[0]);
368         array = MALLOC(array_size);
369         if (!array)
370                 return WIMLIB_ERR_NOMEM;
371         cur = stream_list->next;
372         for (i = 0; i < num_streams; i++) {
373                 array[i] = (struct wim_lookup_table_entry*)((u8*)cur -
374                                                             list_head_offset);
375                 cur = cur->next;
376         }
377
378         qsort(array, num_streams, sizeof(array[0]),
379               cmp_streams_by_sequential_order);
380
381         INIT_LIST_HEAD(stream_list);
382         for (i = 0; i < num_streams; i++) {
383                 list_add_tail((struct list_head*)
384                                ((u8*)array[i] + list_head_offset),
385                               stream_list);
386         }
387         FREE(array);
388         return 0;
389 }
390
391
392 static int
393 add_lte_to_array(struct wim_lookup_table_entry *lte,
394                  void *_pp)
395 {
396         struct wim_lookup_table_entry ***pp = _pp;
397         *(*pp)++ = lte;
398         return 0;
399 }
400
401 /* Iterate through the lookup table entries, but first sort them by stream
402  * offset in the WIM.  Caution: this is intended to be used when the stream
403  * offset field has actually been set. */
404 int
405 for_lookup_table_entry_pos_sorted(struct wim_lookup_table *table,
406                                   int (*visitor)(struct wim_lookup_table_entry *,
407                                                  void *),
408                                   void *arg)
409 {
410         struct wim_lookup_table_entry **lte_array, **p;
411         size_t num_streams = table->num_entries;
412         int ret;
413
414         lte_array = MALLOC(num_streams * sizeof(lte_array[0]));
415         if (!lte_array)
416                 return WIMLIB_ERR_NOMEM;
417         p = lte_array;
418         for_lookup_table_entry(table, add_lte_to_array, &p);
419
420         wimlib_assert(p == lte_array + num_streams);
421
422         qsort(lte_array, num_streams, sizeof(lte_array[0]),
423               cmp_streams_by_sequential_order);
424         ret = 0;
425         for (size_t i = 0; i < num_streams; i++) {
426                 ret = visitor(lte_array[i], arg);
427                 if (ret)
428                         break;
429         }
430         FREE(lte_array);
431         return ret;
432 }
433
434 /* On-disk format of a WIM lookup table entry (stream entry). */
435 struct wim_lookup_table_entry_disk {
436         /* Location, offset, compression status, and metadata status of the
437          * stream. */
438         struct resource_entry_disk resource_entry;
439
440         /* Which part of the split WIM this stream is in; indexed from 1. */
441         le16 part_number;
442
443         /* Reference count of this stream over all WIM images. */
444         le32 refcnt;
445
446         /* SHA1 message digest of the uncompressed data of this stream, or
447          * optionally all zeroes if this stream is of zero length. */
448         u8 hash[SHA1_HASH_SIZE];
449 } _packed_attribute;
450
451 #define WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE 50
452
453 void
454 lte_init_wim(struct wim_lookup_table_entry *lte, WIMStruct *wim)
455 {
456         lte->resource_location = RESOURCE_IN_WIM;
457         lte->wim = wim;
458         if (lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
459                 lte->compression_type = wim->compression_type;
460         else
461                 lte->compression_type = WIMLIB_COMPRESSION_TYPE_NONE;
462
463         if (wim_is_pipable(wim))
464                 lte->is_pipable = 1;
465 }
466
467 /*
468  * Reads the lookup table from a WIM file.
469  *
470  * Saves lookup table entries for non-metadata streams in a hash table, and
471  * saves the metadata entry for each image in a special per-image location (the
472  * image_metadata array).
473  *
474  * Return values:
475  *      WIMLIB_ERR_SUCCESS (0)
476  *      WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY
477  *      WIMLIB_ERR_RESOURCE_NOT_FOUND
478  */
479 int
480 read_wim_lookup_table(WIMStruct *wim)
481 {
482         int ret;
483         size_t i;
484         size_t num_entries;
485         struct wim_lookup_table *table;
486         struct wim_lookup_table_entry *cur_entry, *duplicate_entry;
487         struct wim_lookup_table_entry_disk *buf;
488
489         BUILD_BUG_ON(sizeof(struct wim_lookup_table_entry_disk) !=
490                      WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE);
491
492         DEBUG("Reading lookup table: offset %"PRIu64", size %"PRIu64"",
493               wim->hdr.lookup_table_res_entry.offset,
494               wim->hdr.lookup_table_res_entry.size);
495
496         /* Calculate number of entries in the lookup table.  */
497         num_entries = wim->hdr.lookup_table_res_entry.size /
498                       sizeof(struct wim_lookup_table_entry_disk);
499
500
501         /* Read the lookup table into a buffer.  */
502         ret = res_entry_to_data(&wim->hdr.lookup_table_res_entry, wim,
503                                 (void**)&buf);
504         if (ret)
505                 goto out;
506
507         /* Allocate hash table.  */
508         table = new_lookup_table(num_entries * 2 + 1);
509         if (!table) {
510                 ERROR("Not enough memory to read lookup table.");
511                 ret = WIMLIB_ERR_NOMEM;
512                 goto out_free_buf;
513         }
514
515         /* Allocate and initalize `struct wim_lookup_table_entry's from the
516          * on-disk lookup table.  */
517         wim->current_image = 0;
518         for (i = 0; i < num_entries; i++) {
519                 const struct wim_lookup_table_entry_disk *disk_entry = &buf[i];
520
521                 cur_entry = new_lookup_table_entry();
522                 if (!cur_entry) {
523                         ERROR("Not enough memory to read lookup table.");
524                         ret = WIMLIB_ERR_NOMEM;
525                         goto out_free_lookup_table;
526                 }
527
528                 cur_entry->wim = wim;
529                 cur_entry->resource_location = RESOURCE_IN_WIM;
530                 get_resource_entry(&disk_entry->resource_entry, &cur_entry->resource_entry);
531                 cur_entry->part_number = le16_to_cpu(disk_entry->part_number);
532                 cur_entry->refcnt = le32_to_cpu(disk_entry->refcnt);
533                 copy_hash(cur_entry->hash, disk_entry->hash);
534                 lte_init_wim(cur_entry, wim);
535
536                 if (cur_entry->part_number != wim->hdr.part_number) {
537                         WARNING("A lookup table entry in part %hu of the WIM "
538                                 "points to part %hu (ignoring it)",
539                                 wim->hdr.part_number, cur_entry->part_number);
540                         free_lookup_table_entry(cur_entry);
541                         continue;
542                 }
543
544                 if (is_zero_hash(cur_entry->hash)) {
545                         WARNING("The WIM lookup table contains an entry with a "
546                                 "SHA1 message digest of all 0's (ignoring it)");
547                         free_lookup_table_entry(cur_entry);
548                         continue;
549                 }
550
551                 if (!(cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED)
552                     && (cur_entry->resource_entry.size !=
553                         cur_entry->resource_entry.original_size))
554                 {
555                         if (wimlib_print_errors) {
556                                 WARNING("Found uncompressed resource with "
557                                         "original size (%"PRIu64") not the same "
558                                         "as compressed size (%"PRIu64")",
559                                         cur_entry->resource_entry.original_size,
560                                         cur_entry->resource_entry.size);
561                                 if (cur_entry->resource_entry.original_size) {
562                                         WARNING("Overriding compressed size with original size.");
563                                         cur_entry->resource_entry.size =
564                                                 cur_entry->resource_entry.original_size;
565                                 } else {
566                                         WARNING("Overriding original size with compressed size");
567                                         cur_entry->resource_entry.original_size =
568                                                 cur_entry->resource_entry.size;
569                                 }
570                         }
571                 }
572
573                 if (cur_entry->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) {
574                         /* Lookup table entry for a metadata resource */
575                         if (cur_entry->refcnt != 1) {
576                                 if (wimlib_print_errors) {
577                                         ERROR("Found metadata resource with refcnt != 1:");
578                                         print_lookup_table_entry(cur_entry, stderr);
579                                 }
580                                 ret = WIMLIB_ERR_INVALID_LOOKUP_TABLE_ENTRY;
581                                 goto out_free_cur_entry;
582                         }
583
584                         if (wim->hdr.part_number != 1) {
585                                 WARNING("Ignoring metadata resource found in a "
586                                         "non-first part of the split WIM");
587                                 free_lookup_table_entry(cur_entry);
588                                 continue;
589                         }
590                         if (wim->current_image == wim->hdr.image_count) {
591                                 WARNING("The WIM header says there are %u images "
592                                         "in the WIM, but we found more metadata "
593                                         "resources than this (ignoring the extra)",
594                                         wim->hdr.image_count);
595                                 free_lookup_table_entry(cur_entry);
596                                 continue;
597                         }
598
599                         /* Notice very carefully:  We are assigning the metadata
600                          * resources in the exact order mirrored by their lookup
601                          * table entries on disk, which is the behavior of
602                          * Microsoft's software.  In particular, this overrides
603                          * the actual locations of the metadata resources
604                          * themselves in the WIM file as well as any information
605                          * written in the XML data. */
606                         DEBUG("Found metadata resource for image %u at "
607                               "offset %"PRIu64".",
608                               wim->current_image + 1,
609                               cur_entry->resource_entry.offset);
610                         wim->image_metadata[
611                                 wim->current_image++]->metadata_lte = cur_entry;
612                 } else {
613                         /* Lookup table entry for a stream that is not a
614                          * metadata resource */
615                         duplicate_entry = __lookup_resource(table, cur_entry->hash);
616                         if (duplicate_entry) {
617                                 if (wimlib_print_errors) {
618                                         WARNING("The WIM lookup table contains two entries with the "
619                                               "same SHA1 message digest!");
620                                         WARNING("The first entry is:");
621                                         print_lookup_table_entry(duplicate_entry, stderr);
622                                         WARNING("The second entry is:");
623                                         print_lookup_table_entry(cur_entry, stderr);
624                                 }
625                                 free_lookup_table_entry(cur_entry);
626                                 continue;
627                         } else {
628                                 lookup_table_insert(table, cur_entry);
629                         }
630                 }
631         }
632
633         if (wim->hdr.part_number == 1 && wim->current_image != wim->hdr.image_count) {
634                 WARNING("The header of \"%"TS"\" says there are %u images in\n"
635                         "          the WIM, but we only found %d metadata resources!  Acting as if\n"
636                         "          the header specified only %d images instead.",
637                         wim->filename, wim->hdr.image_count,
638                         wim->current_image, wim->current_image);
639                 for (int i = wim->current_image; i < wim->hdr.image_count; i++)
640                         put_image_metadata(wim->image_metadata[i], NULL);
641                 wim->hdr.image_count = wim->current_image;
642         }
643         DEBUG("Done reading lookup table.");
644         wim->lookup_table = table;
645         ret = 0;
646         goto out_free_buf;
647 out_free_cur_entry:
648         FREE(cur_entry);
649 out_free_lookup_table:
650         free_lookup_table(table);
651 out_free_buf:
652         FREE(buf);
653 out:
654         wim->current_image = 0;
655         return ret;
656 }
657
658
659 static void
660 write_wim_lookup_table_entry(const struct wim_lookup_table_entry *lte,
661                              struct wim_lookup_table_entry_disk *disk_entry)
662 {
663         put_resource_entry(&lte->output_resource_entry, &disk_entry->resource_entry);
664         disk_entry->part_number = cpu_to_le16(lte->part_number);
665         disk_entry->refcnt = cpu_to_le32(lte->out_refcnt);
666         copy_hash(disk_entry->hash, lte->hash);
667 }
668
669 static int
670 write_wim_lookup_table_from_stream_list(struct list_head *stream_list,
671                                         struct filedes *out_fd,
672                                         struct resource_entry *out_res_entry,
673                                         int write_resource_flags)
674 {
675         size_t table_size;
676         struct wim_lookup_table_entry *lte;
677         struct wim_lookup_table_entry_disk *table_buf;
678         struct wim_lookup_table_entry_disk *table_buf_ptr;
679         int ret;
680
681         table_size = 0;
682         list_for_each_entry(lte, stream_list, lookup_table_list)
683                 table_size += sizeof(struct wim_lookup_table_entry_disk);
684
685         DEBUG("Writing WIM lookup table (size=%zu, offset=%"PRIu64")",
686               table_size, out_fd->offset);
687
688         table_buf = MALLOC(table_size);
689         if (!table_buf) {
690                 ERROR("Failed to allocate %zu bytes for temporary lookup table",
691                       table_size);
692                 return WIMLIB_ERR_NOMEM;
693         }
694         table_buf_ptr = table_buf;
695         list_for_each_entry(lte, stream_list, lookup_table_list)
696                 write_wim_lookup_table_entry(lte, table_buf_ptr++);
697
698         /* Write the lookup table uncompressed.  Although wimlib can handle a
699          * compressed lookup table, MS software cannot.  */
700         ret = write_wim_resource_from_buffer(table_buf,
701                                              table_size,
702                                              WIM_RESHDR_FLAG_METADATA,
703                                              out_fd,
704                                              WIMLIB_COMPRESSION_TYPE_NONE,
705                                              out_res_entry,
706                                              NULL,
707                                              write_resource_flags);
708         FREE(table_buf);
709         return ret;
710 }
711
712 static int
713 append_lookup_table_entry(struct wim_lookup_table_entry *lte, void *_list)
714 {
715         if (lte->out_refcnt != 0)
716                 list_add_tail(&lte->lookup_table_list, (struct list_head*)_list);
717         return 0;
718 }
719
720 int
721 write_wim_lookup_table(WIMStruct *wim, int image, int write_flags,
722                        struct resource_entry *out_res_entry,
723                        struct list_head *stream_list_override)
724 {
725         int write_resource_flags;
726         struct list_head _stream_list;
727         struct list_head *stream_list;
728
729         if (stream_list_override) {
730                 stream_list = stream_list_override;
731         } else {
732                 stream_list = &_stream_list;
733                 INIT_LIST_HEAD(stream_list);
734         }
735
736         if (!(write_flags & WIMLIB_WRITE_FLAG_NO_METADATA)) {
737                 int start_image;
738                 int end_image;
739
740                 if (image == WIMLIB_ALL_IMAGES) {
741                         start_image = 1;
742                         end_image = wim->hdr.image_count;
743                 } else {
744                         start_image = image;
745                         end_image = image;
746                 }
747
748                 /* Push metadata resource lookup table entries onto the front of
749                  * the list in reverse order, so that they're written in order.
750                  */
751                 for (int i = end_image; i >= start_image; i--) {
752                         struct wim_lookup_table_entry *metadata_lte;
753
754                         metadata_lte = wim->image_metadata[i - 1]->metadata_lte;
755                         metadata_lte->out_refcnt = 1;
756                         metadata_lte->part_number = wim->hdr.part_number;
757                         metadata_lte->output_resource_entry.flags |= WIM_RESHDR_FLAG_METADATA;
758
759                         list_add(&metadata_lte->lookup_table_list, stream_list);
760                 }
761         }
762
763         /* Append additional lookup table entries that have out_refcnt != 0.  */
764         if (!stream_list_override) {
765                 for_lookup_table_entry(wim->lookup_table,
766                                        append_lookup_table_entry, stream_list);
767         }
768
769         write_resource_flags = 0;
770         if (write_flags & WIMLIB_WRITE_FLAG_PIPABLE)
771                 write_resource_flags |= WIMLIB_WRITE_RESOURCE_FLAG_PIPABLE;
772         return write_wim_lookup_table_from_stream_list(stream_list,
773                                                        &wim->out_fd,
774                                                        out_res_entry,
775                                                        write_resource_flags);
776 }
777
778
779 int
780 lte_zero_real_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
781 {
782         lte->real_refcnt = 0;
783         return 0;
784 }
785
786 int
787 lte_zero_out_refcnt(struct wim_lookup_table_entry *lte, void *_ignore)
788 {
789         lte->out_refcnt = 0;
790         return 0;
791 }
792
793 int
794 lte_free_extracted_file(struct wim_lookup_table_entry *lte, void *_ignore)
795 {
796         if (lte->extracted_file != NULL) {
797                 FREE(lte->extracted_file);
798                 lte->extracted_file = NULL;
799         }
800         return 0;
801 }
802
803 void
804 print_lookup_table_entry(const struct wim_lookup_table_entry *lte, FILE *out)
805 {
806         if (!lte) {
807                 tputc(T('\n'), out);
808                 return;
809         }
810         tfprintf(out, T("Offset            = %"PRIu64" bytes\n"),
811                  lte->resource_entry.offset);
812
813         tfprintf(out, T("Size              = %"PRIu64" bytes\n"),
814                  (u64)lte->resource_entry.size);
815
816         tfprintf(out, T("Original size     = %"PRIu64" bytes\n"),
817                  lte->resource_entry.original_size);
818
819         tfprintf(out, T("Part Number       = %hu\n"), lte->part_number);
820         tfprintf(out, T("Reference Count   = %u\n"), lte->refcnt);
821
822         if (lte->unhashed) {
823                 tfprintf(out, T("(Unhashed: inode %p, stream_id = %u)\n"),
824                          lte->back_inode, lte->back_stream_id);
825         } else {
826                 tfprintf(out, T("Hash              = 0x"));
827                 print_hash(lte->hash, out);
828                 tputc(T('\n'), out);
829         }
830
831         tfprintf(out, T("Flags             = "));
832         u8 flags = lte->resource_entry.flags;
833         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
834                 tfputs(T("WIM_RESHDR_FLAG_COMPRESSED, "), out);
835         if (flags & WIM_RESHDR_FLAG_FREE)
836                 tfputs(T("WIM_RESHDR_FLAG_FREE, "), out);
837         if (flags & WIM_RESHDR_FLAG_METADATA)
838                 tfputs(T("WIM_RESHDR_FLAG_METADATA, "), out);
839         if (flags & WIM_RESHDR_FLAG_SPANNED)
840                 tfputs(T("WIM_RESHDR_FLAG_SPANNED, "), out);
841         tputc(T('\n'), out);
842         switch (lte->resource_location) {
843         case RESOURCE_IN_WIM:
844                 if (lte->wim->filename) {
845                         tfprintf(out, T("WIM file          = `%"TS"'\n"),
846                                  lte->wim->filename);
847                 }
848                 break;
849 #ifdef __WIN32__
850         case RESOURCE_WIN32_ENCRYPTED:
851 #endif
852         case RESOURCE_IN_FILE_ON_DISK:
853                 tfprintf(out, T("File on Disk      = `%"TS"'\n"),
854                          lte->file_on_disk);
855                 break;
856 #ifdef WITH_FUSE
857         case RESOURCE_IN_STAGING_FILE:
858                 tfprintf(out, T("Staging File      = `%"TS"'\n"),
859                                 lte->staging_file_name);
860                 break;
861 #endif
862         default:
863                 break;
864         }
865         tputc(T('\n'), out);
866 }
867
868 void
869 lte_to_wimlib_resource_entry(const struct wim_lookup_table_entry *lte,
870                              struct wimlib_resource_entry *wentry)
871 {
872         wentry->uncompressed_size = lte->resource_entry.original_size;
873         wentry->compressed_size = lte->resource_entry.size;
874         wentry->offset = lte->resource_entry.offset;
875         copy_hash(wentry->sha1_hash, lte->hash);
876         wentry->part_number = lte->part_number;
877         wentry->reference_count = lte->refcnt;
878         wentry->is_compressed = (lte->resource_entry.flags & WIM_RESHDR_FLAG_COMPRESSED) != 0;
879         wentry->is_metadata = (lte->resource_entry.flags & WIM_RESHDR_FLAG_METADATA) != 0;
880         wentry->is_free = (lte->resource_entry.flags & WIM_RESHDR_FLAG_FREE) != 0;
881         wentry->is_spanned = (lte->resource_entry.flags & WIM_RESHDR_FLAG_SPANNED) != 0;
882 }
883
884 struct iterate_lte_context {
885         wimlib_iterate_lookup_table_callback_t cb;
886         void *user_ctx;
887 };
888
889 static int
890 do_iterate_lte(struct wim_lookup_table_entry *lte, void *_ctx)
891 {
892         struct iterate_lte_context *ctx = _ctx;
893         struct wimlib_resource_entry entry;
894
895         lte_to_wimlib_resource_entry(lte, &entry);
896         return (*ctx->cb)(&entry, ctx->user_ctx);
897 }
898
899 /* API function documented in wimlib.h  */
900 WIMLIBAPI int
901 wimlib_iterate_lookup_table(WIMStruct *wim, int flags,
902                             wimlib_iterate_lookup_table_callback_t cb,
903                             void *user_ctx)
904 {
905         struct iterate_lte_context ctx = {
906                 .cb = cb,
907                 .user_ctx = user_ctx,
908         };
909         if (wim->hdr.part_number == 1) {
910                 int ret;
911                 for (int i = 0; i < wim->hdr.image_count; i++) {
912                         ret = do_iterate_lte(wim->image_metadata[i]->metadata_lte,
913                                              &ctx);
914                         if (ret)
915                                 return ret;
916                 }
917         }
918         return for_lookup_table_entry(wim->lookup_table, do_iterate_lte, &ctx);
919 }
920
921 static int
922 do_print_lookup_table_entry(struct wim_lookup_table_entry *lte, void *fp)
923 {
924         print_lookup_table_entry(lte, (FILE*)fp);
925         return 0;
926 }
927
928 /* API function documented in wimlib.h  */
929 WIMLIBAPI void
930 wimlib_print_lookup_table(WIMStruct *wim)
931 {
932         for (int i = 0; i < wim->hdr.image_count; i++)
933                 print_lookup_table_entry(wim->image_metadata[i]->metadata_lte, stdout);
934         for_lookup_table_entry(wim->lookup_table,
935                                do_print_lookup_table_entry,
936                                stdout);
937 }
938
939 /* Given a SHA1 message digest, return the corresponding entry in the WIM's
940  * lookup table, or NULL if there is none.  */
941 struct wim_lookup_table_entry *
942 __lookup_resource(const struct wim_lookup_table *table, const u8 hash[])
943 {
944         size_t i;
945         struct wim_lookup_table_entry *lte;
946         struct hlist_node *pos;
947
948         wimlib_assert(table != NULL);
949         wimlib_assert(hash != NULL);
950
951         i = *(size_t*)hash % table->capacity;
952         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
953                 if (hashes_equal(hash, lte->hash))
954                         return lte;
955         return NULL;
956 }
957
958 #ifdef WITH_FUSE
959 /*
960  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
961  * given a path name.
962  *
963  * This is only for pre-resolved inodes.
964  */
965 int
966 lookup_resource(WIMStruct *wim,
967                 const tchar *path,
968                 int lookup_flags,
969                 struct wim_dentry **dentry_ret,
970                 struct wim_lookup_table_entry **lte_ret,
971                 u16 *stream_idx_ret)
972 {
973         struct wim_dentry *dentry;
974         struct wim_lookup_table_entry *lte;
975         u16 stream_idx;
976         const tchar *stream_name = NULL;
977         struct wim_inode *inode;
978         tchar *p = NULL;
979
980         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
981                 stream_name = path_stream_name(path);
982                 if (stream_name) {
983                         p = (tchar*)stream_name - 1;
984                         *p = T('\0');
985                 }
986         }
987
988         dentry = get_dentry(wim, path);
989         if (p)
990                 *p = T(':');
991         if (!dentry)
992                 return -errno;
993
994         inode = dentry->d_inode;
995
996         if (!inode->i_resolved)
997                 if (inode_resolve_ltes(inode, wim->lookup_table, false))
998                         return -EIO;
999
1000         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
1001               && inode_is_directory(inode))
1002                 return -EISDIR;
1003
1004         if (stream_name) {
1005                 struct wim_ads_entry *ads_entry;
1006                 u16 ads_idx;
1007                 ads_entry = inode_get_ads_entry(inode, stream_name,
1008                                                 &ads_idx);
1009                 if (ads_entry) {
1010                         stream_idx = ads_idx + 1;
1011                         lte = ads_entry->lte;
1012                         goto out;
1013                 } else {
1014                         return -ENOENT;
1015                 }
1016         } else {
1017                 lte = inode->i_lte;
1018                 stream_idx = 0;
1019         }
1020 out:
1021         if (dentry_ret)
1022                 *dentry_ret = dentry;
1023         if (lte_ret)
1024                 *lte_ret = lte;
1025         if (stream_idx_ret)
1026                 *stream_idx_ret = stream_idx;
1027         return 0;
1028 }
1029 #endif
1030
1031 /*
1032  * Resolve an inode's lookup table entries.
1033  *
1034  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
1035  * lookup table) with pointers directly to the lookup table entries.
1036  *
1037  * If @force is %false:
1038  *      If any needed SHA1 message digests are not found in the lookup table,
1039  *      WIMLIB_ERR_RESOURCE_NOT_FOUND is returned and the inode is left
1040  *      unmodified.
1041  * If @force is %true:
1042  *      If any needed SHA1 message digests are not found in the lookup table,
1043  *      new entries are allocated and inserted into the lookup table.
1044  */
1045 int
1046 inode_resolve_ltes(struct wim_inode *inode, struct wim_lookup_table *table,
1047                    bool force)
1048 {
1049         const u8 *hash;
1050
1051         if (!inode->i_resolved) {
1052                 struct wim_lookup_table_entry *lte, *ads_lte;
1053
1054                 /* Resolve the default file stream */
1055                 lte = NULL;
1056                 hash = inode->i_hash;
1057                 if (!is_zero_hash(hash)) {
1058                         lte = __lookup_resource(table, hash);
1059                         if (!lte) {
1060                                 if (force) {
1061                                         lte = new_lookup_table_entry();
1062                                         if (!lte)
1063                                                 return WIMLIB_ERR_NOMEM;
1064                                         copy_hash(lte->hash, hash);
1065                                         lookup_table_insert(table, lte);
1066                                 } else {
1067                                         goto resource_not_found;
1068                                 }
1069                         }
1070                 }
1071
1072                 /* Resolve the alternate data streams */
1073                 struct wim_lookup_table_entry *ads_ltes[inode->i_num_ads];
1074                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1075                         struct wim_ads_entry *cur_entry;
1076
1077                         ads_lte = NULL;
1078                         cur_entry = &inode->i_ads_entries[i];
1079                         hash = cur_entry->hash;
1080                         if (!is_zero_hash(hash)) {
1081                                 ads_lte = __lookup_resource(table, hash);
1082                                 if (!ads_lte) {
1083                                         if (force) {
1084                                                 ads_lte = new_lookup_table_entry();
1085                                                 if (!ads_lte)
1086                                                         return WIMLIB_ERR_NOMEM;
1087                                                 copy_hash(ads_lte->hash, hash);
1088                                                 lookup_table_insert(table, ads_lte);
1089                                         } else {
1090                                                 goto resource_not_found;
1091                                         }
1092                                 }
1093                         }
1094                         ads_ltes[i] = ads_lte;
1095                 }
1096                 inode->i_lte = lte;
1097                 for (u16 i = 0; i < inode->i_num_ads; i++)
1098                         inode->i_ads_entries[i].lte = ads_ltes[i];
1099                 inode->i_resolved = 1;
1100         }
1101         return 0;
1102 resource_not_found:
1103         if (wimlib_print_errors) {
1104                 ERROR("\"%"TS"\": resource not found", inode_first_full_path(inode));
1105                 tfprintf(stderr, T("        SHA-1 message digest of missing resource:\n        "));
1106                 print_hash(hash, stderr);
1107                 tputc(T('\n'), stderr);
1108         }
1109         return WIMLIB_ERR_RESOURCE_NOT_FOUND;
1110 }
1111
1112 void
1113 inode_unresolve_ltes(struct wim_inode *inode)
1114 {
1115         if (inode->i_resolved) {
1116                 if (inode->i_lte)
1117                         copy_hash(inode->i_hash, inode->i_lte->hash);
1118                 else
1119                         zero_out_hash(inode->i_hash);
1120
1121                 for (u16 i = 0; i < inode->i_num_ads; i++) {
1122                         if (inode->i_ads_entries[i].lte)
1123                                 copy_hash(inode->i_ads_entries[i].hash,
1124                                           inode->i_ads_entries[i].lte->hash);
1125                         else
1126                                 zero_out_hash(inode->i_ads_entries[i].hash);
1127                 }
1128                 inode->i_resolved = 0;
1129         }
1130 }
1131
1132 /*
1133  * Returns the lookup table entry for stream @stream_idx of the inode, where
1134  * stream_idx = 0 means the default un-named file stream, and stream_idx >= 1
1135  * corresponds to an alternate data stream.
1136  *
1137  * This works for both resolved and un-resolved inodes.
1138  */
1139 struct wim_lookup_table_entry *
1140 inode_stream_lte(const struct wim_inode *inode, unsigned stream_idx,
1141                  const struct wim_lookup_table *table)
1142 {
1143         if (inode->i_resolved)
1144                 return inode_stream_lte_resolved(inode, stream_idx);
1145         else
1146                 return inode_stream_lte_unresolved(inode, stream_idx, table);
1147 }
1148
1149 struct wim_lookup_table_entry *
1150 inode_unnamed_lte_resolved(const struct wim_inode *inode)
1151 {
1152         wimlib_assert(inode->i_resolved);
1153         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1154                 if (inode_stream_name_nbytes(inode, i) == 0 &&
1155                     !is_zero_hash(inode_stream_hash_resolved(inode, i)))
1156                 {
1157                         return inode_stream_lte_resolved(inode, i);
1158                 }
1159         }
1160         return NULL;
1161 }
1162
1163 struct wim_lookup_table_entry *
1164 inode_unnamed_lte_unresolved(const struct wim_inode *inode,
1165                              const struct wim_lookup_table *table)
1166 {
1167         wimlib_assert(!inode->i_resolved);
1168         for (unsigned i = 0; i <= inode->i_num_ads; i++) {
1169                 if (inode_stream_name_nbytes(inode, i) == 0 &&
1170                     !is_zero_hash(inode_stream_hash_unresolved(inode, i)))
1171                 {
1172                         return inode_stream_lte_unresolved(inode, i, table);
1173                 }
1174         }
1175         return NULL;
1176 }
1177
1178 /* Return the lookup table entry for the unnamed data stream of an inode, or
1179  * NULL if there is none.
1180  *
1181  * You'd think this would be easier than it actually is, since the unnamed data
1182  * stream should be the one referenced from the inode itself.  Alas, if there
1183  * are named data streams, Microsoft's "imagex.exe" program will put the unnamed
1184  * data stream in one of the alternate data streams instead of inside the WIM
1185  * dentry itself.  So we need to check the alternate data streams too.
1186  *
1187  * Also, note that a dentry may appear to have more than one unnamed stream, but
1188  * if the SHA1 message digest is all 0's then the corresponding stream does not
1189  * really "count" (this is the case for the inode's own file stream when the
1190  * file stream that should be there is actually in one of the alternate stream
1191  * entries.).  This is despite the fact that we may need to extract such a
1192  * missing entry as an empty file or empty named data stream.
1193  */
1194 struct wim_lookup_table_entry *
1195 inode_unnamed_lte(const struct wim_inode *inode,
1196                   const struct wim_lookup_table *table)
1197 {
1198         if (inode->i_resolved)
1199                 return inode_unnamed_lte_resolved(inode);
1200         else
1201                 return inode_unnamed_lte_unresolved(inode, table);
1202 }
1203
1204 static int
1205 lte_add_stream_size(struct wim_lookup_table_entry *lte, void *total_bytes_p)
1206 {
1207         *(u64*)total_bytes_p += lte->resource_entry.size;
1208         return 0;
1209 }
1210
1211 u64
1212 lookup_table_total_stream_size(struct wim_lookup_table *table)
1213 {
1214         u64 total_size = 0;
1215         for_lookup_table_entry(table, lte_add_stream_size, &total_size);
1216         return total_size;
1217 }
1218
1219 struct wim_lookup_table_entry **
1220 retrieve_lte_pointer(struct wim_lookup_table_entry *lte)
1221 {
1222         wimlib_assert(lte->unhashed);
1223         struct wim_inode *inode = lte->back_inode;
1224         u32 stream_id = lte->back_stream_id;
1225         if (stream_id == 0)
1226                 return &inode->i_lte;
1227         else
1228                 for (u16 i = 0; i < inode->i_num_ads; i++)
1229                         if (inode->i_ads_entries[i].stream_id == stream_id)
1230                                 return &inode->i_ads_entries[i].lte;
1231         wimlib_assert(0);
1232         return NULL;
1233 }
1234
1235 /* Calculate the SHA1 message digest of a stream and move it from the list of
1236  * unhashed streams to the stream lookup table, possibly joining it with an
1237  * existing lookup table entry for an identical stream.
1238  *
1239  * @lte:  An unhashed lookup table entry.
1240  * @lookup_table:  Lookup table for the WIM.
1241  * @lte_ret:  On success, write a pointer to the resulting lookup table
1242  *            entry to this location.  This will be the same as @lte
1243  *            if it was inserted into the lookup table, or different if
1244  *            a duplicate stream was found.
1245  *
1246  * Returns 0 on success; nonzero if there is an error reading the stream.
1247  */
1248 int
1249 hash_unhashed_stream(struct wim_lookup_table_entry *lte,
1250                      struct wim_lookup_table *lookup_table,
1251                      struct wim_lookup_table_entry **lte_ret)
1252 {
1253         int ret;
1254         struct wim_lookup_table_entry *duplicate_lte;
1255         struct wim_lookup_table_entry **back_ptr;
1256
1257         wimlib_assert(lte->unhashed);
1258
1259         /* back_ptr must be saved because @back_inode and @back_stream_id are in
1260          * union with the SHA1 message digest and will no longer be valid once
1261          * the SHA1 has been calculated. */
1262         back_ptr = retrieve_lte_pointer(lte);
1263
1264         ret = sha1_resource(lte);
1265         if (ret)
1266                 return ret;
1267
1268         /* Look for a duplicate stream */
1269         duplicate_lte = __lookup_resource(lookup_table, lte->hash);
1270         list_del(&lte->unhashed_list);
1271         if (duplicate_lte) {
1272                 /* We have a duplicate stream.  Transfer the reference counts
1273                  * from this stream to the duplicate, update the reference to
1274                  * this stream (in an inode or ads_entry) to point to the
1275                  * duplicate, then free this stream. */
1276                 wimlib_assert(!(duplicate_lte->unhashed));
1277                 duplicate_lte->refcnt += lte->refcnt;
1278                 duplicate_lte->out_refcnt += lte->refcnt;
1279                 *back_ptr = duplicate_lte;
1280                 free_lookup_table_entry(lte);
1281                 lte = duplicate_lte;
1282         } else {
1283                 /* No duplicate stream, so we need to insert
1284                  * this stream into the lookup table and treat
1285                  * it as a hashed stream. */
1286                 lookup_table_insert(lookup_table, lte);
1287                 lte->unhashed = 0;
1288         }
1289         if (lte_ret)
1290                 *lte_ret = lte;
1291         return 0;
1292 }