xml-support.c 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017
  1. /* Helper routines for parsing XML using Expat.
  2. Copyright (C) 2006-2022 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-builtin.h"
  17. #include "xml-support.h"
  18. #include "gdbsupport/filestuff.h"
  19. #include "safe-ctype.h"
  20. #include <vector>
  21. #include <string>
  22. /* Debugging flag. */
  23. static bool debug_xml;
  24. /* The contents of this file are only useful if XML support is
  25. available. */
  26. #ifdef HAVE_LIBEXPAT
  27. #include "gdb_expat.h"
  28. /* The maximum depth of <xi:include> nesting. No need to be miserly,
  29. we just want to avoid running out of stack on loops. */
  30. #define MAX_XINCLUDE_DEPTH 30
  31. /* Simplified XML parser infrastructure. */
  32. /* A parsing level -- used to keep track of the current element
  33. nesting. */
  34. struct scope_level
  35. {
  36. explicit scope_level (const gdb_xml_element *elements_ = NULL)
  37. : elements (elements_),
  38. element (NULL),
  39. seen (0)
  40. {}
  41. /* Elements we allow at this level. */
  42. const struct gdb_xml_element *elements;
  43. /* The element which we are within. */
  44. const struct gdb_xml_element *element;
  45. /* Mask of which elements we've seen at this level (used for
  46. optional and repeatable checking). */
  47. unsigned int seen;
  48. /* Body text accumulation. */
  49. std::string body;
  50. };
  51. /* The parser itself, and our additional state. */
  52. struct gdb_xml_parser
  53. {
  54. gdb_xml_parser (const char *name,
  55. const gdb_xml_element *elements,
  56. void *user_data);
  57. ~gdb_xml_parser();
  58. /* Associate DTD_NAME, which must be the name of a compiled-in DTD,
  59. with the parser. */
  60. void use_dtd (const char *dtd_name);
  61. /* Return the name of the expected / default DTD, if specified. */
  62. const char *dtd_name ()
  63. { return m_dtd_name; }
  64. /* Invoke the parser on BUFFER. BUFFER is the data to parse, which
  65. should be NUL-terminated.
  66. The return value is 0 for success or -1 for error. It may throw,
  67. but only if something unexpected goes wrong during parsing; parse
  68. errors will be caught, warned about, and reported as failure. */
  69. int parse (const char *buffer);
  70. /* Issue a debugging message. */
  71. void vdebug (const char *format, va_list ap)
  72. ATTRIBUTE_PRINTF (2, 0);
  73. /* Issue an error message, and stop parsing. */
  74. void verror (const char *format, va_list ap)
  75. ATTRIBUTE_NORETURN ATTRIBUTE_PRINTF (2, 0);
  76. void body_text (const XML_Char *text, int length);
  77. void start_element (const XML_Char *name, const XML_Char **attrs);
  78. void end_element (const XML_Char *name);
  79. /* Return the name of this parser. */
  80. const char *name ()
  81. { return m_name; }
  82. /* Return the user's callback data, for handlers. */
  83. void *user_data ()
  84. { return m_user_data; };
  85. /* Are we the special <xi:include> parser? */
  86. void set_is_xinclude (bool is_xinclude)
  87. { m_is_xinclude = is_xinclude; }
  88. /* A thrown error, if any. */
  89. void set_error (gdb_exception &&error)
  90. {
  91. m_error = std::move (error);
  92. #ifdef HAVE_XML_STOPPARSER
  93. XML_StopParser (m_expat_parser, XML_FALSE);
  94. #endif
  95. }
  96. /* Return the underlying expat parser. */
  97. XML_Parser expat_parser ()
  98. { return m_expat_parser; }
  99. private:
  100. /* The underlying expat parser. */
  101. XML_Parser m_expat_parser;
  102. /* Name of this parser. */
  103. const char *m_name;
  104. /* The user's callback data, for handlers. */
  105. void *m_user_data;
  106. /* Scoping stack. */
  107. std::vector<scope_level> m_scopes;
  108. /* A thrown error, if any. */
  109. struct gdb_exception m_error;
  110. /* The line of the thrown error, or 0. */
  111. int m_last_line;
  112. /* The name of the expected / default DTD, if specified. */
  113. const char *m_dtd_name;
  114. /* Are we the special <xi:include> parser? */
  115. bool m_is_xinclude;
  116. };
  117. /* Process some body text. We accumulate the text for later use; it's
  118. wrong to do anything with it immediately, because a single block of
  119. text might be broken up into multiple calls to this function. */
  120. void
  121. gdb_xml_parser::body_text (const XML_Char *text, int length)
  122. {
  123. if (m_error.reason < 0)
  124. return;
  125. scope_level &scope = m_scopes.back ();
  126. scope.body.append (text, length);
  127. }
  128. static void
  129. gdb_xml_body_text (void *data, const XML_Char *text, int length)
  130. {
  131. struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
  132. parser->body_text (text, length);
  133. }
  134. /* Issue a debugging message from one of PARSER's handlers. */
  135. void
  136. gdb_xml_parser::vdebug (const char *format, va_list ap)
  137. {
  138. int line = XML_GetCurrentLineNumber (m_expat_parser);
  139. std::string message = string_vprintf (format, ap);
  140. if (line)
  141. gdb_printf (gdb_stderr, "%s (line %d): %s\n",
  142. m_name, line, message.c_str ());
  143. else
  144. gdb_printf (gdb_stderr, "%s: %s\n",
  145. m_name, message.c_str ());
  146. }
  147. void
  148. gdb_xml_debug (struct gdb_xml_parser *parser, const char *format, ...)
  149. {
  150. if (!debug_xml)
  151. return;
  152. va_list ap;
  153. va_start (ap, format);
  154. parser->vdebug (format, ap);
  155. va_end (ap);
  156. }
  157. /* Issue an error message from one of PARSER's handlers, and stop
  158. parsing. */
  159. void
  160. gdb_xml_parser::verror (const char *format, va_list ap)
  161. {
  162. int line = XML_GetCurrentLineNumber (m_expat_parser);
  163. m_last_line = line;
  164. throw_verror (XML_PARSE_ERROR, format, ap);
  165. }
  166. void
  167. gdb_xml_error (struct gdb_xml_parser *parser, const char *format, ...)
  168. {
  169. va_list ap;
  170. va_start (ap, format);
  171. parser->verror (format, ap);
  172. va_end (ap);
  173. }
  174. /* Find the attribute named NAME in the set of parsed attributes
  175. ATTRIBUTES. Returns NULL if not found. */
  176. struct gdb_xml_value *
  177. xml_find_attribute (std::vector<gdb_xml_value> &attributes,
  178. const char *name)
  179. {
  180. for (gdb_xml_value &value : attributes)
  181. if (strcmp (value.name, name) == 0)
  182. return &value;
  183. return NULL;
  184. }
  185. /* Handle the start of an element. NAME is the element, and ATTRS are
  186. the names and values of this element's attributes. */
  187. void
  188. gdb_xml_parser::start_element (const XML_Char *name,
  189. const XML_Char **attrs)
  190. {
  191. if (m_error.reason < 0)
  192. return;
  193. const struct gdb_xml_element *element;
  194. const struct gdb_xml_attribute *attribute;
  195. unsigned int seen;
  196. /* Push an error scope. If we return or throw an exception before
  197. filling this in, it will tell us to ignore children of this
  198. element. Note we don't take a reference to the element yet
  199. because further below we'll process the element which may recurse
  200. back here and push more elements to the vector. When the
  201. recursion unrolls all such elements will have been popped back
  202. already, but if one of those pushes reallocates the vector,
  203. previous element references will be invalidated. */
  204. m_scopes.emplace_back ();
  205. /* Get a reference to the current scope. */
  206. scope_level &scope = m_scopes[m_scopes.size () - 2];
  207. gdb_xml_debug (this, _("Entering element <%s>"), name);
  208. /* Find this element in the list of the current scope's allowed
  209. children. Record that we've seen it. */
  210. seen = 1;
  211. for (element = scope.elements; element && element->name;
  212. element++, seen <<= 1)
  213. if (strcmp (element->name, name) == 0)
  214. break;
  215. if (element == NULL || element->name == NULL)
  216. {
  217. /* If we're working on XInclude, <xi:include> can be the child
  218. of absolutely anything. Copy the previous scope's element
  219. list into the new scope even if there was no match. */
  220. if (m_is_xinclude)
  221. {
  222. XML_DefaultCurrent (m_expat_parser);
  223. scope_level &unknown_scope = m_scopes.back ();
  224. unknown_scope.elements = scope.elements;
  225. return;
  226. }
  227. gdb_xml_debug (this, _("Element <%s> unknown"), name);
  228. return;
  229. }
  230. if (!(element->flags & GDB_XML_EF_REPEATABLE) && (seen & scope.seen))
  231. gdb_xml_error (this, _("Element <%s> only expected once"), name);
  232. scope.seen |= seen;
  233. std::vector<gdb_xml_value> attributes;
  234. for (attribute = element->attributes;
  235. attribute != NULL && attribute->name != NULL;
  236. attribute++)
  237. {
  238. const char *val = NULL;
  239. const XML_Char **p;
  240. void *parsed_value;
  241. for (p = attrs; *p != NULL; p += 2)
  242. if (!strcmp (attribute->name, p[0]))
  243. {
  244. val = p[1];
  245. break;
  246. }
  247. if (*p != NULL && val == NULL)
  248. {
  249. gdb_xml_debug (this, _("Attribute \"%s\" missing a value"),
  250. attribute->name);
  251. continue;
  252. }
  253. if (*p == NULL && !(attribute->flags & GDB_XML_AF_OPTIONAL))
  254. {
  255. gdb_xml_error (this, _("Required attribute \"%s\" of "
  256. "<%s> not specified"),
  257. attribute->name, element->name);
  258. continue;
  259. }
  260. if (*p == NULL)
  261. continue;
  262. gdb_xml_debug (this, _("Parsing attribute %s=\"%s\""),
  263. attribute->name, val);
  264. if (attribute->handler)
  265. parsed_value = attribute->handler (this, attribute, val);
  266. else
  267. parsed_value = xstrdup (val);
  268. attributes.emplace_back (attribute->name, parsed_value);
  269. }
  270. /* Check for unrecognized attributes. */
  271. if (debug_xml)
  272. {
  273. const XML_Char **p;
  274. for (p = attrs; *p != NULL; p += 2)
  275. {
  276. for (attribute = element->attributes;
  277. attribute != NULL && attribute->name != NULL;
  278. attribute++)
  279. if (strcmp (attribute->name, *p) == 0)
  280. break;
  281. if (attribute == NULL || attribute->name == NULL)
  282. gdb_xml_debug (this, _("Ignoring unknown attribute %s"), *p);
  283. }
  284. }
  285. /* Call the element handler if there is one. */
  286. if (element->start_handler)
  287. element->start_handler (this, element, m_user_data, attributes);
  288. /* Fill in a new scope level. Note that we must delay getting a
  289. back reference till here because above we might have recursed,
  290. which may have reallocated the vector which invalidates
  291. iterators/pointers/references. */
  292. scope_level &new_scope = m_scopes.back ();
  293. new_scope.element = element;
  294. new_scope.elements = element->children;
  295. }
  296. /* Wrapper for gdb_xml_start_element, to prevent throwing exceptions
  297. through expat. */
  298. static void
  299. gdb_xml_start_element_wrapper (void *data, const XML_Char *name,
  300. const XML_Char **attrs)
  301. {
  302. struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
  303. try
  304. {
  305. parser->start_element (name, attrs);
  306. }
  307. catch (gdb_exception &ex)
  308. {
  309. parser->set_error (std::move (ex));
  310. }
  311. }
  312. /* Handle the end of an element. NAME is the current element. */
  313. void
  314. gdb_xml_parser::end_element (const XML_Char *name)
  315. {
  316. if (m_error.reason < 0)
  317. return;
  318. struct scope_level *scope = &m_scopes.back ();
  319. const struct gdb_xml_element *element;
  320. unsigned int seen;
  321. gdb_xml_debug (this, _("Leaving element <%s>"), name);
  322. for (element = scope->elements, seen = 1;
  323. element != NULL && element->name != NULL;
  324. element++, seen <<= 1)
  325. if ((scope->seen & seen) == 0
  326. && (element->flags & GDB_XML_EF_OPTIONAL) == 0)
  327. gdb_xml_error (this, _("Required element <%s> is missing"),
  328. element->name);
  329. /* Call the element processor. */
  330. if (scope->element != NULL && scope->element->end_handler)
  331. {
  332. const char *body;
  333. if (scope->body.empty ())
  334. body = "";
  335. else
  336. {
  337. int length;
  338. length = scope->body.size ();
  339. body = scope->body.c_str ();
  340. /* Strip leading and trailing whitespace. */
  341. while (length > 0 && ISSPACE (body[length - 1]))
  342. length--;
  343. scope->body.erase (length);
  344. while (*body && ISSPACE (*body))
  345. body++;
  346. }
  347. scope->element->end_handler (this, scope->element,
  348. m_user_data, body);
  349. }
  350. else if (scope->element == NULL)
  351. XML_DefaultCurrent (m_expat_parser);
  352. /* Pop the scope level. */
  353. m_scopes.pop_back ();
  354. }
  355. /* Wrapper for gdb_xml_end_element, to prevent throwing exceptions
  356. through expat. */
  357. static void
  358. gdb_xml_end_element_wrapper (void *data, const XML_Char *name)
  359. {
  360. struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data;
  361. try
  362. {
  363. parser->end_element (name);
  364. }
  365. catch (gdb_exception &ex)
  366. {
  367. parser->set_error (std::move (ex));
  368. }
  369. }
  370. /* Free a parser and all its associated state. */
  371. gdb_xml_parser::~gdb_xml_parser ()
  372. {
  373. XML_ParserFree (m_expat_parser);
  374. }
  375. /* Initialize a parser. */
  376. gdb_xml_parser::gdb_xml_parser (const char *name,
  377. const gdb_xml_element *elements,
  378. void *user_data)
  379. : m_name (name),
  380. m_user_data (user_data),
  381. m_last_line (0),
  382. m_dtd_name (NULL),
  383. m_is_xinclude (false)
  384. {
  385. m_expat_parser = XML_ParserCreateNS (NULL, '!');
  386. if (m_expat_parser == NULL)
  387. malloc_failure (0);
  388. XML_SetUserData (m_expat_parser, this);
  389. /* Set the callbacks. */
  390. XML_SetElementHandler (m_expat_parser, gdb_xml_start_element_wrapper,
  391. gdb_xml_end_element_wrapper);
  392. XML_SetCharacterDataHandler (m_expat_parser, gdb_xml_body_text);
  393. /* Initialize the outer scope. */
  394. m_scopes.emplace_back (elements);
  395. }
  396. /* External entity handler. The only external entities we support
  397. are those compiled into GDB (we do not fetch entities from the
  398. target). */
  399. static int XMLCALL
  400. gdb_xml_fetch_external_entity (XML_Parser expat_parser,
  401. const XML_Char *context,
  402. const XML_Char *base,
  403. const XML_Char *systemId,
  404. const XML_Char *publicId)
  405. {
  406. XML_Parser entity_parser;
  407. const char *text;
  408. enum XML_Status status;
  409. if (systemId == NULL)
  410. {
  411. gdb_xml_parser *parser
  412. = (gdb_xml_parser *) XML_GetUserData (expat_parser);
  413. text = fetch_xml_builtin (parser->dtd_name ());
  414. if (text == NULL)
  415. internal_error (__FILE__, __LINE__,
  416. _("could not locate built-in DTD %s"),
  417. parser->dtd_name ());
  418. }
  419. else
  420. {
  421. text = fetch_xml_builtin (systemId);
  422. if (text == NULL)
  423. return XML_STATUS_ERROR;
  424. }
  425. entity_parser = XML_ExternalEntityParserCreate (expat_parser,
  426. context, NULL);
  427. /* Don't use our handlers for the contents of the DTD. Just let expat
  428. process it. */
  429. XML_SetElementHandler (entity_parser, NULL, NULL);
  430. XML_SetDoctypeDeclHandler (entity_parser, NULL, NULL);
  431. XML_SetXmlDeclHandler (entity_parser, NULL);
  432. XML_SetDefaultHandler (entity_parser, NULL);
  433. XML_SetUserData (entity_parser, NULL);
  434. status = XML_Parse (entity_parser, text, strlen (text), 1);
  435. XML_ParserFree (entity_parser);
  436. return status;
  437. }
  438. void
  439. gdb_xml_parser::use_dtd (const char *dtd_name)
  440. {
  441. enum XML_Error err;
  442. m_dtd_name = dtd_name;
  443. XML_SetParamEntityParsing (m_expat_parser,
  444. XML_PARAM_ENTITY_PARSING_UNLESS_STANDALONE);
  445. XML_SetExternalEntityRefHandler (m_expat_parser,
  446. gdb_xml_fetch_external_entity);
  447. /* Even if no DTD is provided, use the built-in DTD anyway. */
  448. err = XML_UseForeignDTD (m_expat_parser, XML_TRUE);
  449. if (err != XML_ERROR_NONE)
  450. internal_error (__FILE__, __LINE__,
  451. _("XML_UseForeignDTD failed: %s"),
  452. XML_ErrorString (err));
  453. }
  454. /* Invoke PARSER on BUFFER. BUFFER is the data to parse, which
  455. should be NUL-terminated.
  456. The return value is 0 for success or -1 for error. It may throw,
  457. but only if something unexpected goes wrong during parsing; parse
  458. errors will be caught, warned about, and reported as failure. */
  459. int
  460. gdb_xml_parser::parse (const char *buffer)
  461. {
  462. enum XML_Status status;
  463. const char *error_string;
  464. gdb_xml_debug (this, _("Starting:\n%s"), buffer);
  465. status = XML_Parse (m_expat_parser, buffer, strlen (buffer), 1);
  466. if (status == XML_STATUS_OK && m_error.reason == 0)
  467. return 0;
  468. if (m_error.reason == RETURN_ERROR
  469. && m_error.error == XML_PARSE_ERROR)
  470. {
  471. gdb_assert (m_error.message != NULL);
  472. error_string = m_error.what ();
  473. }
  474. else if (status == XML_STATUS_ERROR)
  475. {
  476. enum XML_Error err = XML_GetErrorCode (m_expat_parser);
  477. error_string = XML_ErrorString (err);
  478. }
  479. else
  480. {
  481. gdb_assert (m_error.reason < 0);
  482. throw_exception (std::move (m_error));
  483. }
  484. if (m_last_line != 0)
  485. warning (_("while parsing %s (at line %d): %s"), m_name,
  486. m_last_line, error_string);
  487. else
  488. warning (_("while parsing %s: %s"), m_name, error_string);
  489. return -1;
  490. }
  491. int
  492. gdb_xml_parse_quick (const char *name, const char *dtd_name,
  493. const struct gdb_xml_element *elements,
  494. const char *document, void *user_data)
  495. {
  496. gdb_xml_parser parser (name, elements, user_data);
  497. if (dtd_name != NULL)
  498. parser.use_dtd (dtd_name);
  499. return parser.parse (document);
  500. }
  501. /* Parse a field VALSTR that we expect to contain an integer value.
  502. The integer is returned in *VALP. The string is parsed with an
  503. equivalent to strtoul.
  504. Returns 0 for success, -1 for error. */
  505. static int
  506. xml_parse_unsigned_integer (const char *valstr, ULONGEST *valp)
  507. {
  508. const char *endptr;
  509. ULONGEST result;
  510. if (*valstr == '\0')
  511. return -1;
  512. result = strtoulst (valstr, &endptr, 0);
  513. if (*endptr != '\0')
  514. return -1;
  515. *valp = result;
  516. return 0;
  517. }
  518. /* Parse an integer string into a ULONGEST and return it, or call
  519. gdb_xml_error if it could not be parsed. */
  520. ULONGEST
  521. gdb_xml_parse_ulongest (struct gdb_xml_parser *parser, const char *value)
  522. {
  523. ULONGEST result;
  524. if (xml_parse_unsigned_integer (value, &result) != 0)
  525. gdb_xml_error (parser, _("Can't convert \"%s\" to an integer"), value);
  526. return result;
  527. }
  528. /* Parse an integer attribute into a ULONGEST. */
  529. void *
  530. gdb_xml_parse_attr_ulongest (struct gdb_xml_parser *parser,
  531. const struct gdb_xml_attribute *attribute,
  532. const char *value)
  533. {
  534. ULONGEST result;
  535. void *ret;
  536. if (xml_parse_unsigned_integer (value, &result) != 0)
  537. gdb_xml_error (parser, _("Can't convert %s=\"%s\" to an integer"),
  538. attribute->name, value);
  539. ret = XNEW (ULONGEST);
  540. memcpy (ret, &result, sizeof (result));
  541. return ret;
  542. }
  543. /* A handler_data for yes/no boolean values. */
  544. const struct gdb_xml_enum gdb_xml_enums_boolean[] = {
  545. { "yes", 1 },
  546. { "no", 0 },
  547. { NULL, 0 }
  548. };
  549. /* Map NAME to VALUE. A struct gdb_xml_enum * should be saved as the
  550. value of handler_data when using gdb_xml_parse_attr_enum to parse a
  551. fixed list of possible strings. The list is terminated by an entry
  552. with NAME == NULL. */
  553. void *
  554. gdb_xml_parse_attr_enum (struct gdb_xml_parser *parser,
  555. const struct gdb_xml_attribute *attribute,
  556. const char *value)
  557. {
  558. const struct gdb_xml_enum *enums
  559. = (const struct gdb_xml_enum *) attribute->handler_data;
  560. void *ret;
  561. for (enums = (const struct gdb_xml_enum *) attribute->handler_data;
  562. enums->name != NULL; enums++)
  563. if (strcasecmp (enums->name, value) == 0)
  564. break;
  565. if (enums->name == NULL)
  566. gdb_xml_error (parser, _("Unknown attribute value %s=\"%s\""),
  567. attribute->name, value);
  568. ret = xmalloc (sizeof (enums->value));
  569. memcpy (ret, &enums->value, sizeof (enums->value));
  570. return ret;
  571. }
  572. /* XInclude processing. This is done as a separate step from actually
  573. parsing the document, so that we can produce a single combined XML
  574. document - e.g. to hand to a front end or to simplify comparing two
  575. documents. We make extensive use of XML_DefaultCurrent, to pass
  576. input text directly into the output without reformatting or
  577. requoting it.
  578. We output the DOCTYPE declaration for the first document unchanged,
  579. if present, and discard DOCTYPEs from included documents. Only the
  580. one we pass through here is used when we feed the result back to
  581. expat. The XInclude standard explicitly does not discuss
  582. validation of the result; we choose to apply the same DTD applied
  583. to the outermost document.
  584. We can not simply include the external DTD subset in the document
  585. as an internal subset, because <!IGNORE> and <!INCLUDE> are valid
  586. only in external subsets. But if we do not pass the DTD into the
  587. output at all, default values will not be filled in.
  588. We don't pass through any <?xml> declaration because we generate
  589. UTF-8, not whatever the input encoding was. */
  590. struct xinclude_parsing_data
  591. {
  592. xinclude_parsing_data (std::string &output_,
  593. xml_fetch_another fetcher_,
  594. int include_depth_)
  595. : output (output_),
  596. skip_depth (0),
  597. include_depth (include_depth_),
  598. fetcher (fetcher_)
  599. {}
  600. /* Where the output goes. */
  601. std::string &output;
  602. /* A count indicating whether we are in an element whose
  603. children should not be copied to the output, and if so,
  604. how deep we are nested. This is used for anything inside
  605. an xi:include, and for the DTD. */
  606. int skip_depth;
  607. /* The number of <xi:include> elements currently being processed,
  608. to detect loops. */
  609. int include_depth;
  610. /* A function to call to obtain additional features, and its
  611. baton. */
  612. xml_fetch_another fetcher;
  613. };
  614. static void
  615. xinclude_start_include (struct gdb_xml_parser *parser,
  616. const struct gdb_xml_element *element,
  617. void *user_data,
  618. std::vector<gdb_xml_value> &attributes)
  619. {
  620. struct xinclude_parsing_data *data
  621. = (struct xinclude_parsing_data *) user_data;
  622. char *href = (char *) xml_find_attribute (attributes, "href")->value.get ();
  623. gdb_xml_debug (parser, _("Processing XInclude of \"%s\""), href);
  624. if (data->include_depth > MAX_XINCLUDE_DEPTH)
  625. gdb_xml_error (parser, _("Maximum XInclude depth (%d) exceeded"),
  626. MAX_XINCLUDE_DEPTH);
  627. gdb::optional<gdb::char_vector> text = data->fetcher (href);
  628. if (!text)
  629. gdb_xml_error (parser, _("Could not load XML document \"%s\""), href);
  630. if (!xml_process_xincludes (data->output, parser->name (),
  631. text->data (), data->fetcher,
  632. data->include_depth + 1))
  633. gdb_xml_error (parser, _("Parsing \"%s\" failed"), href);
  634. data->skip_depth++;
  635. }
  636. static void
  637. xinclude_end_include (struct gdb_xml_parser *parser,
  638. const struct gdb_xml_element *element,
  639. void *user_data, const char *body_text)
  640. {
  641. struct xinclude_parsing_data *data
  642. = (struct xinclude_parsing_data *) user_data;
  643. data->skip_depth--;
  644. }
  645. static void XMLCALL
  646. xml_xinclude_default (void *data_, const XML_Char *s, int len)
  647. {
  648. struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data_;
  649. xinclude_parsing_data *data = (xinclude_parsing_data *) parser->user_data ();
  650. /* If we are inside of e.g. xi:include or the DTD, don't save this
  651. string. */
  652. if (data->skip_depth)
  653. return;
  654. /* Otherwise just add it to the end of the document we're building
  655. up. */
  656. data->output.append (s, len);
  657. }
  658. static void XMLCALL
  659. xml_xinclude_start_doctype (void *data_, const XML_Char *doctypeName,
  660. const XML_Char *sysid, const XML_Char *pubid,
  661. int has_internal_subset)
  662. {
  663. struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data_;
  664. xinclude_parsing_data *data = (xinclude_parsing_data *) parser->user_data ();
  665. /* Don't print out the doctype, or the contents of the DTD internal
  666. subset, if any. */
  667. data->skip_depth++;
  668. }
  669. static void XMLCALL
  670. xml_xinclude_end_doctype (void *data_)
  671. {
  672. struct gdb_xml_parser *parser = (struct gdb_xml_parser *) data_;
  673. xinclude_parsing_data *data = (xinclude_parsing_data *) parser->user_data ();
  674. data->skip_depth--;
  675. }
  676. static void XMLCALL
  677. xml_xinclude_xml_decl (void *data_, const XML_Char *version,
  678. const XML_Char *encoding, int standalone)
  679. {
  680. /* Do nothing - this function prevents the default handler from
  681. being called, thus suppressing the XML declaration from the
  682. output. */
  683. }
  684. const struct gdb_xml_attribute xinclude_attributes[] = {
  685. { "href", GDB_XML_AF_NONE, NULL, NULL },
  686. { NULL, GDB_XML_AF_NONE, NULL, NULL }
  687. };
  688. const struct gdb_xml_element xinclude_elements[] = {
  689. { "http://www.w3.org/2001/XInclude!include", xinclude_attributes, NULL,
  690. GDB_XML_EF_OPTIONAL | GDB_XML_EF_REPEATABLE,
  691. xinclude_start_include, xinclude_end_include },
  692. { NULL, NULL, NULL, GDB_XML_EF_NONE, NULL, NULL }
  693. };
  694. /* The main entry point for <xi:include> processing. */
  695. bool
  696. xml_process_xincludes (std::string &result,
  697. const char *name, const char *text,
  698. xml_fetch_another fetcher, int depth)
  699. {
  700. xinclude_parsing_data data (result, fetcher, depth);
  701. gdb_xml_parser parser (name, xinclude_elements, &data);
  702. parser.set_is_xinclude (true);
  703. XML_SetCharacterDataHandler (parser.expat_parser (), NULL);
  704. XML_SetDefaultHandler (parser.expat_parser (), xml_xinclude_default);
  705. /* Always discard the XML version declarations; the only important
  706. thing this provides is encoding, and our result will have been
  707. converted to UTF-8. */
  708. XML_SetXmlDeclHandler (parser.expat_parser (), xml_xinclude_xml_decl);
  709. if (depth > 0)
  710. /* Discard the doctype for included documents. */
  711. XML_SetDoctypeDeclHandler (parser.expat_parser (),
  712. xml_xinclude_start_doctype,
  713. xml_xinclude_end_doctype);
  714. parser.use_dtd ("xinclude.dtd");
  715. if (parser.parse (text) == 0)
  716. {
  717. if (depth == 0)
  718. gdb_xml_debug (&parser, _("XInclude processing succeeded."));
  719. return true;
  720. }
  721. return false;
  722. }
  723. #endif /* HAVE_LIBEXPAT */
  724. /* Return an XML document which was compiled into GDB, from
  725. the given FILENAME, or NULL if the file was not compiled in. */
  726. const char *
  727. fetch_xml_builtin (const char *filename)
  728. {
  729. const char *const (*p)[2];
  730. for (p = xml_builtin; (*p)[0]; p++)
  731. if (strcmp ((*p)[0], filename) == 0)
  732. return (*p)[1];
  733. return NULL;
  734. }
  735. /* A to_xfer_partial helper function which reads XML files which were
  736. compiled into GDB. The target may call this function from its own
  737. to_xfer_partial handler, after converting object and annex to the
  738. appropriate filename. */
  739. LONGEST
  740. xml_builtin_xfer_partial (const char *filename,
  741. gdb_byte *readbuf, const gdb_byte *writebuf,
  742. ULONGEST offset, LONGEST len)
  743. {
  744. const char *buf;
  745. LONGEST len_avail;
  746. gdb_assert (readbuf != NULL && writebuf == NULL);
  747. gdb_assert (filename != NULL);
  748. buf = fetch_xml_builtin (filename);
  749. if (buf == NULL)
  750. return -1;
  751. len_avail = strlen (buf);
  752. if (offset >= len_avail)
  753. return 0;
  754. if (len > len_avail - offset)
  755. len = len_avail - offset;
  756. memcpy (readbuf, buf + offset, len);
  757. return len;
  758. }
  759. static void
  760. show_debug_xml (struct ui_file *file, int from_tty,
  761. struct cmd_list_element *c, const char *value)
  762. {
  763. gdb_printf (file, _("XML debugging is %s.\n"), value);
  764. }
  765. gdb::optional<gdb::char_vector>
  766. xml_fetch_content_from_file (const char *filename, const char *dirname)
  767. {
  768. gdb_file_up file;
  769. if (dirname != nullptr && *dirname != '\0')
  770. {
  771. gdb::unique_xmalloc_ptr<char> fullname
  772. (concat (dirname, "/", filename, (char *) NULL));
  773. file = gdb_fopen_cloexec (fullname.get (), FOPEN_RB);
  774. }
  775. else
  776. file = gdb_fopen_cloexec (filename, FOPEN_RB);
  777. if (file == NULL)
  778. return {};
  779. /* Read in the whole file. */
  780. size_t len;
  781. if (fseek (file.get (), 0, SEEK_END) == -1)
  782. perror_with_name (_("seek to end of file"));
  783. len = ftell (file.get ());
  784. rewind (file.get ());
  785. gdb::char_vector text (len + 1);
  786. if (fread (text.data (), 1, len, file.get ()) != len
  787. || ferror (file.get ()))
  788. {
  789. warning (_("Read error from \"%s\""), filename);
  790. return {};
  791. }
  792. text.back () = '\0';
  793. return text;
  794. }
  795. void _initialize_xml_support ();
  796. void _initialize_xml_support ();
  797. void
  798. _initialize_xml_support ()
  799. {
  800. add_setshow_boolean_cmd ("xml", class_maintenance, &debug_xml,
  801. _("Set XML parser debugging."),
  802. _("Show XML parser debugging."),
  803. _("When set, debugging messages for XML parsers "
  804. "are displayed."),
  805. NULL, show_debug_xml,
  806. &setdebuglist, &showdebuglist);
  807. }