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