Copyright updates for 2007.
[external/binutils.git] / gdb / xml-support.c
1 /* Helper routines for parsing XML using Expat.
2
3    Copyright (C) 2006, 2007 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 2 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, write to the Free Software
19    Foundation, Inc., 51 Franklin Street, Fifth Floor,
20    Boston, MA 02110-1301, USA.  */
21
22 #include "defs.h"
23 #include "gdbcmd.h"
24
25 /* Debugging flag.  */
26 static int debug_xml;
27
28 /* The contents of this file are only useful if XML support is
29    available.  */
30 #ifdef HAVE_LIBEXPAT
31
32 #include "exceptions.h"
33 #include "xml-support.h"
34
35 #include "gdb_expat.h"
36 #include "gdb_string.h"
37 #include "safe-ctype.h"
38
39 /* A parsing level -- used to keep track of the current element
40    nesting.  */
41 struct scope_level
42 {
43   /* Elements we allow at this level.  */
44   const struct gdb_xml_element *elements;
45
46   /* The element which we are within.  */
47   const struct gdb_xml_element *element;
48
49   /* Mask of which elements we've seen at this level (used for
50      optional and repeatable checking).  */
51   unsigned int seen;
52
53   /* Body text accumulation.  */
54   struct obstack *body;
55 };
56 typedef struct scope_level scope_level_s;
57 DEF_VEC_O(scope_level_s);
58
59 /* The parser itself, and our additional state.  */
60 struct gdb_xml_parser
61 {
62   XML_Parser expat_parser;      /* The underlying expat parser.  */
63
64   const char *name;             /* Name of this parser.  */
65   void *user_data;              /* The user's callback data, for handlers.  */
66
67   VEC(scope_level_s) *scopes;   /* Scoping stack.  */
68
69   struct gdb_exception error;   /* A thrown error, if any.  */
70   int last_line;                /* The line of the thrown error, or 0.  */
71 };
72
73 /* Process some body text.  We accumulate the text for later use; it's
74    wrong to do anything with it immediately, because a single block of
75    text might be broken up into multiple calls to this function.  */
76
77 static void
78 gdb_xml_body_text (void *data, const XML_Char *text, int length)
79 {
80   struct gdb_xml_parser *parser = data;
81   struct scope_level *scope = VEC_last (scope_level_s, parser->scopes);
82
83   if (parser->error.reason < 0)
84     return;
85
86   if (scope->body == NULL)
87     {
88       scope->body = XZALLOC (struct obstack);
89       obstack_init (scope->body);
90     }
91
92   obstack_grow (scope->body, text, length);
93 }
94
95 /* Issue a debugging message from one of PARSER's handlers.  */
96
97 void
98 gdb_xml_debug (struct gdb_xml_parser *parser, const char *format, ...)
99 {
100   int line = XML_GetCurrentLineNumber (parser->expat_parser);
101   va_list ap;
102   char *message;
103
104   if (!debug_xml)
105     return;
106
107   va_start (ap, format);
108   message = xstrvprintf (format, ap);
109   if (line)
110     fprintf_unfiltered (gdb_stderr, "%s (line %d): %s\n",
111                         parser->name, line, message);
112   else
113     fprintf_unfiltered (gdb_stderr, "%s: %s\n",
114                         parser->name, message);
115   xfree (message);
116 }
117
118 /* Issue an error message from one of PARSER's handlers, and stop
119    parsing.  */
120
121 void
122 gdb_xml_error (struct gdb_xml_parser *parser, const char *format, ...)
123 {
124   int line = XML_GetCurrentLineNumber (parser->expat_parser);
125   va_list ap;
126
127   parser->last_line = line;
128   va_start (ap, format);
129   throw_verror (XML_PARSE_ERROR, format, ap);
130 }
131
132 /* Clean up a vector of parsed attribute values.  */
133
134 static void
135 gdb_xml_values_cleanup (void *data)
136 {
137   VEC(gdb_xml_value_s) **values = data;
138   struct gdb_xml_value *value;
139   int ix;
140
141   for (ix = 0; VEC_iterate (gdb_xml_value_s, *values, ix, value); ix++)
142     xfree (value->value);
143   VEC_free (gdb_xml_value_s, *values);
144 }
145
146 /* Handle the start of an element.  DATA is our local XML parser, NAME
147    is the element, and ATTRS are the names and values of this
148    element's attributes.  */
149
150 static void
151 gdb_xml_start_element (void *data, const XML_Char *name,
152                        const XML_Char **attrs)
153 {
154   struct gdb_xml_parser *parser = data;
155   struct scope_level *scope = VEC_last (scope_level_s, parser->scopes);
156   struct scope_level new_scope;
157   const struct gdb_xml_element *element;
158   const struct gdb_xml_attribute *attribute;
159   VEC(gdb_xml_value_s) *attributes = NULL;
160   unsigned int seen;
161   struct cleanup *back_to;
162
163   back_to = make_cleanup (gdb_xml_values_cleanup, &attributes);
164
165   /* Push an error scope.  If we return or throw an exception before
166      filling this in, it will tell us to ignore children of this
167      element.  */
168   memset (&new_scope, 0, sizeof (new_scope));
169   VEC_safe_push (scope_level_s, parser->scopes, &new_scope);
170
171   gdb_xml_debug (parser, _("Entering element <%s>"), name);
172
173   /* Find this element in the list of the current scope's allowed
174      children.  Record that we've seen it.  */
175
176   seen = 1;
177   for (element = scope->elements; element && element->name;
178        element++, seen <<= 1)
179     if (strcmp (element->name, name) == 0)
180       break;
181
182   if (element == NULL || element->name == NULL)
183     {
184       gdb_xml_debug (parser, _("Element <%s> unknown"), name);
185       do_cleanups (back_to);
186       return;
187     }
188
189   if (!(element->flags & GDB_XML_EF_REPEATABLE) && (seen & scope->seen))
190     gdb_xml_error (parser, _("Element <%s> only expected once"), name);
191
192   scope->seen |= seen;
193
194   for (attribute = element->attributes;
195        attribute != NULL && attribute->name != NULL;
196        attribute++)
197     {
198       const char *val = NULL;
199       const XML_Char **p;
200       void *parsed_value;
201       struct gdb_xml_value new_value;
202
203       for (p = attrs; *p != NULL; p += 2)
204         if (!strcmp (attribute->name, p[0]))
205           {
206             val = p[1];
207             break;
208           }
209
210       if (*p != NULL && val == NULL)
211         {
212           gdb_xml_debug (parser, _("Attribute \"%s\" missing a value"),
213                          attribute->name);
214           continue;
215         }
216
217       if (*p == NULL && !(attribute->flags & GDB_XML_AF_OPTIONAL))
218         {
219           gdb_xml_error (parser, _("Required attribute \"%s\" of "
220                                    "<%s> not specified"),
221                          attribute->name, element->name);
222           continue;
223         }
224
225       if (*p == NULL)
226         continue;
227
228       gdb_xml_debug (parser, _("Parsing attribute %s=\"%s\""),
229                      attribute->name, val);
230
231       if (attribute->handler)
232         parsed_value = attribute->handler (parser, attribute, val);
233       else
234         parsed_value = xstrdup (val);
235
236       new_value.name = attribute->name;
237       new_value.value = parsed_value;
238       VEC_safe_push (gdb_xml_value_s, attributes, &new_value);
239     }
240
241   /* Check for unrecognized attributes.  */
242   if (debug_xml)
243     {
244       const XML_Char **p;
245
246       for (p = attrs; *p != NULL; p += 2)
247         {
248           for (attribute = element->attributes;
249                attribute != NULL && attribute->name != NULL;
250                attribute++)
251             if (strcmp (attribute->name, *p) == 0)
252               break;
253
254           if (attribute == NULL || attribute->name == NULL)
255             gdb_xml_debug (parser, _("Ignoring unknown attribute %s"), *p);
256         }
257     }
258
259   /* Call the element handler if there is one.  */
260   if (element->start_handler)
261     element->start_handler (parser, element, parser->user_data, attributes);
262
263   /* Fill in a new scope level.  */
264   scope = VEC_last (scope_level_s, parser->scopes);
265   scope->element = element;
266   scope->elements = element->children;
267
268   do_cleanups (back_to);
269 }
270
271 /* Wrapper for gdb_xml_start_element, to prevent throwing exceptions
272    through expat.  */
273
274 static void
275 gdb_xml_start_element_wrapper (void *data, const XML_Char *name,
276                                const XML_Char **attrs)
277 {
278   struct gdb_xml_parser *parser = data;
279   volatile struct gdb_exception ex;
280
281   if (parser->error.reason < 0)
282     return;
283
284   TRY_CATCH (ex, RETURN_MASK_ALL)
285     {
286       gdb_xml_start_element (data, name, attrs);
287     }
288   if (ex.reason < 0)
289     {
290       parser->error = ex;
291 #ifdef HAVE_XML_STOPPARSER
292       XML_StopParser (parser->expat_parser, XML_FALSE);
293 #endif
294     }
295 }
296
297 /* Handle the end of an element.  DATA is our local XML parser, and
298    NAME is the current element.  */
299
300 static void
301 gdb_xml_end_element (void *data, const XML_Char *name)
302 {
303   struct gdb_xml_parser *parser = data;
304   struct scope_level *scope = VEC_last (scope_level_s, parser->scopes);
305   const struct gdb_xml_element *element;
306   unsigned int seen;
307   char *body;
308
309   gdb_xml_debug (parser, _("Leaving element <%s>"), name);
310
311   for (element = scope->elements, seen = 1;
312        element != NULL && element->name != NULL;
313        element++, seen <<= 1)
314     if ((scope->seen & seen) == 0
315         && (element->flags & GDB_XML_EF_OPTIONAL) == 0)
316       gdb_xml_error (parser, _("Required element <%s> is missing"),
317                      element->name);
318
319   /* Call the element processor. */
320   if (scope->body == NULL)
321     body = "";
322   else
323     {
324       int length;
325
326       length = obstack_object_size (scope->body);
327       obstack_1grow (scope->body, '\0');
328       body = obstack_finish (scope->body);
329
330       /* Strip leading and trailing whitespace.  */
331       while (length > 0 && ISSPACE (body[length-1]))
332         body[--length] = '\0';
333       while (*body && ISSPACE (*body))
334         body++;
335     }
336
337   if (scope->element != NULL && scope->element->end_handler)
338     scope->element->end_handler (parser, scope->element, parser->user_data,
339                                  body);
340
341   /* Pop the scope level.  */
342   if (scope->body)
343     {
344       obstack_free (scope->body, NULL);
345       xfree (scope->body);
346     }
347   VEC_pop (scope_level_s, parser->scopes);
348 }
349
350 /* Wrapper for gdb_xml_end_element, to prevent throwing exceptions
351    through expat.  */
352
353 static void
354 gdb_xml_end_element_wrapper (void *data, const XML_Char *name)
355 {
356   struct gdb_xml_parser *parser = data;
357   volatile struct gdb_exception ex;
358
359   if (parser->error.reason < 0)
360     return;
361
362   TRY_CATCH (ex, RETURN_MASK_ALL)
363     {
364       gdb_xml_end_element (data, name);
365     }
366   if (ex.reason < 0)
367     {
368       parser->error = ex;
369 #ifdef HAVE_XML_STOPPARSER
370       XML_StopParser (parser->expat_parser, XML_FALSE);
371 #endif
372     }
373 }
374
375 /* Free a parser and all its associated state.  */
376
377 static void
378 gdb_xml_cleanup (void *arg)
379 {
380   struct gdb_xml_parser *parser = arg;
381   struct scope_level *scope;
382   int ix;
383
384   XML_ParserFree (parser->expat_parser);
385
386   /* Clean up the scopes.  */
387   for (ix = 0; VEC_iterate (scope_level_s, parser->scopes, ix, scope); ix++)
388     if (scope->body)
389       {
390         obstack_free (scope->body, NULL);
391         xfree (scope->body);
392       }
393   VEC_free (scope_level_s, parser->scopes);
394
395   xfree (parser);
396 }
397
398 /* Initialize and return a parser.  Register a cleanup to destroy the
399    parser.  */
400
401 struct gdb_xml_parser *
402 gdb_xml_create_parser_and_cleanup (const char *name,
403                                    const struct gdb_xml_element *elements,
404                                    void *user_data)
405 {
406   struct gdb_xml_parser *parser;
407   struct scope_level start_scope;
408
409   /* Initialize the parser.  */
410   parser = XZALLOC (struct gdb_xml_parser);
411   parser->expat_parser = XML_ParserCreateNS (NULL, '!');
412   if (parser->expat_parser == NULL)
413     {
414       xfree (parser);
415       nomem (0);
416     }
417
418   parser->name = name;
419
420   parser->user_data = user_data;
421   XML_SetUserData (parser->expat_parser, parser);
422
423   /* Set the callbacks.  */
424   XML_SetElementHandler (parser->expat_parser, gdb_xml_start_element_wrapper,
425                          gdb_xml_end_element_wrapper);
426   XML_SetCharacterDataHandler (parser->expat_parser, gdb_xml_body_text);
427
428   /* Initialize the outer scope.  */
429   memset (&start_scope, 0, sizeof (start_scope));
430   start_scope.elements = elements;
431   VEC_safe_push (scope_level_s, parser->scopes, &start_scope);
432
433   make_cleanup (gdb_xml_cleanup, parser);
434
435   return parser;
436 }
437
438 /* Invoke PARSER on BUFFER.  BUFFER is the data to parse, which
439    should be NUL-terminated.
440
441    The return value is 0 for success or -1 for error.  It may throw,
442    but only if something unexpected goes wrong during parsing; parse
443    errors will be caught, warned about, and reported as failure.  */
444
445 int
446 gdb_xml_parse (struct gdb_xml_parser *parser, const char *buffer)
447 {
448   enum XML_Status status;
449   const char *error_string;
450
451   status = XML_Parse (parser->expat_parser, buffer, strlen (buffer), 1);
452
453   if (status == XML_STATUS_OK && parser->error.reason == 0)
454     return 0;
455
456   if (parser->error.reason == RETURN_ERROR
457       && parser->error.error == XML_PARSE_ERROR)
458     {
459       gdb_assert (parser->error.message != NULL);
460       error_string = parser->error.message;
461     }
462   else if (status == XML_STATUS_ERROR)
463     {
464       enum XML_Error err = XML_GetErrorCode (parser->expat_parser);
465       error_string = XML_ErrorString (err);
466     }
467   else
468     {
469       gdb_assert (parser->error.reason < 0);
470       throw_exception (parser->error);
471     }
472
473   if (parser->last_line != 0)
474     warning (_("while parsing %s (at line %d): %s"), parser->name,
475              parser->last_line, error_string);
476   else
477     warning (_("while parsing %s: %s"), parser->name, error_string);
478
479   return -1;
480 }
481
482 /* Parse a field VALSTR that we expect to contain an integer value.
483    The integer is returned in *VALP.  The string is parsed with an
484    equivalent to strtoul.
485
486    Returns 0 for success, -1 for error.  */
487
488 static int
489 xml_parse_unsigned_integer (const char *valstr, ULONGEST *valp)
490 {
491   const char *endptr;
492   ULONGEST result;
493
494   if (*valstr == '\0')
495     return -1;
496
497   result = strtoulst (valstr, &endptr, 0);
498   if (*endptr != '\0')
499     return -1;
500
501   *valp = result;
502   return 0;
503 }
504
505 /* Parse an integer string into a ULONGEST and return it, or call
506    gdb_xml_error if it could not be parsed.  */
507
508 ULONGEST
509 gdb_xml_parse_ulongest (struct gdb_xml_parser *parser, const char *value)
510 {
511   ULONGEST result;
512
513   if (xml_parse_unsigned_integer (value, &result) != 0)
514     gdb_xml_error (parser, _("Can't convert \"%s\" to an integer"), value);
515
516   return result;
517 }
518
519 /* Parse an integer attribute into a ULONGEST.  */
520
521 void *
522 gdb_xml_parse_attr_ulongest (struct gdb_xml_parser *parser,
523                              const struct gdb_xml_attribute *attribute,
524                              const char *value)
525 {
526   ULONGEST result;
527   void *ret;
528
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
533   ret = xmalloc (sizeof (result));
534   memcpy (ret, &result, sizeof (result));
535   return ret;
536 }
537
538 /* Map NAME to VALUE.  A struct gdb_xml_enum * should be saved as the
539    value of handler_data when using gdb_xml_parse_attr_enum to parse a
540    fixed list of possible strings.  The list is terminated by an entry
541    with NAME == NULL.  */
542
543 void *
544 gdb_xml_parse_attr_enum (struct gdb_xml_parser *parser,
545                          const struct gdb_xml_attribute *attribute,
546                          const char *value)
547 {
548   const struct gdb_xml_enum *enums = attribute->handler_data;
549   void *ret;
550
551   for (enums = attribute->handler_data; enums->name != NULL; enums++)
552     if (strcmp (enums->name, value) == 0)
553       break;
554
555   if (enums->name == NULL)
556     gdb_xml_error (parser, _("Unknown attribute value %s=\"%s\""),
557                  attribute->name, value);
558
559   ret = xmalloc (sizeof (enums->value));
560   memcpy (ret, &enums->value, sizeof (enums->value));
561   return ret;
562 }
563
564 #endif /* HAVE_LIBEXPAT */
565
566 static void
567 show_debug_xml (struct ui_file *file, int from_tty,
568                 struct cmd_list_element *c, const char *value)
569 {
570   fprintf_filtered (file, _("XML debugging is %s.\n"), value);
571 }
572
573 void _initialize_xml_support (void);
574
575 void
576 _initialize_xml_support (void)
577 {
578   add_setshow_boolean_cmd ("xml", class_maintenance, &debug_xml,
579                            _("Set XML parser debugging."),
580                            _("Show XML parser debugging."),
581                            _("When set, debugging messages for XML parsers "
582                              "are displayed."),
583                            NULL, show_debug_xml,
584                            &setdebuglist, &showdebuglist);
585 }