Empty file fix
[wimlib] / src / dentry.c
1 /*
2  * dentry.c
3  *
4  * A dentry (directory entry) contains the metadata for a file.  In the WIM file
5  * format, the dentries are stored in the "metadata resource" section right
6  * after the security data.  Each image in the WIM file has its own metadata
7  * resource with its own security data and dentry tree.  Dentries in different
8  * images may share file resources by referring to the same lookup table
9  * entries.
10  *
11  * Copyright (C) 2010 Carl Thijssen
12  * Copyright (C) 2012 Eric Biggers
13  *
14  * wimlib - Library for working with WIM files 
15  *
16  * This library is free software; you can redistribute it and/or modify it under
17  * the terms of the GNU Lesser General Public License as published by the Free
18  * Software Foundation; either version 2.1 of the License, or (at your option) any
19  * later version.
20  *
21  * This library 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 A
23  * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
24  *
25  * You should have received a copy of the GNU Lesser General Public License along
26  * with this library; if not, write to the Free Software Foundation, Inc., 59
27  * Temple Place, Suite 330, Boston, MA 02111-1307 USA 
28  */
29
30 #include "wimlib_internal.h"
31 #include "dentry.h"
32 #include "io.h"
33 #include "timestamp.h"
34 #include "lookup_table.h"
35 #include "sha1.h"
36 #include <unistd.h>
37 #include <sys/stat.h>
38
39
40 /* Transfers file attributes from a `stat' buffer to a struct dentry. */
41 void stbuf_to_dentry(const struct stat *stbuf, struct dentry *dentry)
42 {
43         if (S_ISDIR(stbuf->st_mode))
44                 dentry->attributes = WIM_FILE_ATTRIBUTE_DIRECTORY;
45         else
46                 dentry->attributes = WIM_FILE_ATTRIBUTE_NORMAL;
47 }
48
49 /* Transfers file attributes from a struct dentry to a `stat' buffer. */
50 void dentry_to_stbuf(const struct dentry *dentry, struct stat *stbuf, 
51                      const struct lookup_table *table)
52 {
53         struct lookup_table_entry *lte;
54
55         if (dentry_is_directory(dentry))
56                 stbuf->st_mode = S_IFDIR | 0755;
57         else
58                 stbuf->st_mode = S_IFREG | 0644;
59
60         if (table)
61                 lte = lookup_resource(table, dentry->hash);
62         else
63                 lte = NULL;
64
65         if (lte) {
66                 stbuf->st_nlink = lte->refcnt;
67                 stbuf->st_size = lte->resource_entry.original_size;
68         } else {
69                 stbuf->st_nlink = 1;
70                 stbuf->st_size = 0;
71         }
72         stbuf->st_uid     = getuid();
73         stbuf->st_gid     = getgid();
74         stbuf->st_atime   = ms_timestamp_to_unix(dentry->last_access_time);
75         stbuf->st_mtime   = ms_timestamp_to_unix(dentry->last_write_time);
76         stbuf->st_ctime   = ms_timestamp_to_unix(dentry->creation_time);
77         stbuf->st_blocks  = (stbuf->st_size + 511) / 512;
78 }
79
80 /* Makes all timestamp fields for the dentry be the current time. */
81 void dentry_update_all_timestamps(struct dentry *dentry)
82 {
83         u64 now = get_timestamp();
84         dentry->creation_time       = now;
85         dentry->last_access_time    = now;
86         dentry->last_write_time     = now;
87 }
88
89 /* 
90  * Calls a function on all directory entries in a directory tree.  It is called
91  * on a parent before its children.
92  */
93 int for_dentry_in_tree(struct dentry *root, 
94                        int (*visitor)(struct dentry*, void*), void *arg)
95 {
96         int ret;
97         struct dentry *child;
98
99         ret = visitor(root, arg);
100
101         if (ret != 0)
102                 return ret;
103
104         child = root->children;
105
106         if (!child)
107                 return 0;
108
109         do {
110                 ret = for_dentry_in_tree(child, visitor, arg);
111                 if (ret != 0)
112                         return ret;
113                 child = child->next;
114         } while (child != root->children);
115         return 0;
116 }
117
118 /* 
119  * Like for_dentry_in_tree(), but the visitor function is always called on a
120  * dentry's children before on itself.
121  */
122 int for_dentry_in_tree_depth(struct dentry *root, 
123                              int (*visitor)(struct dentry*, void*), void *arg)
124 {
125         int ret;
126         struct dentry *child;
127         struct dentry *next;
128
129         child = root->children;
130         if (child) {
131                 do {
132                         next = child->next;
133                         ret = for_dentry_in_tree_depth(child, visitor, arg);
134                         if (ret != 0)
135                                 return ret;
136                         child = next;
137                 } while (child != root->children);
138         }
139         return visitor(root, arg);
140 }
141
142 /* 
143  * Calculate the full path of @dentry, based on its parent's full path and on
144  * its UTF-8 file name. 
145  */
146 int calculate_dentry_full_path(struct dentry *dentry, void *ignore)
147 {
148         int parent_len;
149         int len;
150         char *parent_full_path;
151         char *full_path;
152
153         FREE(dentry->full_path_utf8);
154
155         if (dentry_is_root(dentry)) {
156                 dentry->full_path_utf8 = MALLOC(2);
157                 if (!dentry->full_path_utf8) {
158                         ERROR("Out of memory!\n");
159                         return WIMLIB_ERR_NOMEM;
160                 }
161
162                 dentry->full_path_utf8[0] = '/';
163                 dentry->full_path_utf8[1] = '\0';
164                 dentry->full_path_utf8_len = 1;
165                 return 0;
166         }
167
168         if (dentry_is_root(dentry->parent)) {
169                 parent_len = 0;
170                 parent_full_path = "";
171         } else {
172                 parent_len = dentry->parent->full_path_utf8_len;
173                 parent_full_path = dentry->parent->full_path_utf8;
174         }
175
176         len = parent_len + 1 + dentry->file_name_utf8_len;
177         full_path = MALLOC(len + 1);
178         if (!full_path) {
179                 ERROR("Out of memory!\n");
180                 return WIMLIB_ERR_NOMEM;
181         }
182
183         memcpy(full_path, parent_full_path, parent_len);
184         full_path[parent_len] = '/';
185         memcpy(full_path + parent_len + 1, dentry->file_name_utf8, 
186                                 dentry->file_name_utf8_len);
187         full_path[len] = '\0';
188         dentry->full_path_utf8 = full_path;
189         dentry->full_path_utf8_len = len;
190         return 0;
191 }
192
193 /* 
194  * Recursively calculates the subdir offsets for a directory tree. 
195  *
196  * @dentry:  The root of the directory tree.
197  * @subdir_offset_p:  The current subdirectory offset; i.e., the subdirectory
198  *      offset for @dentry. 
199  */
200 void calculate_subdir_offsets(struct dentry *dentry, u64 *subdir_offset_p)
201 {
202         struct dentry *child;
203
204         child = dentry->children;
205         dentry->subdir_offset = *subdir_offset_p;
206         if (child) {
207
208                 /* Advance the subdir offset by the amount of space the children
209                  * of this dentry take up. */
210                 do {
211                         *subdir_offset_p += child->length;
212                         child = child->next;
213                 } while (child != dentry->children);
214
215                 /* End-of-directory dentry on disk. */
216                 *subdir_offset_p += 8;
217
218                 /* Recursively call calculate_subdir_offsets() on all the
219                  * children. */
220                 do {
221                         calculate_subdir_offsets(child, subdir_offset_p);
222                         child = child->next;
223                 } while (child != dentry->children);
224         } else {
225                 /* On disk, childless directories have a valid subdir_offset
226                  * that points to an 8-byte end-of-directory dentry.  Regular
227                  * files have a subdir_offset of 0. */
228                 if (dentry_is_directory(dentry))
229                         *subdir_offset_p += 8;
230                 else
231                         dentry->subdir_offset = 0;
232         }
233 }
234
235
236 /* Returns the child of @dentry that has the file name @name.  
237  * Returns NULL if no child has the name. */
238 struct dentry *get_dentry_child_with_name(const struct dentry *dentry, 
239                                                         const char *name)
240 {
241         struct dentry *child;
242         size_t name_len;
243         
244         child = dentry->children;
245         if (child) {
246                 name_len = strlen(name);
247                 do {
248                         if (dentry_has_name(child, name, name_len))
249                                 return child;
250                         child = child->next;
251                 } while (child != dentry->children);
252         }
253         return NULL;
254 }
255
256 /* Retrieves the dentry that has the UTF-8 @path relative to the dentry
257  * @cur_dir.  Returns NULL if no dentry having the path is found. */
258 static struct dentry *get_dentry_relative_path(struct dentry *cur_dir, const char *path)
259 {
260         struct dentry *child;
261         size_t base_len;
262         const char *new_path;
263
264         if (*path == '\0')
265                 return cur_dir;
266
267         child = cur_dir->children;
268         if (child) {
269                 new_path = path_next_part(path, &base_len);
270                 do {
271                         if (dentry_has_name(child, path, base_len))
272                                 return get_dentry_relative_path(child, new_path);
273                         child = child->next;
274                 } while (child != cur_dir->children);
275         }
276         return NULL;
277 }
278
279 /* Returns the dentry corresponding to the UTF-8 @path, or NULL if there is no
280  * such dentry. */
281 struct dentry *get_dentry(WIMStruct *w, const char *path)
282 {
283         struct dentry *root = wim_root_dentry(w);
284         while (*path == '/')
285                 path++;
286         return get_dentry_relative_path(root, path);
287 }
288
289 /* Returns the parent directory for the @path. */
290 struct dentry *get_parent_dentry(WIMStruct *w, const char *path)
291 {
292         size_t path_len = strlen(path);
293         char buf[path_len + 1];
294
295         memcpy(buf, path, path_len + 1);
296
297         to_parent_name(buf, path_len);
298
299         return get_dentry(w, buf);
300 }
301
302 /* Prints the full path of a dentry. */
303 int print_dentry_full_path(struct dentry *dentry, void *ignore)
304 {
305         if (dentry->full_path_utf8)
306                 puts(dentry->full_path_utf8);
307         return 0;
308 }
309
310 /* Prints a directory entry.  @lookup_table is a pointer to the lookup table, or
311  * NULL if the resource entry for the dentry is not to be printed. */
312 int print_dentry(struct dentry *dentry, void *lookup_table)
313 {
314         struct lookup_table_entry *lte;
315         printf("[DENTRY]\n");
316         printf("Length            = %"PRIu64"\n", dentry->length);
317         printf("Attributes        = 0x%x\n", dentry->attributes);
318 #ifdef ENABLE_SECURITY_DATA
319         printf("Security ID       = %d\n", dentry->security_id);
320 #endif
321         printf("Subdir offset     = %"PRIu64"\n", dentry->subdir_offset);
322         /*printf("Unused1           = %"PRIu64"\n", dentry->unused1);*/
323         /*printf("Unused2           = %"PRIu64"\n", dentry->unused2);*/
324         printf("Creation Time     = %"PRIu64"\n", dentry->creation_time);
325         printf("Last Access Time  = %"PRIu64"\n", dentry->last_access_time);
326         printf("Last Write Time   = %"PRIu64"\n", dentry->last_write_time);
327         printf("Creation Time     = 0x%"PRIx64"\n", dentry->creation_time);
328         printf("Hash              = "); 
329         print_hash(dentry->hash); 
330         putchar('\n');
331         /*printf("Reparse Tag       = %u\n", dentry->reparse_tag);*/
332         printf("Hard Link Group   = %"PRIu64"\n", dentry->hard_link);
333         /*printf("Number of Streams = %hu\n", dentry->streams);*/
334         printf("Filename          = \"");
335         print_string(dentry->file_name, dentry->file_name_len);
336         puts("\"");
337         printf("Filename Length   = %hu\n", dentry->file_name_len);
338         printf("Filename (UTF-8)  = \"%s\"\n", dentry->file_name_utf8);
339         printf("Filename (UTF-8) Length = %hu\n", dentry->file_name_utf8_len);
340         printf("Short Name        = \"");
341         print_string(dentry->short_name, dentry->short_name_len);
342         puts("\"");
343         printf("Short Name Length = %hu\n", dentry->short_name_len);
344         printf("Full Path (UTF-8) = \"%s\"\n", dentry->full_path_utf8);
345         if (lookup_table) {
346                 lte = lookup_resource(lookup_table, dentry->hash);
347                 if (lte)
348                         print_lookup_table_entry(lte, NULL);
349                 else
350                         putchar('\n');
351         } else {
352                 putchar('\n');
353         }
354         return 0;
355 }
356
357 static inline void dentry_common_init(struct dentry *dentry)
358 {
359         memset(dentry, 0, sizeof(struct dentry));
360         dentry->refcnt = 1;
361 #ifdef ENABLE_SECURITY_DATA
362         dentry->security_id = -1;
363 #endif
364 }
365
366 /* 
367  * Creates an unlinked directory entry.
368  *
369  * @name:    The base name of the new dentry.
370  * @return:  A pointer to the new dentry, or NULL if out of memory.
371  */
372 struct dentry *new_dentry(const char *name)
373 {
374         struct dentry *dentry;
375         
376         dentry = MALLOC(sizeof(struct dentry));
377         if (!dentry)
378                 return NULL;
379
380         dentry_common_init(dentry);
381         if (change_dentry_name(dentry, name) != 0) {
382                 FREE(dentry);
383                 return NULL;
384         }
385
386         dentry_update_all_timestamps(dentry);
387         dentry->next   = dentry;
388         dentry->prev   = dentry;
389         dentry->parent = dentry;
390         return dentry;
391 }
392
393
394 void free_dentry(struct dentry *dentry)
395 {
396         FREE(dentry->file_name);
397         FREE(dentry->file_name_utf8);
398         FREE(dentry->short_name);
399         FREE(dentry->full_path_utf8);
400         FREE(dentry);
401 }
402
403 /* Arguments for do_free_dentry(). */
404 struct free_dentry_args {
405         struct lookup_table *lookup_table;
406         bool decrement_refcnt;
407 };
408
409 /* 
410  * This function is passed as an argument to for_dentry_in_tree_depth() in order
411  * to free a directory tree.  __args is a pointer to a `struct free_dentry_args'.
412  */
413 static int do_free_dentry(struct dentry *dentry, void *__args)
414 {
415         struct free_dentry_args *args = (struct free_dentry_args*)__args;
416
417         if (args->decrement_refcnt && !dentry_is_directory(dentry)) {
418                 lookup_table_decrement_refcnt(args->lookup_table, 
419                                               dentry->hash);
420         }
421
422         wimlib_assert(dentry->refcnt >= 1);
423         if (--dentry->refcnt == 0)
424                 free_dentry(dentry);
425         return 0;
426 }
427
428 /* 
429  * Unlinks and frees a dentry tree.
430  *
431  * @root:               The root of the tree.
432  * @lookup_table:       The lookup table for dentries.
433  * @decrement_refcnt:   True if the dentries in the tree are to have their 
434  *                      reference counts in the lookup table decremented.
435  */
436 void free_dentry_tree(struct dentry *root, struct lookup_table *lookup_table, 
437                       bool decrement_refcnt)
438 {
439         if (!root || !root->parent)
440                 return;
441
442         struct free_dentry_args args;
443         args.lookup_table        = lookup_table;
444         args.decrement_refcnt    = decrement_refcnt;
445         for_dentry_in_tree_depth(root, do_free_dentry, &args);
446 }
447
448 int increment_dentry_refcnt(struct dentry *dentry, void *ignore)
449 {
450         dentry->refcnt++;
451         return 0;
452 }
453
454 /* 
455  * Links a dentry into the directory tree.
456  *
457  * @dentry: The dentry to link.
458  * @parent: The dentry that will be the parent of @dentry.
459  */
460 void link_dentry(struct dentry *dentry, struct dentry *parent)
461 {
462         dentry->parent = parent;
463         if (parent->children) {
464                 /* Not an only child; link to siblings. */
465                 dentry->next = parent->children;
466                 dentry->prev = parent->children->prev;
467                 dentry->next->prev = dentry;
468                 dentry->prev->next = dentry;
469         } else {
470                 /* Only child; link to parent. */
471                 parent->children = dentry;
472                 dentry->next = dentry;
473                 dentry->prev = dentry;
474         }
475 }
476
477 /* Unlink a dentry from the directory tree. */
478 void unlink_dentry(struct dentry *dentry)
479 {
480         if (dentry_is_root(dentry))
481                 return;
482         if (dentry_is_only_child(dentry)) {
483                 dentry->parent->children = NULL;
484         } else {
485                 if (dentry_is_first_sibling(dentry))
486                         dentry->parent->children = dentry->next;
487                 dentry->next->prev = dentry->prev;
488                 dentry->prev->next = dentry->next;
489         }
490 }
491
492
493 /* Recalculates the length of @dentry based on its file name length and short
494  * name length.  */
495 static inline void recalculate_dentry_size(struct dentry *dentry)
496 {
497         dentry->length = WIM_DENTRY_DISK_SIZE + dentry->file_name_len + 
498                          2 + dentry->short_name_len;
499         /* Must be multiple of 8. */
500         dentry->length += (8 - dentry->length % 8) % 8;
501 }
502
503 /* Changes the name of a dentry to @new_name.  Only changes the file_name and
504  * file_name_utf8 fields; does not change the short_name, short_name_utf8, or
505  * full_path_utf8 fields.  Also recalculates its length. */
506 int change_dentry_name(struct dentry *dentry, const char *new_name)
507 {
508         size_t utf8_len;
509         size_t utf16_len;
510
511         FREE(dentry->file_name);
512
513         utf8_len = strlen(new_name);
514
515         dentry->file_name = utf8_to_utf16(new_name, utf8_len, &utf16_len);
516
517         if (!dentry->file_name)
518                 return WIMLIB_ERR_NOMEM;
519
520         FREE(dentry->file_name_utf8);
521         dentry->file_name_utf8 = MALLOC(utf8_len + 1);
522         if (!dentry->file_name_utf8) {
523                 FREE(dentry->file_name);
524                 dentry->file_name = NULL;
525                 return WIMLIB_ERR_NOMEM;
526         }
527
528         dentry->file_name_len = utf16_len;
529         dentry->file_name_utf8_len = utf8_len;
530         memcpy(dentry->file_name_utf8, new_name, utf8_len + 1);
531         recalculate_dentry_size(dentry);
532         return 0;
533 }
534
535 /* Parameters for calculate_dentry_statistics(). */
536 struct image_statistics {
537         struct lookup_table *lookup_table;
538         u64 *dir_count;
539         u64 *file_count;
540         u64 *total_bytes;
541         u64 *hard_link_bytes;
542 };
543
544 static int calculate_dentry_statistics(struct dentry *dentry, void *arg)
545 {
546         struct image_statistics *stats;
547         struct lookup_table_entry *lte; 
548         
549         stats = arg;
550         lte = lookup_resource(stats->lookup_table, dentry->hash);
551
552         if (dentry_is_directory(dentry) && !dentry_is_root(dentry))
553                 ++*stats->dir_count;
554         else
555                 ++*stats->file_count;
556
557         if (lte) {
558                 u64 size = lte->resource_entry.original_size;
559                 *stats->total_bytes += size;
560                 if (++lte->out_refcnt == 1)
561                         *stats->hard_link_bytes += size;
562         }
563         return 0;
564 }
565
566 void calculate_dir_tree_statistics(struct dentry *root, struct lookup_table *table, 
567                                    u64 *dir_count_ret, u64 *file_count_ret, 
568                                    u64 *total_bytes_ret, 
569                                    u64 *hard_link_bytes_ret)
570 {
571         struct image_statistics stats;
572         *dir_count_ret         = 0;
573         *file_count_ret        = 0;
574         *total_bytes_ret       = 0;
575         *hard_link_bytes_ret   = 0;
576         stats.lookup_table     = table;
577         stats.dir_count       = dir_count_ret;
578         stats.file_count      = file_count_ret;
579         stats.total_bytes     = total_bytes_ret;
580         stats.hard_link_bytes = hard_link_bytes_ret;
581         for_lookup_table_entry(table, zero_out_refcnts, NULL);
582         for_dentry_in_tree(root, calculate_dentry_statistics, &stats);
583 }
584
585 /* 
586  * Reads a directory entry from the metadata resource.
587  */
588 int read_dentry(const u8 metadata_resource[], u64 metadata_resource_len, 
589                                         u64 offset, struct dentry *dentry)
590 {
591         const u8 *p;
592         u64 calculated_size;
593         char *file_name;
594         char *file_name_utf8;
595         char *short_name;
596         u16 short_name_len;
597         u16 file_name_len;
598         size_t file_name_utf8_len;
599
600         dentry_common_init(dentry);
601
602         /*Make sure the dentry really fits into the metadata resource.*/
603         if (offset + 8 > metadata_resource_len) {
604                 ERROR("Directory entry starting at %"PRIu64" ends past the "
605                         "end of the metadata resource (size %"PRIu64")!\n",
606                         offset, metadata_resource_len);
607                 return WIMLIB_ERR_INVALID_DENTRY;
608         }
609
610         /* Before reading the whole entry, we need to read just the length.
611          * This is because an entry of length 8 (that is, just the length field)
612          * terminates the list of sibling directory entries. */
613
614         p = get_u64(&metadata_resource[offset], &dentry->length);
615
616         /* A zero length field (really a length of 8, since that's how big the
617          * directory entry is...) indicates that this is the end of directory
618          * dentry.  We do not read it into memory as an actual dentry, so just
619          * return true in that case. */
620         if (dentry->length == 0)
621                 return 0;
622
623         if (offset + dentry->length >= metadata_resource_len) {
624                 ERROR("Directory entry at offset %"PRIu64" and with size "
625                                 "%"PRIu64" ends past the end of the metadata resource "
626                                 "(size %"PRIu64")!\n", offset, dentry->length,
627                                 metadata_resource_len);
628                 return WIMLIB_ERR_INVALID_DENTRY;
629         }
630
631         /* If it is a recognized length, read the rest of the directory entry.
632          * Note: The root directory entry has no name, and its length does not
633          * include the short name length field.  */
634         if (dentry->length < WIM_DENTRY_DISK_SIZE) {
635                 ERROR("Directory entry has invalid length of "
636                                 "%"PRIu64" bytes\n", dentry->length);
637                 return WIMLIB_ERR_INVALID_DENTRY;
638         }
639
640         p = get_u32(p, &dentry->attributes);
641 #ifdef ENABLE_SECURITY_DATA
642         p = get_u32(p, &dentry->security_id);
643 #else
644         p += sizeof(u32);
645 #endif
646         p = get_u64(p, &dentry->subdir_offset);
647
648         /* 2 unused fields */
649         p += 2 * sizeof(u64);
650
651         p = get_u64(p, &dentry->creation_time);
652         p = get_u64(p, &dentry->last_access_time);
653         p = get_u64(p, &dentry->last_write_time);
654
655         p = get_bytes(p, WIM_HASH_SIZE, dentry->hash);
656         
657         /* Currently ignoring reparse_tag. */
658         p += sizeof(u32);
659
660         /* The reparse_reserved field does not actually exist. */
661
662         p = get_u64(p, &dentry->hard_link);
663         
664         /* Currently ignoring streams. */
665         p += sizeof(u16);
666
667         p = get_u16(p, &short_name_len);
668         p = get_u16(p, &file_name_len);
669
670         calculated_size = WIM_DENTRY_DISK_SIZE + file_name_len + 2 +
671                           short_name_len;
672
673         if (dentry->length < calculated_size) {
674                 ERROR("Unexpected end of directory entry! (Expected "
675                                 "%"PRIu64" bytes, got %"PRIu64" bytes. "
676                                 "short_name_len = %hu, file_name_len = %hu)\n", 
677                                 calculated_size, dentry->length,
678                                 short_name_len, file_name_len);
679                 return WIMLIB_ERR_INVALID_DENTRY;
680         }
681
682         /* Read the filename. */
683         file_name = MALLOC(file_name_len);
684         if (!file_name) {
685                 ERROR("Failed to allocate %hu bytes for dentry file name!\n",
686                                 file_name_len);
687                 return WIMLIB_ERR_NOMEM;
688         }
689         p = get_bytes(p, file_name_len, file_name);
690
691         /* Convert filename to UTF-8. */
692         file_name_utf8 = utf16_to_utf8(file_name, file_name_len, 
693                                        &file_name_utf8_len);
694
695         if (!file_name_utf8) {
696                 ERROR("Failed to allocate memory to convert UTF16 "
697                                 "filename (%hu bytes) to UTF8\n",
698                                 file_name_len);
699                 goto err_nomem2;
700         }
701
702         /* Undocumented padding between file name and short name.  This probably
703          * is supposed to be a terminating NULL character. */
704         p += 2;
705
706         /* Read the short filename. */
707         short_name = MALLOC(short_name_len);
708         if (!short_name) {
709                 ERROR("Failed to allocate %hu bytes for short filename\n",
710                                 short_name_len);
711                 goto err_nomem1;
712         }
713
714         get_bytes(p, short_name_len, short_name);
715
716         dentry->file_name          = file_name;
717         dentry->file_name_utf8     = file_name_utf8;
718         dentry->short_name         = short_name;
719         dentry->file_name_len      = file_name_len;
720         dentry->file_name_utf8_len = file_name_utf8_len;
721         dentry->short_name_len     = short_name_len;
722         return 0;
723 err_nomem1:
724         FREE(dentry->file_name_utf8);
725 err_nomem2:
726         FREE(dentry->file_name);
727         return WIMLIB_ERR_NOMEM;
728 }
729
730 /* 
731  * Writes a dentry to an output buffer.
732  *
733  * @dentry:  The dentry structure.
734  * @p:       The memory location to write the data to.
735  * @return:  True on success, false on failure.
736  */
737 static u8 *write_dentry(const struct dentry *dentry, u8 *p)
738 {
739         u8 *orig_p = p;
740         memset(p, 0, dentry->length);
741         p = put_u64(p, dentry->length);
742         p = put_u32(p, dentry->attributes);
743 #ifdef ENABLE_SECURITY_DATA
744         p = put_u32(p, dentry->security_id);
745 #else
746         p = put_u32(p, (u32)(-1));
747 #endif
748         p = put_u64(p, dentry->subdir_offset);
749         p = put_u64(p, 0); /* unused1 */
750         p = put_u64(p, 0); /* unused2 */
751         p = put_u64(p, dentry->creation_time);
752         p = put_u64(p, dentry->last_access_time);
753         p = put_u64(p, dentry->last_write_time);
754         if (!is_empty_file_hash(dentry->hash))
755                 memcpy(p, dentry->hash, WIM_HASH_SIZE);
756         else
757                 printf("zero hash for %s\n", dentry->file_name_utf8);
758         p += WIM_HASH_SIZE;
759         p = put_u32(p, 0); /* reparse_tag */
760         p = put_u64(p, dentry->hard_link);
761         p = put_u16(p, 0); /*streams */
762         p = put_u16(p, dentry->short_name_len);
763         p = put_u16(p, dentry->file_name_len);
764         p = put_bytes(p, dentry->file_name_len, (u8*)dentry->file_name);
765         p = put_u16(p, 0); /* filename padding, 2 bytes. */
766         p = put_bytes(p, dentry->short_name_len, (u8*)dentry->short_name);
767         return orig_p + dentry->length;
768 }
769
770 /* Recursive function that writes a dentry tree rooted at @tree, not including
771  * @tree itself, which has already been written, except in the case of the root
772  * dentry, which is written right away, along with an end-of-directory entry. */
773 u8 *write_dentry_tree(const struct dentry *tree, u8 *p)
774 {
775         const struct dentry *child;
776
777         if (dentry_is_root(tree)) {
778                 p = write_dentry(tree, p);
779
780                 /* write end of directory entry */
781                 p = put_u64(p, 0);
782         } else {
783                 /* Nothing to do for a regular file. */
784                 if (dentry_is_regular_file(tree))
785                         return p;
786         }
787
788         /* Write child dentries and end-of-directory entry. */
789         child = tree->children;
790         if (child) {
791                 do {
792                         p = write_dentry(child, p);
793                         child = child->next;
794                 } while (child != tree->children);
795         }
796
797         /* write end of directory entry */
798         p = put_u64(p, 0);
799
800         /* Recurse on children. */
801         if (child) {
802                 do {
803                         p = write_dentry_tree(child, p);
804                         child = child->next;
805                 } while (child != tree->children);
806         }
807         return p;
808 }
809
810 /* Reads the children of a dentry, and all their children, ..., etc. from the
811  * metadata resource and into the dentry tree.
812  *
813  * @metadata_resource:  An array that contains the uncompressed metadata
814  *                              resource for the WIM file.
815  * @metadata_resource_len:      The length of @metadata_resource.
816  * @dentry:     A pointer to a struct dentry that is the root of the directory tree
817  *              and has already been read from the metadata resource.  It does not 
818  *              need to be the real root, because this procedure is called 
819  *              recursively.
820  * @return:     True on success, false on failure. 
821  */
822 int read_dentry_tree(const u8 metadata_resource[], u64 metadata_resource_len,
823                      struct dentry *dentry)
824 {
825         u64 cur_offset = dentry->subdir_offset;
826         struct dentry *prev_child = NULL;
827         struct dentry *first_child = NULL;
828         struct dentry *child;
829         struct dentry cur_child;
830         int ret;
831
832         /* If @dentry is a regular file, nothing more needs to be done for this
833          * branch. */
834         if (cur_offset == 0)
835                 return 0;
836
837         /* Find and read all the children of @dentry. */
838         while (1) {
839
840                 /* Read next child of @dentry into @cur_child. */
841                 ret = read_dentry(metadata_resource, metadata_resource_len, 
842                                   cur_offset, &cur_child);
843                 if (ret != 0)
844                         break;
845
846                 /* Check for end of directory. */
847                 if (cur_child.length == 0) {
848                         ret = 0;
849                         break;
850                 }
851
852                 /* Not end of directory.  Allocate this child permanently and
853                  * link it to the parent and previous child. */
854                 child = MALLOC(sizeof(struct dentry));
855                 if (!child) {
856                         ERROR("Failed to allocate %zu bytes for new dentry!\n",
857                                         sizeof(struct dentry));
858                         ret = WIMLIB_ERR_NOMEM;
859                         break;
860                 }
861                 memcpy(child, &cur_child, sizeof(struct dentry));
862
863                 if (prev_child) {
864                         prev_child->next = child;
865                         child->prev = prev_child;
866                 } else {
867                         first_child = child;
868                 }
869
870                 child->parent = dentry;
871                 prev_child = child;
872
873                 /* If there are children of this child, call this procedure
874                  * recursively. */
875                 if (child->subdir_offset != 0) {
876                         ret = read_dentry_tree(metadata_resource, 
877                                                metadata_resource_len, child);
878                         if (ret != 0)
879                                 break;
880                 }
881
882                 /* Advance to the offset of the next child. */
883                 cur_offset += child->length;
884         }
885
886         /* Link last child to first one, and set parent's
887          * children pointer to the first child.  */
888         if (prev_child) {
889                 prev_child->next = first_child;
890                 first_child->prev = prev_child;
891         }
892         dentry->children = first_child;
893         return ret;
894 }