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