]> wimlib.net Git - wimlib/blob - src/xml.c
New compression/decompression API
[wimlib] / src / xml.c
1 /*
2  * xml.c
3  *
4  * Deals with the XML information in WIM files.  Uses the C library libxml2.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "wimlib/dentry.h"
31 #include "wimlib/encoding.h"
32 #include "wimlib/error.h"
33 #include "wimlib/file_io.h"
34 #include "wimlib/lookup_table.h"
35 #include "wimlib/metadata.h"
36 #include "wimlib/resource.h"
37 #include "wimlib/timestamp.h"
38 #include "wimlib/xml.h"
39 #include "wimlib/write.h"
40
41 #include <libxml/encoding.h>
42 #include <libxml/parser.h>
43 #include <libxml/tree.h>
44 #include <libxml/xmlwriter.h>
45 #include <limits.h>
46 #include <string.h>
47 #include <unistd.h>
48
49 /* Structures used to form an in-memory representation of the XML data (other
50  * than the raw parse tree from libxml). */
51
52 struct windows_version {
53         u64 major;
54         u64 minor;
55         u64 build;
56         u64 sp_build;
57         u64 sp_level;
58 };
59
60 struct windows_info {
61         u64      arch;
62         tchar   *product_name;
63         tchar   *edition_id;
64         tchar   *installation_type;
65         tchar   *hal;
66         tchar   *product_type;
67         tchar   *product_suite;
68         tchar  **languages;
69         tchar   *default_language;
70         size_t   num_languages;
71         tchar   *system_root;
72         bool     windows_version_exists;
73         struct   windows_version windows_version;
74 };
75
76 struct image_info {
77         int index;
78         bool windows_info_exists;
79         u64 dir_count;
80         u64 file_count;
81         u64 total_bytes;
82         u64 hard_link_bytes;
83         u64 creation_time;
84         u64 last_modification_time;
85         struct windows_info windows_info;
86         tchar *name;
87         tchar *description;
88         tchar *display_name;
89         tchar *display_description;
90         tchar *flags;
91         struct wim_lookup_table *lookup_table; /* temporary field */
92 };
93
94 /* A struct wim_info structure corresponds to the entire XML data for a WIM file. */
95 struct wim_info {
96         u64 total_bytes;
97         int num_images;
98         /* Array of `struct image_info's, one for each image in the WIM that is
99          * mentioned in the XML data. */
100         struct image_info *images;
101 };
102
103 struct xml_string_spec {
104         const char *name;
105         size_t offset;
106 };
107
108 #define ELEM(STRING_NAME, MEMBER_NAME) \
109         {STRING_NAME, offsetof(struct image_info, MEMBER_NAME)}
110 static const struct xml_string_spec
111 image_info_xml_string_specs[] = {
112         ELEM("NAME", name),
113         ELEM("DESCRIPTION", description),
114         ELEM("DISPLAYNAME", display_name),
115         ELEM("DISPLAYDESCRIPTION", display_description),
116         ELEM("FLAGS", flags),
117 };
118 #undef ELEM
119
120 #define ELEM(STRING_NAME, MEMBER_NAME) \
121         {STRING_NAME, offsetof(struct windows_info, MEMBER_NAME)}
122 static const struct xml_string_spec
123 windows_info_xml_string_specs[] = {
124         ELEM("PRODUCTNAME", product_name),
125         ELEM("EDITIONID", edition_id),
126         ELEM("INSTALLATIONTYPE", installation_type),
127         ELEM("HAL", hal),
128         ELEM("PRODUCTTYPE", product_type),
129         ELEM("PRODUCTSUITE", product_suite),
130 };
131 #undef ELEM
132
133 u64
134 wim_info_get_total_bytes(const struct wim_info *info)
135 {
136         if (info)
137                 return info->total_bytes;
138         else
139                 return 0;
140 }
141
142 u64
143 wim_info_get_image_hard_link_bytes(const struct wim_info *info, int image)
144 {
145         if (info)
146                 return info->images[image - 1].hard_link_bytes;
147         else
148                 return 0;
149 }
150
151 u64
152 wim_info_get_image_total_bytes(const struct wim_info *info, int image)
153 {
154         if (info)
155                 return info->images[image - 1].total_bytes;
156         else
157                 return 0;
158 }
159
160 unsigned
161 wim_info_get_num_images(const struct wim_info *info)
162 {
163         if (info)
164                 return info->num_images;
165         else
166                 return 0;
167 }
168
169 /* Architecture constants are from w64 mingw winnt.h  */
170 #define PROCESSOR_ARCHITECTURE_INTEL 0
171 #define PROCESSOR_ARCHITECTURE_MIPS 1
172 #define PROCESSOR_ARCHITECTURE_ALPHA 2
173 #define PROCESSOR_ARCHITECTURE_PPC 3
174 #define PROCESSOR_ARCHITECTURE_SHX 4
175 #define PROCESSOR_ARCHITECTURE_ARM 5
176 #define PROCESSOR_ARCHITECTURE_IA64 6
177 #define PROCESSOR_ARCHITECTURE_ALPHA64 7
178 #define PROCESSOR_ARCHITECTURE_MSIL 8
179 #define PROCESSOR_ARCHITECTURE_AMD64 9
180 #define PROCESSOR_ARCHITECTURE_IA32_ON_WIN64 10
181
182 /* Returns a statically allocated string that is a string representation of the
183  * architecture number. */
184 static const tchar *
185 get_arch(int arch)
186 {
187         switch (arch) {
188         case PROCESSOR_ARCHITECTURE_INTEL:
189                 return T("x86");
190         case PROCESSOR_ARCHITECTURE_MIPS:
191                 return T("MIPS");
192         case PROCESSOR_ARCHITECTURE_ARM:
193                 return T("ARM");
194         case PROCESSOR_ARCHITECTURE_IA64:
195                 return T("ia64");
196         case PROCESSOR_ARCHITECTURE_AMD64:
197                 return T("x86_64");
198         default:
199                 return T("unknown");
200         }
201 }
202
203
204 /* Iterate through the children of an xmlNode. */
205 #define for_node_child(parent, child)   \
206         for (child = parent->children; child != NULL; child = child->next)
207
208 /* Utility functions for xmlNodes */
209 static inline bool
210 node_is_element(xmlNode *node)
211 {
212         return node->type == XML_ELEMENT_NODE;
213 }
214
215 static inline bool
216 node_is_text(xmlNode *node)
217 {
218         return node->type == XML_TEXT_NODE;
219 }
220
221 static inline bool
222 node_name_is(xmlNode *node, const char *name)
223 {
224         /* For now, both upper case and lower case element names are accepted. */
225         return strcasecmp((const char *)node->name, name) == 0;
226 }
227
228 static u64
229 node_get_number(const xmlNode *u64_node, int base)
230 {
231         xmlNode *child;
232         for_node_child(u64_node, child)
233                 if (node_is_text(child))
234                         return strtoull(child->content, NULL, base);
235         return 0;
236 }
237
238 /* Finds the text node that is a child of an element node and returns its
239  * content converted to a 64-bit unsigned integer.  Returns 0 if no text node is
240  * found. */
241 static u64
242 node_get_u64(const xmlNode *u64_node)
243 {
244         return node_get_number(u64_node, 10);
245 }
246
247 /* Like node_get_u64(), but expects a number in base 16. */
248 static u64
249 node_get_hex_u64(const xmlNode *u64_node)
250 {
251         return node_get_number(u64_node, 16);
252 }
253
254 static int
255 node_get_string(const xmlNode *string_node, tchar **tstr_ret)
256 {
257         xmlNode *child;
258         tchar *tstr = NULL;
259         int ret;
260
261         for_node_child(string_node, child) {
262                 if (node_is_text(child) && child->content) {
263                         ret = utf8_to_tstr_simple(child->content, &tstr);
264                         if (ret)
265                                 return ret;
266                         break;
267                 }
268         }
269         *tstr_ret = tstr;
270         return 0;
271 }
272
273 /* Returns the timestamp from a time node.  It has child elements <HIGHPART> and
274  * <LOWPART> that are then used to construct a 64-bit timestamp. */
275 static u64
276 node_get_timestamp(const xmlNode *time_node)
277 {
278         u32 high_part = 0;
279         u32 low_part = 0;
280         xmlNode *child;
281         for_node_child(time_node, child) {
282                 if (!node_is_element(child))
283                         continue;
284                 if (node_name_is(child, "HIGHPART"))
285                         high_part = node_get_hex_u64(child);
286                 else if (node_name_is(child, "LOWPART"))
287                         low_part = node_get_hex_u64(child);
288         }
289         return (u64)low_part | ((u64)high_part << 32);
290 }
291
292 /* Used to sort an array of struct image_infos by their image indices. */
293 static int
294 sort_by_index(const void *p1, const void *p2)
295 {
296         int index_1 = ((const struct image_info*)p1)->index;
297         int index_2 = ((const struct image_info*)p2)->index;
298         if (index_1 < index_2)
299                 return -1;
300         else if (index_1 > index_2)
301                 return 1;
302         else
303                 return 0;
304 }
305
306
307 /* Frees memory allocated inside a struct windows_info structure. */
308 static void
309 destroy_windows_info(struct windows_info *windows_info)
310 {
311         FREE(windows_info->product_name);
312         FREE(windows_info->edition_id);
313         FREE(windows_info->installation_type);
314         FREE(windows_info->hal);
315         FREE(windows_info->product_type);
316         FREE(windows_info->product_suite);
317         for (size_t i = 0; i < windows_info->num_languages; i++)
318                 FREE(windows_info->languages[i]);
319         FREE(windows_info->languages);
320         FREE(windows_info->default_language);
321         FREE(windows_info->system_root);
322 }
323
324 /* Frees memory allocated inside a struct image_info structure. */
325 static void
326 destroy_image_info(struct image_info *image_info)
327 {
328         FREE(image_info->name);
329         FREE(image_info->description);
330         FREE(image_info->flags);
331         FREE(image_info->display_name);
332         FREE(image_info->display_description);
333         destroy_windows_info(&image_info->windows_info);
334         memset(image_info, 0, sizeof(struct image_info));
335 }
336
337 void
338 free_wim_info(struct wim_info *info)
339 {
340         if (info) {
341                 if (info->images) {
342                         for (int i = 0; i < info->num_images; i++)
343                                 destroy_image_info(&info->images[i]);
344                         FREE(info->images);
345                 }
346                 FREE(info);
347         }
348 }
349
350 /* Reads the information from a <VERSION> element inside the <WINDOWS> element.
351  * */
352 static void
353 xml_read_windows_version(const xmlNode *version_node,
354                          struct windows_version* windows_version)
355 {
356         xmlNode *child;
357         for_node_child(version_node, child) {
358                 if (!node_is_element(child))
359                         continue;
360                 if (node_name_is(child, "MAJOR"))
361                         windows_version->major = node_get_u64(child);
362                 else if (node_name_is(child, "MINOR"))
363                         windows_version->minor = node_get_u64(child);
364                 else if (node_name_is(child, "BUILD"))
365                         windows_version->build = node_get_u64(child);
366                 else if (node_name_is(child, "SPBUILD"))
367                         windows_version->sp_build = node_get_u64(child);
368                 else if (node_name_is(child, "SPLEVEL"))
369                         windows_version->sp_level = node_get_u64(child);
370         }
371 }
372
373 /* Reads the information from a <LANGUAGE> element inside a <WINDOWS> element.
374  * */
375 static int
376 xml_read_languages(const xmlNode *languages_node,
377                    tchar ***languages_ret,
378                    size_t *num_languages_ret,
379                    tchar **default_language_ret)
380 {
381         xmlNode *child;
382         size_t num_languages = 0;
383         tchar **languages;
384         int ret;
385
386         for_node_child(languages_node, child)
387                 if (node_is_element(child) && node_name_is(child, "LANGUAGE"))
388                         num_languages++;
389
390         languages = CALLOC(num_languages, sizeof(languages[0]));
391         if (!languages)
392                 return WIMLIB_ERR_NOMEM;
393
394         *languages_ret = languages;
395         *num_languages_ret = num_languages;
396
397         ret = 0;
398         for_node_child(languages_node, child) {
399                 if (!node_is_element(child))
400                         continue;
401                 if (node_name_is(child, "LANGUAGE"))
402                         ret = node_get_string(child, languages++);
403                 else if (node_name_is(child, "DEFAULT"))
404                         ret = node_get_string(child, default_language_ret);
405                 if (ret != 0)
406                         break;
407         }
408         return ret;
409 }
410
411 /* Reads the information from a <WINDOWS> element inside an <IMAGE> element. */
412 static int
413 xml_read_windows_info(const xmlNode *windows_node,
414                       struct windows_info *windows_info)
415 {
416         xmlNode *child;
417         int ret = 0;
418
419         for_node_child(windows_node, child) {
420                 if (!node_is_element(child))
421                         continue;
422                 if (node_name_is(child, "ARCH")) {
423                         windows_info->arch = node_get_u64(child);
424                 } else if (node_name_is(child, "PRODUCTNAME")) {
425                         ret = node_get_string(child,
426                                               &windows_info->product_name);
427                 } else if (node_name_is(child, "EDITIONID")) {
428                         ret = node_get_string(child,
429                                               &windows_info->edition_id);
430                 } else if (node_name_is(child, "INSTALLATIONTYPE")) {
431                         ret = node_get_string(child,
432                                               &windows_info->installation_type);
433                 } else if (node_name_is(child, "PRODUCTTYPE")) {
434                         ret = node_get_string(child,
435                                               &windows_info->product_type);
436                 } else if (node_name_is(child, "PRODUCTSUITE")) {
437                         ret = node_get_string(child,
438                                               &windows_info->product_suite);
439                 } else if (node_name_is(child, "LANGUAGES")) {
440                         ret = xml_read_languages(child,
441                                                  &windows_info->languages,
442                                                  &windows_info->num_languages,
443                                                  &windows_info->default_language);
444                 } else if (node_name_is(child, "VERSION")) {
445                         xml_read_windows_version(child,
446                                                 &windows_info->windows_version);
447                         windows_info->windows_version_exists = true;
448                 } else if (node_name_is(child, "SYSTEMROOT")) {
449                         ret = node_get_string(child, &windows_info->system_root);
450                 } else if (node_name_is(child, "HAL")) {
451                         ret = node_get_string(child, &windows_info->hal);
452                 }
453                 if (ret != 0)
454                         return ret;
455         }
456         return ret;
457 }
458
459 /* Reads the information from an <IMAGE> element. */
460 static int
461 xml_read_image_info(xmlNode *image_node, struct image_info *image_info)
462 {
463         xmlNode *child;
464         xmlChar *index_prop;
465         int ret;
466
467         index_prop = xmlGetProp(image_node, "INDEX");
468         if (index_prop) {
469                 image_info->index = atoi(index_prop);
470                 FREE(index_prop);
471         } else {
472                 image_info->index = 1;
473         }
474
475         ret = 0;
476         for_node_child(image_node, child) {
477                 if (!node_is_element(child))
478                         continue;
479                 if (node_name_is(child, "DIRCOUNT"))
480                         image_info->dir_count = node_get_u64(child);
481                 else if (node_name_is(child, "FILECOUNT"))
482                         image_info->file_count = node_get_u64(child);
483                 else if (node_name_is(child, "TOTALBYTES"))
484                         image_info->total_bytes = node_get_u64(child);
485                 else if (node_name_is(child, "HARDLINKBYTES"))
486                         image_info->hard_link_bytes = node_get_u64(child);
487                 else if (node_name_is(child, "CREATIONTIME"))
488                         image_info->creation_time = node_get_timestamp(child);
489                 else if (node_name_is(child, "LASTMODIFICATIONTIME"))
490                         image_info->last_modification_time = node_get_timestamp(child);
491                 else if (node_name_is(child, "WINDOWS")) {
492                         DEBUG("Found <WINDOWS> tag");
493                         ret = xml_read_windows_info(child,
494                                                     &image_info->windows_info);
495                         image_info->windows_info_exists = true;
496                 } else if (node_name_is(child, "NAME")) {
497                         ret = node_get_string(child, &image_info->name);
498                 } else if (node_name_is(child, "DESCRIPTION")) {
499                         ret = node_get_string(child, &image_info->description);
500                 } else if (node_name_is(child, "FLAGS")) {
501                         ret = node_get_string(child, &image_info->flags);
502                 } else if (node_name_is(child, "DISPLAYNAME")) {
503                         ret = node_get_string(child, &image_info->display_name);
504                 } else if (node_name_is(child, "DISPLAYDESCRIPTION")) {
505                         ret = node_get_string(child, &image_info->display_description);
506                 }
507                 if (ret != 0)
508                         return ret;
509         }
510         if (!image_info->name) {
511                 tchar *empty_name;
512                 /*WARNING("Image with index %d has no name", image_info->index);*/
513                 empty_name = MALLOC(sizeof(tchar));
514                 if (!empty_name)
515                         return WIMLIB_ERR_NOMEM;
516                 *empty_name = T('\0');
517                 image_info->name = empty_name;
518         }
519         return ret;
520 }
521
522 /* Reads the information from a <WIM> element, which should be the root element
523  * of the XML tree. */
524 static int
525 xml_read_wim_info(const xmlNode *wim_node, struct wim_info **wim_info_ret)
526 {
527         struct wim_info *wim_info;
528         xmlNode *child;
529         int ret;
530         int num_images;
531         int i;
532
533         wim_info = CALLOC(1, sizeof(struct wim_info));
534         if (!wim_info)
535                 return WIMLIB_ERR_NOMEM;
536
537         /* Count how many images there are. */
538         num_images = 0;
539         for_node_child(wim_node, child) {
540                 if (node_is_element(child) && node_name_is(child, "IMAGE")) {
541                         if (num_images == INT_MAX) {
542                                 return WIMLIB_ERR_IMAGE_COUNT;
543                         }
544                         num_images++;
545                 }
546         }
547
548         if (num_images > 0) {
549                 /* Allocate the array of struct image_infos and fill them in. */
550                 wim_info->images = CALLOC(num_images, sizeof(wim_info->images[0]));
551                 if (!wim_info->images) {
552                         ret = WIMLIB_ERR_NOMEM;
553                         goto err;
554                 }
555                 wim_info->num_images = num_images;
556                 i = 0;
557                 for_node_child(wim_node, child) {
558                         if (!node_is_element(child))
559                                 continue;
560                         if (node_name_is(child, "IMAGE")) {
561                                 DEBUG("Found <IMAGE> tag");
562                                 ret = xml_read_image_info(child,
563                                                           &wim_info->images[i]);
564                                 if (ret != 0)
565                                         goto err;
566                                 i++;
567                         } else if (node_name_is(child, "TOTALBYTES")) {
568                                 wim_info->total_bytes = node_get_u64(child);
569                         }
570                 }
571
572                 /* Sort the array of image info by image index. */
573                 qsort(wim_info->images, num_images,
574                       sizeof(struct image_info), sort_by_index);
575
576                 /* Make sure the image indices make sense */
577                 for (i = 0; i < num_images; i++) {
578                         if (wim_info->images[i].index != i + 1) {
579                                 ERROR("WIM images are not indexed [1...%d] "
580                                       "in XML data as expected",
581                                       num_images);
582                                 return WIMLIB_ERR_IMAGE_COUNT;
583                         }
584                 }
585
586         }
587         *wim_info_ret = wim_info;
588         return 0;
589 err:
590         free_wim_info(wim_info);
591         return ret;
592 }
593
594 /* Prints the information contained in a `struct windows_info'.
595  *
596  * Warning: any strings printed here are in UTF-8 encoding.  If the locale
597  * character encoding is not UTF-8, the printed strings may be garbled. */
598 static void
599 print_windows_info(const struct windows_info *windows_info)
600 {
601         const struct windows_version *windows_version;
602
603         tprintf(T("Architecture:           %"TS"\n"),
604                 get_arch(windows_info->arch));
605
606         if (windows_info->product_name) {
607                 tprintf(T("Product Name:           %"TS"\n"),
608                         windows_info->product_name);
609         }
610
611         if (windows_info->edition_id) {
612                 tprintf(T("Edition ID:             %"TS"\n"),
613                         windows_info->edition_id);
614         }
615
616         if (windows_info->installation_type) {
617                 tprintf(T("Installation Type:      %"TS"\n"),
618                         windows_info->installation_type);
619         }
620
621         if (windows_info->hal) {
622                 tprintf(T("HAL:                    %"TS"\n"),
623                               windows_info->hal);
624         }
625
626         if (windows_info->product_type) {
627                 tprintf(T("Product Type:           %"TS"\n"),
628                         windows_info->product_type);
629         }
630
631         if (windows_info->product_suite) {
632                 tprintf(T("Product Suite:          %"TS"\n"),
633                         windows_info->product_suite);
634         }
635
636         tprintf(T("Languages:              "));
637         for (size_t i = 0; i < windows_info->num_languages; i++) {
638
639                 tfputs(windows_info->languages[i], stdout);
640                 tputchar(T(' '));
641         }
642         tputchar(T('\n'));
643         if (windows_info->default_language) {
644                 tprintf(T("Default Language:       %"TS"\n"),
645                         windows_info->default_language);
646         }
647         if (windows_info->system_root) {
648                 tprintf(T("System Root:            %"TS"\n"),
649                               windows_info->system_root);
650         }
651
652         if (windows_info->windows_version_exists) {
653                 windows_version = &windows_info->windows_version;
654                 tprintf(T("Major Version:          %"PRIu64"\n"),
655                         windows_version->major);
656                 tprintf(T("Minor Version:          %"PRIu64"\n"),
657                         windows_version->minor);
658                 tprintf(T("Build:                  %"PRIu64"\n"),
659                         windows_version->build);
660                 tprintf(T("Service Pack Build:     %"PRIu64"\n"),
661                         windows_version->sp_build);
662                 tprintf(T("Service Pack Level:     %"PRIu64"\n"),
663                         windows_version->sp_level);
664         }
665 }
666
667 static int
668 xml_write_string(xmlTextWriter *writer, const char *name,
669                  const tchar *tstr)
670 {
671         if (tstr) {
672                 char *utf8_str;
673                 int rc = tstr_to_utf8_simple(tstr, &utf8_str);
674                 if (rc)
675                         return rc;
676                 rc = xmlTextWriterWriteElement(writer, name, utf8_str);
677                 FREE(utf8_str);
678                 if (rc < 0)
679                         return rc;
680         }
681         return 0;
682 }
683
684 static int
685 xml_write_strings_from_specs(xmlTextWriter *writer,
686                              const void *struct_with_strings,
687                              const struct xml_string_spec specs[],
688                              size_t num_specs)
689 {
690         for (size_t i = 0; i < num_specs; i++) {
691                 int rc = xml_write_string(writer, specs[i].name,
692                                       *(const tchar * const *)
693                                         (struct_with_strings + specs[i].offset));
694                 if (rc)
695                         return rc;
696         }
697         return 0;
698 }
699
700 static int
701 dup_strings_from_specs(const void *old_struct_with_strings,
702                        void *new_struct_with_strings,
703                        const struct xml_string_spec specs[],
704                        size_t num_specs)
705 {
706         for (size_t i = 0; i < num_specs; i++) {
707                 const tchar *old_str = *(const tchar * const *)
708                                         ((const void*)old_struct_with_strings + specs[i].offset);
709                 tchar **new_str_p = (tchar **)((void*)new_struct_with_strings + specs[i].offset);
710                 if (old_str) {
711                         *new_str_p = TSTRDUP(old_str);
712                         if (!*new_str_p)
713                                 return WIMLIB_ERR_NOMEM;
714                 }
715         }
716         return 0;
717 }
718
719 /* Writes the information contained in a `struct windows_version' to the XML
720  * document being written.  This is the <VERSION> element inside the <WINDOWS>
721  * element. */
722 static int
723 xml_write_windows_version(xmlTextWriter *writer,
724                           const struct windows_version *version)
725 {
726         int rc;
727         rc = xmlTextWriterStartElement(writer, "VERSION");
728         if (rc < 0)
729                 return rc;
730
731         rc = xmlTextWriterWriteFormatElement(writer, "MAJOR", "%"PRIu64,
732                                              version->major);
733         if (rc < 0)
734                 return rc;
735
736         rc = xmlTextWriterWriteFormatElement(writer, "MINOR", "%"PRIu64,
737                                              version->minor);
738         if (rc < 0)
739                 return rc;
740
741         rc = xmlTextWriterWriteFormatElement(writer, "BUILD", "%"PRIu64,
742                                              version->build);
743         if (rc < 0)
744                 return rc;
745
746         rc = xmlTextWriterWriteFormatElement(writer, "SPBUILD", "%"PRIu64,
747                                              version->sp_build);
748         if (rc < 0)
749                 return rc;
750
751         rc = xmlTextWriterWriteFormatElement(writer, "SPLEVEL", "%"PRIu64,
752                                              version->sp_level);
753         if (rc < 0)
754                 return rc;
755
756         rc = xmlTextWriterEndElement(writer); /* </VERSION> */
757         if (rc < 0)
758                 return rc;
759
760         return 0;
761 }
762
763 /* Writes the information contained in a `struct windows_info' to the XML
764  * document being written. This is the <WINDOWS> element. */
765 static int
766 xml_write_windows_info(xmlTextWriter *writer,
767                        const struct windows_info *windows_info)
768 {
769         int rc;
770         rc = xmlTextWriterStartElement(writer, "WINDOWS");
771         if (rc < 0)
772                 return rc;
773
774         rc = xmlTextWriterWriteFormatElement(writer, "ARCH", "%"PRIu64,
775                                              windows_info->arch);
776         if (rc < 0)
777                 return rc;
778
779         rc = xml_write_strings_from_specs(writer,
780                                           windows_info,
781                                           windows_info_xml_string_specs,
782                                           ARRAY_LEN(windows_info_xml_string_specs));
783         if (rc)
784                 return rc;
785
786         if (windows_info->num_languages) {
787                 rc = xmlTextWriterStartElement(writer, "LANGUAGES");
788                 if (rc < 0)
789                         return rc;
790
791                 for (size_t i = 0; i < windows_info->num_languages; i++) {
792                         rc = xml_write_string(writer, "LANGUAGE",
793                                               windows_info->languages[i]);
794                         if (rc)
795                                 return rc;
796                 }
797
798                 rc = xml_write_string(writer, "DEFAULT",
799                                       windows_info->default_language);
800                 if (rc)
801                         return rc;
802
803                 rc = xmlTextWriterEndElement(writer); /* </LANGUAGES> */
804                 if (rc < 0)
805                         return rc;
806         }
807
808         if (windows_info->windows_version_exists) {
809                 rc = xml_write_windows_version(writer, &windows_info->windows_version);
810                 if (rc)
811                         return rc;
812         }
813
814         rc = xml_write_string(writer, "SYSTEMROOT", windows_info->system_root);
815         if (rc)
816                 return rc;
817
818         rc = xmlTextWriterEndElement(writer); /* </WINDOWS> */
819         if (rc < 0)
820                 return rc;
821
822         return 0;
823 }
824
825 /* Writes a time element to the XML document being constructed in memory. */
826 static int
827 xml_write_time(xmlTextWriter *writer, const char *element_name, u64 time)
828 {
829         int rc;
830         rc = xmlTextWriterStartElement(writer, element_name);
831         if (rc < 0)
832                 return rc;
833
834         rc = xmlTextWriterWriteFormatElement(writer, "HIGHPART",
835                                              "0x%08"PRIX32, (u32)(time >> 32));
836         if (rc < 0)
837                 return rc;
838
839         rc = xmlTextWriterWriteFormatElement(writer, "LOWPART",
840                                              "0x%08"PRIX32, (u32)time);
841         if (rc < 0)
842                 return rc;
843
844         rc = xmlTextWriterEndElement(writer); /* </@element_name> */
845         if (rc < 0)
846                 return rc;
847         return 0;
848 }
849
850 /* Writes an <IMAGE> element to the XML document. */
851 static int
852 xml_write_image_info(xmlTextWriter *writer, const struct image_info *image_info)
853 {
854         int rc;
855         rc = xmlTextWriterStartElement(writer, "IMAGE");
856         if (rc < 0)
857                 return rc;
858
859         rc = xmlTextWriterWriteFormatAttribute(writer, "INDEX", "%d",
860                                                image_info->index);
861         if (rc < 0)
862                 return rc;
863
864         rc = xmlTextWriterWriteFormatElement(writer, "DIRCOUNT", "%"PRIu64,
865                                              image_info->dir_count);
866         if (rc < 0)
867                 return rc;
868
869         rc = xmlTextWriterWriteFormatElement(writer, "FILECOUNT", "%"PRIu64,
870                                              image_info->file_count);
871         if (rc < 0)
872                 return rc;
873
874         rc = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES", "%"PRIu64,
875                                              image_info->total_bytes);
876         if (rc < 0)
877                 return rc;
878
879         rc = xmlTextWriterWriteFormatElement(writer, "HARDLINKBYTES", "%"PRIu64,
880                                              image_info->hard_link_bytes);
881         if (rc < 0)
882                 return rc;
883
884         rc = xml_write_time(writer, "CREATIONTIME", image_info->creation_time);
885         if (rc < 0)
886                 return rc;
887
888         rc = xml_write_time(writer, "LASTMODIFICATIONTIME",
889                             image_info->last_modification_time);
890         if (rc < 0)
891                 return rc;
892
893         if (image_info->windows_info_exists) {
894                 rc = xml_write_windows_info(writer, &image_info->windows_info);
895                 if (rc)
896                         return rc;
897         }
898
899         rc = xml_write_strings_from_specs(writer, image_info,
900                                           image_info_xml_string_specs,
901                                           ARRAY_LEN(image_info_xml_string_specs));
902         if (rc)
903                 return rc;
904
905         rc = xmlTextWriterEndElement(writer); /* </IMAGE> */
906         if (rc < 0)
907                 return rc;
908
909         return 0;
910 }
911
912
913
914 /* Makes space for another image in the XML information and return a pointer to
915  * it.*/
916 static struct image_info *
917 add_image_info_struct(struct wim_info *wim_info)
918 {
919         struct image_info *images;
920
921         images = CALLOC(wim_info->num_images + 1, sizeof(struct image_info));
922         if (!images)
923                 return NULL;
924         memcpy(images, wim_info->images,
925                wim_info->num_images * sizeof(struct image_info));
926         FREE(wim_info->images);
927         wim_info->images = images;
928         wim_info->num_images++;
929         return &images[wim_info->num_images - 1];
930 }
931
932 static int
933 clone_windows_info(const struct windows_info *old, struct windows_info *new)
934 {
935         int ret;
936
937         ret = dup_strings_from_specs(old, new, windows_info_xml_string_specs,
938                                      ARRAY_LEN(windows_info_xml_string_specs));
939         if (ret)
940                 return ret;
941
942         if (old->languages) {
943                 new->languages = CALLOC(old->num_languages, sizeof(new->languages[0]));
944                 if (!new->languages)
945                         return WIMLIB_ERR_NOMEM;
946                 new->num_languages = old->num_languages;
947                 for (size_t i = 0; i < new->num_languages; i++) {
948                         if (!old->languages[i])
949                                 continue;
950                         new->languages[i] = TSTRDUP(old->languages[i]);
951                         if (!new->languages[i])
952                                 return WIMLIB_ERR_NOMEM;
953                 }
954         }
955         if (old->default_language &&
956                         !(new->default_language = TSTRDUP(old->default_language)))
957                 return WIMLIB_ERR_NOMEM;
958         if (old->system_root && !(new->system_root = TSTRDUP(old->system_root)))
959                 return WIMLIB_ERR_NOMEM;
960         if (old->windows_version_exists) {
961                 new->windows_version_exists = true;
962                 memcpy(&new->windows_version, &old->windows_version,
963                        sizeof(old->windows_version));
964         }
965         return 0;
966 }
967
968 static int
969 clone_image_info(const struct image_info *old, struct image_info *new)
970 {
971         int ret;
972
973         new->dir_count              = old->dir_count;
974         new->file_count             = old->file_count;
975         new->total_bytes            = old->total_bytes;
976         new->hard_link_bytes        = old->hard_link_bytes;
977         new->creation_time          = old->creation_time;
978         new->last_modification_time = old->last_modification_time;
979
980         ret = dup_strings_from_specs(old, new,
981                                      image_info_xml_string_specs,
982                                      ARRAY_LEN(image_info_xml_string_specs));
983         if (ret)
984                 return ret;
985
986         if (old->windows_info_exists) {
987                 new->windows_info_exists = true;
988                 ret = clone_windows_info(&old->windows_info,
989                                          &new->windows_info);
990                 if (ret)
991                         return ret;
992         }
993         return 0;
994 }
995
996 /* Copies the XML information for an image between WIM files.
997  *
998  * @dest_image_name and @dest_image_description are ignored if they are NULL;
999  * otherwise, they are used to override the image name and/or image description
1000  * from the XML data in the source WIM file.
1001  *
1002  * On failure, WIMLIB_ERR_NOMEM is returned and no changes are made.  Otherwise,
1003  * 0 is returned and the WIM information at *new_wim_info_p is modified.
1004  */
1005 int
1006 xml_export_image(const struct wim_info *old_wim_info,
1007                  int image,
1008                  struct wim_info **new_wim_info_p,
1009                  const tchar *dest_image_name,
1010                  const tchar *dest_image_description)
1011 {
1012         struct wim_info *new_wim_info;
1013         struct image_info *image_info;
1014         int ret;
1015
1016         DEBUG("Copying XML data between WIM files for source image %d.", image);
1017
1018         wimlib_assert(old_wim_info != NULL);
1019         wimlib_assert(image >= 1 && image <= old_wim_info->num_images);
1020
1021         if (*new_wim_info_p) {
1022                 new_wim_info = *new_wim_info_p;
1023         } else {
1024                 new_wim_info = CALLOC(1, sizeof(struct wim_info));
1025                 if (!new_wim_info)
1026                         goto err;
1027         }
1028
1029         image_info = add_image_info_struct(new_wim_info);
1030         if (!image_info)
1031                 goto err;
1032
1033         ret = clone_image_info(&old_wim_info->images[image - 1], image_info);
1034         if (ret != 0)
1035                 goto err_destroy_image_info;
1036
1037         image_info->index = new_wim_info->num_images;
1038
1039         if (dest_image_name) {
1040                 FREE(image_info->name);
1041                 image_info->name = TSTRDUP(dest_image_name);
1042                 if (!image_info->name)
1043                         goto err_destroy_image_info;
1044         }
1045         if (dest_image_description) {
1046                 FREE(image_info->description);
1047                 image_info->description = TSTRDUP(dest_image_description);
1048                 if (!image_info->description)
1049                         goto err_destroy_image_info;
1050         }
1051         *new_wim_info_p = new_wim_info;
1052         return 0;
1053 err_destroy_image_info:
1054         destroy_image_info(image_info);
1055 err:
1056         if (new_wim_info != *new_wim_info_p)
1057                 free_wim_info(new_wim_info);
1058         return WIMLIB_ERR_NOMEM;
1059 }
1060
1061 /* Removes an image from the XML information. */
1062 void
1063 xml_delete_image(struct wim_info **wim_info_p, int image)
1064 {
1065         struct wim_info *wim_info;
1066
1067         wim_info = *wim_info_p;
1068         wimlib_assert(image >= 1 && image <= wim_info->num_images);
1069         DEBUG("Deleting image %d from the XML data.", image);
1070
1071         destroy_image_info(&wim_info->images[image - 1]);
1072
1073         memmove(&wim_info->images[image - 1],
1074                 &wim_info->images[image],
1075                 (wim_info->num_images - image) * sizeof(struct image_info));
1076
1077         if (--wim_info->num_images == 0) {
1078                 free_wim_info(wim_info);
1079                 *wim_info_p = NULL;
1080         } else {
1081                 for (int i = image - 1; i < wim_info->num_images; i++)
1082                         wim_info->images[i].index--;
1083         }
1084 }
1085
1086 size_t
1087 xml_get_max_image_name_len(const WIMStruct *wim)
1088 {
1089         size_t max_len = 0;
1090         for (u32 i = 0; i < wim->hdr.image_count; i++)
1091                 max_len = max(max_len, tstrlen(wim->wim_info->images[i].name));
1092         return max_len;
1093 }
1094
1095 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
1096 void
1097 xml_set_memory_allocator(void *(*malloc_func)(size_t),
1098                          void (*free_func)(void *),
1099                          void *(*realloc_func)(void *, size_t))
1100 {
1101         xmlMemSetup(free_func, malloc_func, realloc_func, STRDUP);
1102 }
1103 #endif
1104
1105 static int
1106 calculate_dentry_statistics(struct wim_dentry *dentry, void *arg)
1107 {
1108         struct image_info *info = arg;
1109         const struct wim_inode *inode = dentry->d_inode;
1110         struct wim_lookup_table_entry *lte;
1111
1112         /* Update directory count and file count.
1113          *
1114          * Each dentry counts as either a file or a directory, but not both.
1115          * The root directory is an exception: it is not counted at all.
1116          *
1117          * Symbolic links and junction points (and presumably other reparse
1118          * points) count as regular files.  This is despite the fact that
1119          * junction points have FILE_ATTRIBUTE_DIRECTORY set.
1120          */
1121         if (dentry_is_root(dentry))
1122                 return 0;
1123
1124         if (inode_is_directory(inode))
1125                 info->dir_count++;
1126         else
1127                 info->file_count++;
1128
1129         /*
1130          * Update total bytes and hard link bytes.
1131          *
1132          * Unfortunately there are some inconsistencies/bugs in the way this is
1133          * done.
1134          *
1135          * If there are no alternate data streams in the image, the "total
1136          * bytes" is the sum of the size of the un-named data stream of each
1137          * inode times the link count of that inode.  In other words, it would
1138          * be the total number of bytes of regular files you would have if you
1139          * extracted the full image without any hard-links.  The "hard link
1140          * bytes" is equal to the "total bytes" minus the size of the un-named
1141          * data stream of each inode.  In other words, the "hard link bytes"
1142          * counts the size of the un-named data stream for all the links to each
1143          * inode except the first one.
1144          *
1145          * Reparse points and directories don't seem to be counted in either the
1146          * total bytes or the hard link bytes.
1147          *
1148          * And now we get to the most confusing part, the alternate data
1149          * streams.  They are not counted in the "total bytes".  However, if the
1150          * link count of an inode with alternate data streams is 2 or greater,
1151          * the size of all the alternate data streams is included in the "hard
1152          * link bytes", and this size is multiplied by the link count (NOT one
1153          * less than the link count).
1154          */
1155         lte = inode_unnamed_lte(inode, info->lookup_table);
1156         if (lte) {
1157                 info->total_bytes += lte->size;
1158                 if (!dentry_is_first_in_inode(dentry))
1159                         info->hard_link_bytes += lte->size;
1160         }
1161
1162         if (inode->i_nlink >= 2 && dentry_is_first_in_inode(dentry)) {
1163                 for (unsigned i = 0; i < inode->i_num_ads; i++) {
1164                         if (inode->i_ads_entries[i].stream_name_nbytes) {
1165                                 lte = inode_stream_lte(inode, i + 1, info->lookup_table);
1166                                 if (lte) {
1167                                         info->hard_link_bytes += inode->i_nlink *
1168                                                                  lte->size;
1169                                 }
1170                         }
1171                 }
1172         }
1173         return 0;
1174 }
1175
1176 /*
1177  * Calculate what to put in the <FILECOUNT>, <DIRCOUNT>, <TOTALBYTES>, and
1178  * <HARDLINKBYTES> elements of each <IMAGE>.
1179  *
1180  * Please note there is no official documentation for exactly how this is done.
1181  * But, see calculate_dentry_statistics().
1182  */
1183 void
1184 xml_update_image_info(WIMStruct *wim, int image)
1185 {
1186         struct image_info *image_info;
1187
1188         DEBUG("Updating the image info for image %d", image);
1189
1190         image_info = &wim->wim_info->images[image - 1];
1191
1192         image_info->file_count      = 0;
1193         image_info->dir_count       = 0;
1194         image_info->total_bytes     = 0;
1195         image_info->hard_link_bytes = 0;
1196         image_info->lookup_table = wim->lookup_table;
1197
1198         for_dentry_in_tree(wim->image_metadata[image - 1]->root_dentry,
1199                            calculate_dentry_statistics,
1200                            image_info);
1201         image_info->last_modification_time = get_wim_timestamp();
1202 }
1203
1204 /* Adds an image to the XML information. */
1205 int
1206 xml_add_image(WIMStruct *wim, const tchar *name)
1207 {
1208         struct wim_info *wim_info;
1209         struct image_info *image_info;
1210
1211         wimlib_assert(name != NULL);
1212
1213         /* If this is the first image, allocate the struct wim_info.  Otherwise
1214          * use the existing struct wim_info. */
1215         if (wim->wim_info) {
1216                 wim_info = wim->wim_info;
1217         } else {
1218                 wim_info = CALLOC(1, sizeof(struct wim_info));
1219                 if (!wim_info)
1220                         return WIMLIB_ERR_NOMEM;
1221         }
1222
1223         image_info = add_image_info_struct(wim_info);
1224         if (!image_info)
1225                 goto out_free_wim_info;
1226
1227         if (!(image_info->name = TSTRDUP(name)))
1228                 goto out_destroy_image_info;
1229
1230         wim->wim_info = wim_info;
1231         image_info->index = wim_info->num_images;
1232         image_info->creation_time = get_wim_timestamp();
1233         xml_update_image_info(wim, image_info->index);
1234         return 0;
1235
1236 out_destroy_image_info:
1237         destroy_image_info(image_info);
1238         wim_info->num_images--;
1239 out_free_wim_info:
1240         if (wim_info != wim->wim_info)
1241                 FREE(wim_info);
1242         return WIMLIB_ERR_NOMEM;
1243 }
1244
1245 /* Prints information about the specified image from struct wim_info structure.
1246  * */
1247 void
1248 print_image_info(const struct wim_info *wim_info, int image)
1249 {
1250         const struct image_info *image_info;
1251         const tchar *desc;
1252         tchar buf[50];
1253
1254         wimlib_assert(image >= 1 && image <= wim_info->num_images);
1255
1256         image_info = &wim_info->images[image - 1];
1257
1258         tprintf(T("Index:                  %d\n"), image_info->index);
1259         tprintf(T("Name:                   %"TS"\n"), image_info->name);
1260
1261         /* Always print the Description: part even if there is no
1262          * description. */
1263         if (image_info->description)
1264                 desc = image_info->description;
1265         else
1266                 desc = T("");
1267         tprintf(T("Description:            %"TS"\n"), desc);
1268
1269         if (image_info->display_name) {
1270                 tprintf(T("Display Name:           %"TS"\n"),
1271                         image_info->display_name);
1272         }
1273
1274         if (image_info->display_description) {
1275                 tprintf(T("Display Description:    %"TS"\n"),
1276                         image_info->display_description);
1277         }
1278
1279         tprintf(T("Directory Count:        %"PRIu64"\n"), image_info->dir_count);
1280         tprintf(T("File Count:             %"PRIu64"\n"), image_info->file_count);
1281         tprintf(T("Total Bytes:            %"PRIu64"\n"), image_info->total_bytes);
1282         tprintf(T("Hard Link Bytes:        %"PRIu64"\n"), image_info->hard_link_bytes);
1283
1284         wim_timestamp_to_str(image_info->creation_time, buf, sizeof(buf));
1285         tprintf(T("Creation Time:          %"TS"\n"), buf);
1286
1287         wim_timestamp_to_str(image_info->last_modification_time, buf, sizeof(buf));
1288         tprintf(T("Last Modification Time: %"TS"\n"), buf);
1289         if (image_info->windows_info_exists)
1290                 print_windows_info(&image_info->windows_info);
1291         if (image_info->flags)
1292                 tprintf(T("Flags:                  %"TS"\n"), image_info->flags);
1293         tputchar('\n');
1294 }
1295
1296 void
1297 libxml_global_init(void)
1298 {
1299         xmlInitParser();
1300         xmlInitCharEncodingHandlers();
1301 }
1302
1303 void
1304 libxml_global_cleanup(void)
1305 {
1306         xmlCleanupParser();
1307         xmlCleanupCharEncodingHandlers();
1308 }
1309
1310 /* Reads the XML data from a WIM file.  */
1311 int
1312 read_wim_xml_data(WIMStruct *wim)
1313 {
1314         void *buf;
1315         size_t bufsize;
1316         u8 *xml_data;
1317         xmlDoc *doc;
1318         xmlNode *root;
1319         int ret;
1320
1321         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1322         if (ret)
1323                 goto out;
1324         xml_data = buf;
1325
1326         doc = xmlReadMemory((const char *)xml_data, bufsize,
1327                             NULL, "UTF-16LE", 0);
1328         if (!doc) {
1329                 ERROR("Failed to parse XML data");
1330                 ret = WIMLIB_ERR_XML;
1331                 goto out_free_xml_data;
1332         }
1333
1334         root = xmlDocGetRootElement(doc);
1335         if (!root || !node_is_element(root) || !node_name_is(root, "WIM")) {
1336                 ERROR("WIM XML data is invalid");
1337                 ret = WIMLIB_ERR_XML;
1338                 goto out_free_doc;
1339         }
1340
1341         ret = xml_read_wim_info(root, &wim->wim_info);
1342 out_free_doc:
1343         xmlFreeDoc(doc);
1344 out_free_xml_data:
1345         FREE(xml_data);
1346 out:
1347         return ret;
1348 }
1349
1350 /* Prepares an in-memory buffer containing the UTF-16LE XML data for a WIM file.
1351  *
1352  * total_bytes is the number to write in <TOTALBYTES>, or
1353  * WIM_TOTALBYTES_USE_EXISTING to use the existing value in memory, or
1354  * WIM_TOTALBYTES_OMIT to omit <TOTALBYTES> entirely.
1355  */
1356 static int
1357 prepare_wim_xml_data(WIMStruct *wim, int image, u64 total_bytes,
1358                      u8 **xml_data_ret, size_t *xml_len_ret)
1359 {
1360         xmlCharEncodingHandler *encoding_handler;
1361         xmlBuffer *buf;
1362         xmlOutputBuffer *outbuf;
1363         xmlTextWriter *writer;
1364         int ret;
1365         int first, last;
1366         const xmlChar *content;
1367         int len;
1368         u8 *xml_data;
1369         size_t xml_len;
1370
1371         /* Open an xmlTextWriter that writes to an in-memory buffer using
1372          * UTF-16LE encoding.  */
1373
1374         encoding_handler = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF16LE);
1375         if (!encoding_handler) {
1376                 ERROR("Failed to get XML character encoding handler for UTF-16LE");
1377                 ret = WIMLIB_ERR_LIBXML_UTF16_HANDLER_NOT_AVAILABLE;
1378                 goto out;
1379         }
1380
1381         buf = xmlBufferCreate();
1382         if (!buf) {
1383                 ERROR("Failed to create xmlBuffer");
1384                 ret = WIMLIB_ERR_NOMEM;
1385                 goto out;
1386         }
1387
1388         outbuf = xmlOutputBufferCreateBuffer(buf, encoding_handler);
1389         if (!outbuf) {
1390                 ERROR("Failed to allocate xmlOutputBuffer");
1391                 ret = WIMLIB_ERR_NOMEM;
1392                 goto out_buffer_free;
1393         }
1394
1395         writer = xmlNewTextWriter(outbuf);
1396         if (!writer) {
1397                 ERROR("Failed to allocate xmlTextWriter");
1398                 ret = WIMLIB_ERR_NOMEM;
1399                 goto out_output_buffer_close;
1400         }
1401
1402         /* Write the XML document.  */
1403
1404         ret = xmlTextWriterStartElement(writer, "WIM");
1405         if (ret < 0)
1406                 goto out_write_error;
1407
1408         /* The contents of the <TOTALBYTES> element in the XML data, under the
1409          * <WIM> element (not the <IMAGE> element), is for non-split WIMs the
1410          * size of the WIM file excluding the XML data and integrity table.
1411          * For split WIMs, <TOTALBYTES> takes into account the entire WIM, not
1412          * just the current part.  */
1413         if (total_bytes != WIM_TOTALBYTES_OMIT) {
1414                 if (total_bytes == WIM_TOTALBYTES_USE_EXISTING) {
1415                         if (wim->wim_info)
1416                                 total_bytes = wim->wim_info->total_bytes;
1417                         else
1418                                 total_bytes = 0;
1419                 }
1420                 ret = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES",
1421                                                       "%"PRIu64, total_bytes);
1422                 if (ret < 0)
1423                         goto out_write_error;
1424         }
1425
1426         if (image == WIMLIB_ALL_IMAGES) {
1427                 first = 1;
1428                 last = wim->hdr.image_count;
1429         } else {
1430                 first = image;
1431                 last = image;
1432         }
1433
1434         for (int i = first; i <= last; i++) {
1435                 ret = xml_write_image_info(writer, &wim->wim_info->images[i - 1]);
1436                 if (ret) {
1437                         if (ret < 0)
1438                                 goto out_write_error;
1439                         goto out_free_text_writer;
1440                 }
1441         }
1442
1443         ret = xmlTextWriterEndElement(writer);
1444         if (ret < 0)
1445                 goto out_write_error;
1446
1447         ret = xmlTextWriterEndDocument(writer);
1448         if (ret < 0)
1449                 goto out_write_error;
1450
1451         ret = xmlTextWriterFlush(writer);
1452         if (ret < 0)
1453                 goto out_write_error;
1454
1455         /* Retrieve the buffer into which the document was written.  */
1456
1457         content = xmlBufferContent(buf);
1458         len = xmlBufferLength(buf);
1459
1460         /* Copy the data into a new buffer, and prefix it with the UTF-16LE BOM
1461          * (byte order mark), which is required by MS's software to understand
1462          * the data.  */
1463
1464         xml_len = len + 2;
1465         xml_data = MALLOC(xml_len);
1466         if (!xml_data) {
1467                 ret = WIMLIB_ERR_NOMEM;
1468                 goto out_free_text_writer;
1469         }
1470         xml_data[0] = 0xff;
1471         xml_data[1] = 0xfe;
1472         memcpy(&xml_data[2], content, len);
1473
1474         /* Clean up libxml objects and return success.  */
1475         *xml_data_ret = xml_data;
1476         *xml_len_ret = xml_len;
1477         ret = 0;
1478 out_free_text_writer:
1479         /* xmlFreeTextWriter will free the attached xmlOutputBuffer.  */
1480         xmlFreeTextWriter(writer);
1481         goto out_buffer_free;
1482 out_output_buffer_close:
1483         xmlOutputBufferClose(outbuf);
1484 out_buffer_free:
1485         xmlBufferFree(buf);
1486 out:
1487         DEBUG("ret=%d", ret);
1488         return ret;
1489
1490 out_write_error:
1491         ERROR("Error writing XML data");
1492         ret = WIMLIB_ERR_WRITE;
1493         goto out_free_text_writer;
1494 }
1495
1496 /* Writes the XML data to a WIM file.  */
1497 int
1498 write_wim_xml_data(WIMStruct *wim, int image, u64 total_bytes,
1499                    struct wim_reshdr *out_reshdr,
1500                    int write_resource_flags)
1501 {
1502         int ret;
1503         u8 *xml_data;
1504         size_t xml_len;
1505
1506         DEBUG("Writing WIM XML data (image=%d, offset=%"PRIu64")",
1507               image, total_bytes, wim->out_fd.offset);
1508
1509         ret = prepare_wim_xml_data(wim, image, total_bytes,
1510                                    &xml_data, &xml_len);
1511         if (ret)
1512                 return ret;
1513
1514         /* Write the XML data uncompressed.  Although wimlib can handle
1515          * compressed XML data, MS software cannot.  */
1516         ret = write_wim_resource_from_buffer(xml_data,
1517                                              xml_len,
1518                                              WIM_RESHDR_FLAG_METADATA,
1519                                              &wim->out_fd,
1520                                              WIMLIB_COMPRESSION_TYPE_NONE,
1521                                              0,
1522                                              out_reshdr,
1523                                              NULL,
1524                                              write_resource_flags);
1525         FREE(xml_data);
1526         DEBUG("ret=%d", ret);
1527         return ret;
1528 }
1529
1530 /* API function documented in wimlib.h  */
1531 WIMLIBAPI const tchar *
1532 wimlib_get_image_name(const WIMStruct *wim, int image)
1533 {
1534         if (image < 1 || image > wim->hdr.image_count)
1535                 return NULL;
1536         return wim->wim_info->images[image - 1].name;
1537 }
1538
1539 /* API function documented in wimlib.h  */
1540 WIMLIBAPI const tchar *
1541 wimlib_get_image_description(const WIMStruct *wim, int image)
1542 {
1543         if (image < 1 || image > wim->hdr.image_count)
1544                 return NULL;
1545         return wim->wim_info->images[image - 1].description;
1546 }
1547
1548 /* API function documented in wimlib.h  */
1549 WIMLIBAPI bool
1550 wimlib_image_name_in_use(const WIMStruct *wim, const tchar *name)
1551 {
1552         if (!name || !*name)
1553                 return false;
1554         for (int i = 1; i <= wim->hdr.image_count; i++)
1555                 if (!tstrcmp(wim->wim_info->images[i - 1].name, name))
1556                         return true;
1557         return false;
1558 }
1559
1560
1561 /* API function documented in wimlib.h  */
1562 WIMLIBAPI int
1563 wimlib_get_xml_data(WIMStruct *wim, void **buf_ret, size_t *bufsize_ret)
1564 {
1565         const struct wim_reshdr *xml_reshdr;
1566
1567         if (wim->filename == NULL && filedes_is_seekable(&wim->in_fd))
1568                 return WIMLIB_ERR_INVALID_PARAM;
1569
1570         if (buf_ret == NULL || bufsize_ret == NULL)
1571                 return WIMLIB_ERR_INVALID_PARAM;
1572
1573         xml_reshdr = &wim->hdr.xml_data_reshdr;
1574
1575         DEBUG("Reading XML data.");
1576         *bufsize_ret = xml_reshdr->uncompressed_size;
1577         return wim_reshdr_to_data(xml_reshdr, wim, buf_ret);
1578 }
1579
1580 WIMLIBAPI int
1581 wimlib_extract_xml_data(WIMStruct *wim, FILE *fp)
1582 {
1583         int ret;
1584         void *buf;
1585         size_t bufsize;
1586
1587         ret = wimlib_get_xml_data(wim, &buf, &bufsize);
1588         if (ret)
1589                 return ret;
1590
1591         if (fwrite(buf, 1, bufsize, fp) != bufsize) {
1592                 ERROR_WITH_ERRNO("Failed to extract XML data");
1593                 ret = WIMLIB_ERR_WRITE;
1594         }
1595         FREE(buf);
1596         return ret;
1597 }
1598
1599 /* API function documented in wimlib.h  */
1600 WIMLIBAPI int
1601 wimlib_set_image_name(WIMStruct *wim, int image, const tchar *name)
1602 {
1603         tchar *p;
1604         int i;
1605         int ret;
1606
1607         DEBUG("Setting the name of image %d to %"TS, image, name);
1608
1609         ret = can_modify_wim(wim);
1610         if (ret)
1611                 return ret;
1612
1613         if (name == NULL)
1614                 name = T("");
1615
1616         if (image < 1 || image > wim->hdr.image_count) {
1617                 ERROR("%d is not a valid image", image);
1618                 return WIMLIB_ERR_INVALID_IMAGE;
1619         }
1620
1621         for (i = 1; i <= wim->hdr.image_count; i++) {
1622                 if (i == image)
1623                         continue;
1624                 if (!tstrcmp(wim->wim_info->images[i - 1].name, name)) {
1625                         ERROR("The name \"%"TS"\" is already in use in the WIM!",
1626                               name);
1627                         return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1628                 }
1629         }
1630
1631         p = TSTRDUP(name);
1632         if (!p)
1633                 return WIMLIB_ERR_NOMEM;
1634
1635         FREE(wim->wim_info->images[image - 1].name);
1636         wim->wim_info->images[image - 1].name = p;
1637         return 0;
1638 }
1639
1640 static int
1641 do_set_image_info_str(WIMStruct *wim, int image, const tchar *tstr,
1642                       size_t offset)
1643 {
1644         tchar *tstr_copy;
1645         tchar **dest_tstr_p;
1646         int ret;
1647
1648         ret = can_modify_wim(wim);
1649         if (ret)
1650                 return ret;
1651
1652         if (image < 1 || image > wim->hdr.image_count) {
1653                 ERROR("%d is not a valid image", image);
1654                 return WIMLIB_ERR_INVALID_IMAGE;
1655         }
1656         if (tstr) {
1657                 tstr_copy = TSTRDUP(tstr);
1658                 if (!tstr_copy)
1659                         return WIMLIB_ERR_NOMEM;
1660         } else {
1661                 tstr_copy = NULL;
1662         }
1663         dest_tstr_p = (tchar**)((void*)&wim->wim_info->images[image - 1] + offset);
1664
1665         FREE(*dest_tstr_p);
1666         *dest_tstr_p = tstr_copy;
1667         return 0;
1668 }
1669
1670 /* API function documented in wimlib.h  */
1671 WIMLIBAPI int
1672 wimlib_set_image_descripton(WIMStruct *wim, int image,
1673                             const tchar *description)
1674 {
1675         return do_set_image_info_str(wim, image, description,
1676                                      offsetof(struct image_info, description));
1677 }
1678
1679 /* API function documented in wimlib.h  */
1680 WIMLIBAPI int
1681 wimlib_set_image_flags(WIMStruct *wim, int image, const tchar *flags)
1682 {
1683         return do_set_image_info_str(wim, image, flags,
1684                                      offsetof(struct image_info, flags));
1685 }