gdb/xml-support.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* Helper routines for parsing XML using Expat.

  2.    Copyright (C) 2006-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "gdbcmd.h"
  16. #include "xml-support.h"
  17. #include "filestuff.h"
  18. #include "safe-ctype.h"

  19. /* Debugging flag.  */
  20. static int debug_xml;

  21. /* The contents of this file are only useful if XML support is
  22.    available.  */
  23. #ifdef HAVE_LIBEXPAT

  24. #include "gdb_expat.h"

  25. /* The maximum depth of <xi:include> nesting.  No need to be miserly,
  26.    we just want to avoid running out of stack on loops.  */
  27. #define MAX_XINCLUDE_DEPTH 30

  28. /* Simplified XML parser infrastructure.  */

  29. /* A parsing level -- used to keep track of the current element
  30.    nesting.  */
  31. struct scope_level
  32. {
  33.   /* Elements we allow at this level.  */
  34.   const struct gdb_xml_element *elements;

  35.   /* The element which we are within.  */
  36.   const struct gdb_xml_element *element;

  37.   /* Mask of which elements we've seen at this level (used for
  38.      optional and repeatable checking).  */
  39.   unsigned int seen;

  40.   /* Body text accumulation.  */
  41.   struct obstack *body;
  42. };
  43. typedef struct scope_level scope_level_s;
  44. DEF_VEC_O(scope_level_s);

  45. /* The parser itself, and our additional state.  */
  46. struct gdb_xml_parser
  47. {
  48.   XML_Parser expat_parser;        /* The underlying expat parser.  */

  49.   const char *name;                /* Name of this parser.  */
  50.   void *user_data;                /* The user's callback data, for handlers.  */

  51.   VEC(scope_level_s) *scopes;        /* Scoping stack.  */

  52.   struct gdb_exception error;        /* A thrown error, if any.  */
  53.   int last_line;                /* The line of the thrown error, or 0.  */

  54.   const char *dtd_name;                /* The name of the expected / default DTD,
  55.                                    if specified.  */
  56.   int is_xinclude;                /* Are we the special <xi:include> parser?  */
  57. };

  58. /* Process some body text.  We accumulate the text for later use; it's
  59.    wrong to do anything with it immediately, because a single block of
  60.    text might be broken up into multiple calls to this function.  */

  61. static void
  62. gdb_xml_body_text (void *data, const XML_Char *text, int length)
  63. {
  64.   struct gdb_xml_parser *parser = data;
  65.   struct scope_level *scope = VEC_last (scope_level_s, parser->scopes);

  66.   if (parser->error.reason < 0)
  67.     return;

  68.   if (scope->body == NULL)
  69.     {
  70.       scope->body = XCNEW (struct obstack);
  71.       obstack_init (scope->body);
  72.     }

  73.   obstack_grow (scope->body, text, length);
  74. }

  75. /* Issue a debugging message from one of PARSER's handlers.  */

  76. void
  77. gdb_xml_debug (struct gdb_xml_parser *parser, const char *format, ...)
  78. {
  79.   int line = XML_GetCurrentLineNumber (parser->expat_parser);
  80.   va_list ap;
  81.   char *message;

  82.   if (!debug_xml)
  83.     return;

  84.   va_start (ap, format);
  85.   message = xstrvprintf (format, ap);
  86.   if (line)
  87.     fprintf_unfiltered (gdb_stderr, "%s (line %d): %s\n",
  88.                         parser->name, line, message);
  89.   else
  90.     fprintf_unfiltered (gdb_stderr, "%s: %s\n",
  91.                         parser->name, message);
  92.   xfree (message);
  93. }

  94. /* Issue an error message from one of PARSER's handlers, and stop
  95.    parsing.  */

  96. void
  97. gdb_xml_error (struct gdb_xml_parser *parser, const char *format, ...)
  98. {
  99.   int line = XML_GetCurrentLineNumber (parser->expat_parser);
  100.   va_list ap;

  101.   parser->last_line = line;
  102.   va_start (ap, format);
  103.   throw_verror (XML_PARSE_ERROR, format, ap);
  104. }

  105. /* Find the attribute named NAME in the set of parsed attributes
  106.    ATTRIBUTES.  Returns NULL if not found.  */

  107. struct gdb_xml_value *
  108. xml_find_attribute (VEC(gdb_xml_value_s) *attributes, const char *name)
  109. {
  110.   struct gdb_xml_value *value;
  111.   int ix;

  112.   for (ix = 0; VEC_iterate (gdb_xml_value_s, attributes, ix, value); ix++)
  113.     if (strcmp (value->name, name) == 0)
  114.       return value;

  115.   return NULL;
  116. }

  117. /* Clean up a vector of parsed attribute values.  */

  118. static void
  119. gdb_xml_values_cleanup (void *data)
  120. {
  121.   VEC(gdb_xml_value_s) **values = data;
  122.   struct gdb_xml_value *value;
  123.   int ix;

  124.   for (ix = 0; VEC_iterate (gdb_xml_value_s, *values, ix, value); ix++)
  125.     xfree (value->value);
  126.   VEC_free (gdb_xml_value_s, *values);
  127. }

  128. /* Handle the start of an element.  DATA is our local XML parser, NAME
  129.    is the element, and ATTRS are the names and values of this
  130.    element's attributes.  */

  131. static void
  132. gdb_xml_start_element (void *data, const XML_Char *name,
  133.                        const XML_Char **attrs)
  134. {
  135.   struct gdb_xml_parser *parser = data;
  136.   struct scope_level *scope;
  137.   struct scope_level new_scope;
  138.   const struct gdb_xml_element *element;
  139.   const struct gdb_xml_attribute *attribute;
  140.   VEC(gdb_xml_value_s) *attributes = NULL;
  141.   unsigned int seen;
  142.   struct cleanup *back_to;

  143.   /* Push an error scope.  If we return or throw an exception before
  144.      filling this in, it will tell us to ignore children of this
  145.      element.  */
  146.   VEC_reserve (scope_level_s, parser->scopes, 1);
  147.   scope = VEC_last (scope_level_s, parser->scopes);
  148.   memset (&new_scope, 0, sizeof (new_scope));
  149.   VEC_quick_push (scope_level_s, parser->scopes, &new_scope);

  150.   gdb_xml_debug (parser, _("Entering element <%s>"), name);

  151.   /* Find this element in the list of the current scope's allowed
  152.      children.  Record that we've seen it.  */

  153.   seen = 1;
  154.   for (element = scope->elements; element && element->name;
  155.        element++, seen <<= 1)
  156.     if (strcmp (element->name, name) == 0)
  157.       break;

  158.   if (element == NULL || element->name == NULL)
  159.     {
  160.       /* If we're working on XInclude, <xi:include> can be the child
  161.          of absolutely anything.  Copy the previous scope's element
  162.          list into the new scope even if there was no match.  */
  163.       if (parser->is_xinclude)
  164.         {
  165.           struct scope_level *unknown_scope;

  166.           XML_DefaultCurrent (parser->expat_parser);

  167.           unknown_scope = VEC_last (scope_level_s, parser->scopes);
  168.           unknown_scope->elements = scope->elements;
  169.           return;
  170.         }

  171.       gdb_xml_debug (parser, _("Element <%s> unknown"), name);
  172.       return;
  173.     }

  174.   if (!(element->flags & GDB_XML_EF_REPEATABLE) && (seen & scope->seen))
  175.     gdb_xml_error (parser, _("Element <%s> only expected once"), name);

  176.   scope->seen |= seen;

  177.   back_to = make_cleanup (gdb_xml_values_cleanup, &attributes);

  178.   for (attribute = element->attributes;
  179.        attribute != NULL && attribute->name != NULL;
  180.        attribute++)
  181.     {
  182.       const char *val = NULL;
  183.       const XML_Char **p;
  184.       void *parsed_value;
  185.       struct gdb_xml_value new_value;

  186.       for (p = attrs; *p != NULL; p += 2)
  187.         if (!strcmp (attribute->name, p[0]))
  188.           {
  189.             val = p[1];
  190.             break;
  191.           }

  192.       if (*p != NULL && val == NULL)
  193.         {
  194.           gdb_xml_debug (parser, _("Attribute \"%s\" missing a value"),
  195.                          attribute->name);
  196.           continue;
  197.         }

  198.       if (*p == NULL && !(attribute->flags & GDB_XML_AF_OPTIONAL))
  199.         {
  200.           gdb_xml_error (parser, _("Required attribute \"%s\" of "
  201.                                    "<%s> not specified"),
  202.                          attribute->name, element->name);
  203.           continue;
  204.         }

  205.       if (*p == NULL)
  206.         continue;

  207.       gdb_xml_debug (parser, _("Parsing attribute %s=\"%s\""),
  208.                      attribute->name, val);

  209.       if (attribute->handler)
  210.         parsed_value = attribute->handler (parser, attribute, val);
  211.       else
  212.         parsed_value = xstrdup (val);

  213.       new_value.name = attribute->name;
  214.       new_value.value = parsed_value;
  215.       VEC_safe_push (gdb_xml_value_s, attributes, &new_value);
  216.     }

  217.   /* Check for unrecognized attributes.  */
  218.   if (debug_xml)
  219.     {
  220.       const XML_Char **p;

  221.       for (p = attrs; *p != NULL; p += 2)
  222.         {
  223.           for (attribute = element->attributes;
  224.                attribute != NULL && attribute->name != NULL;
  225.                attribute++)
  226.             if (strcmp (attribute->name, *p) == 0)
  227.               break;

  228.           if (attribute == NULL || attribute->name == NULL)
  229.             gdb_xml_debug (parser, _("Ignoring unknown attribute %s"), *p);
  230.         }
  231.     }

  232.   /* Call the element handler if there is one.  */
  233.   if (element->start_handler)
  234.     element->start_handler (parser, element, parser->user_data, attributes);

  235.   /* Fill in a new scope level.  */
  236.   scope = VEC_last (scope_level_s, parser->scopes);
  237.   scope->element = element;
  238.   scope->elements = element->children;

  239.   do_cleanups (back_to);
  240. }

  241. /* Wrapper for gdb_xml_start_element, to prevent throwing exceptions
  242.    through expat.  */

  243. static void
  244. gdb_xml_start_element_wrapper (void *data, const XML_Char *name,
  245.                                const XML_Char **attrs)
  246. {
  247.   struct gdb_xml_parser *parser = data;
  248.   volatile struct gdb_exception ex;

  249.   if (parser->error.reason < 0)
  250.     return;

  251.   TRY_CATCH (ex, RETURN_MASK_ALL)
  252.     {
  253.       gdb_xml_start_element (data, name, attrs);
  254.     }
  255.   if (ex.reason < 0)
  256.     {
  257.       parser->error = ex;
  258. #ifdef HAVE_XML_STOPPARSER
  259.       XML_StopParser (parser->expat_parser, XML_FALSE);
  260. #endif
  261.     }
  262. }

  263. /* Handle the end of an element.  DATA is our local XML parser, and
  264.    NAME is the current element.  */

  265. static void
  266. gdb_xml_end_element (void *data, const XML_Char *name)
  267. {
  268.   struct gdb_xml_parser *parser = data;
  269.   struct scope_level *scope = VEC_last (scope_level_s, parser->scopes);
  270.   const struct gdb_xml_element *element;
  271.   unsigned int seen;

  272.   gdb_xml_debug (parser, _("Leaving element <%s>"), name);

  273.   for (element = scope->elements, seen = 1;
  274.        element != NULL && element->name != NULL;
  275.        element++, seen <<= 1)
  276.     if ((scope->seen & seen) == 0
  277.         && (element->flags & GDB_XML_EF_OPTIONAL) == 0)
  278.       gdb_xml_error (parser, _("Required element <%s> is missing"),
  279.                      element->name);

  280.   /* Call the element processor.  */
  281.   if (scope->element != NULL && scope->element->end_handler)
  282.     {
  283.       char *body;

  284.       if (scope->body == NULL)
  285.         body = "";
  286.       else
  287.         {
  288.           int length;

  289.           length = obstack_object_size (scope->body);
  290.           obstack_1grow (scope->body, '\0');
  291.           body = obstack_finish (scope->body);

  292.           /* Strip leading and trailing whitespace.  */
  293.           while (length > 0 && ISSPACE (body[length-1]))
  294.             body[--length] = '\0';
  295.           while (*body && ISSPACE (*body))
  296.             body++;
  297.         }

  298.       scope->element->end_handler (parser, scope->element, parser->user_data,
  299.                                    body);
  300.     }
  301.   else if (scope->element == NULL)
  302.     XML_DefaultCurrent (parser->expat_parser);

  303.   /* Pop the scope level.  */
  304.   if (scope->body)
  305.     {
  306.       obstack_free (scope->body, NULL);
  307.       xfree (scope->body);
  308.     }
  309.   VEC_pop (scope_level_s, parser->scopes);
  310. }

  311. /* Wrapper for gdb_xml_end_element, to prevent throwing exceptions
  312.    through expat.  */

  313. static void
  314. gdb_xml_end_element_wrapper (void *data, const XML_Char *name)
  315. {
  316.   struct gdb_xml_parser *parser = data;
  317.   volatile struct gdb_exception ex;

  318.   if (parser->error.reason < 0)
  319.     return;

  320.   TRY_CATCH (ex, RETURN_MASK_ALL)
  321.     {
  322.       gdb_xml_end_element (data, name);
  323.     }
  324.   if (ex.reason < 0)
  325.     {
  326.       parser->error = ex;
  327. #ifdef HAVE_XML_STOPPARSER
  328.       XML_StopParser (parser->expat_parser, XML_FALSE);
  329. #endif
  330.     }
  331. }

  332. /* Free a parser and all its associated state.  */

  333. static void
  334. gdb_xml_cleanup (void *arg)
  335. {
  336.   struct gdb_xml_parser *parser = arg;
  337.   struct scope_level *scope;
  338.   int ix;

  339.   XML_ParserFree (parser->expat_parser);

  340.   /* Clean up the scopes.  */
  341.   for (ix = 0; VEC_iterate (scope_level_s, parser->scopes, ix, scope); ix++)
  342.     if (scope->body)
  343.       {
  344.         obstack_free (scope->body, NULL);
  345.         xfree (scope->body);
  346.       }
  347.   VEC_free (scope_level_s, parser->scopes);

  348.   xfree (parser);
  349. }

  350. /* Initialize a parser and store it to *PARSER_RESULT.  Register a
  351.    cleanup to destroy the parser.  */

  352. static struct cleanup *
  353. gdb_xml_create_parser_and_cleanup (const char *name,
  354.                                    const struct gdb_xml_element *elements,
  355.                                    void *user_data,
  356.                                    struct gdb_xml_parser **parser_result)
  357. {
  358.   struct gdb_xml_parser *parser;
  359.   struct scope_level start_scope;
  360.   struct cleanup *result;

  361.   /* Initialize the parser.  */
  362.   parser = XCNEW (struct gdb_xml_parser);
  363.   parser->expat_parser = XML_ParserCreateNS (NULL, '!');
  364.   if (parser->expat_parser == NULL)
  365.     {
  366.       xfree (parser);
  367.       malloc_failure (0);
  368.     }

  369.   parser->name = name;

  370.   parser->user_data = user_data;
  371.   XML_SetUserData (parser->expat_parser, parser);

  372.   /* Set the callbacks.  */
  373.   XML_SetElementHandler (parser->expat_parser, gdb_xml_start_element_wrapper,
  374.                          gdb_xml_end_element_wrapper);
  375.   XML_SetCharacterDataHandler (parser->expat_parser, gdb_xml_body_text);

  376.   /* Initialize the outer scope.  */
  377.   memset (&start_scope, 0, sizeof (start_scope));
  378.   start_scope.elements = elements;
  379.   VEC_safe_push (scope_level_s, parser->scopes, &start_scope);

  380.   *parser_result = parser;
  381.   return make_cleanup (gdb_xml_cleanup, parser);
  382. }

  383. /* External entity handler.  The only external entities we support
  384.    are those compiled into GDB (we do not fetch entities from the
  385.    target).  */

  386. static int XMLCALL
  387. gdb_xml_fetch_external_entity (XML_Parser expat_parser,
  388.                                const XML_Char *context,
  389.                                const XML_Char *base,
  390.                                const XML_Char *systemId,
  391.                                const XML_Char *publicId)
  392. {
  393.   struct gdb_xml_parser *parser = XML_GetUserData (expat_parser);
  394.   XML_Parser entity_parser;
  395.   const char *text;
  396.   enum XML_Status status;

  397.   if (systemId == NULL)
  398.     {
  399.       text = fetch_xml_builtin (parser->dtd_name);
  400.       if (text == NULL)
  401.         internal_error (__FILE__, __LINE__,
  402.                         _("could not locate built-in DTD %s"),
  403.                         parser->dtd_name);
  404.     }
  405.   else
  406.     {
  407.       text = fetch_xml_builtin (systemId);
  408.       if (text == NULL)
  409.         return XML_STATUS_ERROR;
  410.     }

  411.   entity_parser = XML_ExternalEntityParserCreate (expat_parser, context, NULL);

  412.   /* Don't use our handlers for the contents of the DTD.  Just let expat
  413.      process it.  */
  414.   XML_SetElementHandler (entity_parser, NULL, NULL);
  415.   XML_SetDoctypeDeclHandler (entity_parser, NULL, NULL);
  416.   XML_SetXmlDeclHandler (entity_parser, NULL);
  417.   XML_SetDefaultHandler (entity_parser, NULL);
  418.   XML_SetUserData (entity_parser, NULL);

  419.   status = XML_Parse (entity_parser, text, strlen (text), 1);

  420.   XML_ParserFree (entity_parser);
  421.   return status;
  422. }

  423. /* Associate DTD_NAME, which must be the name of a compiled-in DTD,
  424.    with PARSER.  */

  425. void
  426. gdb_xml_use_dtd (struct gdb_xml_parser *parser, const char *dtd_name)
  427. {
  428.   enum XML_Error err;

  429.   parser->dtd_name = dtd_name;

  430.   XML_SetParamEntityParsing (parser->expat_parser,
  431.                              XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
  432.   XML_SetExternalEntityRefHandler (parser->expat_parser,
  433.                                    gdb_xml_fetch_external_entity);

  434.   /* Even if no DTD is provided, use the built-in DTD anyway.  */
  435.   err = XML_UseForeignDTD (parser->expat_parser, XML_TRUE);
  436.   if (err != XML_ERROR_NONE)
  437.     internal_error (__FILE__, __LINE__,
  438.                     _("XML_UseForeignDTD failed: %s"),
  439.                     XML_ErrorString (err));
  440. }

  441. /* Invoke PARSER on BUFFER.  BUFFER is the data to parse, which
  442.    should be NUL-terminated.

  443.    The return value is 0 for success or -1 for error.  It may throw,
  444.    but only if something unexpected goes wrong during parsing; parse
  445.    errors will be caught, warned about, and reported as failure.  */

  446. int
  447. gdb_xml_parse (struct gdb_xml_parser *parser, const char *buffer)
  448. {
  449.   enum XML_Status status;
  450.   const char *error_string;

  451.   gdb_xml_debug (parser, _("Starting:\n%s"), buffer);

  452.   status = XML_Parse (parser->expat_parser, buffer, strlen (buffer), 1);

  453.   if (status == XML_STATUS_OK && parser->error.reason == 0)
  454.     return 0;

  455.   if (parser->error.reason == RETURN_ERROR
  456.       && parser->error.error == XML_PARSE_ERROR)
  457.     {
  458.       gdb_assert (parser->error.message != NULL);
  459.       error_string = parser->error.message;
  460.     }
  461.   else if (status == XML_STATUS_ERROR)
  462.     {
  463.       enum XML_Error err = XML_GetErrorCode (parser->expat_parser);

  464.       error_string = XML_ErrorString (err);
  465.     }
  466.   else
  467.     {
  468.       gdb_assert (parser->error.reason < 0);
  469.       throw_exception (parser->error);
  470.     }

  471.   if (parser->last_line != 0)
  472.     warning (_("while parsing %s (at line %d): %s"), parser->name,
  473.              parser->last_line, error_string);
  474.   else
  475.     warning (_("while parsing %s: %s"), parser->name, error_string);

  476.   return -1;
  477. }

  478. int
  479. gdb_xml_parse_quick (const char *name, const char *dtd_name,
  480.                      const struct gdb_xml_element *elements,
  481.                      const char *document, void *user_data)
  482. {
  483.   struct gdb_xml_parser *parser;
  484.   struct cleanup *back_to;
  485.   int result;

  486.   back_to = gdb_xml_create_parser_and_cleanup (name, elements,
  487.                                                user_data, &parser);
  488.   if (dtd_name != NULL)
  489.     gdb_xml_use_dtd (parser, dtd_name);
  490.   result = gdb_xml_parse (parser, document);

  491.   do_cleanups (back_to);

  492.   return result;
  493. }

  494. /* Parse a field VALSTR that we expect to contain an integer value.
  495.    The integer is returned in *VALP.  The string is parsed with an
  496.    equivalent to strtoul.

  497.    Returns 0 for success, -1 for error.  */

  498. static int
  499. xml_parse_unsigned_integer (const char *valstr, ULONGEST *valp)
  500. {
  501.   const char *endptr;
  502.   ULONGEST result;

  503.   if (*valstr == '\0')
  504.     return -1;

  505.   result = strtoulst (valstr, &endptr, 0);
  506.   if (*endptr != '\0')
  507.     return -1;

  508.   *valp = result;
  509.   return 0;
  510. }

  511. /* Parse an integer string into a ULONGEST and return it, or call
  512.    gdb_xml_error if it could not be parsed.  */

  513. ULONGEST
  514. gdb_xml_parse_ulongest (struct gdb_xml_parser *parser, const char *value)
  515. {
  516.   ULONGEST result;

  517.   if (xml_parse_unsigned_integer (value, &result) != 0)
  518.     gdb_xml_error (parser, _("Can't convert \"%s\" to an integer"), value);

  519.   return result;
  520. }

  521. /* Parse an integer attribute into a ULONGEST.  */

  522. void *
  523. gdb_xml_parse_attr_ulongest (struct gdb_xml_parser *parser,
  524.                              const struct gdb_xml_attribute *attribute,
  525.                              const char *value)
  526. {
  527.   ULONGEST result;
  528.   void *ret;

  529.   if (xml_parse_unsigned_integer (value, &result) != 0)
  530.     gdb_xml_error (parser, _("Can't convert %s=\"%s\" to an integer"),
  531.                    attribute->name, value);

  532.   ret = xmalloc (sizeof (result));
  533.   memcpy (ret, &result, sizeof (result));
  534.   return ret;
  535. }

  536. /* A handler_data for yes/no boolean values.  */

  537. const struct gdb_xml_enum gdb_xml_enums_boolean[] = {
  538.   { "yes", 1 },
  539.   { "no", 0 },
  540.   { NULL, 0 }
  541. };

  542. /* Map NAME to VALUE.  A struct gdb_xml_enum * should be saved as the
  543.    value of handler_data when using gdb_xml_parse_attr_enum to parse a
  544.    fixed list of possible strings.  The list is terminated by an entry
  545.    with NAME == NULL.  */

  546. void *
  547. gdb_xml_parse_attr_enum (struct gdb_xml_parser *parser,
  548.                          const struct gdb_xml_attribute *attribute,
  549.                          const char *value)
  550. {
  551.   const struct gdb_xml_enum *enums = attribute->handler_data;
  552.   void *ret;

  553.   for (enums = attribute->handler_data; enums->name != NULL; enums++)
  554.     if (strcasecmp (enums->name, value) == 0)
  555.       break;

  556.   if (enums->name == NULL)
  557.     gdb_xml_error (parser, _("Unknown attribute value %s=\"%s\""),
  558.                  attribute->name, value);

  559.   ret = xmalloc (sizeof (enums->value));
  560.   memcpy (ret, &enums->value, sizeof (enums->value));
  561.   return ret;
  562. }


  563. /* XInclude processing.  This is done as a separate step from actually
  564.    parsing the document, so that we can produce a single combined XML
  565.    document - e.g. to hand to a front end or to simplify comparing two
  566.    documents.  We make extensive use of XML_DefaultCurrent, to pass
  567.    input text directly into the output without reformatting or
  568.    requoting it.

  569.    We output the DOCTYPE declaration for the first document unchanged,
  570.    if present, and discard DOCTYPEs from included documents.  Only the
  571.    one we pass through here is used when we feed the result back to
  572.    expat.  The XInclude standard explicitly does not discuss
  573.    validation of the result; we choose to apply the same DTD applied
  574.    to the outermost document.

  575.    We can not simply include the external DTD subset in the document
  576.    as an internal subset, because <!IGNORE> and <!INCLUDE> are valid
  577.    only in external subsets.  But if we do not pass the DTD into the
  578.    output at all, default values will not be filled in.

  579.    We don't pass through any <?xml> declaration because we generate
  580.    UTF-8, not whatever the input encoding was.  */

  581. struct xinclude_parsing_data
  582. {
  583.   /* The obstack to build the output in.  */
  584.   struct obstack obstack;

  585.   /* A count indicating whether we are in an element whose
  586.      children should not be copied to the output, and if so,
  587.      how deep we are nested.  This is used for anything inside
  588.      an xi:include, and for the DTD.  */
  589.   int skip_depth;

  590.   /* The number of <xi:include> elements currently being processed,
  591.      to detect loops.  */
  592.   int include_depth;

  593.   /* A function to call to obtain additional features, and its
  594.      baton.  */
  595.   xml_fetch_another fetcher;
  596.   void *fetcher_baton;
  597. };

  598. static void
  599. xinclude_start_include (struct gdb_xml_parser *parser,
  600.                         const struct gdb_xml_element *element,
  601.                         void *user_data, VEC(gdb_xml_value_s) *attributes)
  602. {
  603.   struct xinclude_parsing_data *data = user_data;
  604.   char *href = xml_find_attribute (attributes, "href")->value;
  605.   struct cleanup *back_to;
  606.   char *text, *output;

  607.   gdb_xml_debug (parser, _("Processing XInclude of \"%s\""), href);

  608.   if (data->include_depth > MAX_XINCLUDE_DEPTH)
  609.     gdb_xml_error (parser, _("Maximum XInclude depth (%d) exceeded"),
  610.                    MAX_XINCLUDE_DEPTH);

  611.   text = data->fetcher (href, data->fetcher_baton);
  612.   if (text == NULL)
  613.     gdb_xml_error (parser, _("Could not load XML document \"%s\""), href);
  614.   back_to = make_cleanup (xfree, text);

  615.   output = xml_process_xincludes (parser->name, text, data->fetcher,
  616.                                   data->fetcher_baton,
  617.                                   data->include_depth + 1);
  618.   if (output == NULL)
  619.     gdb_xml_error (parser, _("Parsing \"%s\" failed"), href);

  620.   obstack_grow (&data->obstack, output, strlen (output));
  621.   xfree (output);

  622.   do_cleanups (back_to);

  623.   data->skip_depth++;
  624. }

  625. static void
  626. xinclude_end_include (struct gdb_xml_parser *parser,
  627.                       const struct gdb_xml_element *element,
  628.                       void *user_data, const char *body_text)
  629. {
  630.   struct xinclude_parsing_data *data = user_data;

  631.   data->skip_depth--;
  632. }

  633. static void XMLCALL
  634. xml_xinclude_default (void *data_, const XML_Char *s, int len)
  635. {
  636.   struct gdb_xml_parser *parser = data_;
  637.   struct xinclude_parsing_data *data = parser->user_data;

  638.   /* If we are inside of e.g. xi:include or the DTD, don't save this
  639.      string.  */
  640.   if (data->skip_depth)
  641.     return;

  642.   /* Otherwise just add it to the end of the document we're building
  643.      up.  */
  644.   obstack_grow (&data->obstack, s, len);
  645. }

  646. static void XMLCALL
  647. xml_xinclude_start_doctype (void *data_, const XML_Char *doctypeName,
  648.                             const XML_Char *sysid, const XML_Char *pubid,
  649.                             int has_internal_subset)
  650. {
  651.   struct gdb_xml_parser *parser = data_;
  652.   struct xinclude_parsing_data *data = parser->user_data;

  653.   /* Don't print out the doctype, or the contents of the DTD internal
  654.      subset, if any.  */
  655.   data->skip_depth++;
  656. }

  657. static void XMLCALL
  658. xml_xinclude_end_doctype (void *data_)
  659. {
  660.   struct gdb_xml_parser *parser = data_;
  661.   struct xinclude_parsing_data *data = parser->user_data;

  662.   data->skip_depth--;
  663. }

  664. static void XMLCALL
  665. xml_xinclude_xml_decl (void *data_, const XML_Char *version,
  666.                        const XML_Char *encoding, int standalone)
  667. {
  668.   /* Do nothing - this function prevents the default handler from
  669.      being called, thus suppressing the XML declaration from the
  670.      output.  */
  671. }

  672. static void
  673. xml_xinclude_cleanup (void *data_)
  674. {
  675.   struct xinclude_parsing_data *data = data_;

  676.   obstack_free (&data->obstack, NULL);
  677.   xfree (data);
  678. }

  679. const struct gdb_xml_attribute xinclude_attributes[] = {
  680.   { "href", GDB_XML_AF_NONE, NULL, NULL },
  681.   { NULL, GDB_XML_AF_NONE, NULL, NULL }
  682. };

  683. const struct gdb_xml_element xinclude_elements[] = {
  684.   { "http://www.w3.org/2001/XInclude!include", xinclude_attributes, NULL,
  685.     GDB_XML_EF_OPTIONAL | GDB_XML_EF_REPEATABLE,
  686.     xinclude_start_include, xinclude_end_include },
  687.   { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  688. };

  689. /* The main entry point for <xi:include> processing.  */

  690. char *
  691. xml_process_xincludes (const char *name, const char *text,
  692.                        xml_fetch_another fetcher, void *fetcher_baton,
  693.                        int depth)
  694. {
  695.   struct gdb_xml_parser *parser;
  696.   struct xinclude_parsing_data *data;
  697.   struct cleanup *back_to;
  698.   char *result = NULL;

  699.   data = XCNEW (struct xinclude_parsing_data);
  700.   obstack_init (&data->obstack);
  701.   back_to = make_cleanup (xml_xinclude_cleanup, data);

  702.   gdb_xml_create_parser_and_cleanup (name, xinclude_elements,
  703.                                      data, &parser);
  704.   parser->is_xinclude = 1;

  705.   data->include_depth = depth;
  706.   data->fetcher = fetcher;
  707.   data->fetcher_baton = fetcher_baton;

  708.   XML_SetCharacterDataHandler (parser->expat_parser, NULL);
  709.   XML_SetDefaultHandler (parser->expat_parser, xml_xinclude_default);

  710.   /* Always discard the XML version declarations; the only important
  711.      thing this provides is encoding, and our result will have been
  712.      converted to UTF-8.  */
  713.   XML_SetXmlDeclHandler (parser->expat_parser, xml_xinclude_xml_decl);

  714.   if (depth > 0)
  715.     /* Discard the doctype for included documents.  */
  716.     XML_SetDoctypeDeclHandler (parser->expat_parser,
  717.                                xml_xinclude_start_doctype,
  718.                                xml_xinclude_end_doctype);

  719.   gdb_xml_use_dtd (parser, "xinclude.dtd");

  720.   if (gdb_xml_parse (parser, text) == 0)
  721.     {
  722.       obstack_1grow (&data->obstack, '\0');
  723.       result = xstrdup (obstack_finish (&data->obstack));

  724.       if (depth == 0)
  725.         gdb_xml_debug (parser, _("XInclude processing succeeded."));
  726.     }
  727.   else
  728.     result = NULL;

  729.   do_cleanups (back_to);
  730.   return result;
  731. }
  732. #endif /* HAVE_LIBEXPAT */


  733. /* Return an XML document which was compiled into GDB, from
  734.    the given FILENAME, or NULL if the file was not compiled in.  */

  735. const char *
  736. fetch_xml_builtin (const char *filename)
  737. {
  738.   const char *(*p)[2];

  739.   for (p = xml_builtin; (*p)[0]; p++)
  740.     if (strcmp ((*p)[0], filename) == 0)
  741.       return (*p)[1];

  742.   return NULL;
  743. }

  744. /* A to_xfer_partial helper function which reads XML files which were
  745.    compiled into GDB.  The target may call this function from its own
  746.    to_xfer_partial handler, after converting object and annex to the
  747.    appropriate filename.  */

  748. LONGEST
  749. xml_builtin_xfer_partial (const char *filename,
  750.                           gdb_byte *readbuf, const gdb_byte *writebuf,
  751.                           ULONGEST offset, LONGEST len)
  752. {
  753.   const char *buf;
  754.   LONGEST len_avail;

  755.   gdb_assert (readbuf != NULL && writebuf == NULL);
  756.   gdb_assert (filename != NULL);

  757.   buf = fetch_xml_builtin (filename);
  758.   if (buf == NULL)
  759.     return -1;

  760.   len_avail = strlen (buf);
  761.   if (offset >= len_avail)
  762.     return 0;

  763.   if (len > len_avail - offset)
  764.     len = len_avail - offset;
  765.   memcpy (readbuf, buf + offset, len);
  766.   return len;
  767. }


  768. static void
  769. show_debug_xml (struct ui_file *file, int from_tty,
  770.                 struct cmd_list_element *c, const char *value)
  771. {
  772.   fprintf_filtered (file, _("XML debugging is %s.\n"), value);
  773. }

  774. void
  775. obstack_xml_printf (struct obstack *obstack, const char *format, ...)
  776. {
  777.   va_list ap;
  778.   const char *f;
  779.   const char *prev;
  780.   int percent = 0;

  781.   va_start (ap, format);

  782.   prev = format;
  783.   for (f = format; *f; f++)
  784.     {
  785.       if (percent)
  786.        {
  787.          switch (*f)
  788.            {
  789.            case 's':
  790.              {
  791.                char *p;
  792.                char *a = va_arg (ap, char *);

  793.                obstack_grow (obstack, prev, f - prev - 1);
  794.                p = xml_escape_text (a);
  795.                obstack_grow_str (obstack, p);
  796.                xfree (p);
  797.                prev = f + 1;
  798.              }
  799.              break;
  800.            }
  801.          percent = 0;
  802.        }
  803.       else if (*f == '%')
  804.        percent = 1;
  805.     }

  806.   obstack_grow_str (obstack, prev);
  807.   va_end (ap);
  808. }

  809. char *
  810. xml_fetch_content_from_file (const char *filename, void *baton)
  811. {
  812.   const char *dirname = baton;
  813.   FILE *file;
  814.   struct cleanup *back_to;
  815.   char *text;
  816.   size_t len, offset;

  817.   if (dirname && *dirname)
  818.     {
  819.       char *fullname = concat (dirname, "/", filename, (char *) NULL);

  820.       if (fullname == NULL)
  821.         malloc_failure (0);
  822.       file = gdb_fopen_cloexec (fullname, FOPEN_RT);
  823.       xfree (fullname);
  824.     }
  825.   else
  826.     file = gdb_fopen_cloexec (filename, FOPEN_RT);

  827.   if (file == NULL)
  828.     return NULL;

  829.   back_to = make_cleanup_fclose (file);

  830.   /* Read in the whole file, one chunk at a time.  */
  831.   len = 4096;
  832.   offset = 0;
  833.   text = xmalloc (len);
  834.   make_cleanup (free_current_contents, &text);
  835.   while (1)
  836.     {
  837.       size_t bytes_read;

  838.       /* Continue reading where the last read left off.  Leave at least
  839.          one byte so that we can NUL-terminate the result.  */
  840.       bytes_read = fread (text + offset, 1, len - offset - 1, file);
  841.       if (ferror (file))
  842.         {
  843.           warning (_("Read error from \"%s\""), filename);
  844.           do_cleanups (back_to);
  845.           return NULL;
  846.         }

  847.       offset += bytes_read;

  848.       if (feof (file))
  849.         break;

  850.       len = len * 2;
  851.       text = xrealloc (text, len);
  852.     }

  853.   fclose (file);
  854.   discard_cleanups (back_to);

  855.   text[offset] = '\0';
  856.   return text;
  857. }

  858. void _initialize_xml_support (void);

  859. void
  860. _initialize_xml_support (void)
  861. {
  862.   add_setshow_boolean_cmd ("xml", class_maintenance, &debug_xml,
  863.                            _("Set XML parser debugging."),
  864.                            _("Show XML parser debugging."),
  865.                            _("When set, debugging messages for XML parsers "
  866.                              "are displayed."),
  867.                            NULL, show_debug_xml,
  868.                            &setdebuglist, &showdebuglist);
  869. }