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