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