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