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