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