]> wimlib.net Git - wimlib/blob - src/xml.c
Various cleanups
[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 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 = ((struct image_info*)p1)->index;
189         int index_2 = ((struct image_info*)p1)->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         wimlib_assert(wim_info != NULL);
954         wimlib_assert(image >= 1 && image <= wim_info->num_images);
955
956         destroy_image_info(&wim_info->images[image - 1]);
957
958         memcpy(&wim_info->images[image - 1],
959                &wim_info->images[image],
960                (wim_info->num_images - image) * sizeof(struct image_info));
961
962         if (--wim_info->num_images == 0) {
963                 free_wim_info(wim_info);
964                 *wim_info_p = NULL;
965         } else {
966                 for (int i = image - 1; i < wim_info->num_images; i++)
967                         wim_info->images[i].index--;
968         }
969 }
970
971 size_t xml_get_max_image_name_len(const WIMStruct *w)
972 {
973         size_t max_len = 0;
974         if (w->wim_info) {
975                 size_t len;
976                 for (int i = 0; i < w->wim_info->num_images; i++) {
977                         len = strlen(w->wim_info->images[i].name);
978                         if (len > max_len)
979                                 max_len = len;
980                 }
981         }
982         return max_len;
983 }
984
985 #ifdef ENABLE_CUSTOM_MEMORY_ALLOCATOR
986 void xml_set_memory_allocator(void *(*malloc_func)(size_t),
987                                    void (*free_func)(void *),
988                                    void *(*realloc_func)(void *, size_t))
989 {
990         xmlMemSetup(free_func, malloc_func, realloc_func, STRDUP);
991 }
992 #endif
993
994 static int calculate_dentry_statistics(struct dentry *dentry, void *arg)
995 {
996         struct image_info *info = arg;
997         struct lookup_table *lookup_table = info->lookup_table;
998         const struct inode *inode = dentry->d_inode;
999         struct lookup_table_entry *lte;
1000
1001         /* Update directory count and file count.
1002          *
1003          * Each dentry counts as either a file or a directory, but not both.
1004          * The root directory is an exception: it is not counted at all.
1005          *
1006          * Symbolic links and junction points (and presumably other reparse
1007          * points) count as regular files.  This is despite the fact that
1008          * junction points have FILE_ATTRIBUTE_DIRECTORY set.
1009          */
1010         if (dentry_is_root(dentry))
1011                 return 0;
1012
1013         if (inode_is_directory(inode))
1014                 info->dir_count++;
1015         else
1016                 info->file_count++;
1017
1018         /*
1019          * Update total bytes and hard link bytes.
1020          *
1021          * Unfortunately there are some inconsistencies/bugs in the way this is
1022          * done.
1023          *
1024          * If there are no alternate data streams in the image, the "total
1025          * bytes" is the sum of the size of the un-named data stream of each
1026          * inode times the link count of that inode.  In other words, it would
1027          * be the total number of bytes of regular files you would have if you
1028          * extracted the full image without any hard-links.  The "hard link
1029          * bytes" is equal to the "total bytes" minus the size of the un-named
1030          * data stream of each inode.  In other words, the "hard link bytes"
1031          * counts the size of the un-named data stream for all the links to each
1032          * inode except the first one.
1033          *
1034          * Reparse points and directories don't seem to be counted in either the
1035          * total bytes or the hard link bytes.
1036          *
1037          * And now we get to the most confusing part, the alternate data
1038          * streams.  They are not counted in the "total bytes".  However, if the
1039          * link count of an inode with alternate data streams is 2 or greater,
1040          * the size of all the alternate data streams is included in the "hard
1041          * link bytes", and this size is multiplied by the link count (NOT one
1042          * less than the link count).
1043          */
1044         lte = inode_unnamed_lte(inode, info->lookup_table);
1045         if (lte) {
1046                 info->total_bytes += wim_resource_size(lte);
1047                 if (!dentry_is_first_in_inode(dentry))
1048                         info->hard_link_bytes += wim_resource_size(lte);
1049         }
1050
1051         if (inode->link_count >= 2 && dentry_is_first_in_inode(dentry)) {
1052                 for (unsigned i = 0; i < inode->num_ads; i++) {
1053                         if (inode->ads_entries[i].stream_name_len) {
1054                                 lte = inode_stream_lte(inode, i + 1, lookup_table);
1055                                 if (lte) {
1056                                         info->hard_link_bytes += inode->link_count *
1057                                                                  wim_resource_size(lte);
1058                                 }
1059                         }
1060                 }
1061         }
1062         return 0;
1063 }
1064
1065 /*
1066  * Calculate what to put in the <FILECOUNT>, <DIRCOUNT>, <TOTALBYTES>, and
1067  * <HARDLINKBYTES> elements of each <IMAGE>.
1068  *
1069  * Please note there is no official documentation for exactly how this is done.
1070  * But, see calculate_dentry_statistics().
1071  */
1072 void xml_update_image_info(WIMStruct *w, int image)
1073 {
1074         struct image_info *image_info;
1075         char *flags_save;
1076
1077         DEBUG("Updating the image info for image %d", image);
1078
1079         image_info = &w->wim_info->images[image - 1];
1080
1081         image_info->file_count      = 0;
1082         image_info->dir_count       = 0;
1083         image_info->total_bytes     = 0;
1084         image_info->hard_link_bytes = 0;
1085
1086         flags_save = image_info->flags;
1087         image_info->lookup_table = w->lookup_table;
1088         for_dentry_in_tree(w->image_metadata[image - 1].root_dentry,
1089                            calculate_dentry_statistics,
1090                            image_info);
1091         image_info->flags = flags_save;
1092         image_info->last_modification_time = get_wim_timestamp();
1093 }
1094
1095 /* Adds an image to the XML information. */
1096 int xml_add_image(WIMStruct *w, const char *name)
1097 {
1098         struct wim_info *wim_info;
1099         struct image_info *image_info;
1100
1101         wimlib_assert(name != NULL);
1102
1103         /* If this is the first image, allocate the struct wim_info.  Otherwise
1104          * use the existing struct wim_info. */
1105         if (w->wim_info) {
1106                 wim_info = w->wim_info;
1107         } else {
1108                 wim_info = CALLOC(1, sizeof(struct wim_info));
1109                 if (!wim_info)
1110                         return WIMLIB_ERR_NOMEM;
1111         }
1112
1113         image_info = add_image_info_struct(wim_info);
1114         if (!image_info)
1115                 goto out_free_wim_info;
1116
1117         if (!(image_info->name = STRDUP(name)))
1118                 goto out_destroy_image_info;
1119
1120         w->wim_info = wim_info;
1121         image_info->index = wim_info->num_images;
1122         image_info->creation_time = get_wim_timestamp();
1123         xml_update_image_info(w, image_info->index);
1124         return 0;
1125
1126 out_destroy_image_info:
1127         destroy_image_info(image_info);
1128         wim_info->num_images--;
1129 out_free_wim_info:
1130         if (wim_info != w->wim_info)
1131                 FREE(wim_info);
1132         return WIMLIB_ERR_NOMEM;
1133 }
1134
1135 /* Prints information about the specified image from struct wim_info structure.
1136  * */
1137 void print_image_info(const struct wim_info *wim_info, int image)
1138 {
1139         const struct image_info *image_info;
1140         const char *desc;
1141         char buf[50];
1142
1143         wimlib_assert(image >= 1 && image <= wim_info->num_images);
1144
1145         image_info = &wim_info->images[image - 1];
1146
1147         printf("Index:                  %d\n", image_info->index);
1148         printf("Name:                   %s\n", image_info->name);
1149
1150         /* Always print the Description: part even if there is no
1151          * description. */
1152         if (image_info->description)
1153                 desc = image_info->description;
1154         else
1155                 desc = "";
1156         printf("Description:            %s\n", desc);
1157
1158         if (image_info->display_name)
1159                 printf("Display Name:           %s\n",
1160                        image_info->display_name);
1161
1162         if (image_info->display_description)
1163                 printf("Display Description:    %s\n",
1164                        image_info->display_description);
1165
1166         printf("Directory Count:        %"PRIu64"\n", image_info->dir_count);
1167         printf("File Count:             %"PRIu64"\n", image_info->file_count);
1168         printf("Total Bytes:            %"PRIu64"\n", image_info->total_bytes);
1169         printf("Hard Link Bytes:        %"PRIu64"\n", image_info->hard_link_bytes);
1170
1171         wim_timestamp_to_str(image_info->creation_time, buf, sizeof(buf));
1172         printf("Creation Time:          %s\n", buf);
1173
1174         wim_timestamp_to_str(image_info->creation_time, buf, sizeof(buf));
1175         printf("Last Modification Time: %s\n", buf);
1176         if (image_info->windows_info_exists)
1177                 print_windows_info(&image_info->windows_info);
1178         if (image_info->flags)
1179                 printf("Flags:                  %s\n", image_info->flags);
1180         putchar('\n');
1181 }
1182
1183 /*
1184  * Reads the XML data from a WIM file.
1185  */
1186 int read_xml_data(FILE *fp, const struct resource_entry *res_entry,
1187                   u8 **xml_data_ret, struct wim_info **info_ret)
1188 {
1189         u8 *xml_data;
1190         xmlDoc *doc;
1191         xmlNode *root;
1192         int ret;
1193
1194         DEBUG("XML data is %"PRIu64" bytes at offset %"PRIu64"",
1195               (u64)res_entry->size, res_entry->offset);
1196
1197         if (resource_is_compressed(res_entry)) {
1198                 ERROR("XML data is supposed to be uncompressed");
1199                 ret = WIMLIB_ERR_XML;
1200                 goto out_cleanup_parser;
1201         }
1202
1203         if (res_entry->size < 2) {
1204                 ERROR("XML data must be at least 2 bytes long");
1205                 ret = WIMLIB_ERR_XML;
1206                 goto out_cleanup_parser;
1207         }
1208
1209         xml_data = MALLOC(res_entry->size + 2);
1210         if (!xml_data) {
1211                 ret = WIMLIB_ERR_NOMEM;
1212                 goto out_cleanup_parser;
1213         }
1214
1215         ret = read_uncompressed_resource(fp, res_entry->offset,
1216                                          res_entry->size, xml_data);
1217         if (ret != 0)
1218                 goto out_free_xml_data;
1219
1220         /* Null-terminate just in case */
1221         xml_data[res_entry->size] = 0;
1222         xml_data[res_entry->size + 1] = 0;
1223
1224         DEBUG("Parsing XML using libxml2 to create XML tree");
1225
1226         doc = xmlReadMemory(xml_data, res_entry->size,
1227                             "noname.xml", "UTF-16", 0);
1228
1229         if (!doc) {
1230                 ERROR("Failed to parse XML data");
1231                 ret = WIMLIB_ERR_XML;
1232                 goto out_free_xml_data;
1233         }
1234
1235         DEBUG("Constructing WIM information structure from XML tree.");
1236
1237         root = xmlDocGetRootElement(doc);
1238         if (!root) {
1239                 ERROR("WIM XML data is an empty XML document");
1240                 ret = WIMLIB_ERR_XML;
1241                 goto out_free_doc;
1242         }
1243
1244         if (!node_is_element(root) || !node_name_is(root, "WIM")) {
1245                 ERROR("Expected <WIM> for the root XML element (found <%s>)",
1246                       root->name);
1247                 ret = WIMLIB_ERR_XML;
1248                 goto out_free_doc;
1249         }
1250
1251         ret = xml_read_wim_info(root, info_ret);
1252         if (ret != 0)
1253                 goto out_free_doc;
1254
1255         DEBUG("Freeing XML tree.");
1256
1257         *xml_data_ret = xml_data;
1258         xml_data = NULL;
1259 out_free_doc:
1260         xmlFreeDoc(doc);
1261 out_free_xml_data:
1262         FREE(xml_data);
1263 out_cleanup_parser:
1264         xmlCleanupParser();
1265         return ret;
1266 }
1267
1268 #define CHECK_RET  ({   if (ret < 0)  { \
1269                                 ERROR("Error writing XML data"); \
1270                                 ret = WIMLIB_ERR_WRITE; \
1271                                 goto out_free_text_writer; \
1272                         } })
1273
1274 /*
1275  * Writes XML data to a WIM file.
1276  *
1277  * If @total_bytes is non-zero, it specifies what to write to the TOTALBYTES
1278  * element in the XML data.  If zero, TOTALBYTES is given the default value of
1279  * the offset of the XML data.
1280  */
1281 int write_xml_data(const struct wim_info *wim_info, int image, FILE *out,
1282                    u64 total_bytes, struct resource_entry *out_res_entry)
1283 {
1284         xmlCharEncodingHandler *encoding_handler;
1285         xmlOutputBuffer *out_buffer;
1286         xmlTextWriter *writer;
1287         int ret;
1288         off_t start_offset;
1289         off_t end_offset;
1290
1291         wimlib_assert(image == WIMLIB_ALL_IMAGES ||
1292                         (wim_info != NULL && image >= 1 &&
1293                          image <= wim_info->num_images));
1294
1295         start_offset = ftello(out);
1296         if (start_offset == -1)
1297                 return WIMLIB_ERR_WRITE;
1298
1299         DEBUG("Writing XML data for image %d at offset %"PRIu64,
1300               image, start_offset);
1301
1302         /* 2 bytes endianness marker for UTF-16LE.  This is _required_ for WIM
1303          * XML data. */
1304         if ((putc(0xff, out)) == EOF || (putc(0xfe, out) == EOF)) {
1305                 ERROR_WITH_ERRNO("Error writing XML data");
1306                 return WIMLIB_ERR_WRITE;
1307         }
1308
1309         /* The contents of the <TOTALBYTES> element in the XML data, under the
1310          * <WIM> element (not the <IMAGE> element), is for non-split WIMs the
1311          * size of the WIM file excluding the XML data and integrity table.
1312          * This should be equal to the current position in the output stream,
1313          * since the XML data and integrity table are the last elements of the
1314          * WIM.
1315          *
1316          * For split WIMs, <TOTALBYTES> takes into account the entire WIM, not
1317          * just the current part.  In that case, @total_bytes should be passed
1318          * in to this function. */
1319         if (total_bytes == 0)
1320                 total_bytes = start_offset;
1321
1322         xmlInitCharEncodingHandlers();
1323
1324         /* The encoding of the XML data must be UTF-16LE. */
1325         encoding_handler = xmlGetCharEncodingHandler(XML_CHAR_ENCODING_UTF16LE);
1326         if (!encoding_handler) {
1327                 ERROR("Failed to get XML character encoding handler for UTF-16LE");
1328                 ret = WIMLIB_ERR_CHAR_CONVERSION;
1329                 goto out_cleanup_char_encoding_handlers;
1330         }
1331
1332         out_buffer = xmlOutputBufferCreateFile(out, encoding_handler);
1333         if (!out_buffer) {
1334                 ERROR("Failed to allocate xmlOutputBuffer");
1335                 ret = WIMLIB_ERR_NOMEM;
1336                 goto out_cleanup_char_encoding_handlers;
1337         }
1338
1339         writer = xmlNewTextWriter(out_buffer);
1340         if (!writer) {
1341                 ERROR("Failed to allocate xmlTextWriter");
1342                 ret = WIMLIB_ERR_NOMEM;
1343                 goto out_output_buffer_close;
1344         }
1345
1346         DEBUG("Writing <WIM> element");
1347
1348         ret = xmlTextWriterStartElement(writer, "WIM");
1349         CHECK_RET;
1350
1351         ret = xmlTextWriterWriteFormatElement(writer, "TOTALBYTES", "%"PRIu64,
1352                                               total_bytes);
1353         CHECK_RET;
1354
1355         if (wim_info != NULL) {
1356                 int first, last;
1357                 if (image == WIMLIB_ALL_IMAGES) {
1358                         first = 1;
1359                         last = wim_info->num_images;
1360                 } else {
1361                         first = image;
1362                         last = image;
1363                 }
1364                 DEBUG("Writing %d <IMAGE> elements", last - first + 1);
1365                 for (int i = first; i <= last; i++) {
1366                         ret = xml_write_image_info(writer, &wim_info->images[i - 1]);
1367                         CHECK_RET;
1368                 }
1369         }
1370
1371         ret = xmlTextWriterEndElement(writer);
1372         CHECK_RET;
1373
1374         ret = xmlTextWriterEndDocument(writer);
1375         CHECK_RET;
1376
1377         DEBUG("Ended XML document");
1378
1379         /* Call xmlFreeTextWriter() before ftello() because the former will
1380          * flush the file stream. */
1381         xmlFreeTextWriter(writer);
1382         writer = NULL;
1383
1384         end_offset = ftello(out);
1385         if (end_offset == -1) {
1386                 ret = WIMLIB_ERR_WRITE;
1387         } else {
1388                 ret = 0;
1389                 out_res_entry->offset        = start_offset;
1390                 out_res_entry->size          = end_offset - start_offset;
1391                 out_res_entry->original_size = end_offset - start_offset;
1392                 out_res_entry->flags         = WIM_RESHDR_FLAG_METADATA;
1393         }
1394 out_free_text_writer:
1395         /* xmlFreeTextWriter will free the attached xmlOutputBuffer. */
1396         xmlFreeTextWriter(writer);
1397         out_buffer = NULL;
1398 out_output_buffer_close:
1399         if (out_buffer != NULL)
1400                 xmlOutputBufferClose(out_buffer);
1401 out_cleanup_char_encoding_handlers:
1402         xmlCleanupCharEncodingHandlers();
1403 out:
1404         if (ret == 0)
1405                 DEBUG("Successfully wrote XML data");
1406         return ret;
1407 }
1408
1409 /* Returns the name of the specified image. */
1410 WIMLIBAPI const char *wimlib_get_image_name(const WIMStruct *w, int image)
1411 {
1412         if (image < 1 || image > w->hdr.image_count)
1413                 return NULL;
1414         return w->wim_info->images[image - 1].name;
1415 }
1416
1417 /* Returns the description of the specified image. */
1418 WIMLIBAPI const char *wimlib_get_image_description(const WIMStruct *w,
1419                                                    int image)
1420 {
1421         if (image < 1 || image > w->hdr.image_count)
1422                 return NULL;
1423         return w->wim_info->images[image - 1].description;
1424 }
1425
1426 /* Determines if an image name is already used by some image in the WIM. */
1427 WIMLIBAPI bool wimlib_image_name_in_use(const WIMStruct *w, const char *name)
1428 {
1429         if (!name || !*name)
1430                 return false;
1431         for (int i = 1; i <= w->hdr.image_count; i++)
1432                 if (strcmp(w->wim_info->images[i - 1].name, name) == 0)
1433                         return true;
1434         return false;
1435 }
1436
1437 /* Extracts the raw XML data to a file stream. */
1438 WIMLIBAPI int wimlib_extract_xml_data(WIMStruct *w, FILE *fp)
1439 {
1440         if (!w->xml_data)
1441                 return WIMLIB_ERR_INVALID_PARAM;
1442         if (fwrite(w->xml_data, 1, w->hdr.xml_res_entry.size, fp) !=
1443                         w->hdr.xml_res_entry.size) {
1444                 ERROR_WITH_ERRNO("Failed to extract XML data");
1445                 return WIMLIB_ERR_WRITE;
1446         }
1447         return 0;
1448 }
1449
1450 /* Sets the name of an image in the WIM. */
1451 WIMLIBAPI int wimlib_set_image_name(WIMStruct *w, int image, const char *name)
1452 {
1453         char *p;
1454         int i;
1455
1456         DEBUG("Setting the name of image %d to %s", image, name);
1457
1458         if (!name || !*name) {
1459                 ERROR("Must specify a non-empty string for the image name");
1460                 return WIMLIB_ERR_INVALID_PARAM;
1461         }
1462
1463         if (image < 1 || image > w->hdr.image_count) {
1464                 ERROR("%d is not a valid image", image);
1465                 return WIMLIB_ERR_INVALID_IMAGE;
1466         }
1467
1468         for (i = 1; i <= w->hdr.image_count; i++) {
1469                 if (i == image)
1470                         continue;
1471                 if (strcmp(w->wim_info->images[i - 1].name, name) == 0) {
1472                         ERROR("The name `%s' is already used for image %d",
1473                               name, i);
1474                         return WIMLIB_ERR_IMAGE_NAME_COLLISION;
1475                 }
1476         }
1477
1478         p = STRDUP(name);
1479         if (!p)
1480                 return WIMLIB_ERR_NOMEM;
1481
1482         FREE(w->wim_info->images[image - 1].name);
1483         w->wim_info->images[image - 1].name = p;
1484         return 0;
1485 }
1486
1487 /* Sets the description of an image in the WIM. */
1488 WIMLIBAPI int wimlib_set_image_descripton(WIMStruct *w, int image,
1489                                           const char *description)
1490 {
1491         char *p;
1492
1493         if (image < 1 || image > w->hdr.image_count) {
1494                 ERROR("%d is not a valid image", image);
1495                 return WIMLIB_ERR_INVALID_IMAGE;
1496         }
1497         if (description) {
1498                 p = STRDUP(description);
1499                 if (!p)
1500                         return WIMLIB_ERR_NOMEM;
1501         } else {
1502                 p = NULL;
1503         }
1504         FREE(w->wim_info->images[image - 1].description);
1505         w->wim_info->images[image - 1].description = p;
1506         return 0;
1507 }
1508
1509 /* Set the <FLAGS> element of a WIM image */
1510 WIMLIBAPI int wimlib_set_image_flags(WIMStruct *w, int image,
1511                                      const char *flags)
1512 {
1513         char *p;
1514
1515         if (image < 1 || image > w->hdr.image_count) {
1516                 ERROR("%d is not a valid image", image);
1517                 return WIMLIB_ERR_INVALID_IMAGE;
1518         }
1519         if (flags) {
1520                 p = STRDUP(flags);
1521                 if (!p)
1522                         return WIMLIB_ERR_NOMEM;
1523         } else {
1524                 p = NULL;
1525         }
1526         FREE(w->wim_info->images[image - 1].flags);
1527         w->wim_info->images[image - 1].flags = p;
1528         return 0;
1529 }