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