Various fixes
[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 hlist_head *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 void free_lookup_table_entry(struct lookup_table_entry *lte)
74 {
75         if (lte) {
76                 if (lte->staging_list.next)
77                         list_del(&lte->staging_list);
78                 FREE(lte->file_on_disk);
79                 FREE(lte);
80         }
81 }
82
83 static int do_free_lookup_table_entry(struct lookup_table_entry *entry,
84                                       void *ignore)
85 {
86         free_lookup_table_entry(entry);
87         return 0;
88 }
89
90
91 void free_lookup_table(struct lookup_table *table)
92 {
93         DEBUG("Freeing lookup table");
94         if (table) {
95                 if (table->array) {
96                         for_lookup_table_entry(table,
97                                                do_free_lookup_table_entry,
98                                                NULL);
99                         FREE(table->array);
100                 }
101                 FREE(table);
102         }
103 }
104
105 /*
106  * Inserts an entry into the lookup table.
107  *
108  * @table:      A pointer to the lookup table.
109  * @entry:      A pointer to the entry to insert.
110  */
111 void lookup_table_insert(struct lookup_table *table, 
112                          struct lookup_table_entry *lte)
113 {
114         size_t i = lte->hash_short % table->capacity;
115         hlist_add_head(&lte->hash_list, &table->array[i]);
116
117         /* XXX Make the table grow when too many entries have been inserted. */
118         table->num_entries++;
119 }
120
121
122
123 /* Decrements the reference count for the lookup table entry @lte.  If its
124  * reference count reaches 0, it is unlinked from the lookup table.  If,
125  * furthermore, the entry has no opened file descriptors associated with it, the
126  * entry is freed.  */
127 struct lookup_table_entry *
128 lte_decrement_refcnt(struct lookup_table_entry *lte, struct lookup_table *table)
129 {
130         if (lte) {
131                 wimlib_assert(lte->refcnt);
132                 if (--lte->refcnt == 0) {
133                         lookup_table_unlink(table, lte);
134                         if (lte->num_opened_fds == 0) {
135                                 free_lookup_table_entry(lte);
136                                 lte = NULL;
137                         }
138                 }
139         }
140         return lte;
141 }
142
143 /* 
144  * Calls a function on all the entries in the lookup table.  Stop early and
145  * return nonzero if any call to the function returns nonzero.
146  */
147 int for_lookup_table_entry(struct lookup_table *table, 
148                            int (*visitor)(struct lookup_table_entry *, void *),
149                            void *arg)
150 {
151         struct lookup_table_entry *lte;
152         struct hlist_node *pos, *tmp;
153         int ret;
154
155         for (size_t i = 0; i < table->capacity; i++) {
156                 hlist_for_each_entry_safe(lte, pos, tmp, &table->array[i],
157                                           hash_list)
158                 {
159                         ret = visitor(lte, arg);
160                         if (ret != 0)
161                                 return ret;
162                 }
163         }
164         return 0;
165 }
166
167
168 /*
169  * Reads the lookup table from a WIM file.
170  *
171  * @fp:                 The FILE* for the WIM file.
172  * @offset:             The offset of the lookup table resource.
173  * @size:               The size of the lookup table resource.
174  * @lookup_table_ret:   A pointer to a struct lookup_table structure into which the
175  *                              lookup table will be returned.
176  * @return:             True on success, false on failure.
177  */
178 int read_lookup_table(FILE *fp, u64 offset, u64 size, 
179                       struct lookup_table **table_ret)
180 {
181         size_t num_entries;
182         u8     buf[WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE];
183         int    ret;
184         struct lookup_table *table;
185         const u8 *p;
186         struct lookup_table_entry *cur_entry;
187
188         DEBUG("Reading lookup table: offset %"PRIu64", size %"PRIu64"",
189               offset, size);
190
191         if (fseeko(fp, offset, SEEK_SET) != 0) {
192                 ERROR_WITH_ERRNO("Failed to seek to byte %"PRIu64" to read "
193                                  "lookup table", offset);
194                 return WIMLIB_ERR_READ;
195         }
196
197         num_entries = size / WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE;
198         table = new_lookup_table(num_entries * 2 + 1);
199         if (!table)
200                 return WIMLIB_ERR_NOMEM;
201
202         while (num_entries--) {
203                 if (fread(buf, 1, sizeof(buf), fp) != sizeof(buf)) {
204                         if (feof(fp)) {
205                                 ERROR("Unexpected EOF in WIM lookup table!");
206                         } else {
207                                 ERROR_WITH_ERRNO("Error reading WIM lookup "
208                                                  "table");
209                         }
210                         ret = WIMLIB_ERR_READ;
211                         goto out;
212                 }
213                 cur_entry = new_lookup_table_entry();
214                 if (!cur_entry) {
215                         ret = WIMLIB_ERR_NOMEM;
216                         goto out;
217                 }
218                          
219                 p = get_resource_entry(buf, &cur_entry->resource_entry);
220                 p = get_u16(p, &cur_entry->part_number);
221                 p = get_u32(p, &cur_entry->refcnt);
222                 p = get_bytes(p, SHA1_HASH_SIZE, cur_entry->hash);
223                 lookup_table_insert(table, cur_entry);
224         }
225         DEBUG("Done reading lookup table.");
226         *table_ret = table;
227         return 0;
228 out:
229         free_lookup_table(table);
230         return ret;
231 }
232
233
234 /* 
235  * Writes a lookup table entry to the output file.
236  */
237 int write_lookup_table_entry(struct lookup_table_entry *lte, void *__out)
238 {
239         FILE *out;
240         u8 buf[WIM_LOOKUP_TABLE_ENTRY_DISK_SIZE];
241         u8 *p;
242
243         out = __out;
244
245         /* do not write lookup table entries for empty files */
246         if (lte->output_resource_entry.original_size == 0)
247                 return 0;
248
249         /* Don't write entries that have not had file resources or metadata
250          * resources written for them. */
251         if (lte->out_refcnt == 0)
252                 return 0;
253
254         if (lte->output_resource_entry.flags & WIM_RESHDR_FLAG_METADATA)
255                 DEBUG("Writing metadata entry at %lu (orig size = %zu)",
256                       ftello(out), lte->output_resource_entry.original_size);
257
258         p = put_resource_entry(buf, &lte->output_resource_entry);
259         p = put_u16(p, lte->part_number);
260         p = put_u32(p, lte->out_refcnt);
261         p = put_bytes(p, SHA1_HASH_SIZE, lte->hash);
262         if (fwrite(buf, 1, sizeof(buf), out) != sizeof(buf)) {
263                 ERROR_WITH_ERRNO("Failed to write lookup table entry");
264                 return WIMLIB_ERR_WRITE;
265         }
266         return 0;
267 }
268
269
270
271 int zero_out_refcnts(struct lookup_table_entry *entry, void *ignore)
272 {
273         entry->out_refcnt = 0;
274         return 0;
275 }
276
277 void print_lookup_table_entry(struct lookup_table_entry *lte)
278 {
279         if (!lte) {
280                 putchar('\n');
281                 return;
282         }
283         printf("Offset            = %"PRIu64" bytes\n", 
284                lte->resource_entry.offset);
285         printf("Size              = %"PRIu64" bytes\n", 
286                (u64)lte->resource_entry.size);
287         printf("Original size     = %"PRIu64" bytes\n", 
288                lte->resource_entry.original_size);
289         printf("Part Number       = %hu\n", lte->part_number);
290         printf("Reference Count   = %u\n", lte->refcnt);
291         printf("Hash              = 0x");
292         print_hash(lte->hash);
293         putchar('\n');
294         printf("Flags             = ");
295         u8 flags = lte->resource_entry.flags;
296         if (flags & WIM_RESHDR_FLAG_COMPRESSED)
297                 fputs("WIM_RESHDR_FLAG_COMPRESSED, ", stdout);
298         if (flags & WIM_RESHDR_FLAG_FREE)
299                 fputs("WIM_RESHDR_FLAG_FREE, ", stdout);
300         if (flags & WIM_RESHDR_FLAG_METADATA)
301                 fputs("WIM_RESHDR_FLAG_METADATA, ", stdout);
302         if (flags & WIM_RESHDR_FLAG_SPANNED)
303                 fputs("WIM_RESHDR_FLAG_SPANNED, ", stdout);
304         putchar('\n');
305         if (lte->file_on_disk && !lte->is_symlink)
306                 printf("File on Disk      = `%s'\n", lte->file_on_disk);
307         putchar('\n');
308 }
309
310 static int do_print_lookup_table_entry(struct lookup_table_entry *lte,
311                                        void *ignore)
312 {
313         print_lookup_table_entry(lte);
314         return 0;
315 }
316
317 /*
318  * Prints the lookup table of a WIM file. 
319  */
320 WIMLIBAPI void wimlib_print_lookup_table(WIMStruct *w)
321 {
322         for_lookup_table_entry(w->lookup_table, 
323                                do_print_lookup_table_entry,
324                                NULL);
325 }
326
327 /* 
328  * Looks up an entry in the lookup table.
329  */
330 struct lookup_table_entry *
331 __lookup_resource(const struct lookup_table *table, const u8 hash[])
332 {
333         size_t i;
334         struct lookup_table_entry *lte;
335         struct hlist_node *pos;
336
337         i = *(size_t*)hash % table->capacity;
338         hlist_for_each_entry(lte, pos, &table->array[i], hash_list)
339                 if (hashes_equal(hash, lte->hash))
340                         return lte;
341         return NULL;
342 }
343
344 /* 
345  * Finds the dentry, lookup table entry, and stream index for a WIM file stream,
346  * given a path name.
347  *
348  * This is only for pre-resolved dentries.
349  */
350 int lookup_resource(WIMStruct *w, const char *path,
351                     int lookup_flags,
352                     struct dentry **dentry_ret,
353                     struct lookup_table_entry **lte_ret,
354                     unsigned *stream_idx_ret)
355 {
356         struct dentry *dentry;
357         struct lookup_table_entry *lte;
358         unsigned stream_idx;
359         dentry = get_dentry(w, path);
360         if (!dentry)
361                 return -ENOENT;
362
363         wimlib_assert(dentry->resolved);
364
365         lte = dentry->lte;
366         if (!(lookup_flags & LOOKUP_FLAG_DIRECTORY_OK)
367               && dentry_is_directory(dentry))
368                 return -EISDIR;
369         stream_idx = 0;
370         if (lookup_flags & LOOKUP_FLAG_ADS_OK) {
371                 const char *stream_name = path_stream_name(path);
372                 if (stream_name) {
373                         size_t stream_name_len = strlen(stream_name);
374                         for (u16 i = 0; i < dentry->num_ads; i++) {
375                                 if (ads_entry_has_name(&dentry->ads_entries[i],
376                                                        stream_name,
377                                                        stream_name_len))
378                                 {
379                                         stream_idx = i + 1;
380                                         lte = dentry->ads_entries[i].lte;
381                                         goto out;
382                                 }
383                         }
384                         return -ENOENT;
385                 }
386         }
387 out:
388         if (dentry_ret)
389                 *dentry_ret = dentry;
390         if (lte_ret)
391                 *lte_ret = lte;
392         if (stream_idx_ret)
393                 *stream_idx_ret = stream_idx;
394         return 0;
395 }
396
397 /* Resolve a dentry's lookup table entries 
398  *
399  * This replaces the SHA1 hash fields (which are used to lookup an entry in the
400  * lookup table) with pointers directly to the lookup table entries.  A circular
401  * linked list of streams sharing the same lookup table entry is created.
402  *
403  * This function always succeeds; unresolved lookup table entries are given a
404  * NULL pointer.
405  */
406 int dentry_resolve_ltes(struct dentry *dentry, void *__table)
407 {
408         struct lookup_table *table = __table;
409         struct lookup_table_entry *lte;
410
411         if (dentry->resolved)
412                 return 0;
413
414         /* Resolve the default file stream */
415         lte = __lookup_resource(table, dentry->hash);
416         if (lte)
417                 list_add(&dentry->lte_group_list.list, &lte->lte_group_list);
418         else
419                 INIT_LIST_HEAD(&dentry->lte_group_list.list);
420         dentry->lte = lte;
421         dentry->lte_group_list.type = STREAM_TYPE_NORMAL;
422         dentry->resolved = true;
423
424         /* Resolve the alternate data streams */
425         if (dentry->ads_entries_status != ADS_ENTRIES_USER) {
426                 for (u16 i = 0; i < dentry->num_ads; i++) {
427                         struct ads_entry *cur_entry = &dentry->ads_entries[i];
428
429                         lte = __lookup_resource(table, cur_entry->hash);
430                         if (lte)
431                                 list_add(&cur_entry->lte_group_list.list,
432                                          &lte->lte_group_list);
433                         else
434                                 INIT_LIST_HEAD(&cur_entry->lte_group_list.list);
435                         cur_entry->lte = lte;
436                         cur_entry->lte_group_list.type = STREAM_TYPE_ADS;
437                 }
438         }
439         return 0;
440 }
441
442 struct lookup_table_entry *
443 dentry_first_lte(const struct dentry *dentry, const struct lookup_table *table)
444 {
445         if (dentry->resolved)
446                 return dentry_first_lte_resolved(dentry);
447         else
448                 return dentry_first_lte_unresolved(dentry, table);
449 }
450