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