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