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