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