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