9edde937d54f87d429b787a429b567121e641bcc
[wimlib] / src / lookup_table.c
1 /*
2  * lookup_table.c
3  *
4  * Lookup table, implemented as a hash table, that maps dentries to file
5  * resources.
6  */
7
8 /*
9  * Copyright (C) 2012 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 Lesser General Public License as published by the Free
15  * Software Foundation; either version 2.1 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 Lesser General Public License for more
21  * details.
22  *
23  * You should have received a copy of the GNU Lesser General Public License
24  * along with wimlib; if not, see http://www.gnu.org/licenses/.
25  */
26
27 #include "wimlib_internal.h"
28 #include "lookup_table.h"
29 #include "io.h"
30 #include <errno.h>
31
32 struct lookup_table *new_lookup_table(size_t capacity)
33 {
34         struct lookup_table *table;
35         struct lookup_table_entry **array;
36
37         table = MALLOC(sizeof(struct lookup_table));
38         if (!table)
39                 goto err;
40         array = CALLOC(capacity, sizeof(array[0]));
41         if (!array) {
42                 FREE(table);
43                 goto err;
44         }
45         table->num_entries = 0;
46         table->capacity = capacity;
47         table->array = array;
48         return table;
49 err:
50         ERROR("Failed to allocate memory for lookup table with capacity %zu",
51               capacity);
52         return NULL;
53 }
54
55 struct lookup_table_entry *new_lookup_table_entry()
56 {
57         struct lookup_table_entry *lte;
58         
59         lte = CALLOC(1, sizeof(struct lookup_table_entry));
60         if (!lte) {
61                 ERROR("Out of memory (tried to allocate %zu bytes for "
62                       "lookup table entry)",
63                       sizeof(struct lookup_table_entry));
64                 return NULL;
65         }
66
67         lte->part_number  = 1;
68         lte->refcnt       = 1;
69         INIT_LIST_HEAD(&lte->lte_group_list);
70         return lte;
71 }
72
73
74 void free_lookup_table_entry(struct lookup_table_entry *lte)
75 {
76         if (lte) {
77                 if (lte->staging_list.next)
78                         list_del(&lte->staging_list);
79                 FREE(lte->file_on_disk);
80                 FREE(lte);
81         }
82 }
83
84 /*
85  * Inserts an entry into the lookup table.
86  *
87  * @lookup_table:       A pointer to the lookup table.
88  * @entry:              A pointer to the entry to insert.
89  */
90 void lookup_table_insert(struct lookup_table *table, 
91                          struct lookup_table_entry *lte)
92 {
93         size_t pos;
94         pos = lte->hash_short % table->capacity;
95         lte->next = table->array[pos];
96         table->array[pos] = lte;
97         /* XXX Make the table grow when too many entries have been inserted. */
98         table->num_entries++;
99 }
100
101
102 /* Unlinks a lookup table entry from the table; does not free it. */
103 void lookup_table_unlink(struct lookup_table *table, 
104                          struct lookup_table_entry *lte)
105 {
106         size_t pos;
107         struct lookup_table_entry *prev, *cur_entry, *next;
108
109         pos = lte->hash_short % table->capacity;
110         prev = NULL;
111         cur_entry = table->array[pos];
112
113         while (cur_entry) {
114                 next = cur_entry->next;
115                 if (cur_entry == lte) {
116                         if (prev)
117                                 prev->next = next;
118                         else
119                                 table->array[pos] = next;
120                         table->num_entries--;
121                         return;
122                 }
123                 prev = cur_entry;
124                 cur_entry = next;
125         }
126 }
127
128
129 /* Decrement the reference count for the dentry having hash value @hash in the
130  * lookup table.  The lookup table entry is unlinked and freed if there are no
131  * references to in remaining.  */
132 struct lookup_table_entry *
133 lookup_table_decrement_refcnt(struct lookup_table* table, const u8 hash[])
134 {
135         size_t pos = *(size_t*)hash % table->capacity;
136         struct lookup_table_entry *prev = NULL;
137         struct lookup_table_entry *entry = table->array[pos];
138         struct lookup_table_entry *next;
139         while (entry) {
140                 next = entry->next;
141                 if (memcmp(hash, entry->hash, WIM_HASH_SIZE) == 0) {
142                         wimlib_assert(entry->refcnt != 0);
143                         if (--entry->refcnt == 0) {
144                                 if (entry->num_opened_fds == 0) {
145                                         free_lookup_table_entry(entry);
146                                         entry = NULL;
147                                 }
148                                 if (prev)
149                                         prev->next = next;
150                                 else
151                                         table->array[pos] = next;
152                                 break;
153                         }
154                 }
155                 prev = entry;
156                 entry = next;
157         }
158         return entry;
159 }
160
161 /* Like lookup_table_decrement_refcnt(), but for when we already know the lookup
162  * table entry. */
163 struct lookup_table_entry *
164 lte_decrement_refcnt(struct lookup_table_entry *lte, struct lookup_table *table)
165 {
166         wimlib_assert(lte->refcnt);
167         if (lte && --lte->refcnt == 0) {
168                 lookup_table_unlink(table, lte);
169                 if (lte->num_opened_fds == 0) {
170                         free_lookup_table_entry(lte);
171                         lte = NULL;
172                 }
173         }
174         return lte;
175 }
176
177 /* 
178  * Calls a function on all the entries in the lookup table.  Stop early and
179  * return nonzero if any call to the function returns nonzero.
180  */
181 int for_lookup_table_entry(struct lookup_table *table, 
182                            int (*visitor)(struct lookup_table_entry *, void *),
183                            void *arg)
184 {
185         struct lookup_table_entry *entry, *next;
186         size_t i;
187         int ret;
188
189         for (i = 0; i < table->capacity; i++) {
190                 entry = table->array[i];
191                 while (entry) {
192                         next = entry->next;
193                         ret = visitor(entry, arg);
194                         if (ret != 0)
195                                 return ret;
196                         entry = next;
197                 }
198         }
199         return 0;
200 }
201
202
203 /*
204  * Reads the lookup table from a WIM file.
205  *
206  * @fp:                 The FILE* for the WIM file.
207  * @offset:             The offset of the lookup table resource.
208  * @size:               The size of the lookup table resource.
209  * @lookup_table_ret:   A pointer to a struct lookup_table structure into which the
210  *                              lookup table will be returned.
211  * @return:             True on success, false on failure.
212  */
213 int read_lookup_table(FILE *fp, u64 offset, u64 size, 
214                       struct lookup_table **table_ret)
215 {
216         size_t num_entries;
217         u8     buf[WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE];
218         int    ret;
219         struct lookup_table *table;
220         const u8 *p;
221         struct lookup_table_entry *cur_entry;
222
223         DEBUG("Reading lookup table: offset %"PRIu64", size %"PRIu64"",
224               offset, size);
225
226         if (fseeko(fp, offset, SEEK_SET) != 0) {
227                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
228                                  "lookup table", offset);
229                 return WIMLIB_ERR_READ;
230         }
231
232         num_entries = size / WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE;
233         table = new_lookup_table(num_entries * 2 + 1);
234         if (!table)
235                 return WIMLIB_ERR_NOMEM;
236
237         while (num_entries--) {
238                 if (fread(buf, 1, sizeof(buf), fp) != sizeof(buf)) {
239                         if (feof(fp)) {
240                                 ERROR("Unexpected EOF in WIM lookup table!");
241                         } else {
242                                 ERROR_WITH_ERRNO("Error reading WIM lookup "
243                                                  "table");
244                         }
245                         ret = WIMLIB_ERR_READ;
246                         goto out;
247                 }
248                 cur_entry = new_lookup_table_entry();
249                 if (!cur_entry) {
250                         ret = WIMLIB_ERR_NOMEM;
251                         goto out;
252                 }
253                          
254                 p = get_resource_entry(buf, &cur_entry->resource_entry);
255                 p = get_u16(p, &cur_entry->part_number);
256                 p = get_u32(p, &cur_entry->refcnt);
257                 p = get_bytes(p, WIM_HASH_SIZE, cur_entry->hash);
258                 lookup_table_insert(table, cur_entry);
259         }
260         DEBUG("Done reading lookup table.");
261         *table_ret = table;
262         return 0;
263 out:
264         free_lookup_table(table);
265         return ret;
266 }
267
268
269 /* 
270  * Writes a lookup table entry to the output file.
271  */
272 int write_lookup_table_entry(struct lookup_table_entry *lte, void *__out)
273 {
274         FILE *out;
275         u8 buf[WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE];
276         u8 *p;
277
278         out = __out;
279
280         /* do not write lookup table entries for empty files */
281         if (lte->output_resource_entry.original_size == 0)
282                 return 0;
283
284         /* Don't write entries that have not had file resources or metadata
285          * resources written for them. */
286         if (lte->out_refcnt == 0)
287                 return 0;
288
289         if (lte->output_resource_entry.flags & WIM_RESHDR_FLAG_METADATA)
290                 DEBUG("Writing metadata entry at %lu (orig size = %zu)",
291                       ftello(out), lte->output_resource_entry.original_size);
292
293         p = put_resource_entry(buf, &lte->output_resource_entry);
294         p = put_u16(p, lte->part_number);
295         p = put_u32(p, lte->out_refcnt);
296         p = put_bytes(p, WIM_HASH_SIZE, lte->hash);
297         if (fwrite(buf, 1, sizeof(buf), out) != sizeof(buf)) {
298                 ERROR_WITH_ERRNO("Failed to write lookup table entry");
299                 return WIMLIB_ERR_WRITE;
300         }
301         return 0;
302 }
303
304 static int do_free_lookup_table_entry(struct lookup_table_entry *entry,
305                                       void *ignore)
306 {
307         free_lookup_table_entry(entry);
308         return 0;
309 }
310
311 void free_lookup_table(struct lookup_table *table)
312 {
313         if (!table)
314                 return;
315         if (table->array) {
316                 for_lookup_table_entry(table, do_free_lookup_table_entry, NULL);
317                 FREE(table->array);
318         }
319         FREE(table);
320 }
321
322 int zero_out_refcnts(struct lookup_table_entry *entry, void *ignore)
323 {
324         entry->out_refcnt = 0;
325         return 0;
326 }
327
328 int print_lookup_table_entry(struct lookup_table_entry *entry, void *ignore)
329 {
330         printf("Offset            = %"PRIu64" bytes\n", 
331                entry->resource_entry.offset);
332         printf("Size              = %"PRIu64" bytes\n", 
333                (u64)entry->resource_entry.size);
334         printf("Original size     = %"PRIu64" bytes\n", 
335                entry->resource_entry.original_size);
336         printf("Part Number       = %hu\n", entry->part_number);
337         printf("Reference Count   = %u\n", entry->refcnt);
338         printf("Hash              = ");
339         print_hash(entry->hash);
340         putchar('\n');
341         printf("Flags             = ");
342         u8 flags = entry->resource_entry.flags;
343         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
344                 fputs("WIM_RESHDR_FLAG_COMPRESSED, ", stdout);
345         if (flags & WIM_RESHDR_FLAG_FREE)
346                 fputs("WIM_RESHDR_FLAG_FREE, ", stdout);
347         if (flags & WIM_RESHDR_FLAG_METADATA)
348                 fputs("WIM_RESHDR_FLAG_METADATA, ", stdout);
349         if (flags & WIM_RESHDR_FLAG_SPANNED)
350                 fputs("WIM_RESHDR_FLAG_SPANNED, ", stdout);
351         putchar('\n');
352         if (entry->file_on_disk)
353                 printf("File on Disk      = `%s'\n", entry->file_on_disk);
354         putchar('\n');
355         return 0;
356 }
357
358 /*
359  * Prints the lookup table of a WIM file. 
360  */
361 WIMLIBAPI void wimlib_print_lookup_table(WIMStruct *w)
362 {
363         for_lookup_table_entry(w->lookup_table, 
364                                print_lookup_table_entry, NULL);
365 }
366
367 /* 
368  * Looks up an entry in the lookup table.
369  */
370 struct lookup_table_entry *
371 __lookup_resource(const struct lookup_table *lookup_table, const u8 hash[])
372 {
373         size_t pos;
374         struct lookup_table_entry *lte;
375
376         pos = *(size_t*)hash % lookup_table->capacity;
377         lte = lookup_table->array[pos];
378         while (lte) {
379                 if (memcmp(hash, lte->hash, WIM_HASH_SIZE) == 0)
380                         return lte;
381                 lte = lte->next;
382         }
383         return NULL;
384 }
385
386 /* 
387  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
388  * given a path name.
389  *
390  * This is only for pre-resolved dentries.
391  */
392 int lookup_resource(WIMStruct *w, const char *path,
393                     int lookup_flags,
394                     struct dentry **dentry_ret,
395                     struct lookup_table_entry **lte_ret,
396                     unsigned *stream_idx_ret)
397 {
398         struct dentry *dentry;
399         struct lookup_table_entry *lte;
400         unsigned stream_idx;
401         dentry = get_dentry(w, path);
402         if (!dentry)
403                 return -ENOENT;
404
405         wimlib_assert(dentry->resolved);
406
407         lte = dentry->lte;
408         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
409               && dentry_is_directory(dentry))
410                 return -EISDIR;
411         stream_idx = 0;
412         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
413                 const char *stream_name = path_stream_name(path);
414                 if (stream_name) {
415                         size_t stream_name_len = strlen(stream_name);
416                         for (u16 i = 0; i < dentry->num_ads; i++) {
417                                 if (ads_entry_has_name(&dentry->ads_entries[i],
418                                                        stream_name,
419                                                        stream_name_len))
420                                 {
421                                         stream_idx = i + 1;
422                                         lte = dentry->ads_entries[i].lte;
423                                         goto out;
424                                 }
425                         }
426                         return -ENOENT;
427                 }
428         }
429 out:
430         if (dentry_ret)
431                 *dentry_ret = dentry;
432         if (lte_ret)
433                 *lte_ret = lte;
434         if (stream_idx_ret)
435                 *stream_idx_ret = stream_idx;
436         return 0;
437 }
438
439 /* Resolve a dentry's lookup table entries 
440  *
441  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
442  * lookup table) with pointers directly to the lookup table entries.  A circular
443  * linked list of streams sharing the same lookup table entry is created.
444  *
445  * This function always succeeds; unresolved lookup table entries are given a
446  * NULL pointer.
447  */
448 int dentry_resolve_ltes(struct dentry *dentry, void *__table)
449 {
450         struct lookup_table *table = __table;
451         struct lookup_table_entry *lte;
452
453         wimlib_assert(!dentry->resolved);
454
455         /* Resolve the default file stream */
456         lte = __lookup_resource(table, dentry->hash);
457         if (lte)
458                 list_add(&dentry->lte_group_list.list, &lte->lte_group_list);
459         else
460                 INIT_LIST_HEAD(&dentry->lte_group_list.list);
461         dentry->lte = lte;
462         dentry->lte_group_list.type = STREAM_TYPE_NORMAL;
463         dentry->resolved = true;
464
465         /* Resolve the alternate data streams */
466         if (dentry->ads_entries_status != ADS_ENTRIES_USER) {
467                 for (u16 i = 0; i < dentry->num_ads; i++) {
468                         struct ads_entry *cur_entry = &dentry->ads_entries[i];
469
470                         lte = __lookup_resource(table, cur_entry->hash);
471                         if (lte)
472                                 list_add(&cur_entry->lte_group_list.list,
473                                          &lte->lte_group_list);
474                         else
475                                 INIT_LIST_HEAD(&cur_entry->lte_group_list.list);
476                         cur_entry->lte = lte;
477                         cur_entry->lte_group_list.type = STREAM_TYPE_ADS;
478                 }
479         }
480         return 0;
481 }