]> wimlib.net Git - wimlib/blob - src/dentry.c
--hardlink fix
[wimlib] / src / dentry.c
1 /*
2  * dentry.c
3  *
4  * A dentry (directory entry) contains the metadata for a file.  In the WIM file
5  * format, the dentries are stored in the "metadata resource" section right
6  * after the security data.  Each image in the WIM file has its own metadata
7  * resource with its own security data and dentry tree.  Dentries in different
8  * images may share file resources by referring to the same lookup table
9  * entries.
10  */
11
12 /*
13  *
14  * Copyright (C) 2010 Carl Thijssen
15  * Copyright (C) 2012 Eric Biggers
16  *
17  * This file is part of wimlib, a library for working with WIM files.
18  *
19  * wimlib is free software; you can redistribute it and/or modify it under the
20  * terms of the GNU Lesser General Public License as published by the Free
21  * Software Foundation; either version 2.1 of the License, or (at your option)
22  * any later version.
23  *
24  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
25  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
26  * A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
27  * details.
28  *
29  * You should have received a copy of the GNU Lesser General Public License
30  * along with wimlib; if not, see http://www.gnu.org/licenses/.
31  */
32
33 #include "wimlib_internal.h"
34 #include "dentry.h"
35 #include "io.h"
36 #include "timestamp.h"
37 #include "lookup_table.h"
38 #include "sha1.h"
39 #include <errno.h>
40 #include <unistd.h>
41 #include <sys/stat.h>
42
43 /*
44  * Returns true if @dentry has the UTF-8 file name @name that has length
45  * @name_len.
46  */
47 static bool dentry_has_name(const struct dentry *dentry, const char *name, 
48                             size_t name_len)
49 {
50         if (dentry->file_name_utf8_len != name_len)
51                 return false;
52         return memcmp(dentry->file_name_utf8, name, name_len) == 0;
53 }
54
55 /* Real length of a dentry, including the alternate data stream entries, which
56  * are not included in the dentry->length field... */
57 u64 dentry_total_length(const struct dentry *dentry)
58 {
59         u64 length = (dentry->length + 7) & ~7;
60         for (u16 i = 0 ; i < dentry->num_ads; i++)
61                 length += ads_entry_length(&dentry->ads_entries[i]);
62         return length;
63 }
64
65 /* Transfers file attributes from a `stat' buffer to a struct dentry. */
66 void stbuf_to_dentry(const struct stat *stbuf, struct dentry *dentry)
67 {
68         if (S_ISLNK(stbuf->st_mode)) {
69                 dentry->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
70                 dentry->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
71         } else if (S_ISDIR(stbuf->st_mode)) {
72                 dentry->attributes = FILE_ATTRIBUTE_DIRECTORY;
73         } else {
74                 dentry->attributes = FILE_ATTRIBUTE_NORMAL;
75         }
76         if (sizeof(ino_t) >= 8)
77                 dentry->hard_link = (u64)stbuf->st_ino;
78         else
79                 dentry->hard_link = (u64)stbuf->st_ino |
80                                    ((u64)stbuf->st_dev << (sizeof(ino_t) * 8));
81 }
82
83 /* Transfers file attributes from a struct dentry to a `stat' buffer. */
84 int dentry_to_stbuf(const struct dentry *dentry, struct stat *stbuf, 
85                     const struct lookup_table *table)
86 {
87         struct lookup_table_entry *lte;
88
89         if (dentry_is_symlink(dentry))
90                 stbuf->st_mode = S_IFLNK | 0777;
91         else if (dentry_is_directory(dentry))
92                 stbuf->st_mode = S_IFDIR | 0755;
93         else
94                 stbuf->st_mode = S_IFREG | 0644;
95
96         stbuf->st_ino = (ino_t)dentry->hard_link;
97
98         stbuf->st_nlink = dentry_link_group_size(dentry);
99         stbuf->st_uid   = getuid();
100         stbuf->st_gid   = getgid();
101
102         /* Use the size of the unnamed (default) file stream. */
103         if (table && (lte = __lookup_resource(table, dentry_hash(dentry)))) {
104                 if (lte->staging_file_name) {
105                         struct stat native_stat;
106                         if (stat(lte->staging_file_name, &native_stat) != 0)
107                                 return -errno;
108                         stbuf->st_size = native_stat.st_size;
109                 } else {
110                         stbuf->st_size = lte->resource_entry.original_size;
111                 }
112         } else {
113                 stbuf->st_size = 0;
114         }
115
116         stbuf->st_atime   = ms_timestamp_to_unix(dentry->last_access_time);
117         stbuf->st_mtime   = ms_timestamp_to_unix(dentry->last_write_time);
118         stbuf->st_ctime   = ms_timestamp_to_unix(dentry->creation_time);
119         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
120         return 0;
121 }
122
123 /* Makes all timestamp fields for the dentry be the current time. */
124 void dentry_update_all_timestamps(struct dentry *dentry)
125 {
126         u64 now = get_timestamp();
127         dentry->creation_time    = now;
128         dentry->last_access_time = now;
129         dentry->last_write_time  = now;
130 }
131
132 struct ads_entry *dentry_get_ads_entry(struct dentry *dentry,
133                                        const char *stream_name)
134 {
135         size_t stream_name_len = strlen(stream_name);
136         if (!stream_name)
137                 return NULL;
138         for (u16 i = 0; i < dentry->num_ads; i++)
139                 if (ads_entry_has_name(&dentry->ads_entries[i],
140                                        stream_name, stream_name_len))
141                         return &dentry->ads_entries[i];
142         return NULL;
143 }
144
145 /* Add an alternate stream entry to a dentry and return a pointer to it, or NULL
146  * on failure. */
147 struct ads_entry *dentry_add_ads(struct dentry *dentry, const char *stream_name)
148 {
149         u16 num_ads = dentry->num_ads + 1;
150         struct ads_entry *ads_entries;
151         struct ads_entry *new_entry;
152         if (num_ads == 0xffff)
153                 return NULL;
154         ads_entries = MALLOC(num_ads * sizeof(struct ads_entry));
155         if (!ads_entries)
156                 return NULL;
157
158         new_entry = &ads_entries[num_ads - 1];
159         if (change_ads_name(new_entry, stream_name) != 0) {
160                 FREE(ads_entries);
161                 return NULL;
162         }
163
164         memcpy(ads_entries, dentry->ads_entries,
165                (num_ads - 1) * sizeof(struct ads_entry));
166         FREE(dentry->ads_entries);
167         dentry->ads_entries = ads_entries;
168         dentry->num_ads = num_ads;
169         return memset(new_entry, 0, sizeof(struct ads_entry));
170 }
171
172 void dentry_remove_ads(struct dentry *dentry, struct ads_entry *sentry)
173 {
174         destroy_ads_entry(sentry);
175         memcpy(sentry, sentry + 1,
176                (dentry->num_ads - (sentry - dentry->ads_entries + 1))
177                  * sizeof(struct ads_entry));
178         dentry->num_ads--;
179 }
180
181 /* 
182  * Calls a function on all directory entries in a directory tree.  It is called
183  * on a parent before its children.
184  */
185 int for_dentry_in_tree(struct dentry *root, 
186                        int (*visitor)(struct dentry*, void*), void *arg)
187 {
188         int ret;
189         struct dentry *child;
190
191         ret = visitor(root, arg);
192
193         if (ret != 0)
194                 return ret;
195
196         child = root->children;
197
198         if (!child)
199                 return 0;
200
201         do {
202                 ret = for_dentry_in_tree(child, visitor, arg);
203                 if (ret != 0)
204                         return ret;
205                 child = child->next;
206         } while (child != root->children);
207         return 0;
208 }
209
210 /* 
211  * Like for_dentry_in_tree(), but the visitor function is always called on a
212  * dentry's children before on itself.
213  */
214 int for_dentry_in_tree_depth(struct dentry *root, 
215                              int (*visitor)(struct dentry*, void*), void *arg)
216 {
217         int ret;
218         struct dentry *child;
219         struct dentry *next;
220
221         child = root->children;
222         if (child) {
223                 do {
224                         next = child->next;
225                         ret = for_dentry_in_tree_depth(child, visitor, arg);
226                         if (ret != 0)
227                                 return ret;
228                         child = next;
229                 } while (child != root->children);
230         }
231         return visitor(root, arg);
232 }
233
234 /* 
235  * Calculate the full path of @dentry, based on its parent's full path and on
236  * its UTF-8 file name. 
237  */
238 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
239 {
240         char *full_path;
241         u32 full_path_len;
242         if (dentry_is_root(dentry)) {
243                 full_path = MALLOC(2);
244                 if (!full_path)
245                         goto oom;
246                 full_path[0] = '/';
247                 full_path[1] = '\0';
248                 full_path_len = 1;
249         } else {
250                 char *parent_full_path;
251                 u32 parent_full_path_len;
252                 const struct dentry *parent = dentry->parent;
253
254                 if (dentry_is_root(parent)) {
255                         parent_full_path = "";
256                         parent_full_path_len = 0;
257                 } else {
258                         parent_full_path = parent->full_path_utf8;
259                         parent_full_path_len = parent->full_path_utf8_len;
260                 }
261
262                 full_path_len = parent_full_path_len + 1 +
263                                 dentry->file_name_utf8_len;
264                 full_path = MALLOC(full_path_len + 1);
265                 if (!full_path)
266                         goto oom;
267
268                 memcpy(full_path, parent_full_path, parent_full_path_len);
269                 full_path[parent_full_path_len] = '/';
270                 memcpy(full_path + parent_full_path_len + 1,
271                        dentry->file_name_utf8,
272                        dentry->file_name_utf8_len);
273                 full_path[full_path_len] = '\0';
274         }
275         FREE(dentry->full_path_utf8);
276         dentry->full_path_utf8 = full_path;
277         dentry->full_path_utf8_len = full_path_len;
278         return 0;
279 oom:
280         ERROR("Out of memory while calculating dentry full path");
281         return WIMLIB_ERR_NOMEM;
282 }
283
284 /* 
285  * Recursively calculates the subdir offsets for a directory tree. 
286  *
287  * @dentry:  The root of the directory tree.
288  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
289  *      offset for @dentry. 
290  */
291 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
292 {
293         struct dentry *child;
294
295         child = dentry->children;
296         dentry->subdir_offset = *subdir_offset_p;
297         if (child) {
298
299                 /* Advance the subdir offset by the amount of space the children
300                  * of this dentry take up. */
301                 do {
302                         *subdir_offset_p += dentry_total_length(child);
303                         child = child->next;
304                 } while (child != dentry->children);
305
306                 /* End-of-directory dentry on disk. */
307                 *subdir_offset_p += 8;
308
309                 /* Recursively call calculate_subdir_offsets() on all the
310                  * children. */
311                 do {
312                         calculate_subdir_offsets(child, subdir_offset_p);
313                         child = child->next;
314                 } while (child != dentry->children);
315         } else {
316                 /* On disk, childless directories have a valid subdir_offset
317                  * that points to an 8-byte end-of-directory dentry.  Regular
318                  * files have a subdir_offset of 0. */
319                 if (dentry_is_directory(dentry))
320                         *subdir_offset_p += 8;
321                 else
322                         dentry->subdir_offset = 0;
323         }
324 }
325
326
327 /* Returns the child of @dentry that has the file name @name.  
328  * Returns NULL if no child has the name. */
329 struct dentry *get_dentry_child_with_name(const struct dentry *dentry, 
330                                                         const char *name)
331 {
332         struct dentry *child;
333         size_t name_len;
334         
335         child = dentry->children;
336         if (child) {
337                 name_len = strlen(name);
338                 do {
339                         if (dentry_has_name(child, name, name_len))
340                                 return child;
341                         child = child->next;
342                 } while (child != dentry->children);
343         }
344         return NULL;
345 }
346
347 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
348  * @cur_dir.  Returns NULL if no dentry having the path is found. */
349 static struct dentry *get_dentry_relative_path(struct dentry *cur_dir, const char *path)
350 {
351         struct dentry *child;
352         size_t base_len;
353         const char *new_path;
354
355         if (*path == '\0')
356                 return cur_dir;
357
358         child = cur_dir->children;
359         if (child) {
360                 new_path = path_next_part(path, &base_len);
361                 do {
362                         if (dentry_has_name(child, path, base_len))
363                                 return get_dentry_relative_path(child, new_path);
364                         child = child->next;
365                 } while (child != cur_dir->children);
366         }
367         return NULL;
368 }
369
370 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
371  * such dentry. */
372 struct dentry *get_dentry(WIMStruct *w, const char *path)
373 {
374         struct dentry *root = wim_root_dentry(w);
375         while (*path == '/')
376                 path++;
377         return get_dentry_relative_path(root, path);
378 }
379
380 /* Returns the parent directory for the @path. */
381 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
382 {
383         size_t path_len = strlen(path);
384         char buf[path_len + 1];
385
386         memcpy(buf, path, path_len + 1);
387
388         to_parent_name(buf, path_len);
389
390         return get_dentry(w, buf);
391 }
392
393 /* Prints the full path of a dentry. */
394 int print_dentry_full_path(struct dentry *dentry, void *ignore)
395 {
396         if (dentry->full_path_utf8)
397                 puts(dentry->full_path_utf8);
398         return 0;
399 }
400
401 struct file_attr_flag {
402         u32 flag;
403         const char *name;
404 };
405 struct file_attr_flag file_attr_flags[] = {
406         {FILE_ATTRIBUTE_READONLY,               "READONLY"},
407         {FILE_ATTRIBUTE_HIDDEN,         "HIDDEN"},
408         {FILE_ATTRIBUTE_SYSTEM,         "SYSTEM"},
409         {FILE_ATTRIBUTE_DIRECTORY,              "DIRECTORY"},
410         {FILE_ATTRIBUTE_ARCHIVE,                "ARCHIVE"},
411         {FILE_ATTRIBUTE_DEVICE,         "DEVICE"},
412         {FILE_ATTRIBUTE_NORMAL,         "NORMAL"},
413         {FILE_ATTRIBUTE_TEMPORARY,              "TEMPORARY"},
414         {FILE_ATTRIBUTE_SPARSE_FILE,    "SPARSE_FILE"},
415         {FILE_ATTRIBUTE_REPARSE_POINT,  "REPARSE_POINT"},
416         {FILE_ATTRIBUTE_COMPRESSED,             "COMPRESSED"},
417         {FILE_ATTRIBUTE_OFFLINE,                "OFFLINE"},
418         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
419         {FILE_ATTRIBUTE_ENCRYPTED,              "ENCRYPTED"},
420         {FILE_ATTRIBUTE_VIRTUAL,                "VIRTUAL"},
421 };
422
423 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, or
424  * NULL if the resource entry for the dentry is not to be printed. */
425 int print_dentry(struct dentry *dentry, void *lookup_table)
426 {
427         struct lookup_table_entry *lte;
428         unsigned i;
429
430         printf("[DENTRY]\n");
431         printf("Length            = %"PRIu64"\n", dentry->length);
432         printf("Attributes        = 0x%x\n", dentry->attributes);
433         for (i = 0; i < ARRAY_LEN(file_attr_flags); i++)
434                 if (file_attr_flags[i].flag & dentry->attributes)
435                         printf("    FILE_ATTRIBUTE_%s is set\n",
436                                 file_attr_flags[i].name);
437         printf("Security ID       = %d\n", dentry->security_id);
438         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
439         /*printf("Unused1           = 0x%"PRIu64"\n", dentry->unused1);*/
440         /*printf("Unused2           = %"PRIu64"\n", dentry->unused2);*/
441         printf("Creation Time     = 0x%"PRIx64"\n", dentry->creation_time);
442         printf("Last Access Time  = 0x%"PRIx64"\n", dentry->last_access_time);
443         printf("Last Write Time   = 0x%"PRIx64"\n", dentry->last_write_time);
444         printf("Hash              = 0x"); 
445         print_hash(dentry->hash); 
446         putchar('\n');
447         printf("Reparse Tag       = 0x%"PRIx32"\n", dentry->reparse_tag);
448         printf("Hard Link Group   = 0x%"PRIx64"\n", dentry->hard_link);
449         printf("Number of Alternate Data Streams = %hu\n", dentry->num_ads);
450         printf("Filename          = \"");
451         print_string(dentry->file_name, dentry->file_name_len);
452         puts("\"");
453         printf("Filename Length   = %hu\n", dentry->file_name_len);
454         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
455         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
456         printf("Short Name        = \"");
457         print_string(dentry->short_name, dentry->short_name_len);
458         puts("\"");
459         printf("Short Name Length = %hu\n", dentry->short_name_len);
460         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
461         if (lookup_table && (lte = __lookup_resource(lookup_table, dentry->hash)))
462                 print_lookup_table_entry(lte, NULL);
463         else
464                 putchar('\n');
465         for (u16 i = 0; i < dentry->num_ads; i++) {
466                 printf("[Alternate Stream Entry %u]\n", i);
467                 printf("Name = \"%s\"\n", dentry->ads_entries[i].stream_name_utf8);
468                 printf("Name Length (UTF-16) = %u\n",
469                                 dentry->ads_entries[i].stream_name_len);
470                 printf("Hash              = 0x"); 
471                 print_hash(dentry->ads_entries[i].hash); 
472                 if (lookup_table &&
473                      (lte = __lookup_resource(lookup_table,
474                                               dentry->ads_entries[i].hash)))
475                 {
476                         print_lookup_table_entry(lte, NULL);
477                 } else {
478                         putchar('\n');
479                 }
480         }
481         return 0;
482 }
483
484 static inline void dentry_common_init(struct dentry *dentry)
485 {
486         memset(dentry, 0, sizeof(struct dentry));
487         dentry->refcnt = 1;
488         dentry->security_id = -1;
489         dentry->link_group_master_status = GROUP_SLAVE;
490 }
491
492 /* 
493  * Creates an unlinked directory entry.
494  *
495  * @name:    The base name of the new dentry.
496  * @return:  A pointer to the new dentry, or NULL if out of memory.
497  */
498 struct dentry *new_dentry(const char *name)
499 {
500         struct dentry *dentry;
501         
502         dentry = MALLOC(sizeof(struct dentry));
503         if (!dentry)
504                 goto err;
505
506         dentry_common_init(dentry);
507         if (change_dentry_name(dentry, name) != 0)
508                 goto err;
509
510         dentry_update_all_timestamps(dentry);
511         dentry->next   = dentry;
512         dentry->prev   = dentry;
513         dentry->parent = dentry;
514         INIT_LIST_HEAD(&dentry->link_group_list);
515         return dentry;
516 err:
517         FREE(dentry);
518         ERROR("Failed to allocate new dentry");
519         return NULL;
520 }
521
522 void dentry_free_ads_entries(struct dentry *dentry)
523 {
524         for (u16 i = 0; i < dentry->num_ads; i++)
525                 destroy_ads_entry(&dentry->ads_entries[i]);
526         FREE(dentry->ads_entries);
527         dentry->ads_entries = NULL;
528         dentry->num_ads = 0;
529 }
530
531 static void __destroy_dentry(struct dentry *dentry)
532 {
533         FREE(dentry->file_name);
534         FREE(dentry->file_name_utf8);
535         FREE(dentry->short_name);
536         FREE(dentry->full_path_utf8);
537         FREE(dentry->extracted_file);
538 }
539
540 void free_dentry(struct dentry *dentry)
541 {
542         __destroy_dentry(dentry);
543         if (dentry->link_group_master_status != GROUP_SLAVE)
544                 dentry_free_ads_entries(dentry);
545         FREE(dentry);
546 }
547
548 void put_dentry(struct dentry *dentry)
549 {
550         if (dentry->link_group_master_status == GROUP_MASTER) {
551                 struct dentry *new_master;
552                 list_for_each_entry(new_master, &dentry->link_group_list,
553                                     link_group_list)
554                 {
555                         if (new_master->link_group_master_status == GROUP_SLAVE) {
556                                 new_master->link_group_master_status = GROUP_MASTER;
557                                 dentry->link_group_master_status = GROUP_SLAVE;
558                                 break;
559                         }
560                 }
561         }
562         struct list_head *next;
563         next = dentry->link_group_list.next;
564         list_del(&dentry->link_group_list);
565         /*if (next->next == next)*/
566                 /*container_of(next, struct dentry, link_group_list)->hard_link = 0;*/
567         free_dentry(dentry);
568 }
569
570 static bool dentries_have_same_ads(const struct dentry *d1,
571                                    const struct dentry *d2)
572 {
573         /* Verify stream names and hashes are the same */
574         for (u16 i = 0; i < d1->num_ads; i++) {
575                 if (strcmp(d1->ads_entries[i].stream_name_utf8,
576                            d2->ads_entries[i].stream_name_utf8) != 0)
577                         return false;
578                 if (memcmp(d1->ads_entries[i].hash,
579                            d2->ads_entries[i].hash,
580                            WIM_HASH_SIZE) != 0)
581                         return false;
582         }
583         return true;
584 }
585
586 /* Share the alternate stream entries between hard-linked dentries. */
587 int share_dentry_ads(struct dentry *master, struct dentry *slave)
588 {
589         const char *mismatch_type;
590         wimlib_assert(master->num_ads == 0 ||
591                       master->ads_entries != slave->ads_entries);
592         if (master->attributes != slave->attributes) {
593                 mismatch_type = "attributes";
594                 goto mismatch;
595         }
596         if (master->attributes & FILE_ATTRIBUTE_DIRECTORY) {
597                 WARNING("`%s' is hard-linked to `%s', which is a directory ",
598                         slave->full_path_utf8, master->full_path_utf8);
599                 return WIMLIB_ERR_INVALID_DENTRY;
600         }
601         if (master->security_id != slave->security_id) {
602                 mismatch_type = "security ID";
603                 goto mismatch;
604         }
605         if (memcmp(master->hash, slave->hash, WIM_HASH_SIZE) != 0) {
606                 mismatch_type = "main file resource";
607                 goto mismatch;
608         }
609         if (!dentries_have_same_ads(master, slave)) {
610                 mismatch_type = "Alternate Stream Entries";
611                 goto mismatch;
612         }
613         dentry_free_ads_entries(slave);
614         slave->ads_entries = master->ads_entries;
615         slave->link_group_master_status = GROUP_SLAVE;
616         return 0;
617 mismatch:
618         WARNING("Dentries `%s' and `%s' in the same hard-link group but "
619                 "do not share the same %s",
620                 master->full_path_utf8, slave->full_path_utf8,
621                 mismatch_type);
622         return WIMLIB_ERR_INVALID_DENTRY;
623 }
624
625 /* clones a dentry.
626  *
627  * Beware:
628  *      - memory for file names is not cloned
629  *      - next, prev, and children pointers and not touched
630  *      - stream entries are not cloned.
631  */
632 struct dentry *clone_dentry(struct dentry *old)
633 {
634         struct dentry *new = MALLOC(sizeof(struct dentry));
635         if (!new)
636                 return NULL;
637         memcpy(new, old, sizeof(struct dentry));
638         new->file_name          = NULL;
639         new->file_name_len      = 0;
640         new->file_name_utf8     = NULL;
641         new->file_name_utf8_len = 0;
642         new->short_name         = NULL;
643         new->short_name_len     = 0;
644         return new;
645 }
646
647 /* Arguments for do_free_dentry(). */
648 struct free_dentry_args {
649         struct lookup_table *lookup_table;
650         bool lt_decrement_refcnt;
651 };
652
653 /* 
654  * This function is passed as an argument to for_dentry_in_tree_depth() in order
655  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
656  */
657 static int do_free_dentry(struct dentry *dentry, void *__args)
658 {
659         struct free_dentry_args *args = (struct free_dentry_args*)__args;
660
661         if (args->lt_decrement_refcnt && !dentry_is_directory(dentry)) {
662                 lookup_table_decrement_refcnt(args->lookup_table, 
663                                               dentry->hash);
664         }
665
666         wimlib_assert(dentry->refcnt >= 1);
667         if (--dentry->refcnt == 0)
668                 free_dentry(dentry);
669         return 0;
670 }
671
672 /* 
673  * Unlinks and frees a dentry tree.
674  *
675  * @root:               The root of the tree.
676  * @lookup_table:       The lookup table for dentries.
677  * @decrement_refcnt:   True if the dentries in the tree are to have their 
678  *                      reference counts in the lookup table decremented.
679  */
680 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table, 
681                       bool lt_decrement_refcnt)
682 {
683         if (!root || !root->parent)
684                 return;
685
686         struct free_dentry_args args;
687         args.lookup_table        = lookup_table;
688         args.lt_decrement_refcnt = lt_decrement_refcnt;
689         for_dentry_in_tree_depth(root, do_free_dentry, &args);
690 }
691
692 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
693 {
694         dentry->refcnt++;
695         return 0;
696 }
697
698 /* 
699  * Links a dentry into the directory tree.
700  *
701  * @dentry: The dentry to link.
702  * @parent: The dentry that will be the parent of @dentry.
703  */
704 void link_dentry(struct dentry *dentry, struct dentry *parent)
705 {
706         dentry->parent = parent;
707         if (parent->children) {
708                 /* Not an only child; link to siblings. */
709                 dentry->next = parent->children;
710                 dentry->prev = parent->children->prev;
711                 dentry->next->prev = dentry;
712                 dentry->prev->next = dentry;
713         } else {
714                 /* Only child; link to parent. */
715                 parent->children = dentry;
716                 dentry->next = dentry;
717                 dentry->prev = dentry;
718         }
719 }
720
721
722 /* Unlink a dentry from the directory tree. 
723  *
724  * Note: This merely removes it from the in-memory tree structure.  See
725  * remove_dentry() in mount.c for a function implemented on top of this one that
726  * frees the dentry and implements reference counting for the lookup table
727  * entries. */
728 void unlink_dentry(struct dentry *dentry)
729 {
730         if (dentry_is_root(dentry))
731                 return;
732         if (dentry_is_only_child(dentry)) {
733                 dentry->parent->children = NULL;
734         } else {
735                 if (dentry_is_first_sibling(dentry))
736                         dentry->parent->children = dentry->next;
737                 dentry->next->prev = dentry->prev;
738                 dentry->prev->next = dentry->next;
739         }
740 }
741
742
743 /* Recalculates the length of @dentry based on its file name length and short
744  * name length.  */
745 static inline void recalculate_dentry_size(struct dentry *dentry)
746 {
747         dentry->length = WIM_DENTRY_DISK_SIZE + dentry->file_name_len + 
748                          2 + dentry->short_name_len;
749         /* Must be multiple of 8. */
750         dentry->length = (dentry->length + 7) & ~7;
751 }
752
753 int get_names(char **name_utf16_ret, char **name_utf8_ret,
754               u16 *name_utf16_len_ret, u16 *name_utf8_len_ret,
755               const char *name)
756 {
757         size_t utf8_len;
758         size_t utf16_len;
759         char *name_utf16, *name_utf8;
760
761         utf8_len = strlen(name);
762
763         name_utf16 = utf8_to_utf16(name, utf8_len, &utf16_len);
764
765         if (!name_utf16)
766                 return WIMLIB_ERR_NOMEM;
767
768         name_utf8 = MALLOC(utf8_len + 1);
769         if (!name_utf8) {
770                 FREE(name_utf8);
771                 return WIMLIB_ERR_NOMEM;
772         }
773         memcpy(name_utf8, name, utf8_len + 1);
774         FREE(*name_utf8_ret);
775         FREE(*name_utf16_ret);
776         *name_utf8_ret      = name_utf8;
777         *name_utf16_ret     = name_utf16;
778         *name_utf8_len_ret  = utf8_len;
779         *name_utf16_len_ret = utf16_len;
780         return 0;
781 }
782
783 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
784  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
785  * full_path_utf8 fields.  Also recalculates its length. */
786 int change_dentry_name(struct dentry *dentry, const char *new_name)
787 {
788         int ret;
789
790         ret = get_names(&dentry->file_name, &dentry->file_name_utf8,
791                         &dentry->file_name_len, &dentry->file_name_utf8_len,
792                          new_name);
793         if (ret == 0)
794                 recalculate_dentry_size(dentry);
795         return ret;
796 }
797
798 int change_ads_name(struct ads_entry *entry, const char *new_name)
799 {
800         return get_names(&entry->stream_name, &entry->stream_name_utf8,
801                          &entry->stream_name_len,
802                          &entry->stream_name_utf8_len,
803                           new_name);
804 }
805
806 /* Parameters for calculate_dentry_statistics(). */
807 struct image_statistics {
808         struct lookup_table *lookup_table;
809         u64 *dir_count;
810         u64 *file_count;
811         u64 *total_bytes;
812         u64 *hard_link_bytes;
813 };
814
815 static int calculate_dentry_statistics(struct dentry *dentry, void *arg)
816 {
817         struct image_statistics *stats;
818         struct lookup_table_entry *lte; 
819         u16 i;
820         
821         stats = arg;
822
823         if (dentry_is_directory(dentry) && !dentry_is_root(dentry))
824                 ++*stats->dir_count;
825         else
826                 ++*stats->file_count;
827
828         lte = __lookup_resource(stats->lookup_table, dentry->hash);
829         i = 0;
830         while (1) {
831                 if (lte) {
832                         u64 size = lte->resource_entry.original_size;
833                         *stats->total_bytes += size;
834                         if (++lte->out_refcnt == 1)
835                                 *stats->hard_link_bytes += size;
836                 }
837                 if (i == dentry->num_ads)
838                         break;
839                 lte = __lookup_resource(stats->lookup_table,
840                                         dentry->ads_entries[i].hash);
841                 i++;
842         }
843
844         return 0;
845 }
846
847 void calculate_dir_tree_statistics(struct dentry *root, struct lookup_table *table, 
848                                    u64 *dir_count_ret, u64 *file_count_ret, 
849                                    u64 *total_bytes_ret, 
850                                    u64 *hard_link_bytes_ret)
851 {
852         struct image_statistics stats;
853         *dir_count_ret         = 0;
854         *file_count_ret        = 0;
855         *total_bytes_ret       = 0;
856         *hard_link_bytes_ret   = 0;
857         stats.lookup_table     = table;
858         stats.dir_count       = dir_count_ret;
859         stats.file_count      = file_count_ret;
860         stats.total_bytes     = total_bytes_ret;
861         stats.hard_link_bytes = hard_link_bytes_ret;
862         for_lookup_table_entry(table, zero_out_refcnts, NULL);
863         for_dentry_in_tree(root, calculate_dentry_statistics, &stats);
864 }
865
866 static int read_ads_entries(const u8 *p, struct dentry *dentry,
867                             u64 remaining_size)
868 {
869         u16 num_ads = dentry->num_ads;
870         struct ads_entry *ads_entries = CALLOC(num_ads, sizeof(struct ads_entry));
871         int ret;
872         if (!ads_entries) {
873                 ERROR("Could not allocate memory for %"PRIu16" "
874                       "alternate data stream entries", num_ads);
875                 return WIMLIB_ERR_NOMEM;
876         }
877         DEBUG2("Reading %"PRIu16" alternate data streams "
878                "(remaining size = %"PRIu64")", num_ads, remaining_size);
879
880         for (u16 i = 0; i < num_ads; i++) {
881                 struct ads_entry *cur_entry = &ads_entries[i];
882                 u64 length;
883                 size_t utf8_len;
884                 const char *p_save = p;
885                 /* Read the base stream entry, excluding the stream name. */
886                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
887                         ERROR("Stream entries go past end of metadata resource");
888                         ERROR("(remaining_size = %"PRIu64")", remaining_size);
889                         ret = WIMLIB_ERR_INVALID_DENTRY;
890                         goto out_free_ads_entries;
891                 }
892                 remaining_size -= WIM_ADS_ENTRY_DISK_SIZE;
893
894                 p = get_u64(p, &length); /* ADS entry length */
895
896                 DEBUG2("ADS length = %"PRIu64, length);
897
898                 p += 8; /* Unused */
899                 p = get_bytes(p, WIM_HASH_SIZE, (u8*)cur_entry->hash);
900                 p = get_u16(p, &cur_entry->stream_name_len);
901
902                 DEBUG2("Stream name length = %u", cur_entry->stream_name_len);
903
904                 cur_entry->stream_name = NULL;
905                 cur_entry->stream_name_utf8 = NULL;
906
907                 if (remaining_size < cur_entry->stream_name_len + 2) {
908                         ERROR("Stream entries go past end of metadata resource");
909                         ERROR("(remaining_size = %"PRIu64" bytes, stream_name_len "
910                               "= %"PRIu16" bytes", remaining_size,
911                               cur_entry->stream_name_len);
912                         ret = WIMLIB_ERR_INVALID_DENTRY;
913                         goto out_free_ads_entries;
914                 }
915                 remaining_size -= cur_entry->stream_name_len + 2;
916
917                 cur_entry->stream_name = MALLOC(cur_entry->stream_name_len);
918                 if (!cur_entry->stream_name) {
919                         ret = WIMLIB_ERR_NOMEM;
920                         goto out_free_ads_entries;
921                 }
922                 get_bytes(p, cur_entry->stream_name_len,
923                           (u8*)cur_entry->stream_name);
924                 cur_entry->stream_name_utf8 = utf16_to_utf8(cur_entry->stream_name,
925                                                             cur_entry->stream_name_len,
926                                                             &utf8_len);
927                 cur_entry->stream_name_utf8_len = utf8_len;
928
929                 if (!cur_entry->stream_name_utf8) {
930                         ret = WIMLIB_ERR_NOMEM;
931                         goto out_free_ads_entries;
932                 }
933                 p = p_save + ads_entry_length(cur_entry);
934         }
935         dentry->ads_entries = ads_entries;
936         return 0;
937 out_free_ads_entries:
938         for (u16 i = 0; i < num_ads; i++) {
939                 FREE(ads_entries[i].stream_name);
940                 FREE(ads_entries[i].stream_name_utf8);
941         }
942         FREE(ads_entries);
943         return ret;
944 }
945
946 /* 
947  * Reads a directory entry from the metadata resource.
948  */
949 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len, 
950                 u64 offset, struct dentry *dentry)
951 {
952         const u8 *p;
953         u64 calculated_size;
954         char *file_name;
955         char *file_name_utf8;
956         char *short_name;
957         u16 short_name_len;
958         u16 file_name_len;
959         size_t file_name_utf8_len;
960         int ret;
961
962         dentry_common_init(dentry);
963
964         /*Make sure the dentry really fits into the metadata resource.*/
965         if (offset + 8 > metadata_resource_len) {
966                 ERROR("Directory entry starting at %"PRIu64" ends past the "
967                       "end of the metadata resource (size %"PRIu64")",
968                       offset, metadata_resource_len);
969                 return WIMLIB_ERR_INVALID_DENTRY;
970         }
971
972         /* Before reading the whole entry, we need to read just the length.
973          * This is because an entry of length 8 (that is, just the length field)
974          * terminates the list of sibling directory entries. */
975
976         p = get_u64(&metadata_resource[offset], &dentry->length);
977
978         /* A zero length field (really a length of 8, since that's how big the
979          * directory entry is...) indicates that this is the end of directory
980          * dentry.  We do not read it into memory as an actual dentry, so just
981          * return true in that case. */
982         if (dentry->length == 0)
983                 return 0;
984
985         if (offset + dentry->length >= metadata_resource_len) {
986                 ERROR("Directory entry at offset %"PRIu64" and with size "
987                       "%"PRIu64" ends past the end of the metadata resource "
988                       "(size %"PRIu64")",
989                       offset, dentry->length, metadata_resource_len);
990                 return WIMLIB_ERR_INVALID_DENTRY;
991         }
992
993         /* If it is a recognized length, read the rest of the directory entry.
994          * Note: The root directory entry has no name, and its length does not
995          * include the short name length field.  */
996         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
997                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
998                       dentry->length);
999                 return WIMLIB_ERR_INVALID_DENTRY;
1000         }
1001
1002         p = get_u32(p, &dentry->attributes);
1003         p = get_u32(p, (u32*)&dentry->security_id);
1004         p = get_u64(p, &dentry->subdir_offset);
1005
1006         /* 2 unused fields */
1007         p += 2 * sizeof(u64);
1008         /*p = get_u64(p, &dentry->unused1);*/
1009         /*p = get_u64(p, &dentry->unused2);*/
1010
1011         p = get_u64(p, &dentry->creation_time);
1012         p = get_u64(p, &dentry->last_access_time);
1013         p = get_u64(p, &dentry->last_write_time);
1014
1015         p = get_bytes(p, WIM_HASH_SIZE, dentry->hash);
1016         
1017         /*
1018          * I don't know what's going on here.  It seems like M$ screwed up the
1019          * reparse points, then put the fields in the same place and didn't
1020          * document it.  The WIM_HDR_FLAG_RP_FIX flag in the WIM header might
1021          * have something to do with this, but it's not documented.
1022          */
1023         if (dentry->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1024                 /* ??? */
1025                 p += 4;
1026                 p = get_u32(p, &dentry->reparse_tag);
1027                 p += 4;
1028         } else {
1029                 p = get_u32(p, &dentry->reparse_tag);
1030                 p = get_u64(p, &dentry->hard_link);
1031         }
1032
1033         /* By the way, the reparse_reserved field does not actually exist (at
1034          * least when the file is not a reparse point) */
1035
1036         
1037         p = get_u16(p, &dentry->num_ads);
1038
1039         p = get_u16(p, &short_name_len);
1040         p = get_u16(p, &file_name_len);
1041
1042         calculated_size = WIM_DENTRY_DISK_SIZE + file_name_len + 2 +
1043                           short_name_len;
1044
1045         if (dentry->length < calculated_size) {
1046                 ERROR("Unexpected end of directory entry! (Expected "
1047                       "%"PRIu64" bytes, got %"PRIu64" bytes. "
1048                       "short_name_len = %hu, file_name_len = %hu)", 
1049                       calculated_size, dentry->length,
1050                       short_name_len, file_name_len);
1051                 return WIMLIB_ERR_INVALID_DENTRY;
1052         }
1053
1054         /* Read the filename. */
1055         file_name = MALLOC(file_name_len);
1056         if (!file_name) {
1057                 ERROR("Failed to allocate %hu bytes for dentry file name",
1058                       file_name_len);
1059                 return WIMLIB_ERR_NOMEM;
1060         }
1061         p = get_bytes(p, file_name_len, file_name);
1062
1063         /* Convert filename to UTF-8. */
1064         file_name_utf8 = utf16_to_utf8(file_name, file_name_len, 
1065                                        &file_name_utf8_len);
1066
1067         if (!file_name_utf8) {
1068                 ERROR("Failed to allocate memory to convert UTF-16 "
1069                       "filename (%hu bytes) to UTF-8", file_name_len);
1070                 ret = WIMLIB_ERR_NOMEM;
1071                 goto out_free_file_name;
1072         }
1073
1074         /* Undocumented padding between file name and short name.  This probably
1075          * is supposed to be a terminating null character. */
1076         p += 2;
1077
1078         /* Read the short filename. */
1079         short_name = MALLOC(short_name_len);
1080         if (!short_name) {
1081                 ERROR("Failed to allocate %hu bytes for short filename",
1082                       short_name_len);
1083                 ret = WIMLIB_ERR_NOMEM;
1084                 goto out_free_file_name_utf8;
1085         }
1086
1087         p = get_bytes(p, short_name_len, short_name);
1088
1089         /* Some directory entries inexplicibly have a little over 70 bytes of
1090          * extra data.  The exact amount of data seems to be 72 bytes, but it is
1091          * aligned on the next 8-byte boundary.  Here's an example of the
1092          * aligned data:
1093          *
1094          * 01000000400000006c786bbac58ede11b0bb00261870892ab6adb76fe63a3
1095          * e468fca86530d2effa16c786bbac58ede11b0bb00261870892a0000000000
1096          * 0000000000000000000000
1097          *
1098          * Here's one interpretation of how the data is laid out.
1099          *
1100          * struct unknown {
1101          *      u32 field1; (always 0x00000001)
1102          *      u32 field2; (always 0x40000000)
1103          *      u16 field3;
1104          *      u32 field4;
1105          *      u32 field5;
1106          *      u32 field6;
1107          *      u8  data[48]; (???)
1108          *      u64 reserved1; (always 0)
1109          *      u64 reserved2; (always 0)
1110          * };*/
1111 #if 0
1112         if (dentry->length - calculated_size >= WIM_ADS_ENTRY_DISK_SIZE) {
1113                 printf("%s: %lu / %lu (", file_name_utf8, 
1114                                 calculated_size, dentry->length);
1115                 print_string(p + WIM_ADS_ENTRY_DISK_SIZE, dentry->length - calculated_size - WIM_ADS_ENTRY_DISK_SIZE);
1116                 puts(")");
1117                 print_byte_field(p, dentry->length - calculated_size);
1118                 putchar('\n');
1119         }
1120 #endif
1121
1122         if (dentry->num_ads != 0) {
1123                 calculated_size = (calculated_size + 7) & ~7;
1124                 if (calculated_size > metadata_resource_len - offset) {
1125                         ERROR("Not enough space in metadata resource for "
1126                               "alternate stream entries");
1127                         ret = WIMLIB_ERR_INVALID_DENTRY;
1128                         goto out_free_short_name;
1129                 }
1130                 ret = read_ads_entries(&metadata_resource[offset + calculated_size],
1131                                        dentry,
1132                                        metadata_resource_len - offset - calculated_size);
1133                 if (ret != 0)
1134                         goto out_free_short_name;
1135         }
1136
1137         dentry->file_name          = file_name;
1138         dentry->file_name_utf8     = file_name_utf8;
1139         dentry->short_name         = short_name;
1140         dentry->file_name_len      = file_name_len;
1141         dentry->file_name_utf8_len = file_name_utf8_len;
1142         dentry->short_name_len     = short_name_len;
1143         return 0;
1144 out_free_short_name:
1145         FREE(short_name);
1146 out_free_file_name_utf8:
1147         FREE(file_name_utf8);
1148 out_free_file_name:
1149         FREE(file_name);
1150         return ret;
1151 }
1152
1153 /* 
1154  * Writes a dentry to an output buffer.
1155  *
1156  * @dentry:  The dentry structure.
1157  * @p:       The memory location to write the data to.
1158  * @return:  Pointer to the byte after the last byte we wrote as part of the
1159  *              dentry.
1160  */
1161 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
1162 {
1163         u8 *orig_p = p;
1164         unsigned padding;
1165
1166         p = put_u64(p, dentry->length);
1167         p = put_u32(p, dentry->attributes);
1168         p = put_u32(p, dentry->security_id);
1169         p = put_u64(p, dentry->subdir_offset);
1170         p = put_u64(p, 0); /* unused1 */
1171         p = put_u64(p, 0); /* unused2 */
1172         p = put_u64(p, dentry->creation_time);
1173         p = put_u64(p, dentry->last_access_time);
1174         p = put_u64(p, dentry->last_write_time);
1175         p = put_bytes(p, WIM_HASH_SIZE, dentry->hash);
1176         if (dentry->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1177                 p = put_zeroes(p, 4);
1178                 p = put_u32(p, dentry->reparse_tag);
1179                 p = put_zeroes(p, 4);
1180         } else {
1181                 u64 hard_link;
1182                 p = put_u32(p, dentry->reparse_tag);
1183                 if (dentry->link_group_list.next == &dentry->link_group_list)
1184                         hard_link = 0;
1185                 else
1186                         hard_link = dentry->hard_link;
1187                 p = put_u64(p, hard_link);
1188         }
1189         p = put_u16(p, dentry->num_ads);
1190         p = put_u16(p, dentry->short_name_len);
1191         p = put_u16(p, dentry->file_name_len);
1192         p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
1193         p = put_u16(p, 0); /* filename padding, 2 bytes. */
1194         p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
1195
1196         wimlib_assert(p - orig_p <= dentry->length);
1197         if (p - orig_p < dentry->length)
1198                 p = put_zeroes(p, dentry->length - (p - orig_p));
1199
1200         p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1201
1202         for (u16 i = 0; i < dentry->num_ads; i++) {
1203                 p = put_u64(p, ads_entry_length(&dentry->ads_entries[i]));
1204                 p = put_u64(p, 0); /* Unused */
1205                 p = put_bytes(p, WIM_HASH_SIZE, dentry->ads_entries[i].hash);
1206                 p = put_u16(p, dentry->ads_entries[i].stream_name_len);
1207                 p = put_bytes(p, dentry->ads_entries[i].stream_name_len,
1208                                  (u8*)dentry->ads_entries[i].stream_name);
1209                 p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1210         }
1211         return p;
1212 }
1213
1214 /* Recursive function that writes a dentry tree rooted at @tree, not including
1215  * @tree itself, which has already been written, except in the case of the root
1216  * dentry, which is written right away, along with an end-of-directory entry. */
1217 u8 *write_dentry_tree(const struct dentry *tree, u8 *p)
1218 {
1219         const struct dentry *child;
1220
1221         if (dentry_is_root(tree)) {
1222                 p = write_dentry(tree, p);
1223
1224                 /* write end of directory entry */
1225                 p = put_u64(p, 0);
1226         } else {
1227                 /* Nothing to do for non-directories */
1228                 if (!dentry_is_directory(tree))
1229                         return p;
1230         }
1231
1232         /* Write child dentries and end-of-directory entry. */
1233         child = tree->children;
1234         if (child) {
1235                 do {
1236                         p = write_dentry(child, p);
1237                         child = child->next;
1238                 } while (child != tree->children);
1239         }
1240
1241         /* write end of directory entry */
1242         p = put_u64(p, 0);
1243
1244         /* Recurse on children. */
1245         if (child) {
1246                 do {
1247                         p = write_dentry_tree(child, p);
1248                         child = child->next;
1249                 } while (child != tree->children);
1250         }
1251         return p;
1252 }
1253
1254 /* Reads the children of a dentry, and all their children, ..., etc. from the
1255  * metadata resource and into the dentry tree.
1256  *
1257  * @metadata_resource:  An array that contains the uncompressed metadata
1258  *                      resource for the WIM file.
1259  * @metadata_resource_len:      The length of @metadata_resource.
1260  * @dentry:     A pointer to a struct dentry that is the root of the directory
1261  *              tree and has already been read from the metadata resource.  It
1262  *              does not need to be the real root because this procedure is
1263  *              called recursively.
1264  *
1265  * @return:     Zero on success, nonzero on failure.
1266  */
1267 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1268                      struct dentry *dentry)
1269 {
1270         u64 cur_offset = dentry->subdir_offset;
1271         struct dentry *prev_child = NULL;
1272         struct dentry *first_child = NULL;
1273         struct dentry *child;
1274         struct dentry cur_child;
1275         int ret;
1276
1277         /* If @dentry is a regular file, nothing more needs to be done for this
1278          * branch. */
1279         if (cur_offset == 0)
1280                 return 0;
1281
1282         /* Find and read all the children of @dentry. */
1283         while (1) {
1284
1285                 /* Read next child of @dentry into @cur_child. */
1286                 ret = read_dentry(metadata_resource, metadata_resource_len, 
1287                                   cur_offset, &cur_child);
1288                 if (ret != 0)
1289                         break;
1290
1291                 /* Check for end of directory. */
1292                 if (cur_child.length == 0) {
1293                         ret = 0;
1294                         break;
1295                 }
1296
1297                 /* Not end of directory.  Allocate this child permanently and
1298                  * link it to the parent and previous child. */
1299                 child = MALLOC(sizeof(struct dentry));
1300                 if (!child) {
1301                         ERROR("Failed to allocate %zu bytes for new dentry",
1302                               sizeof(struct dentry));
1303                         ret = WIMLIB_ERR_NOMEM;
1304                         break;
1305                 }
1306                 memcpy(child, &cur_child, sizeof(struct dentry));
1307
1308                 if (prev_child) {
1309                         prev_child->next = child;
1310                         child->prev = prev_child;
1311                 } else {
1312                         first_child = child;
1313                 }
1314
1315                 child->parent = dentry;
1316                 prev_child = child;
1317
1318                 /* If there are children of this child, call this procedure
1319                  * recursively. */
1320                 if (child->subdir_offset != 0) {
1321                         ret = read_dentry_tree(metadata_resource, 
1322                                                metadata_resource_len, child);
1323                         if (ret != 0)
1324                                 break;
1325                 }
1326
1327                 /* Advance to the offset of the next child. */
1328                 cur_offset += dentry_total_length(child);
1329         }
1330
1331         /* Link last child to first one, and set parent's
1332          * children pointer to the first child.  */
1333         if (prev_child) {
1334                 prev_child->next = first_child;
1335                 first_child->prev = prev_child;
1336         }
1337         dentry->children = first_child;
1338         return ret;
1339 }