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