]> wimlib.net Git - wimlib/blob - src/dentry.c
Non-recursive for_dentry_in_tree()
[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  * Copyright (C) 2012 Eric Biggers
14  *
15  * This file is part of wimlib, a library for working with WIM files.
16  *
17  * wimlib is free software; you can redistribute it and/or modify it under the
18  * terms of the GNU General Public License as published by the Free Software
19  * Foundation; either version 3 of the License, or (at your option) any later
20  * version.
21  *
22  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
23  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
24  * A PARTICULAR PURPOSE. See the GNU General Public License for more details.
25  *
26  * You should have received a copy of the GNU General Public License along with
27  * wimlib; if not, see http://www.gnu.org/licenses/.
28  */
29
30 #include <errno.h>
31 #include <sys/stat.h>
32 #include <time.h>
33 #include <unistd.h>
34
35 #include "dentry.h"
36 #include "io.h"
37 #include "lookup_table.h"
38 #include "sha1.h"
39 #include "timestamp.h"
40 #include "wimlib_internal.h"
41
42
43 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry that has
44  * a file name and short name that take the specified numbers of bytes.  This
45  * excludes any alternate data stream entries that may follow the dentry. */
46 static u64 __dentry_correct_length_unaligned(u16 file_name_len,
47                                              u16 short_name_len)
48 {
49         u64 length = WIM_DENTRY_DISK_SIZE;
50         if (file_name_len)
51                 length += file_name_len + 2;
52         if (short_name_len)
53                 length += short_name_len + 2;
54         return length;
55 }
56
57 /* Calculates the unaligned length, in bytes, of an on-disk WIM dentry, based on
58  * the file name length and short name length.  Note that dentry->length is
59  * ignored; also, this excludes any alternate data stream entries that may
60  * follow the dentry. */
61 static u64 dentry_correct_length_unaligned(const struct dentry *dentry)
62 {
63         return __dentry_correct_length_unaligned(dentry->file_name_len,
64                                                  dentry->short_name_len);
65 }
66
67 /* Return the "correct" value to write in the length field of a WIM dentry,
68  * based on the file name length and short name length. */
69 static u64 dentry_correct_length(const struct dentry *dentry)
70 {
71         return (dentry_correct_length_unaligned(dentry) + 7) & ~7;
72 }
73
74 /* Return %true iff @dentry has the UTF-8 file name @name that has length
75  * @name_len bytes. */
76 static bool dentry_has_name(const struct dentry *dentry, const char *name,
77                             size_t name_len)
78 {
79         if (dentry->file_name_utf8_len != name_len)
80                 return false;
81         return memcmp(dentry->file_name_utf8, name, name_len) == 0;
82 }
83
84 /* Return %true iff the alternate data stream entry @entry has the UTF-8 stream
85  * name @name that has length @name_len bytes. */
86 static inline bool ads_entry_has_name(const struct ads_entry *entry,
87                                       const char *name, size_t name_len)
88 {
89         if (entry->stream_name_utf8_len != name_len)
90                 return false;
91         return memcmp(entry->stream_name_utf8, name, name_len) == 0;
92 }
93
94 /* Duplicates a UTF-8 name into UTF-8 and UTF-16 strings and returns the strings
95  * and their lengths in the pointer arguments */
96 int get_names(char **name_utf16_ret, char **name_utf8_ret,
97               u16 *name_utf16_len_ret, u16 *name_utf8_len_ret,
98               const char *name)
99 {
100         size_t utf8_len;
101         size_t utf16_len;
102         char *name_utf16, *name_utf8;
103
104         utf8_len = strlen(name);
105
106         name_utf16 = utf8_to_utf16(name, utf8_len, &utf16_len);
107
108         if (!name_utf16)
109                 return WIMLIB_ERR_NOMEM;
110
111         name_utf8 = MALLOC(utf8_len + 1);
112         if (!name_utf8) {
113                 FREE(name_utf8);
114                 return WIMLIB_ERR_NOMEM;
115         }
116         memcpy(name_utf8, name, utf8_len + 1);
117         FREE(*name_utf8_ret);
118         FREE(*name_utf16_ret);
119         *name_utf8_ret      = name_utf8;
120         *name_utf16_ret     = name_utf16;
121         *name_utf8_len_ret  = utf8_len;
122         *name_utf16_len_ret = utf16_len;
123         return 0;
124 }
125
126 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
127  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
128  * full_path_utf8 fields.  Also recalculates its length. */
129 static int change_dentry_name(struct dentry *dentry, const char *new_name)
130 {
131         int ret;
132
133         ret = get_names(&dentry->file_name, &dentry->file_name_utf8,
134                         &dentry->file_name_len, &dentry->file_name_utf8_len,
135                          new_name);
136         FREE(dentry->short_name);
137         dentry->short_name_len = 0;
138         if (ret == 0)
139                 dentry->length = dentry_correct_length(dentry);
140         return ret;
141 }
142
143 /*
144  * Changes the name of an alternate data stream */
145 static int change_ads_name(struct ads_entry *entry, const char *new_name)
146 {
147         return get_names(&entry->stream_name, &entry->stream_name_utf8,
148                          &entry->stream_name_len,
149                          &entry->stream_name_utf8_len,
150                          new_name);
151 }
152
153 /* Returns the total length of a WIM alternate data stream entry on-disk,
154  * including the stream name, the null terminator, AND the padding after the
155  * entry to align the next one (or the next dentry) on an 8-byte boundary. */
156 static u64 ads_entry_total_length(const struct ads_entry *entry)
157 {
158         u64 len = WIM_ADS_ENTRY_DISK_SIZE;
159         if (entry->stream_name_len)
160                 len += entry->stream_name_len + 2;
161         return (len + 7) & ~7;
162 }
163
164
165 static u64 __dentry_total_length(const struct dentry *dentry, u64 length)
166 {
167         const struct inode *inode = dentry->d_inode;
168         for (u16 i = 0; i < inode->num_ads; i++)
169                 length += ads_entry_total_length(&inode->ads_entries[i]);
170         return (length + 7) & ~7;
171 }
172
173 /* Calculate the aligned *total* length of an on-disk WIM dentry.  This includes
174  * all alternate data streams. */
175 u64 dentry_correct_total_length(const struct dentry *dentry)
176 {
177         return __dentry_total_length(dentry,
178                                      dentry_correct_length_unaligned(dentry));
179 }
180
181 /* Like dentry_correct_total_length(), but use the existing dentry->length field
182  * instead of calculating its "correct" value. */
183 static u64 dentry_total_length(const struct dentry *dentry)
184 {
185         return __dentry_total_length(dentry, dentry->length);
186 }
187
188 /* Transfers file attributes from a `stat' buffer to a WIM "inode". */
189 void stbuf_to_inode(const struct stat *stbuf, struct inode *inode)
190 {
191         if (S_ISLNK(stbuf->st_mode)) {
192                 inode->attributes = FILE_ATTRIBUTE_REPARSE_POINT;
193                 inode->reparse_tag = WIM_IO_REPARSE_TAG_SYMLINK;
194         } else if (S_ISDIR(stbuf->st_mode)) {
195                 inode->attributes = FILE_ATTRIBUTE_DIRECTORY;
196         } else {
197                 inode->attributes = FILE_ATTRIBUTE_NORMAL;
198         }
199         if (sizeof(ino_t) >= 8)
200                 inode->ino = (u64)stbuf->st_ino;
201         else
202                 inode->ino = (u64)stbuf->st_ino |
203                                    ((u64)stbuf->st_dev << ((sizeof(ino_t) * 8) & 63));
204         /* Set timestamps */
205         inode->creation_time = timespec_to_wim_timestamp(&stbuf->st_mtim);
206         inode->last_write_time = timespec_to_wim_timestamp(&stbuf->st_mtim);
207         inode->last_access_time = timespec_to_wim_timestamp(&stbuf->st_atim);
208 }
209
210 #ifdef WITH_FUSE
211 /* Transfers file attributes from a struct inode to a `stat' buffer.
212  *
213  * The lookup table entry tells us which stream in the inode we are statting.
214  * For a named data stream, everything returned is the same as the unnamed data
215  * stream except possibly the size and block count. */
216 int inode_to_stbuf(const struct inode *inode, struct lookup_table_entry *lte,
217                    struct stat *stbuf)
218 {
219         if (inode_is_symlink(inode))
220                 stbuf->st_mode = S_IFLNK | 0777;
221         else if (inode_is_directory(inode))
222                 stbuf->st_mode = S_IFDIR | 0755;
223         else
224                 stbuf->st_mode = S_IFREG | 0755;
225
226         stbuf->st_ino   = (ino_t)inode->ino;
227         stbuf->st_nlink = inode->link_count;
228         stbuf->st_uid   = getuid();
229         stbuf->st_gid   = getgid();
230
231         if (lte) {
232                 if (lte->resource_location == RESOURCE_IN_STAGING_FILE) {
233                         wimlib_assert(lte->staging_file_name);
234                         struct stat native_stat;
235                         if (stat(lte->staging_file_name, &native_stat) != 0) {
236                                 DEBUG("Failed to stat `%s': %m",
237                                       lte->staging_file_name);
238                                 return -errno;
239                         }
240                         stbuf->st_size = native_stat.st_size;
241                 } else {
242                         stbuf->st_size = wim_resource_size(lte);
243                 }
244         } else {
245                 stbuf->st_size = 0;
246         }
247
248         stbuf->st_atime   = wim_timestamp_to_unix(inode->last_access_time);
249         stbuf->st_mtime   = wim_timestamp_to_unix(inode->last_write_time);
250         stbuf->st_ctime   = wim_timestamp_to_unix(inode->creation_time);
251         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
252         return 0;
253 }
254 #endif
255
256 int for_dentry_in_rbtree(struct rb_node *root,
257                          int (*visitor)(struct dentry *, void *),
258                          void *arg)
259 {
260         int ret;
261         struct rb_node *node = root;
262         LIST_HEAD(stack);
263         while (true) {
264                 if (node) {
265                         list_add(&rbnode_dentry(node)->tmp_list, &stack);
266                         node = node->rb_left;
267                 } else {
268                         struct list_head *next;
269                         struct dentry *dentry;
270
271                         next = stack.next;
272                         if (next == &stack)
273                                 return 0;
274                         dentry = container_of(next, struct dentry, tmp_list);
275                         list_del(next);
276                         ret = visitor(dentry, arg);
277                         if (ret != 0)
278                                 return ret;
279                         node = dentry->rb_node.rb_right;
280                 }
281         }
282 }
283
284 static int for_dentry_tree_in_rbtree_depth(struct rb_node *node,
285                                            int (*visitor)(struct dentry*, void*),
286                                            void *arg)
287 {
288         int ret;
289         if (node) {
290                 ret = for_dentry_tree_in_rbtree_depth(node->rb_left,
291                                                       visitor, arg);
292                 if (ret != 0)
293                         return ret;
294                 ret = for_dentry_tree_in_rbtree_depth(node->rb_right,
295                                                       visitor, arg);
296                 if (ret != 0)
297                         return ret;
298                 ret = for_dentry_in_tree_depth(rbnode_dentry(node), visitor, arg);
299                 if (ret != 0)
300                         return ret;
301         }
302         return 0;
303 }
304
305 /*
306  * Calls a function on all directory entries in a WIM dentry tree.  Logically,
307  * this is a pre-order traversal (the function is called on a parent dentry
308  * before its children), but sibling dentries will be visited in order as well.
309  *
310  * In reality, the data structures are more complicated than the above might
311  * suggest because there is a separate red-black tree for each dentry that
312  * contains its direct children.
313  */
314 int for_dentry_in_tree(struct dentry *root,
315                        int (*visitor)(struct dentry*, void*), void *arg)
316 {
317         int ret;
318         struct list_head main_stack;
319         struct list_head sibling_stack;
320         struct list_head *sibling_stack_bottom;
321         struct dentry *main_dentry;
322         struct rb_node *node;
323         struct list_head *next_sibling;
324         struct dentry *dentry;
325
326         ret = visitor(root, arg);
327         if (ret != 0)
328                 return ret;
329
330         main_dentry = root;
331         sibling_stack_bottom = &sibling_stack;
332         INIT_LIST_HEAD(&main_stack);
333         INIT_LIST_HEAD(&sibling_stack);
334
335         list_add(&main_dentry->tmp_list, &main_stack);
336
337         while (1) {
338                 // Prepare for non-recursive in-order traversal of the red-black
339                 // tree of this dentry's children
340                 node = main_dentry->d_inode->children.rb_node;
341
342                 while (node) {
343                         // Push this node to the sibling stack and examine the
344                         // left neighbor, if any
345                         list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
346                 push_left_siblings:
347                         node = node->rb_left;
348                 }
349
350
351                 pop_sibling:
352
353                 next_sibling = sibling_stack.next;
354                 if (next_sibling == sibling_stack_bottom) {
355                         // Done with all siblings.  Pop the main dentry to move
356                         // back up one level.
357                         main_dentry = container_of(main_stack.next,
358                                                    struct dentry,
359                                                    tmp_list);
360                         list_del(&main_dentry->tmp_list);
361
362                         if (main_dentry == root) {
363                                 ret = 0;
364                                 goto out;
365                         }
366
367                         // Restore sibling stack bottom from the previous level
368                         sibling_stack_bottom = (void*)main_dentry->parent;
369
370                         // Restore the just-popped main dentry's parent
371                         main_dentry->parent = container_of(main_stack.next,
372                                                            struct dentry,
373                                                            tmp_list);
374
375                         // The next sibling to traverse in the previous level,
376                         // in the in-order traversal of the red-black tree, is
377                         // the one to the right.
378                         node = main_dentry->rb_node.rb_right;
379                         if (node)  {
380                                 list_add(&rbnode_dentry(node)->tmp_list,
381                                          &sibling_stack);
382                                 goto push_left_siblings;
383                         } else {
384                                 goto pop_sibling;
385                         }
386                 } else {
387                         // The sibling stack is not empty, so there are more to
388                         // go!
389
390                         // Pop a sibling from the stack.
391                         list_del(next_sibling);
392                         dentry = container_of(next_sibling, struct dentry, tmp_list);
393
394                         // Visit the sibling.
395                         ret = visitor(dentry, arg);
396                         if (ret != 0) {
397                                 // Failed.  Restore parent pointers for the
398                                 // dentries in the main stack
399                                 list_del(&root->tmp_list);
400                                 list_for_each_entry(dentry, &main_stack, tmp_list) {
401                                         dentry->parent = container_of(dentry->tmp_list.next,
402                                                                       struct dentry,
403                                                                       tmp_list);
404                                 }
405                                 goto out;
406                         }
407
408                         // We'd like to recursively visit the dentry tree rooted
409                         // at this sibling.  To do this, add it to the main
410                         // stack, save the bottom of this level's sibling stack
411                         // in the dentry->parent field, re-set the bottom of the
412                         // sibling stack to be its current height, and set
413                         // main_dentry to the sibling so it becomes the parent
414                         // dentry in the next iteration through the outer loop.
415                         list_add(&dentry->tmp_list, &main_stack);
416                         dentry->parent = (void*)sibling_stack_bottom;
417                         sibling_stack_bottom = sibling_stack.next;
418
419                         main_dentry = dentry;
420                 }
421         }
422 out:
423         root->parent = root;
424         return ret;
425 }
426
427 /*
428  * Like for_dentry_in_tree(), but the visitor function is always called on a
429  * dentry's children before on itself.
430  */
431 int for_dentry_in_tree_depth(struct dentry *root,
432                              int (*visitor)(struct dentry*, void*), void *arg)
433 {
434 #if 1
435         int ret;
436         ret = for_dentry_tree_in_rbtree_depth(root->d_inode->children.rb_node,
437                                               visitor, arg);
438         if (ret != 0)
439                 return ret;
440         return visitor(root, arg);
441
442 #else
443         int ret;
444         struct list_head main_stack;
445         struct list_head sibling_stack;
446         struct list_head *sibling_stack_bottom;
447         struct dentry *main_dentry;
448         struct rb_node *node;
449         struct list_head *next_sibling;
450         struct dentry *dentry;
451
452         main_dentry = root;
453         sibling_stack_bottom = &sibling_stack;
454         INIT_LIST_HEAD(&main_stack);
455         INIT_LIST_HEAD(&sibling_stack);
456
457         list_add(&main_dentry->tmp_list, &main_stack);
458
459         while (1) {
460                 node = main_dentry->d_inode->children.rb_node;
461
462                 while (1) {
463                         if (node->rb_left) {
464                                 list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
465                                 node = node->rb_left;
466                                 continue;
467                         }
468                         if (node->rb_right) {
469                                 list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
470                                 node = node->rb_right;
471                                 continue;
472                         }
473                         list_add(&rbnode_dentry(node)->tmp_list, &sibling_stack);
474                 }
475
476         pop_sibling:
477                 next_sibling = sibling_stack.next;
478                 if (next_sibling == sibling_stack_bottom) {
479                         main_dentry = container_of(main_stack.next,
480                                                    struct dentry,
481                                                    tmp_list);
482                         list_del(&main_dentry->tmp_list);
483
484
485                         sibling_stack_bottom = (void*)main_dentry->parent;
486
487                         if (main_dentry == root) {
488                                 main_dentry->parent = main_dentry;
489                                 ret = visitor(dentry, arg);
490                                 return ret;
491                         } else {
492                                 main_dentry->parent = container_of(main_stack.next,
493                                                                    struct dentry,
494                                                                    tmp_list);
495                         }
496
497                         ret = visitor(main_dentry, arg);
498
499                         if (ret != 0) {
500                                 list_del(&root->tmp_list);
501                                 list_for_each_entry(dentry, &main_stack, tmp_list) {
502                                         dentry->parent = container_of(dentry->tmp_list.next,
503                                                                       struct dentry,
504                                                                       tmp_list);
505                                 }
506                                 root->parent = root;
507                                 return ret;
508                         }
509                         goto pop_sibling;
510                 } else {
511
512                         list_del(next_sibling);
513                         dentry = container_of(next_sibling, struct dentry, tmp_list);
514
515
516                         list_add(&dentry->tmp_list, &main_stack);
517                         dentry->parent = (void*)sibling_stack_bottom;
518                         sibling_stack_bottom = sibling_stack.next;
519
520                         main_dentry = dentry;
521                 }
522         }
523 #endif
524 }
525
526 /*
527  * Calculate the full path of @dentry, based on its parent's full path and on
528  * its UTF-8 file name.
529  */
530 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
531 {
532         char *full_path;
533         u32 full_path_len;
534         if (dentry_is_root(dentry)) {
535                 full_path = MALLOC(2);
536                 if (!full_path)
537                         goto oom;
538                 full_path[0] = '/';
539                 full_path[1] = '\0';
540                 full_path_len = 1;
541         } else {
542                 char *parent_full_path;
543                 u32 parent_full_path_len;
544                 const struct dentry *parent = dentry->parent;
545
546                 if (dentry_is_root(parent)) {
547                         parent_full_path = "";
548                         parent_full_path_len = 0;
549                 } else {
550                         parent_full_path = parent->full_path_utf8;
551                         parent_full_path_len = parent->full_path_utf8_len;
552                 }
553
554                 full_path_len = parent_full_path_len + 1 +
555                                 dentry->file_name_utf8_len;
556                 full_path = MALLOC(full_path_len + 1);
557                 if (!full_path)
558                         goto oom;
559
560                 memcpy(full_path, parent_full_path, parent_full_path_len);
561                 full_path[parent_full_path_len] = '/';
562                 memcpy(full_path + parent_full_path_len + 1,
563                        dentry->file_name_utf8,
564                        dentry->file_name_utf8_len);
565                 full_path[full_path_len] = '\0';
566         }
567         FREE(dentry->full_path_utf8);
568         dentry->full_path_utf8 = full_path;
569         dentry->full_path_utf8_len = full_path_len;
570         return 0;
571 oom:
572         ERROR("Out of memory while calculating dentry full path");
573         return WIMLIB_ERR_NOMEM;
574 }
575
576 static int increment_subdir_offset(struct dentry *dentry, void *subdir_offset_p)
577 {
578         *(u64*)subdir_offset_p += dentry_correct_total_length(dentry);
579         return 0;
580 }
581
582 static int call_calculate_subdir_offsets(struct dentry *dentry,
583                                          void *subdir_offset_p)
584 {
585         calculate_subdir_offsets(dentry, subdir_offset_p);
586         return 0;
587 }
588
589 /*
590  * Recursively calculates the subdir offsets for a directory tree.
591  *
592  * @dentry:  The root of the directory tree.
593  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
594  *                    offset for @dentry.
595  */
596 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
597 {
598         struct rb_node *node;
599
600         dentry->subdir_offset = *subdir_offset_p;
601         node = dentry->d_inode->children.rb_node;
602         if (node) {
603                 /* Advance the subdir offset by the amount of space the children
604                  * of this dentry take up. */
605                 for_dentry_in_rbtree(node, increment_subdir_offset, subdir_offset_p);
606
607                 /* End-of-directory dentry on disk. */
608                 *subdir_offset_p += 8;
609
610                 /* Recursively call calculate_subdir_offsets() on all the
611                  * children. */
612                 for_dentry_in_rbtree(node, call_calculate_subdir_offsets, subdir_offset_p);
613         } else {
614                 /* On disk, childless directories have a valid subdir_offset
615                  * that points to an 8-byte end-of-directory dentry.  Regular
616                  * files or reparse points have a subdir_offset of 0. */
617                 if (dentry_is_directory(dentry))
618                         *subdir_offset_p += 8;
619                 else
620                         dentry->subdir_offset = 0;
621         }
622 }
623
624 static int compare_names(const char *name_1, size_t len_1,
625                          const char *name_2, size_t len_2)
626 {
627         if (len_1 < len_2)
628                 return -1;
629         else if (len_1 > len_2)
630                 return 1;
631         else
632                 return memcmp(name_1, name_2, len_1);
633 }
634
635 static int dentry_compare_names(const struct dentry *d1, const struct dentry *d2)
636 {
637         return compare_names(d1->file_name_utf8, d1->file_name_utf8_len,
638                              d2->file_name_utf8, d2->file_name_utf8_len);
639 }
640
641
642 static struct dentry *
643 get_rbtree_child_with_name(const struct rb_node *node,
644                            const char *name, size_t name_len)
645 {
646         do {
647                 struct dentry *child = rbnode_dentry(node);
648                 int result = compare_names(name, name_len,
649                                            child->file_name_utf8,
650                                            child->file_name_utf8_len);
651                 if (result < 0)
652                         node = node->rb_left;
653                 else if (result > 0)
654                         node = node->rb_right;
655                 else
656                         return child;
657         } while (node);
658         return NULL;
659 }
660
661 /* Returns the child of @dentry that has the file name @name.
662  * Returns NULL if no child has the name. */
663 struct dentry *get_dentry_child_with_name(const struct dentry *dentry,
664                                           const char *name)
665 {
666         struct rb_node *node = dentry->d_inode->children.rb_node;
667         if (node)
668                 return get_rbtree_child_with_name(node, name, strlen(name));
669         else
670                 return NULL;
671 }
672
673 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
674  * @cur_dentry.  Returns NULL if no dentry having the path is found. */
675 static struct dentry *get_dentry_relative_path(struct dentry *cur_dentry,
676                                                const char *path)
677 {
678         if (*path == '\0')
679                 return cur_dentry;
680
681         struct rb_node *node = cur_dentry->d_inode->children.rb_node;
682         if (node) {
683                 struct dentry *child;
684                 size_t base_len;
685                 const char *new_path;
686
687                 new_path = path_next_part(path, &base_len);
688
689                 child = get_rbtree_child_with_name(node, path, base_len);
690                 if (child)
691                         return get_dentry_relative_path(child, new_path);
692         }
693         return NULL;
694 }
695
696 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
697  * such dentry. */
698 struct dentry *get_dentry(WIMStruct *w, const char *path)
699 {
700         struct dentry *root = wim_root_dentry(w);
701         while (*path == '/')
702                 path++;
703         return get_dentry_relative_path(root, path);
704 }
705
706 struct inode *wim_pathname_to_inode(WIMStruct *w, const char *path)
707 {
708         struct dentry *dentry;
709         dentry = get_dentry(w, path);
710         if (dentry)
711                 return dentry->d_inode;
712         else
713                 return NULL;
714 }
715
716 /* Returns the dentry that corresponds to the parent directory of @path, or NULL
717  * if the dentry is not found. */
718 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
719 {
720         size_t path_len = strlen(path);
721         char buf[path_len + 1];
722
723         memcpy(buf, path, path_len + 1);
724
725         to_parent_name(buf, path_len);
726
727         return get_dentry(w, buf);
728 }
729
730 /* Prints the full path of a dentry. */
731 int print_dentry_full_path(struct dentry *dentry, void *ignore)
732 {
733         if (dentry->full_path_utf8)
734                 puts(dentry->full_path_utf8);
735         return 0;
736 }
737
738 /* We want to be able to show the names of the file attribute flags that are
739  * set. */
740 struct file_attr_flag {
741         u32 flag;
742         const char *name;
743 };
744 struct file_attr_flag file_attr_flags[] = {
745         {FILE_ATTRIBUTE_READONLY,           "READONLY"},
746         {FILE_ATTRIBUTE_HIDDEN,             "HIDDEN"},
747         {FILE_ATTRIBUTE_SYSTEM,             "SYSTEM"},
748         {FILE_ATTRIBUTE_DIRECTORY,          "DIRECTORY"},
749         {FILE_ATTRIBUTE_ARCHIVE,            "ARCHIVE"},
750         {FILE_ATTRIBUTE_DEVICE,             "DEVICE"},
751         {FILE_ATTRIBUTE_NORMAL,             "NORMAL"},
752         {FILE_ATTRIBUTE_TEMPORARY,          "TEMPORARY"},
753         {FILE_ATTRIBUTE_SPARSE_FILE,        "SPARSE_FILE"},
754         {FILE_ATTRIBUTE_REPARSE_POINT,      "REPARSE_POINT"},
755         {FILE_ATTRIBUTE_COMPRESSED,         "COMPRESSED"},
756         {FILE_ATTRIBUTE_OFFLINE,            "OFFLINE"},
757         {FILE_ATTRIBUTE_NOT_CONTENT_INDEXED,"NOT_CONTENT_INDEXED"},
758         {FILE_ATTRIBUTE_ENCRYPTED,          "ENCRYPTED"},
759         {FILE_ATTRIBUTE_VIRTUAL,            "VIRTUAL"},
760 };
761
762 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, if
763  * available.  If the dentry is unresolved and the lookup table is NULL, the
764  * lookup table entries will not be printed.  Otherwise, they will be. */
765 int print_dentry(struct dentry *dentry, void *lookup_table)
766 {
767         const u8 *hash;
768         struct lookup_table_entry *lte;
769         const struct inode *inode = dentry->d_inode;
770         time_t time;
771         char *p;
772
773         printf("[DENTRY]\n");
774         printf("Length            = %"PRIu64"\n", dentry->length);
775         printf("Attributes        = 0x%x\n", inode->attributes);
776         for (unsigned i = 0; i < ARRAY_LEN(file_attr_flags); i++)
777                 if (file_attr_flags[i].flag & inode->attributes)
778                         printf("    FILE_ATTRIBUTE_%s is set\n",
779                                 file_attr_flags[i].name);
780         printf("Security ID       = %d\n", inode->security_id);
781         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
782
783         /* Translate the timestamps into something readable */
784         time = wim_timestamp_to_unix(inode->creation_time);
785         p = asctime(gmtime(&time));
786         *(strrchr(p, '\n')) = '\0';
787         printf("Creation Time     = %s UTC\n", p);
788
789         time = wim_timestamp_to_unix(inode->last_access_time);
790         p = asctime(gmtime(&time));
791         *(strrchr(p, '\n')) = '\0';
792         printf("Last Access Time  = %s UTC\n", p);
793
794         time = wim_timestamp_to_unix(inode->last_write_time);
795         p = asctime(gmtime(&time));
796         *(strrchr(p, '\n')) = '\0';
797         printf("Last Write Time   = %s UTC\n", p);
798
799         printf("Reparse Tag       = 0x%"PRIx32"\n", inode->reparse_tag);
800         printf("Hard Link Group   = 0x%"PRIx64"\n", inode->ino);
801         printf("Hard Link Group Size = %"PRIu32"\n", inode->link_count);
802         printf("Number of Alternate Data Streams = %hu\n", inode->num_ads);
803         printf("Filename          = \"");
804         print_string(dentry->file_name, dentry->file_name_len);
805         puts("\"");
806         printf("Filename Length   = %hu\n", dentry->file_name_len);
807         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
808         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
809         printf("Short Name        = \"");
810         print_string(dentry->short_name, dentry->short_name_len);
811         puts("\"");
812         printf("Short Name Length = %hu\n", dentry->short_name_len);
813         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
814         lte = inode_stream_lte(dentry->d_inode, 0, lookup_table);
815         if (lte) {
816                 print_lookup_table_entry(lte);
817         } else {
818                 hash = inode_stream_hash(inode, 0);
819                 if (hash) {
820                         printf("Hash              = 0x");
821                         print_hash(hash);
822                         putchar('\n');
823                         putchar('\n');
824                 }
825         }
826         for (u16 i = 0; i < inode->num_ads; i++) {
827                 printf("[Alternate Stream Entry %u]\n", i);
828                 printf("Name = \"%s\"\n", inode->ads_entries[i].stream_name_utf8);
829                 printf("Name Length (UTF-16) = %u\n",
830                         inode->ads_entries[i].stream_name_len);
831                 hash = inode_stream_hash(inode, i + 1);
832                 if (hash) {
833                         printf("Hash              = 0x");
834                         print_hash(hash);
835                         putchar('\n');
836                 }
837                 print_lookup_table_entry(inode_stream_lte(inode, i + 1,
838                                                           lookup_table));
839         }
840         return 0;
841 }
842
843 /* Initializations done on every `struct dentry'. */
844 static void dentry_common_init(struct dentry *dentry)
845 {
846         memset(dentry, 0, sizeof(struct dentry));
847         dentry->refcnt = 1;
848 }
849
850 static struct inode *new_timeless_inode()
851 {
852         struct inode *inode = CALLOC(1, sizeof(struct inode));
853         if (inode) {
854                 inode->security_id = -1;
855                 inode->link_count = 1;
856         #ifdef WITH_FUSE
857                 inode->next_stream_id = 1;
858         #endif
859                 INIT_LIST_HEAD(&inode->dentry_list);
860         }
861         return inode;
862 }
863
864 static struct inode *new_inode()
865 {
866         struct inode *inode = new_timeless_inode();
867         if (inode) {
868                 u64 now = get_wim_timestamp();
869                 inode->creation_time = now;
870                 inode->last_access_time = now;
871                 inode->last_write_time = now;
872         }
873         return inode;
874 }
875
876 /*
877  * Creates an unlinked directory entry.
878  *
879  * @name:  The UTF-8 filename of the new dentry.
880  *
881  * Returns a pointer to the new dentry, or NULL if out of memory.
882  */
883 struct dentry *new_dentry(const char *name)
884 {
885         struct dentry *dentry;
886
887         dentry = MALLOC(sizeof(struct dentry));
888         if (!dentry)
889                 goto err;
890
891         dentry_common_init(dentry);
892         if (change_dentry_name(dentry, name) != 0)
893                 goto err;
894
895         dentry->parent = dentry;
896
897         return dentry;
898 err:
899         FREE(dentry);
900         ERROR("Failed to allocate new dentry");
901         return NULL;
902 }
903
904
905 static struct dentry *__new_dentry_with_inode(const char *name, bool timeless)
906 {
907         struct dentry *dentry;
908         dentry = new_dentry(name);
909         if (dentry) {
910                 if (timeless)
911                         dentry->d_inode = new_timeless_inode();
912                 else
913                         dentry->d_inode = new_inode();
914                 if (dentry->d_inode) {
915                         inode_add_dentry(dentry, dentry->d_inode);
916                 } else {
917                         free_dentry(dentry);
918                         dentry = NULL;
919                 }
920         }
921         return dentry;
922 }
923
924 struct dentry *new_dentry_with_timeless_inode(const char *name)
925 {
926         return __new_dentry_with_inode(name, true);
927 }
928
929 struct dentry *new_dentry_with_inode(const char *name)
930 {
931         return __new_dentry_with_inode(name, false);
932 }
933
934
935 static int init_ads_entry(struct ads_entry *ads_entry, const char *name)
936 {
937         int ret = 0;
938         memset(ads_entry, 0, sizeof(*ads_entry));
939         if (name && *name)
940                 ret = change_ads_name(ads_entry, name);
941         return ret;
942 }
943
944 static void destroy_ads_entry(struct ads_entry *ads_entry)
945 {
946         FREE(ads_entry->stream_name);
947         FREE(ads_entry->stream_name_utf8);
948 }
949
950
951 /* Frees an inode. */
952 void free_inode(struct inode *inode)
953 {
954         if (inode) {
955                 if (inode->ads_entries) {
956                         for (u16 i = 0; i < inode->num_ads; i++)
957                                 destroy_ads_entry(&inode->ads_entries[i]);
958                         FREE(inode->ads_entries);
959                 }
960         #ifdef WITH_FUSE
961                 wimlib_assert(inode->num_opened_fds == 0);
962                 FREE(inode->fds);
963         #endif
964                 FREE(inode->extracted_file);
965                 FREE(inode);
966         }
967 }
968
969 /* Decrements link count on an inode and frees it if the link count reaches 0.
970  * */
971 static void put_inode(struct inode *inode)
972 {
973         wimlib_assert(inode);
974         wimlib_assert(inode->link_count);
975         if (--inode->link_count == 0) {
976         #ifdef WITH_FUSE
977                 if (inode->num_opened_fds == 0)
978         #endif
979                 {
980                         free_inode(inode);
981                 }
982         }
983 }
984
985 /* Frees a WIM dentry.
986  *
987  * The inode is freed only if its link count is decremented to 0.
988  */
989 void free_dentry(struct dentry *dentry)
990 {
991         wimlib_assert(dentry != NULL);
992         FREE(dentry->file_name);
993         FREE(dentry->file_name_utf8);
994         FREE(dentry->short_name);
995         FREE(dentry->full_path_utf8);
996         if (dentry->d_inode)
997                 put_inode(dentry->d_inode);
998         FREE(dentry);
999 }
1000
1001 void put_dentry(struct dentry *dentry)
1002 {
1003         wimlib_assert(dentry != NULL);
1004         wimlib_assert(dentry->refcnt != 0);
1005
1006         if (--dentry->refcnt == 0)
1007                 free_dentry(dentry);
1008 }
1009
1010 /*
1011  * This function is passed as an argument to for_dentry_in_tree_depth() in order
1012  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
1013  */
1014 static int do_free_dentry(struct dentry *dentry, void *__lookup_table)
1015 {
1016         struct lookup_table *lookup_table = __lookup_table;
1017         unsigned i;
1018
1019         if (lookup_table) {
1020                 struct lookup_table_entry *lte;
1021                 struct inode *inode = dentry->d_inode;
1022                 wimlib_assert(inode->link_count);
1023                 for (i = 0; i <= inode->num_ads; i++) {
1024                         lte = inode_stream_lte(inode, i, lookup_table);
1025                         if (lte)
1026                                 lte_decrement_refcnt(lte, lookup_table);
1027                 }
1028         }
1029
1030         put_dentry(dentry);
1031         return 0;
1032 }
1033
1034 /*
1035  * Unlinks and frees a dentry tree.
1036  *
1037  * @root:               The root of the tree.
1038  * @lookup_table:       The lookup table for dentries.  If non-NULL, the
1039  *                      reference counts in the lookup table for the lookup
1040  *                      table entries corresponding to the dentries will be
1041  *                      decremented.
1042  */
1043 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table)
1044 {
1045         if (!root || !root->parent)
1046                 return;
1047         for_dentry_in_tree_depth(root, do_free_dentry, lookup_table);
1048 }
1049
1050 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
1051 {
1052         dentry->refcnt++;
1053         return 0;
1054 }
1055
1056 /*
1057  * Links a dentry into the directory tree.
1058  *
1059  * @dentry: The dentry to link.
1060  * @parent: The dentry that will be the parent of @dentry.
1061  */
1062 bool dentry_add_child(struct dentry * restrict parent,
1063                       struct dentry * restrict child)
1064 {
1065         wimlib_assert(dentry_is_directory(parent));
1066
1067         struct rb_root *root = &parent->d_inode->children;
1068         struct rb_node **new = &(root->rb_node);
1069         struct rb_node *rb_parent = NULL;
1070
1071         while (*new) {
1072                 struct dentry *this = rbnode_dentry(*new);
1073                 int result = dentry_compare_names(child, this);
1074
1075                 rb_parent = *new;
1076
1077                 if (result < 0)
1078                         new = &((*new)->rb_left);
1079                 else if (result > 0)
1080                         new = &((*new)->rb_right);
1081                 else
1082                         return false;
1083         }
1084         child->parent = parent;
1085         rb_link_node(&child->rb_node, rb_parent, new);
1086         rb_insert_color(&child->rb_node, root);
1087         return true;
1088 }
1089
1090 #ifdef WITH_FUSE
1091 /*
1092  * Unlink a dentry from the directory tree.
1093  *
1094  * Note: This merely removes it from the in-memory tree structure.
1095  */
1096 void unlink_dentry(struct dentry *dentry)
1097 {
1098         struct dentry *parent = dentry->parent;
1099         if (parent == dentry)
1100                 return;
1101         rb_erase(&dentry->rb_node, &parent->d_inode->children);
1102 }
1103 #endif
1104
1105 static inline struct dentry *inode_first_dentry(struct inode *inode)
1106 {
1107         wimlib_assert(inode->dentry_list.next != &inode->dentry_list);
1108         return container_of(inode->dentry_list.next, struct dentry,
1109                             inode_dentry_list);
1110 }
1111
1112 static int verify_inode(struct inode *inode, const WIMStruct *w)
1113 {
1114         const struct lookup_table *table = w->lookup_table;
1115         const struct wim_security_data *sd = wim_const_security_data(w);
1116         const struct dentry *first_dentry = inode_first_dentry(inode);
1117         int ret = WIMLIB_ERR_INVALID_DENTRY;
1118
1119         /* Check the security ID */
1120         if (inode->security_id < -1) {
1121                 ERROR("Dentry `%s' has an invalid security ID (%d)",
1122                         first_dentry->full_path_utf8, inode->security_id);
1123                 goto out;
1124         }
1125         if (inode->security_id >= sd->num_entries) {
1126                 ERROR("Dentry `%s' has an invalid security ID (%d) "
1127                       "(there are only %u entries in the security table)",
1128                         first_dentry->full_path_utf8, inode->security_id,
1129                         sd->num_entries);
1130                 goto out;
1131         }
1132
1133         /* Check that lookup table entries for all the resources exist, except
1134          * if the SHA1 message digest is all 0's, which indicates there is
1135          * intentionally no resource there.  */
1136         if (w->hdr.total_parts == 1) {
1137                 for (unsigned i = 0; i <= inode->num_ads; i++) {
1138                         struct lookup_table_entry *lte;
1139                         const u8 *hash;
1140                         hash = inode_stream_hash_unresolved(inode, i);
1141                         lte = __lookup_resource(table, hash);
1142                         if (!lte && !is_zero_hash(hash)) {
1143                                 ERROR("Could not find lookup table entry for stream "
1144                                       "%u of dentry `%s'", i, first_dentry->full_path_utf8);
1145                                 goto out;
1146                         }
1147                         if (lte && (lte->real_refcnt += inode->link_count) > lte->refcnt)
1148                         {
1149                         #ifdef ENABLE_ERROR_MESSAGES
1150                                 WARNING("The following lookup table entry "
1151                                         "has a reference count of %u, but",
1152                                         lte->refcnt);
1153                                 WARNING("We found %u references to it",
1154                                         lte->real_refcnt);
1155                                 WARNING("(One dentry referencing it is at `%s')",
1156                                          first_dentry->full_path_utf8);
1157
1158                                 print_lookup_table_entry(lte);
1159                         #endif
1160                                 /* Guess what!  install.wim for Windows 8
1161                                  * contains a stream with 2 dentries referencing
1162                                  * it, but the lookup table entry has reference
1163                                  * count of 1.  So we will need to handle this
1164                                  * case and not just make it be an error...  I'm
1165                                  * just setting the reference count to the
1166                                  * number of references we found.
1167                                  * (Unfortunately, even after doing this, the
1168                                  * reference count could be too low if it's also
1169                                  * referenced in other WIM images) */
1170
1171                         #if 1
1172                                 lte->refcnt = lte->real_refcnt;
1173                                 WARNING("Fixing reference count");
1174                         #else
1175                                 goto out;
1176                         #endif
1177                         }
1178                 }
1179         }
1180
1181         /* Make sure there is only one un-named stream. */
1182         unsigned num_unnamed_streams = 0;
1183         for (unsigned i = 0; i <= inode->num_ads; i++) {
1184                 const u8 *hash;
1185                 hash = inode_stream_hash_unresolved(inode, i);
1186                 if (!inode_stream_name_len(inode, i) && !is_zero_hash(hash))
1187                         num_unnamed_streams++;
1188         }
1189         if (num_unnamed_streams > 1) {
1190                 ERROR("Dentry `%s' has multiple (%u) un-named streams",
1191                       first_dentry->full_path_utf8, num_unnamed_streams);
1192                 goto out;
1193         }
1194         inode->verified = true;
1195         ret = 0;
1196 out:
1197         return ret;
1198 }
1199
1200 /* Run some miscellaneous verifications on a WIM dentry */
1201 int verify_dentry(struct dentry *dentry, void *wim)
1202 {
1203         int ret;
1204
1205         if (!dentry->d_inode->verified) {
1206                 ret = verify_inode(dentry->d_inode, wim);
1207                 if (ret != 0)
1208                         return ret;
1209         }
1210
1211         /* Cannot have a short name but no long name */
1212         if (dentry->short_name_len && !dentry->file_name_len) {
1213                 ERROR("Dentry `%s' has a short name but no long name",
1214                       dentry->full_path_utf8);
1215                 return WIMLIB_ERR_INVALID_DENTRY;
1216         }
1217
1218         /* Make sure root dentry is unnamed */
1219         if (dentry_is_root(dentry)) {
1220                 if (dentry->file_name_len) {
1221                         ERROR("The root dentry is named `%s', but it must "
1222                               "be unnamed", dentry->file_name_utf8);
1223                         return WIMLIB_ERR_INVALID_DENTRY;
1224                 }
1225         }
1226
1227 #if 0
1228         /* Check timestamps */
1229         if (inode->last_access_time < inode->creation_time ||
1230             inode->last_write_time < inode->creation_time) {
1231                 WARNING("Dentry `%s' was created after it was last accessed or "
1232                       "written to", dentry->full_path_utf8);
1233         }
1234 #endif
1235
1236         return 0;
1237 }
1238
1239
1240 #ifdef WITH_FUSE
1241 /* Returns the alternate data stream entry belonging to @inode that has the
1242  * stream name @stream_name. */
1243 struct ads_entry *inode_get_ads_entry(struct inode *inode,
1244                                       const char *stream_name,
1245                                       u16 *idx_ret)
1246 {
1247         size_t stream_name_len;
1248         if (!stream_name)
1249                 return NULL;
1250         if (inode->num_ads) {
1251                 u16 i = 0;
1252                 stream_name_len = strlen(stream_name);
1253                 do {
1254                         if (ads_entry_has_name(&inode->ads_entries[i],
1255                                                stream_name, stream_name_len))
1256                         {
1257                                 if (idx_ret)
1258                                         *idx_ret = i;
1259                                 return &inode->ads_entries[i];
1260                         }
1261                 } while (++i != inode->num_ads);
1262         }
1263         return NULL;
1264 }
1265 #endif
1266
1267 #if defined(WITH_FUSE) || defined(WITH_NTFS_3G)
1268 /*
1269  * Add an alternate stream entry to an inode and return a pointer to it, or NULL
1270  * if memory could not be allocated.
1271  */
1272 struct ads_entry *inode_add_ads(struct inode *inode, const char *stream_name)
1273 {
1274         u16 num_ads;
1275         struct ads_entry *ads_entries;
1276         struct ads_entry *new_entry;
1277
1278         DEBUG("Add alternate data stream \"%s\"", stream_name);
1279
1280         if (inode->num_ads >= 0xfffe) {
1281                 ERROR("Too many alternate data streams in one inode!");
1282                 return NULL;
1283         }
1284         num_ads = inode->num_ads + 1;
1285         ads_entries = REALLOC(inode->ads_entries,
1286                               num_ads * sizeof(inode->ads_entries[0]));
1287         if (!ads_entries) {
1288                 ERROR("Failed to allocate memory for new alternate data stream");
1289                 return NULL;
1290         }
1291         inode->ads_entries = ads_entries;
1292
1293         new_entry = &inode->ads_entries[num_ads - 1];
1294         if (init_ads_entry(new_entry, stream_name) != 0)
1295                 return NULL;
1296 #ifdef WITH_FUSE
1297         new_entry->stream_id = inode->next_stream_id++;
1298 #endif
1299         inode->num_ads = num_ads;
1300         return new_entry;
1301 }
1302 #endif
1303
1304 #ifdef WITH_FUSE
1305 /* Remove an alternate data stream from the inode  */
1306 void inode_remove_ads(struct inode *inode, u16 idx,
1307                       struct lookup_table *lookup_table)
1308 {
1309         struct ads_entry *ads_entry;
1310         struct lookup_table_entry *lte;
1311
1312         wimlib_assert(idx < inode->num_ads);
1313         wimlib_assert(inode->resolved);
1314
1315         ads_entry = &inode->ads_entries[idx];
1316
1317         DEBUG("Remove alternate data stream \"%s\"", ads_entry->stream_name_utf8);
1318
1319         lte = ads_entry->lte;
1320         if (lte)
1321                 lte_decrement_refcnt(lte, lookup_table);
1322
1323         destroy_ads_entry(ads_entry);
1324
1325         memcpy(&inode->ads_entries[idx],
1326                &inode->ads_entries[idx + 1],
1327                (inode->num_ads - idx - 1) * sizeof(inode->ads_entries[0]));
1328         inode->num_ads--;
1329 }
1330 #endif
1331
1332
1333
1334 /*
1335  * Reads the alternate data stream entries for a dentry.
1336  *
1337  * @p:  Pointer to buffer that starts with the first alternate stream entry.
1338  *
1339  * @inode:      Inode to load the alternate data streams into.
1340  *                      @inode->num_ads must have been set to the number of
1341  *                      alternate data streams that are expected.
1342  *
1343  * @remaining_size:     Number of bytes of data remaining in the buffer pointed
1344  *                              to by @p.
1345  *
1346  * The format of the on-disk alternate stream entries is as follows:
1347  *
1348  * struct ads_entry_on_disk {
1349  *      u64  length;          // Length of the entry, in bytes.  This includes
1350  *                                  all fields (including the stream name and
1351  *                                  null terminator if present, AND the padding!).
1352  *      u64  reserved;        // Seems to be unused
1353  *      u8   hash[20];        // SHA1 message digest of the uncompressed stream
1354  *      u16  stream_name_len; // Length of the stream name, in bytes
1355  *      char stream_name[];   // Stream name in UTF-16LE, @stream_name_len bytes long,
1356  *                                  not including null terminator
1357  *      u16  zero;            // UTF-16 null terminator for the stream name, NOT
1358  *                                  included in @stream_name_len.  Based on what
1359  *                                  I've observed from filenames in dentries,
1360  *                                  this field should not exist when
1361  *                                  (@stream_name_len == 0), but you can't
1362  *                                  actually tell because of the padding anyway
1363  *                                  (provided that the padding is zeroed, which
1364  *                                  it always seems to be).
1365  *      char padding[];       // Padding to make the size a multiple of 8 bytes.
1366  * };
1367  *
1368  * In addition, the entries are 8-byte aligned.
1369  *
1370  * Return 0 on success or nonzero on failure.  On success, inode->ads_entries
1371  * is set to an array of `struct ads_entry's of length inode->num_ads.  On
1372  * failure, @inode is not modified.
1373  */
1374 static int read_ads_entries(const u8 *p, struct inode *inode,
1375                             u64 remaining_size)
1376 {
1377         u16 num_ads;
1378         struct ads_entry *ads_entries;
1379         int ret;
1380
1381         num_ads = inode->num_ads;
1382         ads_entries = CALLOC(num_ads, sizeof(inode->ads_entries[0]));
1383         if (!ads_entries) {
1384                 ERROR("Could not allocate memory for %"PRIu16" "
1385                       "alternate data stream entries", num_ads);
1386                 return WIMLIB_ERR_NOMEM;
1387         }
1388
1389         for (u16 i = 0; i < num_ads; i++) {
1390                 struct ads_entry *cur_entry;
1391                 u64 length;
1392                 u64 length_no_padding;
1393                 u64 total_length;
1394                 size_t utf8_len;
1395                 const u8 *p_save = p;
1396
1397                 cur_entry = &ads_entries[i];
1398
1399         #ifdef WITH_FUSE
1400                 ads_entries[i].stream_id = i + 1;
1401         #endif
1402
1403                 /* Read the base stream entry, excluding the stream name. */
1404                 if (remaining_size < WIM_ADS_ENTRY_DISK_SIZE) {
1405                         ERROR("Stream entries go past end of metadata resource");
1406                         ERROR("(remaining_size = %"PRIu64")", remaining_size);
1407                         ret = WIMLIB_ERR_INVALID_DENTRY;
1408                         goto out_free_ads_entries;
1409                 }
1410
1411                 p = get_u64(p, &length);
1412                 p += 8; /* Skip the reserved field */
1413                 p = get_bytes(p, SHA1_HASH_SIZE, (u8*)cur_entry->hash);
1414                 p = get_u16(p, &cur_entry->stream_name_len);
1415
1416                 cur_entry->stream_name = NULL;
1417                 cur_entry->stream_name_utf8 = NULL;
1418
1419                 /* Length including neither the null terminator nor the padding
1420                  * */
1421                 length_no_padding = WIM_ADS_ENTRY_DISK_SIZE +
1422                                     cur_entry->stream_name_len;
1423
1424                 /* Length including the null terminator and the padding */
1425                 total_length = ((length_no_padding + 2) + 7) & ~7;
1426
1427                 wimlib_assert(total_length == ads_entry_total_length(cur_entry));
1428
1429                 if (remaining_size < length_no_padding) {
1430                         ERROR("Stream entries go past end of metadata resource");
1431                         ERROR("(remaining_size = %"PRIu64" bytes, "
1432                               "length_no_padding = %"PRIu64" bytes)",
1433                               remaining_size, length_no_padding);
1434                         ret = WIMLIB_ERR_INVALID_DENTRY;
1435                         goto out_free_ads_entries;
1436                 }
1437
1438                 /* The @length field in the on-disk ADS entry is expected to be
1439                  * equal to @total_length, which includes all of the entry and
1440                  * the padding that follows it to align the next ADS entry to an
1441                  * 8-byte boundary.  However, to be safe, we'll accept the
1442                  * length field as long as it's not less than the un-padded
1443                  * total length and not more than the padded total length. */
1444                 if (length < length_no_padding || length > total_length) {
1445                         ERROR("Stream entry has unexpected length "
1446                               "field (length field = %"PRIu64", "
1447                               "unpadded total length = %"PRIu64", "
1448                               "padded total length = %"PRIu64")",
1449                               length, length_no_padding, total_length);
1450                         ret = WIMLIB_ERR_INVALID_DENTRY;
1451                         goto out_free_ads_entries;
1452                 }
1453
1454                 if (cur_entry->stream_name_len) {
1455                         cur_entry->stream_name = MALLOC(cur_entry->stream_name_len);
1456                         if (!cur_entry->stream_name) {
1457                                 ret = WIMLIB_ERR_NOMEM;
1458                                 goto out_free_ads_entries;
1459                         }
1460                         get_bytes(p, cur_entry->stream_name_len,
1461                                   (u8*)cur_entry->stream_name);
1462                         cur_entry->stream_name_utf8 = utf16_to_utf8(cur_entry->stream_name,
1463                                                                     cur_entry->stream_name_len,
1464                                                                     &utf8_len);
1465                         cur_entry->stream_name_utf8_len = utf8_len;
1466
1467                         if (!cur_entry->stream_name_utf8) {
1468                                 ret = WIMLIB_ERR_NOMEM;
1469                                 goto out_free_ads_entries;
1470                         }
1471                 }
1472                 /* It's expected that the size of every ADS entry is a multiple
1473                  * of 8.  However, to be safe, I'm allowing the possibility of
1474                  * an ADS entry at the very end of the metadata resource ending
1475                  * un-aligned.  So although we still need to increment the input
1476                  * pointer by @total_length to reach the next ADS entry, it's
1477                  * possible that less than @total_length is actually remaining
1478                  * in the metadata resource. We should set the remaining size to
1479                  * 0 bytes if this happens. */
1480                 p = p_save + total_length;
1481                 if (remaining_size < total_length)
1482                         remaining_size = 0;
1483                 else
1484                         remaining_size -= total_length;
1485         }
1486         inode->ads_entries = ads_entries;
1487 #ifdef WITH_FUSE
1488         inode->next_stream_id = inode->num_ads + 1;
1489 #endif
1490         return 0;
1491 out_free_ads_entries:
1492         for (u16 i = 0; i < num_ads; i++)
1493                 destroy_ads_entry(&ads_entries[i]);
1494         FREE(ads_entries);
1495         return ret;
1496 }
1497
1498 /*
1499  * Reads a directory entry, including all alternate data stream entries that
1500  * follow it, from the WIM image's metadata resource.
1501  *
1502  * @metadata_resource:  Buffer containing the uncompressed metadata resource.
1503  * @metadata_resource_len:   Length of the metadata resource.
1504  * @offset:     Offset of this directory entry in the metadata resource.
1505  * @dentry:     A `struct dentry' that will be filled in by this function.
1506  *
1507  * Return 0 on success or nonzero on failure.  On failure, @dentry have been
1508  * modified, bu it will be left with no pointers to any allocated buffers.
1509  * On success, the dentry->length field must be examined.  If zero, this was a
1510  * special "end of directory" dentry and not a real dentry.  If nonzero, this
1511  * was a real dentry.
1512  */
1513 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len,
1514                 u64 offset, struct dentry *dentry)
1515 {
1516         const u8 *p;
1517         u64 calculated_size;
1518         char *file_name = NULL;
1519         char *file_name_utf8 = NULL;
1520         char *short_name = NULL;
1521         u16 short_name_len;
1522         u16 file_name_len;
1523         size_t file_name_utf8_len = 0;
1524         int ret;
1525         struct inode *inode = NULL;
1526
1527         dentry_common_init(dentry);
1528
1529         /*Make sure the dentry really fits into the metadata resource.*/
1530         if (offset + 8 > metadata_resource_len || offset + 8 < offset) {
1531                 ERROR("Directory entry starting at %"PRIu64" ends past the "
1532                       "end of the metadata resource (size %"PRIu64")",
1533                       offset, metadata_resource_len);
1534                 return WIMLIB_ERR_INVALID_DENTRY;
1535         }
1536
1537         /* Before reading the whole dentry, we need to read just the length.
1538          * This is because a dentry of length 8 (that is, just the length field)
1539          * terminates the list of sibling directory entries. */
1540
1541         p = get_u64(&metadata_resource[offset], &dentry->length);
1542
1543         /* A zero length field (really a length of 8, since that's how big the
1544          * directory entry is...) indicates that this is the end of directory
1545          * dentry.  We do not read it into memory as an actual dentry, so just
1546          * return successfully in that case. */
1547         if (dentry->length == 0)
1548                 return 0;
1549
1550         /* If the dentry does not overflow the metadata resource buffer and is
1551          * not too short, read the rest of it (excluding the alternate data
1552          * streams, but including the file name and short name variable-length
1553          * fields) into memory. */
1554         if (offset + dentry->length >= metadata_resource_len
1555             || offset + dentry->length < offset)
1556         {
1557                 ERROR("Directory entry at offset %"PRIu64" and with size "
1558                       "%"PRIu64" ends past the end of the metadata resource "
1559                       "(size %"PRIu64")",
1560                       offset, dentry->length, metadata_resource_len);
1561                 return WIMLIB_ERR_INVALID_DENTRY;
1562         }
1563
1564         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
1565                 ERROR("Directory entry has invalid length of %"PRIu64" bytes",
1566                       dentry->length);
1567                 return WIMLIB_ERR_INVALID_DENTRY;
1568         }
1569
1570         inode = new_timeless_inode();
1571         if (!inode)
1572                 return WIMLIB_ERR_NOMEM;
1573
1574         p = get_u32(p, &inode->attributes);
1575         p = get_u32(p, (u32*)&inode->security_id);
1576         p = get_u64(p, &dentry->subdir_offset);
1577
1578         /* 2 unused fields */
1579         p += 2 * sizeof(u64);
1580         /*p = get_u64(p, &dentry->unused1);*/
1581         /*p = get_u64(p, &dentry->unused2);*/
1582
1583         p = get_u64(p, &inode->creation_time);
1584         p = get_u64(p, &inode->last_access_time);
1585         p = get_u64(p, &inode->last_write_time);
1586
1587         p = get_bytes(p, SHA1_HASH_SIZE, inode->hash);
1588
1589         /*
1590          * I don't know what's going on here.  It seems like M$ screwed up the
1591          * reparse points, then put the fields in the same place and didn't
1592          * document it.  The WIM_HDR_FLAG_RP_FIX flag in the WIM header might
1593          * have something to do with this, but it's not documented.
1594          */
1595         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1596                 /* ??? */
1597                 p += 4;
1598                 p = get_u32(p, &inode->reparse_tag);
1599                 p += 4;
1600         } else {
1601                 p = get_u32(p, &inode->reparse_tag);
1602                 p = get_u64(p, &inode->ino);
1603         }
1604
1605         /* By the way, the reparse_reserved field does not actually exist (at
1606          * least when the file is not a reparse point) */
1607
1608         p = get_u16(p, &inode->num_ads);
1609
1610         p = get_u16(p, &short_name_len);
1611         p = get_u16(p, &file_name_len);
1612
1613         /* We now know the length of the file name and short name.  Make sure
1614          * the length of the dentry is large enough to actually hold them.
1615          *
1616          * The calculated length here is unaligned to allow for the possibility
1617          * that the dentry->length names an unaligned length, although this
1618          * would be unexpected. */
1619         calculated_size = __dentry_correct_length_unaligned(file_name_len,
1620                                                             short_name_len);
1621
1622         if (dentry->length < calculated_size) {
1623                 ERROR("Unexpected end of directory entry! (Expected "
1624                       "at least %"PRIu64" bytes, got %"PRIu64" bytes. "
1625                       "short_name_len = %hu, file_name_len = %hu)",
1626                       calculated_size, dentry->length,
1627                       short_name_len, file_name_len);
1628                 ret = WIMLIB_ERR_INVALID_DENTRY;
1629                 goto out_free_inode;
1630         }
1631
1632         /* Read the filename if present.  Note: if the filename is empty, there
1633          * is no null terminator following it. */
1634         if (file_name_len) {
1635                 file_name = MALLOC(file_name_len);
1636                 if (!file_name) {
1637                         ERROR("Failed to allocate %hu bytes for dentry file name",
1638                               file_name_len);
1639                         ret = WIMLIB_ERR_NOMEM;
1640                         goto out_free_inode;
1641                 }
1642                 p = get_bytes(p, file_name_len, file_name);
1643
1644                 /* Convert filename to UTF-8. */
1645                 file_name_utf8 = utf16_to_utf8(file_name, file_name_len,
1646                                                &file_name_utf8_len);
1647
1648                 if (!file_name_utf8) {
1649                         ERROR("Failed to allocate memory to convert UTF-16 "
1650                               "filename (%hu bytes) to UTF-8", file_name_len);
1651                         ret = WIMLIB_ERR_NOMEM;
1652                         goto out_free_file_name;
1653                 }
1654                 if (*(u16*)p)
1655                         WARNING("Expected two zero bytes following the file name "
1656                                 "`%s', but found non-zero bytes", file_name_utf8);
1657                 p += 2;
1658         }
1659
1660         /* Align the calculated size */
1661         calculated_size = (calculated_size + 7) & ~7;
1662
1663         if (dentry->length > calculated_size) {
1664                 /* Weird; the dentry says it's longer than it should be.  Note
1665                  * that the length field does NOT include the size of the
1666                  * alternate stream entries. */
1667
1668                 /* Strangely, some directory entries inexplicably have a little
1669                  * over 70 bytes of extra data.  The exact amount of data seems
1670                  * to be 72 bytes, but it is aligned on the next 8-byte
1671                  * boundary.  It does NOT seem to be alternate data stream
1672                  * entries.  Here's an example of the aligned data:
1673                  *
1674                  * 01000000 40000000 6c786bba c58ede11 b0bb0026 1870892a b6adb76f
1675                  * e63a3e46 8fca8653 0d2effa1 6c786bba c58ede11 b0bb0026 1870892a
1676                  * 00000000 00000000 00000000 00000000
1677                  *
1678                  * Here's one interpretation of how the data is laid out.
1679                  *
1680                  * struct unknown {
1681                  *      u32 field1; (always 0x00000001)
1682                  *      u32 field2; (always 0x40000000)
1683                  *      u8  data[48]; (???)
1684                  *      u64 reserved1; (always 0)
1685                  *      u64 reserved2; (always 0)
1686                  * };*/
1687                 DEBUG("Dentry for file or directory `%s' has %zu extra "
1688                       "bytes of data",
1689                       file_name_utf8, dentry->length - calculated_size);
1690         }
1691
1692         /* Read the short filename if present.  Note: if there is no short
1693          * filename, there is no null terminator following it. */
1694         if (short_name_len) {
1695                 short_name = MALLOC(short_name_len);
1696                 if (!short_name) {
1697                         ERROR("Failed to allocate %hu bytes for short filename",
1698                               short_name_len);
1699                         ret = WIMLIB_ERR_NOMEM;
1700                         goto out_free_file_name_utf8;
1701                 }
1702
1703                 p = get_bytes(p, short_name_len, short_name);
1704                 if (*(u16*)p)
1705                         WARNING("Expected two zero bytes following the short name of "
1706                                 "`%s', but found non-zero bytes", file_name_utf8);
1707                 p += 2;
1708         }
1709
1710         /*
1711          * Read the alternate data streams, if present.  dentry->num_ads tells
1712          * us how many they are, and they will directly follow the dentry
1713          * on-disk.
1714          *
1715          * Note that each alternate data stream entry begins on an 8-byte
1716          * aligned boundary, and the alternate data stream entries are NOT
1717          * included in the dentry->length field for some reason.
1718          */
1719         if (inode->num_ads != 0) {
1720
1721                 /* Trying different lengths is just a hack to make sure we have
1722                  * a chance of reading the ADS entries correctly despite the
1723                  * poor documentation. */
1724
1725                 if (calculated_size != dentry->length) {
1726                         WARNING("Trying calculated dentry length (%"PRIu64") "
1727                                 "instead of dentry->length field (%"PRIu64") "
1728                                 "to read ADS entries",
1729                                 calculated_size, dentry->length);
1730                 }
1731                 u64 lengths_to_try[3] = {calculated_size,
1732                                          (dentry->length + 7) & ~7,
1733                                          dentry->length};
1734                 ret = WIMLIB_ERR_INVALID_DENTRY;
1735                 for (size_t i = 0; i < ARRAY_LEN(lengths_to_try); i++) {
1736                         if (lengths_to_try[i] > metadata_resource_len - offset)
1737                                 continue;
1738                         ret = read_ads_entries(&metadata_resource[offset + lengths_to_try[i]],
1739                                                inode,
1740                                                metadata_resource_len - offset - lengths_to_try[i]);
1741                         if (ret == 0)
1742                                 goto out;
1743                 }
1744                 ERROR("Failed to read alternate data stream "
1745                       "entries of `%s'", dentry->file_name_utf8);
1746                 goto out_free_short_name;
1747         }
1748 out:
1749
1750         /* We've read all the data for this dentry.  Set the names and their
1751          * lengths, and we've done. */
1752         dentry->d_inode            = inode;
1753         dentry->file_name          = file_name;
1754         dentry->file_name_utf8     = file_name_utf8;
1755         dentry->short_name         = short_name;
1756         dentry->file_name_len      = file_name_len;
1757         dentry->file_name_utf8_len = file_name_utf8_len;
1758         dentry->short_name_len     = short_name_len;
1759         return 0;
1760 out_free_short_name:
1761         FREE(short_name);
1762 out_free_file_name_utf8:
1763         FREE(file_name_utf8);
1764 out_free_file_name:
1765         FREE(file_name);
1766 out_free_inode:
1767         free_inode(inode);
1768         return ret;
1769 }
1770
1771 /* Reads the children of a dentry, and all their children, ..., etc. from the
1772  * metadata resource and into the dentry tree.
1773  *
1774  * @metadata_resource:  An array that contains the uncompressed metadata
1775  *                      resource for the WIM file.
1776  *
1777  * @metadata_resource_len:  The length of the uncompressed metadata resource, in
1778  *                          bytes.
1779  *
1780  * @dentry:     A pointer to a `struct dentry' that is the root of the directory
1781  *              tree and has already been read from the metadata resource.  It
1782  *              does not need to be the real root because this procedure is
1783  *              called recursively.
1784  *
1785  * @return:     Zero on success, nonzero on failure.
1786  */
1787 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
1788                      struct dentry *dentry)
1789 {
1790         u64 cur_offset = dentry->subdir_offset;
1791         struct dentry *prev_child = NULL;
1792         struct dentry *first_child = NULL;
1793         struct dentry *child;
1794         struct dentry cur_child;
1795         int ret;
1796
1797         /*
1798          * If @dentry has no child dentries, nothing more needs to be done for
1799          * this branch.  This is the case for regular files, symbolic links, and
1800          * *possibly* empty directories (although an empty directory may also
1801          * have one child dentry that is the special end-of-directory dentry)
1802          */
1803         if (cur_offset == 0)
1804                 return 0;
1805
1806         /* Find and read all the children of @dentry. */
1807         while (1) {
1808
1809                 /* Read next child of @dentry into @cur_child. */
1810                 ret = read_dentry(metadata_resource, metadata_resource_len,
1811                                   cur_offset, &cur_child);
1812                 if (ret != 0)
1813                         break;
1814
1815                 /* Check for end of directory. */
1816                 if (cur_child.length == 0)
1817                         break;
1818
1819                 /* Not end of directory.  Allocate this child permanently and
1820                  * link it to the parent and previous child. */
1821                 child = MALLOC(sizeof(struct dentry));
1822                 if (!child) {
1823                         ERROR("Failed to allocate %zu bytes for new dentry",
1824                               sizeof(struct dentry));
1825                         ret = WIMLIB_ERR_NOMEM;
1826                         break;
1827                 }
1828                 memcpy(child, &cur_child, sizeof(struct dentry));
1829
1830                 dentry_add_child(dentry, child);
1831
1832                 inode_add_dentry(child, child->d_inode);
1833
1834                 /* If there are children of this child, call this procedure
1835                  * recursively. */
1836                 if (child->subdir_offset != 0) {
1837                         ret = read_dentry_tree(metadata_resource,
1838                                                metadata_resource_len, child);
1839                         if (ret != 0)
1840                                 break;
1841                 }
1842
1843                 /* Advance to the offset of the next child.  Note: We need to
1844                  * advance by the TOTAL length of the dentry, not by the length
1845                  * child->length, which although it does take into account the
1846                  * padding, it DOES NOT take into account alternate stream
1847                  * entries. */
1848                 cur_offset += dentry_total_length(child);
1849         }
1850         return ret;
1851 }
1852
1853 /*
1854  * Writes a WIM dentry to an output buffer.
1855  *
1856  * @dentry:  The dentry structure.
1857  * @p:       The memory location to write the data to.
1858  * @return:  Pointer to the byte after the last byte we wrote as part of the
1859  *              dentry.
1860  */
1861 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
1862 {
1863         u8 *orig_p = p;
1864         const u8 *hash;
1865         const struct inode *inode = dentry->d_inode;
1866
1867         /* We calculate the correct length of the dentry ourselves because the
1868          * dentry->length field may been set to an unexpected value from when we
1869          * read the dentry in (for example, there may have been unknown data
1870          * appended to the end of the dentry...) */
1871         u64 length = dentry_correct_length(dentry);
1872
1873         p = put_u64(p, length);
1874         p = put_u32(p, inode->attributes);
1875         p = put_u32(p, inode->security_id);
1876         p = put_u64(p, dentry->subdir_offset);
1877         p = put_u64(p, 0); /* unused1 */
1878         p = put_u64(p, 0); /* unused2 */
1879         p = put_u64(p, inode->creation_time);
1880         p = put_u64(p, inode->last_access_time);
1881         p = put_u64(p, inode->last_write_time);
1882         hash = inode_stream_hash(inode, 0);
1883         p = put_bytes(p, SHA1_HASH_SIZE, hash);
1884         if (inode->attributes & FILE_ATTRIBUTE_REPARSE_POINT) {
1885                 p = put_zeroes(p, 4);
1886                 p = put_u32(p, inode->reparse_tag);
1887                 p = put_zeroes(p, 4);
1888         } else {
1889                 u64 link_group_id;
1890                 p = put_u32(p, 0);
1891                 if (inode->link_count == 1)
1892                         link_group_id = 0;
1893                 else
1894                         link_group_id = inode->ino;
1895                 p = put_u64(p, link_group_id);
1896         }
1897         p = put_u16(p, inode->num_ads);
1898         p = put_u16(p, dentry->short_name_len);
1899         p = put_u16(p, dentry->file_name_len);
1900         if (dentry->file_name_len) {
1901                 p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
1902                 p = put_u16(p, 0); /* filename padding, 2 bytes. */
1903         }
1904         if (dentry->short_name) {
1905                 p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
1906                 p = put_u16(p, 0); /* short name padding, 2 bytes */
1907         }
1908
1909         /* Align to 8-byte boundary */
1910         wimlib_assert(length >= (p - orig_p) && length - (p - orig_p) <= 7);
1911         p = put_zeroes(p, length - (p - orig_p));
1912
1913         /* Write the alternate data streams, if there are any.  Please see
1914          * read_ads_entries() for comments about the format of the on-disk
1915          * alternate data stream entries. */
1916         for (u16 i = 0; i < inode->num_ads; i++) {
1917                 p = put_u64(p, ads_entry_total_length(&inode->ads_entries[i]));
1918                 p = put_u64(p, 0); /* Unused */
1919                 hash = inode_stream_hash(inode, i + 1);
1920                 p = put_bytes(p, SHA1_HASH_SIZE, hash);
1921                 p = put_u16(p, inode->ads_entries[i].stream_name_len);
1922                 if (inode->ads_entries[i].stream_name_len) {
1923                         p = put_bytes(p, inode->ads_entries[i].stream_name_len,
1924                                          (u8*)inode->ads_entries[i].stream_name);
1925                         p = put_u16(p, 0);
1926                 }
1927                 p = put_zeroes(p, (8 - (p - orig_p) % 8) % 8);
1928         }
1929         wimlib_assert(p - orig_p == __dentry_total_length(dentry, length));
1930         return p;
1931 }
1932
1933 static int write_dentry_cb(struct dentry *dentry, void *_p)
1934 {
1935         u8 **p = _p;
1936         *p = write_dentry(dentry, *p);
1937         return 0;
1938 }
1939
1940 static u8 *write_dentry_tree_recursive(const struct dentry *parent, u8 *p);
1941
1942 static int write_dentry_tree_recursive_cb(struct dentry *dentry, void *_p)
1943 {
1944         u8 **p = _p;
1945         *p = write_dentry_tree_recursive(dentry, *p);
1946         return 0;
1947 }
1948
1949 /* Recursive function that writes a dentry tree rooted at @parent, not including
1950  * @parent itself, which has already been written. */
1951 static u8 *write_dentry_tree_recursive(const struct dentry *parent, u8 *p)
1952 {
1953         /* Nothing to do if this dentry has no children. */
1954         if (parent->subdir_offset == 0)
1955                 return p;
1956
1957         /* Write child dentries and end-of-directory entry.
1958          *
1959          * Note: we need to write all of this dentry's children before
1960          * recursively writing the directory trees rooted at each of the child
1961          * dentries, since the on-disk dentries for a dentry's children are
1962          * always located at consecutive positions in the metadata resource! */
1963         for_dentry_in_rbtree(parent->d_inode->children.rb_node, write_dentry_cb, &p);
1964
1965         /* write end of directory entry */
1966         p = put_u64(p, 0);
1967
1968         /* Recurse on children. */
1969         for_dentry_in_rbtree(parent->d_inode->children.rb_node,
1970                              write_dentry_tree_recursive_cb, &p);
1971         return p;
1972 }
1973
1974 /* Writes a directory tree to the metadata resource.
1975  *
1976  * @root:       Root of the dentry tree.
1977  * @p:          Pointer to a buffer with enough space for the dentry tree.
1978  *
1979  * Returns pointer to the byte after the last byte we wrote.
1980  */
1981 u8 *write_dentry_tree(const struct dentry *root, u8 *p)
1982 {
1983         DEBUG("Writing dentry tree.");
1984         wimlib_assert(dentry_is_root(root));
1985
1986         /* If we're the root dentry, we have no parent that already
1987          * wrote us, so we need to write ourselves. */
1988         p = write_dentry(root, p);
1989
1990         /* Write end of directory entry after the root dentry just to be safe;
1991          * however the root dentry obviously cannot have any siblings. */
1992         p = put_u64(p, 0);
1993
1994         /* Recursively write the rest of the dentry tree. */
1995         return write_dentry_tree_recursive(root, p);
1996 }
1997