PR macros/12999
[external/binutils.git] / gdb / macrocmd.c
1 /* C preprocessor macro expansion commands for GDB.
2    Copyright (C) 2002, 2007, 2008, 2009, 2010, 2011
3    Free Software Foundation, Inc.
4    Contributed by Red Hat, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21
22 #include "defs.h"
23 #include "macrotab.h"
24 #include "macroexp.h"
25 #include "macroscope.h"
26 #include "command.h"
27 #include "gdbcmd.h"
28 #include "gdb_string.h"
29
30 \f
31 /* The `macro' prefix command.  */
32
33 static struct cmd_list_element *macrolist;
34
35 static void
36 macro_command (char *arg, int from_tty)
37 {
38   printf_unfiltered
39     ("\"macro\" must be followed by the name of a macro command.\n");
40   help_list (macrolist, "macro ", -1, gdb_stdout);
41 }
42
43
44 \f
45 /* Macro expansion commands.  */
46
47
48 static void
49 macro_expand_command (char *exp, int from_tty)
50 {
51   struct macro_scope *ms = NULL;
52   char *expanded = NULL;
53   struct cleanup *cleanup_chain = make_cleanup (free_current_contents, &ms);
54
55   make_cleanup (free_current_contents, &expanded);
56
57   /* You know, when the user doesn't specify any expression, it would be
58      really cool if this defaulted to the last expression evaluated.
59      Then it would be easy to ask, "Hey, what did I just evaluate?"  But
60      at the moment, the `print' commands don't save the last expression
61      evaluated, just its value.  */
62   if (! exp || ! *exp)
63     error (_("You must follow the `macro expand' command with the"
64            " expression you\n"
65            "want to expand."));
66
67   ms = default_macro_scope ();
68   if (ms)
69     {
70       expanded = macro_expand (exp, standard_macro_lookup, ms);
71       fputs_filtered ("expands to: ", gdb_stdout);
72       fputs_filtered (expanded, gdb_stdout);
73       fputs_filtered ("\n", gdb_stdout);
74     }
75   else
76     fputs_filtered ("GDB has no preprocessor macro information for "
77                     "that code.\n",
78                     gdb_stdout);
79
80   do_cleanups (cleanup_chain);
81   return;
82 }
83
84
85 static void
86 macro_expand_once_command (char *exp, int from_tty)
87 {
88   struct macro_scope *ms = NULL;
89   char *expanded = NULL;
90   struct cleanup *cleanup_chain = make_cleanup (free_current_contents, &ms);
91   make_cleanup (free_current_contents, &expanded);
92
93   /* You know, when the user doesn't specify any expression, it would be
94      really cool if this defaulted to the last expression evaluated.
95      And it should set the once-expanded text as the new `last
96      expression'.  That way, you could just hit return over and over and
97      see the expression expanded one level at a time.  */
98   if (! exp || ! *exp)
99     error (_("You must follow the `macro expand-once' command with"
100            " the expression\n"
101            "you want to expand."));
102
103   ms = default_macro_scope ();
104   if (ms)
105     {
106       expanded = macro_expand_once (exp, standard_macro_lookup, ms);
107       fputs_filtered ("expands to: ", gdb_stdout);
108       fputs_filtered (expanded, gdb_stdout);
109       fputs_filtered ("\n", gdb_stdout);
110     }
111   else
112     fputs_filtered ("GDB has no preprocessor macro information for "
113                     "that code.\n",
114                     gdb_stdout);
115
116   do_cleanups (cleanup_chain);
117   return;
118 }
119
120 /*  Outputs the include path of a macro starting at FILE and LINE to STREAM.
121
122     Care should be taken that this function does not cause any lookups into
123     the splay tree so that it can be safely used while iterating.  */
124 static void
125 show_pp_source_pos (struct ui_file *stream,
126                     struct macro_source_file *file,
127                     int line)
128 {
129   fprintf_filtered (stream, "%s:%d\n", file->filename, line);
130
131   while (file->included_by)
132     {
133       fprintf_filtered (gdb_stdout, "  included at %s:%d\n",
134                         file->included_by->filename,
135                         file->included_at_line);
136       file = file->included_by;
137     }
138 }
139
140 /* Outputs a macro for human consumption, detailing the include path
141    and macro definition.  NAME is the name of the macro.
142    D the definition.  FILE the start of the include path, and LINE the
143    line number in FILE.
144
145    Care should be taken that this function does not cause any lookups into
146    the splay tree so that it can be safely used while iterating.  */
147 static void
148 print_macro_definition (const char *name,
149                         const struct macro_definition *d,
150                         struct macro_source_file *file,
151                         int line)
152 {
153       fprintf_filtered (gdb_stdout, "Defined at ");
154       show_pp_source_pos (gdb_stdout, file, line);
155
156       if (line != 0)
157         fprintf_filtered (gdb_stdout, "#define %s", name);
158       else
159         fprintf_filtered (gdb_stdout, "-D%s", name);
160
161       if (d->kind == macro_function_like)
162         {
163           int i;
164
165           fputs_filtered ("(", gdb_stdout);
166           for (i = 0; i < d->argc; i++)
167             {
168               fputs_filtered (d->argv[i], gdb_stdout);
169               if (i + 1 < d->argc)
170                 fputs_filtered (", ", gdb_stdout);
171             }
172           fputs_filtered (")", gdb_stdout);
173         }
174
175       if (line != 0)
176         fprintf_filtered (gdb_stdout, " %s\n", d->replacement);
177       else
178         fprintf_filtered (gdb_stdout, "=%s\n", d->replacement);
179 }
180
181 static void
182 info_macro_command (char *name, int from_tty)
183 {
184   struct macro_scope *ms = NULL;
185   struct cleanup *cleanup_chain = make_cleanup (free_current_contents, &ms);
186   struct macro_definition *d;
187
188   if (! name || ! *name)
189     error (_("You must follow the `info macro' command with the name"
190            " of the macro\n"
191            "whose definition you want to see."));
192
193   ms = default_macro_scope ();
194   if (! ms)
195     error (_("GDB has no preprocessor macro information for that code."));
196
197   d = macro_lookup_definition (ms->file, ms->line, name);
198   if (d)
199     {
200       int line;
201       struct macro_source_file *file
202         = macro_definition_location (ms->file, ms->line, name, &line);
203
204       print_macro_definition (name, d, file, line);
205     }
206   else
207     {
208       fprintf_filtered (gdb_stdout,
209                         "The symbol `%s' has no definition as a C/C++"
210                         " preprocessor macro\n"
211                         "at ", name);
212       show_pp_source_pos (gdb_stdout, ms->file, ms->line);
213     }
214
215   do_cleanups (cleanup_chain);
216 }
217
218 /* A callback function for usage with macro_for_each and friends.
219    If USER_DATA is null all macros will be printed.
220    Otherwise USER_DATA is considered to be a string, printing
221    only macros who's NAME matches USER_DATA.  Other arguments are
222    routed to print_macro_definition.  */
223 static void
224 print_macro_callback (const char *name, const struct macro_definition *macro,
225                    struct macro_source_file *source, int line,
226                    void *user_data)
227 {
228   if (! user_data || strcmp (user_data, name) == 0)
229     print_macro_definition (name, macro, source, line);
230 }
231
232 /* Implementation of the "info definitions" command. */
233 static void
234 info_definitions_command (char *name, int from_tty)
235 {
236   struct macro_scope *ms = NULL;
237   struct cleanup *cleanup_chain = make_cleanup (free_current_contents, &ms);
238
239   if (! name || ! *name)
240     error (_("The `info definitions' command requires a macro name as an \
241 argument."));
242
243   ms = default_macro_scope ();
244
245   if (! ms || ! ms->file || ! ms->file->table)
246     error (_("GDB has no preprocessor macro information for that code."));
247
248   macro_for_each (ms->file->table, print_macro_callback, name);
249   do_cleanups (cleanup_chain);
250 }
251
252 /* Implementation of the "info macros" command. */
253 static void
254 info_macros_command (char *args, int from_tty)
255 {
256   struct macro_scope *ms = NULL;
257   struct cleanup *cleanup_chain = make_cleanup (free_current_contents, &ms);
258
259   if (args == NULL)
260     ms = default_macro_scope ();
261   else
262     {
263       struct symtabs_and_lines sals = decode_line_spec (args, 0);
264
265       if (sals.nelts)
266         ms = sal_macro_scope (sals.sals[0]);
267     }
268
269   if (! ms || ! ms->file || ! ms->file->table)
270     error (_("GDB has no preprocessor macro information for that code."));
271
272   macro_for_each_in_scope (ms->file, ms->line, print_macro_callback, NULL);
273   do_cleanups (cleanup_chain);
274 }
275
276 \f
277 /* User-defined macros.  */
278
279 static void
280 skip_ws (char **expp)
281 {
282   while (macro_is_whitespace (**expp))
283     ++*expp;
284 }
285
286 /* Try to find the bounds of an identifier.  If an identifier is
287    found, returns a newly allocated string; otherwise returns NULL.
288    EXPP is a pointer to an input string; it is updated to point to the
289    text following the identifier.  If IS_PARAMETER is true, this
290    function will also allow "..." forms as used in varargs macro
291    parameters.  */
292
293 static char *
294 extract_identifier (char **expp, int is_parameter)
295 {
296   char *result;
297   char *p = *expp;
298   unsigned int len;
299
300   if (is_parameter && !strncmp (p, "...", 3))
301     {
302       /* Ok.  */
303     }
304   else
305     {
306       if (! *p || ! macro_is_identifier_nondigit (*p))
307         return NULL;
308       for (++p;
309            *p && (macro_is_identifier_nondigit (*p) || macro_is_digit (*p));
310            ++p)
311         ;
312     }
313
314   if (is_parameter && !strncmp (p, "...", 3))      
315     p += 3;
316
317   len = p - *expp;
318   result = (char *) xmalloc (len + 1);
319   memcpy (result, *expp, len);
320   result[len] = '\0';
321   *expp += len;
322   return result;
323 }
324
325 /* Helper function to clean up a temporarily-constructed macro object.
326    This assumes that the contents were all allocated with xmalloc.  */
327 static void
328 free_macro_definition_ptr (void *ptr)
329 {
330   int i;
331   struct macro_definition *loc = (struct macro_definition *) ptr;
332
333   for (i = 0; i < loc->argc; ++i)
334     xfree ((char *) loc->argv[i]);
335   xfree ((char *) loc->argv);
336   /* Note that the 'replacement' field is not allocated.  */
337 }
338
339 static void
340 macro_define_command (char *exp, int from_tty)
341 {
342   struct macro_definition new_macro;
343   char *name = NULL;
344   struct cleanup *cleanup_chain;
345
346   if (!exp)
347     error (_("usage: macro define NAME[(ARGUMENT-LIST)] [REPLACEMENT-LIST]"));
348
349   cleanup_chain = make_cleanup (free_macro_definition_ptr, &new_macro);
350   make_cleanup (free_current_contents, &name);
351
352   memset (&new_macro, 0, sizeof (struct macro_definition));
353
354   skip_ws (&exp);
355   name = extract_identifier (&exp, 0);
356   if (! name)
357     error (_("Invalid macro name."));
358   if (*exp == '(')
359     {
360       /* Function-like macro.  */
361       int alloced = 5;
362       char **argv = (char **) xmalloc (alloced * sizeof (char *));
363
364       new_macro.kind = macro_function_like;
365       new_macro.argc = 0;
366       new_macro.argv = (const char * const *) argv;
367
368       /* Skip the '(' and whitespace.  */
369       ++exp;
370       skip_ws (&exp);
371
372       while (*exp != ')')
373         {
374           int i;
375
376           if (new_macro.argc == alloced)
377             {
378               alloced *= 2;
379               argv = (char **) xrealloc (argv, alloced * sizeof (char *));
380               /* Must update new_macro as well...  */
381               new_macro.argv = (const char * const *) argv;
382             }
383           argv[new_macro.argc] = extract_identifier (&exp, 1);
384           if (! argv[new_macro.argc])
385             error (_("Macro is missing an argument."));
386           ++new_macro.argc;
387
388           for (i = new_macro.argc - 2; i >= 0; --i)
389             {
390               if (! strcmp (argv[i], argv[new_macro.argc - 1]))
391                 error (_("Two macro arguments with identical names."));
392             }
393
394           skip_ws (&exp);
395           if (*exp == ',')
396             {
397               ++exp;
398               skip_ws (&exp);
399             }
400           else if (*exp != ')')
401             error (_("',' or ')' expected at end of macro arguments."));
402         }
403       /* Skip the closing paren.  */
404       ++exp;
405       skip_ws (&exp);
406
407       macro_define_function (macro_main (macro_user_macros), -1, name,
408                              new_macro.argc, (const char **) new_macro.argv,
409                              exp);
410     }
411   else
412     {
413       skip_ws (&exp);
414       macro_define_object (macro_main (macro_user_macros), -1, name, exp);
415     }
416
417   do_cleanups (cleanup_chain);
418 }
419
420
421 static void
422 macro_undef_command (char *exp, int from_tty)
423 {
424   char *name;
425
426   if (!exp)
427     error (_("usage: macro undef NAME"));
428
429   skip_ws (&exp);
430   name = extract_identifier (&exp, 0);
431   if (! name)
432     error (_("Invalid macro name."));
433   macro_undef (macro_main (macro_user_macros), -1, name);
434   xfree (name);
435 }
436
437
438 static void
439 print_one_macro (const char *name, const struct macro_definition *macro,
440                  struct macro_source_file *source, int line,
441                  void *ignore)
442 {
443   fprintf_filtered (gdb_stdout, "macro define %s", name);
444   if (macro->kind == macro_function_like)
445     {
446       int i;
447
448       fprintf_filtered (gdb_stdout, "(");
449       for (i = 0; i < macro->argc; ++i)
450         fprintf_filtered (gdb_stdout, "%s%s", (i > 0) ? ", " : "",
451                           macro->argv[i]);
452       fprintf_filtered (gdb_stdout, ")");
453     }
454   fprintf_filtered (gdb_stdout, " %s\n", macro->replacement);
455 }
456
457
458 static void
459 macro_list_command (char *exp, int from_tty)
460 {
461   macro_for_each (macro_user_macros, print_one_macro, NULL);
462 }
463
464 \f
465 /* Initializing the `macrocmd' module.  */
466
467 extern initialize_file_ftype _initialize_macrocmd; /* -Wmissing-prototypes */
468
469 void
470 _initialize_macrocmd (void)
471 {
472   /* We introduce a new command prefix, `macro', under which we'll put
473      the various commands for working with preprocessor macros.  */
474   add_prefix_cmd ("macro", class_info, macro_command,
475                   _("Prefix for commands dealing with C preprocessor macros."),
476                   &macrolist, "macro ", 0, &cmdlist);
477
478   add_cmd ("expand", no_class, macro_expand_command, _("\
479 Fully expand any C/C++ preprocessor macro invocations in EXPRESSION.\n\
480 Show the expanded expression."),
481            &macrolist);
482   add_alias_cmd ("exp", "expand", no_class, 1, &macrolist);
483   add_cmd ("expand-once", no_class, macro_expand_once_command, _("\
484 Expand C/C++ preprocessor macro invocations appearing directly in EXPRESSION.\n\
485 Show the expanded expression.\n\
486 \n\
487 This command differs from `macro expand' in that it only expands macro\n\
488 invocations that appear directly in EXPRESSION; if expanding a macro\n\
489 introduces further macro invocations, those are left unexpanded.\n\
490 \n\
491 `macro expand-once' helps you see how a particular macro expands,\n\
492 whereas `macro expand' shows you how all the macros involved in an\n\
493 expression work together to yield a pre-processed expression."),
494            &macrolist);
495   add_alias_cmd ("exp1", "expand-once", no_class, 1, &macrolist);
496
497   add_cmd ("macro", no_class, info_macro_command,
498            _("Show the definition of MACRO, and its source location."),
499            &infolist);
500
501   add_cmd ("macros", no_class, info_macros_command,
502            _("Show the definitions of all macros at LINESPEC, or the current \
503 source location.\n\
504 Usage: info macros [LINESPEC]"),
505            &infolist);
506
507   add_cmd ("definitions", no_class, info_definitions_command,
508            _("Show all definitions of MACRO in the current compilation unit.\n\
509 Usage: info definitions MACRO"),
510            &infolist);
511
512   add_cmd ("define", no_class, macro_define_command, _("\
513 Define a new C/C++ preprocessor macro.\n\
514 The GDB command `macro define DEFINITION' is equivalent to placing a\n\
515 preprocessor directive of the form `#define DEFINITION' such that the\n\
516 definition is visible in all the inferior's source files.\n\
517 For example:\n\
518   (gdb) macro define PI (3.1415926)\n\
519   (gdb) macro define MIN(x,y) ((x) < (y) ? (x) : (y))"),
520            &macrolist);
521
522   add_cmd ("undef", no_class, macro_undef_command, _("\
523 Remove the definition of the C/C++ preprocessor macro with the given name."),
524            &macrolist);
525
526   add_cmd ("list", no_class, macro_list_command,
527            _("List all the macros defined using the `macro define' command."),
528            &macrolist);
529 }