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