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