d6c940c0de95c8dc41ec7d00f715ad454354c609
[binutils-gdb.git] / gdb / xml-support.c
1 /* Helper routines for parsing XML using Expat.
2
3 Copyright (C) 2006-2017 Free Software Foundation, Inc.
4
5 This file is part of GDB.
6
7 This program is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with this program. If not, see <http://www.gnu.org/licenses/>. */
19
20 #include "defs.h"
21 #include "gdbcmd.h"
22 #include "xml-support.h"
23 #include "filestuff.h"
24 #include "safe-ctype.h"
25 #include <vector>
26
27 /* Debugging flag. */
28 static int debug_xml;
29
30 /* The contents of this file are only useful if XML support is
31 available. */
32 #ifdef HAVE_LIBEXPAT
33
34 #include "gdb_expat.h"
35
36 /* The maximum depth of <xi:include> nesting. No need to be miserly,
37 we just want to avoid running out of stack on loops. */
38 #define MAX_XINCLUDE_DEPTH 30
39
40 /* Simplified XML parser infrastructure. */
41
42 /* A parsing level -- used to keep track of the current element
43 nesting. */
44 struct scope_level
45 {
46 explicit scope_level (const gdb_xml_element *elements_ = NULL)
47 : elements (elements_),
48 element (NULL),
49 seen (0),
50 body (NULL)
51 {}
52
53 scope_level (scope_level &&other) noexcept
54 : elements (other.elements),
55 element (other.element),
56 seen (other.seen),
57 body (other.body)
58 {
59 if (this != &other)
60 other.body = NULL;
61 }
62
63 ~scope_level ()
64 {
65 if (this->body)
66 {
67 obstack_free (this->body, NULL);
68 xfree (this->body);
69 }
70 }
71
72 /* Elements we allow at this level. */
73 const struct gdb_xml_element *elements;
74
75 /* The element which we are within. */
76 const struct gdb_xml_element *element;
77
78 /* Mask of which elements we've seen at this level (used for
79 optional and repeatable checking). */
80 unsigned int seen;
81
82 /* Body text accumulation. This is an owning pointer. */
83 struct obstack *body;
84 };
85
86 /* The parser itself, and our additional state. */
87 struct gdb_xml_parser
88 {
89 gdb_xml_parser (const char *name,
90 const gdb_xml_element *elements,
91 void *user_data);
92 ~gdb_xml_parser();
93
94 XML_Parser expat_parser; /* The underlying expat parser. */
95
96 const char *name; /* Name of this parser. */
97 void *user_data; /* The user's callback data, for handlers. */
98
99 /* Scoping stack. */
100 std::vector<scope_level> scopes;
101
102 struct gdb_exception error; /* A thrown error, if any. */
103 int last_line; /* The line of the thrown error, or 0. */
104
105 const char *dtd_name; /* The name of the expected / default DTD,
106 if specified. */
107 bool is_xinclude; /* Are we the special <xi:include> parser? */
108 };
109
110 /* Process some body text. We accumulate the text for later use; it's
111 wrong to do anything with it immediately, because a single block of
112 text might be broken up into multiple calls to this function. */
113
114 static void
115 gdb_xml_body_text (void *data, const XML_Char *text, int length)
116 {
117 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
118
119 if (parser->error.reason < 0)
120 return;
121
122 scope_level &scope = parser->scopes.back ();
123
124 if (scope.body == NULL)
125 {
126 scope.body = XCNEW (struct obstack);
127 obstack_init (scope.body);
128 }
129
130 obstack_grow (scope.body, text, length);
131 }
132
133 /* Issue a debugging message from one of PARSER's handlers. */
134
135 void
136 gdb_xml_debug (struct gdb_xml_parser *parser, const char *format, ...)
137 {
138 int line = XML_GetCurrentLineNumber (parser->expat_parser);
139 va_list ap;
140 char *message;
141
142 if (!debug_xml)
143 return;
144
145 va_start (ap, format);
146 message = xstrvprintf (format, ap);
147 if (line)
148 fprintf_unfiltered (gdb_stderr, "%s (line %d): %s\n",
149 parser->name, line, message);
150 else
151 fprintf_unfiltered (gdb_stderr, "%s: %s\n",
152 parser->name, message);
153 xfree (message);
154 }
155
156 /* Issue an error message from one of PARSER's handlers, and stop
157 parsing. */
158
159 void
160 gdb_xml_error (struct gdb_xml_parser *parser, const char *format, ...)
161 {
162 int line = XML_GetCurrentLineNumber (parser->expat_parser);
163 va_list ap;
164
165 parser->last_line = line;
166 va_start (ap, format);
167 throw_verror (XML_PARSE_ERROR, format, ap);
168 }
169
170 /* Find the attribute named NAME in the set of parsed attributes
171 ATTRIBUTES. Returns NULL if not found. */
172
173 struct gdb_xml_value *
174 xml_find_attribute (VEC(gdb_xml_value_s) *attributes, const char *name)
175 {
176 struct gdb_xml_value *value;
177 int ix;
178
179 for (ix = 0; VEC_iterate (gdb_xml_value_s, attributes, ix, value); ix++)
180 if (strcmp (value->name, name) == 0)
181 return value;
182
183 return NULL;
184 }
185
186 /* Clean up a vector of parsed attribute values. */
187
188 static void
189 gdb_xml_values_cleanup (void *data)
190 {
191 VEC(gdb_xml_value_s) **values = (VEC(gdb_xml_value_s) **) data;
192 struct gdb_xml_value *value;
193 int ix;
194
195 for (ix = 0; VEC_iterate (gdb_xml_value_s, *values, ix, value); ix++)
196 xfree (value->value);
197 VEC_free (gdb_xml_value_s, *values);
198 }
199
200 /* Handle the start of an element. DATA is our local XML parser, NAME
201 is the element, and ATTRS are the names and values of this
202 element's attributes. */
203
204 static void
205 gdb_xml_start_element (void *data, const XML_Char *name,
206 const XML_Char **attrs)
207 {
208 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
209 const struct gdb_xml_element *element;
210 const struct gdb_xml_attribute *attribute;
211 VEC(gdb_xml_value_s) *attributes = NULL;
212 unsigned int seen;
213 struct cleanup *back_to;
214
215 /* Push an error scope. If we return or throw an exception before
216 filling this in, it will tell us to ignore children of this
217 element. Note we don't take a reference to the element yet
218 because further below we'll process the element which may recurse
219 back here and push more elements to the vector. When the
220 recursion unrolls all such elements will have been popped back
221 already, but if one of those pushes reallocates the vector,
222 previous element references will be invalidated. */
223 parser->scopes.emplace_back ();
224
225 /* Get a reference to the current scope. */
226 scope_level &scope = parser->scopes[parser->scopes.size () - 2];
227
228 gdb_xml_debug (parser, _("Entering element <%s>"), name);
229
230 /* Find this element in the list of the current scope's allowed
231 children. Record that we've seen it. */
232
233 seen = 1;
234 for (element = scope.elements; element && element->name;
235 element++, seen <<= 1)
236 if (strcmp (element->name, name) == 0)
237 break;
238
239 if (element == NULL || element->name == NULL)
240 {
241 /* If we're working on XInclude, <xi:include> can be the child
242 of absolutely anything. Copy the previous scope's element
243 list into the new scope even if there was no match. */
244 if (parser->is_xinclude)
245 {
246 XML_DefaultCurrent (parser->expat_parser);
247
248 scope_level &unknown_scope = parser->scopes.back ();
249 unknown_scope.elements = scope.elements;
250 return;
251 }
252
253 gdb_xml_debug (parser, _("Element <%s> unknown"), name);
254 return;
255 }
256
257 if (!(element->flags & GDB_XML_EF_REPEATABLE) && (seen & scope.seen))
258 gdb_xml_error (parser, _("Element <%s> only expected once"), name);
259
260 scope.seen |= seen;
261
262 back_to = make_cleanup (gdb_xml_values_cleanup, &attributes);
263
264 for (attribute = element->attributes;
265 attribute != NULL && attribute->name != NULL;
266 attribute++)
267 {
268 const char *val = NULL;
269 const XML_Char **p;
270 void *parsed_value;
271 struct gdb_xml_value new_value;
272
273 for (p = attrs; *p != NULL; p += 2)
274 if (!strcmp (attribute->name, p[0]))
275 {
276 val = p[1];
277 break;
278 }
279
280 if (*p != NULL && val == NULL)
281 {
282 gdb_xml_debug (parser, _("Attribute \"%s\" missing a value"),
283 attribute->name);
284 continue;
285 }
286
287 if (*p == NULL && !(attribute->flags & GDB_XML_AF_OPTIONAL))
288 {
289 gdb_xml_error (parser, _("Required attribute \"%s\" of "
290 "<%s> not specified"),
291 attribute->name, element->name);
292 continue;
293 }
294
295 if (*p == NULL)
296 continue;
297
298 gdb_xml_debug (parser, _("Parsing attribute %s=\"%s\""),
299 attribute->name, val);
300
301 if (attribute->handler)
302 parsed_value = attribute->handler (parser, attribute, val);
303 else
304 parsed_value = xstrdup (val);
305
306 new_value.name = attribute->name;
307 new_value.value = parsed_value;
308 VEC_safe_push (gdb_xml_value_s, attributes, &new_value);
309 }
310
311 /* Check for unrecognized attributes. */
312 if (debug_xml)
313 {
314 const XML_Char **p;
315
316 for (p = attrs; *p != NULL; p += 2)
317 {
318 for (attribute = element->attributes;
319 attribute != NULL && attribute->name != NULL;
320 attribute++)
321 if (strcmp (attribute->name, *p) == 0)
322 break;
323
324 if (attribute == NULL || attribute->name == NULL)
325 gdb_xml_debug (parser, _("Ignoring unknown attribute %s"), *p);
326 }
327 }
328
329 /* Call the element handler if there is one. */
330 if (element->start_handler)
331 element->start_handler (parser, element, parser->user_data, attributes);
332
333 /* Fill in a new scope level. Note that we must delay getting a
334 back reference till here because above we might have recursed,
335 which may have reallocated the vector which invalidates
336 iterators/pointers/references. */
337 scope_level &new_scope = parser->scopes.back ();
338 new_scope.element = element;
339 new_scope.elements = element->children;
340
341 do_cleanups (back_to);
342 }
343
344 /* Wrapper for gdb_xml_start_element, to prevent throwing exceptions
345 through expat. */
346
347 static void
348 gdb_xml_start_element_wrapper (void *data, const XML_Char *name,
349 const XML_Char **attrs)
350 {
351 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
352
353 if (parser->error.reason < 0)
354 return;
355
356 TRY
357 {
358 gdb_xml_start_element (data, name, attrs);
359 }
360 CATCH (ex, RETURN_MASK_ALL)
361 {
362 parser->error = ex;
363 #ifdef HAVE_XML_STOPPARSER
364 XML_StopParser (parser->expat_parser, XML_FALSE);
365 #endif
366 }
367 END_CATCH
368 }
369
370 /* Handle the end of an element. PARSER is our local XML parser, and
371 NAME is the current element. */
372
373 static void
374 gdb_xml_end_element (gdb_xml_parser *parser, const XML_Char *name)
375 {
376 struct scope_level *scope = &parser->scopes.back ();
377 const struct gdb_xml_element *element;
378 unsigned int seen;
379
380 gdb_xml_debug (parser, _("Leaving element <%s>"), name);
381
382 for (element = scope->elements, seen = 1;
383 element != NULL && element->name != NULL;
384 element++, seen <<= 1)
385 if ((scope->seen & seen) == 0
386 && (element->flags & GDB_XML_EF_OPTIONAL) == 0)
387 gdb_xml_error (parser, _("Required element <%s> is missing"),
388 element->name);
389
390 /* Call the element processor. */
391 if (scope->element != NULL && scope->element->end_handler)
392 {
393 const char *scope_body;
394
395 if (scope->body == NULL)
396 scope_body = "";
397 else
398 {
399 int length;
400
401 length = obstack_object_size (scope->body);
402 obstack_1grow (scope->body, '\0');
403 char *body = (char *) obstack_finish (scope->body);
404
405 /* Strip leading and trailing whitespace. */
406 while (length > 0 && ISSPACE (body[length-1]))
407 body[--length] = '\0';
408 while (*body && ISSPACE (*body))
409 body++;
410
411 scope_body = body;
412 }
413
414 scope->element->end_handler (parser, scope->element, parser->user_data,
415 scope_body);
416 }
417 else if (scope->element == NULL)
418 XML_DefaultCurrent (parser->expat_parser);
419
420 /* Pop the scope level. */
421 parser->scopes.pop_back ();
422 }
423
424 /* Wrapper for gdb_xml_end_element, to prevent throwing exceptions
425 through expat. */
426
427 static void
428 gdb_xml_end_element_wrapper (void *data, const XML_Char *name)
429 {
430 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
431
432 if (parser->error.reason < 0)
433 return;
434
435 TRY
436 {
437 gdb_xml_end_element (parser, name);
438 }
439 CATCH (ex, RETURN_MASK_ALL)
440 {
441 parser->error = ex;
442 #ifdef HAVE_XML_STOPPARSER
443 XML_StopParser (parser->expat_parser, XML_FALSE);
444 #endif
445 }
446 END_CATCH
447 }
448
449 /* Free a parser and all its associated state. */
450
451 gdb_xml_parser::~gdb_xml_parser ()
452 {
453 XML_ParserFree (this->expat_parser);
454 }
455
456 /* Initialize a parser. */
457
458 gdb_xml_parser::gdb_xml_parser (const char *name_,
459 const gdb_xml_element *elements,
460 void *user_data_)
461 : name (name_),
462 user_data (user_data_),
463 error (exception_none),
464 last_line (0),
465 dtd_name (NULL),
466 is_xinclude (false)
467 {
468 this->expat_parser = XML_ParserCreateNS (NULL, '!');
469 if (this->expat_parser == NULL)
470 malloc_failure (0);
471
472 XML_SetUserData (this->expat_parser, this);
473
474 /* Set the callbacks. */
475 XML_SetElementHandler (this->expat_parser, gdb_xml_start_element_wrapper,
476 gdb_xml_end_element_wrapper);
477 XML_SetCharacterDataHandler (this->expat_parser, gdb_xml_body_text);
478
479 /* Initialize the outer scope. */
480 this->scopes.emplace_back (elements);
481 }
482
483 /* External entity handler. The only external entities we support
484 are those compiled into GDB (we do not fetch entities from the
485 target). */
486
487 static int XMLCALL
488 gdb_xml_fetch_external_entity (XML_Parser expat_parser,
489 const XML_Char *context,
490 const XML_Char *base,
491 const XML_Char *systemId,
492 const XML_Char *publicId)
493 {
494 struct gdb_xml_parser *parser
495 = (struct gdb_xml_parser *) XML_GetUserData (expat_parser);
496 XML_Parser entity_parser;
497 const char *text;
498 enum XML_Status status;
499
500 if (systemId == NULL)
501 {
502 text = fetch_xml_builtin (parser->dtd_name);
503 if (text == NULL)
504 internal_error (__FILE__, __LINE__,
505 _("could not locate built-in DTD %s"),
506 parser->dtd_name);
507 }
508 else
509 {
510 text = fetch_xml_builtin (systemId);
511 if (text == NULL)
512 return XML_STATUS_ERROR;
513 }
514
515 entity_parser = XML_ExternalEntityParserCreate (expat_parser, context, NULL);
516
517 /* Don't use our handlers for the contents of the DTD. Just let expat
518 process it. */
519 XML_SetElementHandler (entity_parser, NULL, NULL);
520 XML_SetDoctypeDeclHandler (entity_parser, NULL, NULL);
521 XML_SetXmlDeclHandler (entity_parser, NULL);
522 XML_SetDefaultHandler (entity_parser, NULL);
523 XML_SetUserData (entity_parser, NULL);
524
525 status = XML_Parse (entity_parser, text, strlen (text), 1);
526
527 XML_ParserFree (entity_parser);
528 return status;
529 }
530
531 /* Associate DTD_NAME, which must be the name of a compiled-in DTD,
532 with PARSER. */
533
534 void
535 gdb_xml_use_dtd (struct gdb_xml_parser *parser, const char *dtd_name)
536 {
537 enum XML_Error err;
538
539 parser->dtd_name = dtd_name;
540
541 XML_SetParamEntityParsing (parser->expat_parser,
542 XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
543 XML_SetExternalEntityRefHandler (parser->expat_parser,
544 gdb_xml_fetch_external_entity);
545
546 /* Even if no DTD is provided, use the built-in DTD anyway. */
547 err = XML_UseForeignDTD (parser->expat_parser, XML_TRUE);
548 if (err != XML_ERROR_NONE)
549 internal_error (__FILE__, __LINE__,
550 _("XML_UseForeignDTD failed: %s"),
551 XML_ErrorString (err));
552 }
553
554 /* Invoke PARSER on BUFFER. BUFFER is the data to parse, which
555 should be NUL-terminated.
556
557 The return value is 0 for success or -1 for error. It may throw,
558 but only if something unexpected goes wrong during parsing; parse
559 errors will be caught, warned about, and reported as failure. */
560
561 int
562 gdb_xml_parse (struct gdb_xml_parser *parser, const char *buffer)
563 {
564 enum XML_Status status;
565 const char *error_string;
566
567 gdb_xml_debug (parser, _("Starting:\n%s"), buffer);
568
569 status = XML_Parse (parser->expat_parser, buffer, strlen (buffer), 1);
570
571 if (status == XML_STATUS_OK && parser->error.reason == 0)
572 return 0;
573
574 if (parser->error.reason == RETURN_ERROR
575 && parser->error.error == XML_PARSE_ERROR)
576 {
577 gdb_assert (parser->error.message != NULL);
578 error_string = parser->error.message;
579 }
580 else if (status == XML_STATUS_ERROR)
581 {
582 enum XML_Error err = XML_GetErrorCode (parser->expat_parser);
583
584 error_string = XML_ErrorString (err);
585 }
586 else
587 {
588 gdb_assert (parser->error.reason < 0);
589 throw_exception (parser->error);
590 }
591
592 if (parser->last_line != 0)
593 warning (_("while parsing %s (at line %d): %s"), parser->name,
594 parser->last_line, error_string);
595 else
596 warning (_("while parsing %s: %s"), parser->name, error_string);
597
598 return -1;
599 }
600
601 int
602 gdb_xml_parse_quick (const char *name, const char *dtd_name,
603 const struct gdb_xml_element *elements,
604 const char *document, void *user_data)
605 {
606 gdb_xml_parser parser (name, elements, user_data);
607 if (dtd_name != NULL)
608 gdb_xml_use_dtd (&parser, dtd_name);
609 return gdb_xml_parse (&parser, document);
610 }
611
612 /* Parse a field VALSTR that we expect to contain an integer value.
613 The integer is returned in *VALP. The string is parsed with an
614 equivalent to strtoul.
615
616 Returns 0 for success, -1 for error. */
617
618 static int
619 xml_parse_unsigned_integer (const char *valstr, ULONGEST *valp)
620 {
621 const char *endptr;
622 ULONGEST result;
623
624 if (*valstr == '\0')
625 return -1;
626
627 result = strtoulst (valstr, &endptr, 0);
628 if (*endptr != '\0')
629 return -1;
630
631 *valp = result;
632 return 0;
633 }
634
635 /* Parse an integer string into a ULONGEST and return it, or call
636 gdb_xml_error if it could not be parsed. */
637
638 ULONGEST
639 gdb_xml_parse_ulongest (struct gdb_xml_parser *parser, const char *value)
640 {
641 ULONGEST result;
642
643 if (xml_parse_unsigned_integer (value, &result) != 0)
644 gdb_xml_error (parser, _("Can't convert \"%s\" to an integer"), value);
645
646 return result;
647 }
648
649 /* Parse an integer attribute into a ULONGEST. */
650
651 void *
652 gdb_xml_parse_attr_ulongest (struct gdb_xml_parser *parser,
653 const struct gdb_xml_attribute *attribute,
654 const char *value)
655 {
656 ULONGEST result;
657 void *ret;
658
659 if (xml_parse_unsigned_integer (value, &result) != 0)
660 gdb_xml_error (parser, _("Can't convert %s=\"%s\" to an integer"),
661 attribute->name, value);
662
663 ret = XNEW (ULONGEST);
664 memcpy (ret, &result, sizeof (result));
665 return ret;
666 }
667
668 /* A handler_data for yes/no boolean values. */
669
670 const struct gdb_xml_enum gdb_xml_enums_boolean[] = {
671 { "yes", 1 },
672 { "no", 0 },
673 { NULL, 0 }
674 };
675
676 /* Map NAME to VALUE. A struct gdb_xml_enum * should be saved as the
677 value of handler_data when using gdb_xml_parse_attr_enum to parse a
678 fixed list of possible strings. The list is terminated by an entry
679 with NAME == NULL. */
680
681 void *
682 gdb_xml_parse_attr_enum (struct gdb_xml_parser *parser,
683 const struct gdb_xml_attribute *attribute,
684 const char *value)
685 {
686 const struct gdb_xml_enum *enums
687 = (const struct gdb_xml_enum *) attribute->handler_data;
688 void *ret;
689
690 for (enums = (const struct gdb_xml_enum *) attribute->handler_data;
691 enums->name != NULL; enums++)
692 if (strcasecmp (enums->name, value) == 0)
693 break;
694
695 if (enums->name == NULL)
696 gdb_xml_error (parser, _("Unknown attribute value %s=\"%s\""),
697 attribute->name, value);
698
699 ret = xmalloc (sizeof (enums->value));
700 memcpy (ret, &enums->value, sizeof (enums->value));
701 return ret;
702 }
703 \f
704
705 /* XInclude processing. This is done as a separate step from actually
706 parsing the document, so that we can produce a single combined XML
707 document - e.g. to hand to a front end or to simplify comparing two
708 documents. We make extensive use of XML_DefaultCurrent, to pass
709 input text directly into the output without reformatting or
710 requoting it.
711
712 We output the DOCTYPE declaration for the first document unchanged,
713 if present, and discard DOCTYPEs from included documents. Only the
714 one we pass through here is used when we feed the result back to
715 expat. The XInclude standard explicitly does not discuss
716 validation of the result; we choose to apply the same DTD applied
717 to the outermost document.
718
719 We can not simply include the external DTD subset in the document
720 as an internal subset, because <!IGNORE> and <!INCLUDE> are valid
721 only in external subsets. But if we do not pass the DTD into the
722 output at all, default values will not be filled in.
723
724 We don't pass through any <?xml> declaration because we generate
725 UTF-8, not whatever the input encoding was. */
726
727 struct xinclude_parsing_data
728 {
729 xinclude_parsing_data (xml_fetch_another fetcher_, void *fetcher_baton_,
730 int include_depth_)
731 : skip_depth (0),
732 include_depth (include_depth_),
733 fetcher (fetcher_),
734 fetcher_baton (fetcher_baton_)
735 {
736 obstack_init (&this->obstack);
737 }
738
739 ~xinclude_parsing_data ()
740 {
741 obstack_free (&this->obstack, NULL);
742 }
743
744 /* The obstack to build the output in. */
745 struct obstack obstack;
746
747 /* A count indicating whether we are in an element whose
748 children should not be copied to the output, and if so,
749 how deep we are nested. This is used for anything inside
750 an xi:include, and for the DTD. */
751 int skip_depth;
752
753 /* The number of <xi:include> elements currently being processed,
754 to detect loops. */
755 int include_depth;
756
757 /* A function to call to obtain additional features, and its
758 baton. */
759 xml_fetch_another fetcher;
760 void *fetcher_baton;
761 };
762
763 static void
764 xinclude_start_include (struct gdb_xml_parser *parser,
765 const struct gdb_xml_element *element,
766 void *user_data, VEC(gdb_xml_value_s) *attributes)
767 {
768 struct xinclude_parsing_data *data
769 = (struct xinclude_parsing_data *) user_data;
770 char *href = (char *) xml_find_attribute (attributes, "href")->value;
771 struct cleanup *back_to;
772 char *text, *output;
773
774 gdb_xml_debug (parser, _("Processing XInclude of \"%s\""), href);
775
776 if (data->include_depth > MAX_XINCLUDE_DEPTH)
777 gdb_xml_error (parser, _("Maximum XInclude depth (%d) exceeded"),
778 MAX_XINCLUDE_DEPTH);
779
780 text = data->fetcher (href, data->fetcher_baton);
781 if (text == NULL)
782 gdb_xml_error (parser, _("Could not load XML document \"%s\""), href);
783 back_to = make_cleanup (xfree, text);
784
785 output = xml_process_xincludes (parser->name, text, data->fetcher,
786 data->fetcher_baton,
787 data->include_depth + 1);
788 if (output == NULL)
789 gdb_xml_error (parser, _("Parsing \"%s\" failed"), href);
790
791 obstack_grow (&data->obstack, output, strlen (output));
792 xfree (output);
793
794 do_cleanups (back_to);
795
796 data->skip_depth++;
797 }
798
799 static void
800 xinclude_end_include (struct gdb_xml_parser *parser,
801 const struct gdb_xml_element *element,
802 void *user_data, const char *body_text)
803 {
804 struct xinclude_parsing_data *data
805 = (struct xinclude_parsing_data *) user_data;
806
807 data->skip_depth--;
808 }
809
810 static void XMLCALL
811 xml_xinclude_default (void *data_, const XML_Char *s, int len)
812 {
813 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data_;
814 struct xinclude_parsing_data *data
815 = (struct xinclude_parsing_data *) parser->user_data;
816
817 /* If we are inside of e.g. xi:include or the DTD, don't save this
818 string. */
819 if (data->skip_depth)
820 return;
821
822 /* Otherwise just add it to the end of the document we're building
823 up. */
824 obstack_grow (&data->obstack, s, len);
825 }
826
827 static void XMLCALL
828 xml_xinclude_start_doctype (void *data_, const XML_Char *doctypeName,
829 const XML_Char *sysid, const XML_Char *pubid,
830 int has_internal_subset)
831 {
832 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data_;
833 struct xinclude_parsing_data *data
834 = (struct xinclude_parsing_data *) parser->user_data;
835
836 /* Don't print out the doctype, or the contents of the DTD internal
837 subset, if any. */
838 data->skip_depth++;
839 }
840
841 static void XMLCALL
842 xml_xinclude_end_doctype (void *data_)
843 {
844 struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data_;
845 struct xinclude_parsing_data *data
846 = (struct xinclude_parsing_data *) parser->user_data;
847
848 data->skip_depth--;
849 }
850
851 static void XMLCALL
852 xml_xinclude_xml_decl (void *data_, const XML_Char *version,
853 const XML_Char *encoding, int standalone)
854 {
855 /* Do nothing - this function prevents the default handler from
856 being called, thus suppressing the XML declaration from the
857 output. */
858 }
859
860 const struct gdb_xml_attribute xinclude_attributes[] = {
861 { "href", GDB_XML_AF_NONE, NULL, NULL },
862 { NULL, GDB_XML_AF_NONE, NULL, NULL }
863 };
864
865 const struct gdb_xml_element xinclude_elements[] = {
866 { "http://www.w3.org/2001/XInclude!include", xinclude_attributes, NULL,
867 GDB_XML_EF_OPTIONAL | GDB_XML_EF_REPEATABLE,
868 xinclude_start_include, xinclude_end_include },
869 { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
870 };
871
872 /* The main entry point for <xi:include> processing. */
873
874 char *
875 xml_process_xincludes (const char *name, const char *text,
876 xml_fetch_another fetcher, void *fetcher_baton,
877 int depth)
878 {
879 char *result = NULL;
880
881 xinclude_parsing_data data (fetcher, fetcher_baton, depth);
882
883 gdb_xml_parser parser (name, xinclude_elements, &data);
884 parser.is_xinclude = true;
885
886 XML_SetCharacterDataHandler (parser.expat_parser, NULL);
887 XML_SetDefaultHandler (parser.expat_parser, xml_xinclude_default);
888
889 /* Always discard the XML version declarations; the only important
890 thing this provides is encoding, and our result will have been
891 converted to UTF-8. */
892 XML_SetXmlDeclHandler (parser.expat_parser, xml_xinclude_xml_decl);
893
894 if (depth > 0)
895 /* Discard the doctype for included documents. */
896 XML_SetDoctypeDeclHandler (parser.expat_parser,
897 xml_xinclude_start_doctype,
898 xml_xinclude_end_doctype);
899
900 gdb_xml_use_dtd (&parser, "xinclude.dtd");
901
902 if (gdb_xml_parse (&parser, text) == 0)
903 {
904 obstack_1grow (&data.obstack, '\0');
905 result = xstrdup ((const char *) obstack_finish (&data.obstack));
906
907 if (depth == 0)
908 gdb_xml_debug (&parser, _("XInclude processing succeeded."));
909 }
910 else
911 result = NULL;
912
913 return result;
914 }
915 #endif /* HAVE_LIBEXPAT */
916 \f
917
918 /* Return an XML document which was compiled into GDB, from
919 the given FILENAME, or NULL if the file was not compiled in. */
920
921 const char *
922 fetch_xml_builtin (const char *filename)
923 {
924 const char *(*p)[2];
925
926 for (p = xml_builtin; (*p)[0]; p++)
927 if (strcmp ((*p)[0], filename) == 0)
928 return (*p)[1];
929
930 return NULL;
931 }
932
933 /* A to_xfer_partial helper function which reads XML files which were
934 compiled into GDB. The target may call this function from its own
935 to_xfer_partial handler, after converting object and annex to the
936 appropriate filename. */
937
938 LONGEST
939 xml_builtin_xfer_partial (const char *filename,
940 gdb_byte *readbuf, const gdb_byte *writebuf,
941 ULONGEST offset, LONGEST len)
942 {
943 const char *buf;
944 LONGEST len_avail;
945
946 gdb_assert (readbuf != NULL && writebuf == NULL);
947 gdb_assert (filename != NULL);
948
949 buf = fetch_xml_builtin (filename);
950 if (buf == NULL)
951 return -1;
952
953 len_avail = strlen (buf);
954 if (offset >= len_avail)
955 return 0;
956
957 if (len > len_avail - offset)
958 len = len_avail - offset;
959 memcpy (readbuf, buf + offset, len);
960 return len;
961 }
962 \f
963
964 static void
965 show_debug_xml (struct ui_file *file, int from_tty,
966 struct cmd_list_element *c, const char *value)
967 {
968 fprintf_filtered (file, _("XML debugging is %s.\n"), value);
969 }
970
971 void
972 obstack_xml_printf (struct obstack *obstack, const char *format, ...)
973 {
974 va_list ap;
975 const char *f;
976 const char *prev;
977 int percent = 0;
978
979 va_start (ap, format);
980
981 prev = format;
982 for (f = format; *f; f++)
983 {
984 if (percent)
985 {
986 switch (*f)
987 {
988 case 's':
989 {
990 char *p;
991 char *a = va_arg (ap, char *);
992
993 obstack_grow (obstack, prev, f - prev - 1);
994 p = xml_escape_text (a);
995 obstack_grow_str (obstack, p);
996 xfree (p);
997 prev = f + 1;
998 }
999 break;
1000 }
1001 percent = 0;
1002 }
1003 else if (*f == '%')
1004 percent = 1;
1005 }
1006
1007 obstack_grow_str (obstack, prev);
1008 va_end (ap);
1009 }
1010
1011 char *
1012 xml_fetch_content_from_file (const char *filename, void *baton)
1013 {
1014 const char *dirname = (const char *) baton;
1015 FILE *file;
1016 struct cleanup *back_to;
1017 char *text;
1018 size_t len, offset;
1019
1020 if (dirname && *dirname)
1021 {
1022 char *fullname = concat (dirname, "/", filename, (char *) NULL);
1023
1024 if (fullname == NULL)
1025 malloc_failure (0);
1026 file = gdb_fopen_cloexec (fullname, FOPEN_RT);
1027 xfree (fullname);
1028 }
1029 else
1030 file = gdb_fopen_cloexec (filename, FOPEN_RT);
1031
1032 if (file == NULL)
1033 return NULL;
1034
1035 back_to = make_cleanup_fclose (file);
1036
1037 /* Read in the whole file, one chunk at a time. */
1038 len = 4096;
1039 offset = 0;
1040 text = (char *) xmalloc (len);
1041 make_cleanup (free_current_contents, &text);
1042 while (1)
1043 {
1044 size_t bytes_read;
1045
1046 /* Continue reading where the last read left off. Leave at least
1047 one byte so that we can NUL-terminate the result. */
1048 bytes_read = fread (text + offset, 1, len - offset - 1, file);
1049 if (ferror (file))
1050 {
1051 warning (_("Read error from \"%s\""), filename);
1052 do_cleanups (back_to);
1053 return NULL;
1054 }
1055
1056 offset += bytes_read;
1057
1058 if (feof (file))
1059 break;
1060
1061 len = len * 2;
1062 text = (char *) xrealloc (text, len);
1063 }
1064
1065 fclose (file);
1066 discard_cleanups (back_to);
1067
1068 text[offset] = '\0';
1069 return text;
1070 }
1071
1072 void _initialize_xml_support (void);
1073
1074 void
1075 _initialize_xml_support (void)
1076 {
1077 add_setshow_boolean_cmd ("xml", class_maintenance, &debug_xml,
1078 _("Set XML parser debugging."),
1079 _("Show XML parser debugging."),
1080 _("When set, debugging messages for XML parsers "
1081 "are displayed."),
1082 NULL, show_debug_xml,
1083 &setdebuglist, &showdebuglist);
1084 }