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