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