* NEWS: Document "define" for prefixed commands.
[external/binutils.git] / gdb / cli / cli-script.c
1 /* GDB CLI command scripting.
2
3    Copyright (c) 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995,
4    1996, 1997, 1998, 1999, 2000, 2001, 2002, 2004, 2005, 2006, 2007, 2008,
5    2009 Free Software Foundation, Inc.
6
7    This file is part of GDB.
8
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 3 of the License, or
12    (at your option) any later version.
13
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18
19    You should have received a copy of the GNU General Public License
20    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
21
22 #include "defs.h"
23 #include "value.h"
24 #include "language.h"           /* For value_true */
25 #include <ctype.h>
26
27 #include "ui-out.h"
28 #include "gdb_string.h"
29 #include "exceptions.h"
30 #include "top.h"
31 #include "breakpoint.h"
32 #include "cli/cli-cmds.h"
33 #include "cli/cli-decode.h"
34 #include "cli/cli-script.h"
35 #include "gdb_assert.h"
36
37 #include "python/python.h"
38
39 /* Prototypes for local functions */
40
41 static enum command_control_type
42         recurse_read_control_structure (struct command_line *current_cmd);
43
44 static char *insert_args (char *line);
45
46 static struct cleanup * setup_user_args (char *p);
47
48 /* Level of control structure when reading.  */
49 static int control_level;
50
51 /* Level of control structure when executing.  */
52 static int command_nest_depth = 1;
53
54 /* This is to prevent certain commands being printed twice.  */
55 static int suppress_next_print_command_trace = 0;
56
57 /* Structure for arguments to user defined functions.  */
58 #define MAXUSERARGS 10
59 struct user_args
60   {
61     struct user_args *next;
62     /* It is necessary to store a malloced copy of the command line to
63        ensure that the arguments are not overwritten before they are used.  */
64     char *command;
65     struct
66       {
67         char *arg;
68         int len;
69       }
70     a[MAXUSERARGS];
71     int count;
72   }
73  *user_args;
74
75 \f
76 /* Allocate, initialize a new command line structure for one of the
77    control commands (if/while).  */
78
79 static struct command_line *
80 build_command_line (enum command_control_type type, char *args)
81 {
82   struct command_line *cmd;
83
84   if (args == NULL && (type == if_control || type == while_control))
85     error (_("if/while commands require arguments."));
86   gdb_assert (args != NULL);
87
88   cmd = (struct command_line *) xmalloc (sizeof (struct command_line));
89   cmd->next = NULL;
90   cmd->control_type = type;
91
92   cmd->body_count = 1;
93   cmd->body_list
94     = (struct command_line **) xmalloc (sizeof (struct command_line *)
95                                         * cmd->body_count);
96   memset (cmd->body_list, 0, sizeof (struct command_line *) * cmd->body_count);
97   cmd->line = savestring (args, strlen (args));
98
99   return cmd;
100 }
101
102 /* Build and return a new command structure for the control commands
103    such as "if" and "while".  */
104
105 struct command_line *
106 get_command_line (enum command_control_type type, char *arg)
107 {
108   struct command_line *cmd;
109   struct cleanup *old_chain = NULL;
110
111   /* Allocate and build a new command line structure.  */
112   cmd = build_command_line (type, arg);
113
114   old_chain = make_cleanup_free_command_lines (&cmd);
115
116   /* Read in the body of this command.  */
117   if (recurse_read_control_structure (cmd) == invalid_control)
118     {
119       warning (_("Error reading in canned sequence of commands."));
120       do_cleanups (old_chain);
121       return NULL;
122     }
123
124   discard_cleanups (old_chain);
125   return cmd;
126 }
127
128 /* Recursively print a command (including full control structures).  */
129
130 void
131 print_command_lines (struct ui_out *uiout, struct command_line *cmd,
132                      unsigned int depth)
133 {
134   struct command_line *list;
135
136   list = cmd;
137   while (list)
138     {
139
140       if (depth)
141         ui_out_spaces (uiout, 2 * depth);
142
143       /* A simple command, print it and continue.  */
144       if (list->control_type == simple_control)
145         {
146           ui_out_field_string (uiout, NULL, list->line);
147           ui_out_text (uiout, "\n");
148           list = list->next;
149           continue;
150         }
151
152       /* loop_continue to jump to the start of a while loop, print it
153          and continue. */
154       if (list->control_type == continue_control)
155         {
156           ui_out_field_string (uiout, NULL, "loop_continue");
157           ui_out_text (uiout, "\n");
158           list = list->next;
159           continue;
160         }
161
162       /* loop_break to break out of a while loop, print it and continue.  */
163       if (list->control_type == break_control)
164         {
165           ui_out_field_string (uiout, NULL, "loop_break");
166           ui_out_text (uiout, "\n");
167           list = list->next;
168           continue;
169         }
170
171       /* A while command.  Recursively print its subcommands and continue.  */
172       if (list->control_type == while_control)
173         {
174           ui_out_field_fmt (uiout, NULL, "while %s", list->line);
175           ui_out_text (uiout, "\n");
176           print_command_lines (uiout, *list->body_list, depth + 1);
177           if (depth)
178             ui_out_spaces (uiout, 2 * depth);
179           ui_out_field_string (uiout, NULL, "end");
180           ui_out_text (uiout, "\n");
181           list = list->next;
182           continue;
183         }
184
185       /* An if command.  Recursively print both arms before continueing.  */
186       if (list->control_type == if_control)
187         {
188           ui_out_field_fmt (uiout, NULL, "if %s", list->line);
189           ui_out_text (uiout, "\n");
190           /* The true arm. */
191           print_command_lines (uiout, list->body_list[0], depth + 1);
192
193           /* Show the false arm if it exists.  */
194           if (list->body_count == 2)
195             {
196               if (depth)
197                 ui_out_spaces (uiout, 2 * depth);
198               ui_out_field_string (uiout, NULL, "else");
199               ui_out_text (uiout, "\n");
200               print_command_lines (uiout, list->body_list[1], depth + 1);
201             }
202
203           if (depth)
204             ui_out_spaces (uiout, 2 * depth);
205           ui_out_field_string (uiout, NULL, "end");
206           ui_out_text (uiout, "\n");
207           list = list->next;
208           continue;
209         }
210
211       /* A commands command.  Print the breakpoint commands and continue.  */
212       if (list->control_type == commands_control)
213         {
214           if (*(list->line))
215             ui_out_field_fmt (uiout, NULL, "commands %s", list->line);
216           else
217             ui_out_field_string (uiout, NULL, "commands");
218           ui_out_text (uiout, "\n");
219           print_command_lines (uiout, *list->body_list, depth + 1);
220           if (depth)
221             ui_out_spaces (uiout, 2 * depth);
222           ui_out_field_string (uiout, NULL, "end");
223           ui_out_text (uiout, "\n");
224           list = list->next;
225           continue;
226         }
227
228       if (list->control_type == python_control)
229         {
230           ui_out_field_string (uiout, NULL, "python");
231           ui_out_text (uiout, "\n");
232           /* Don't indent python code at all.  */
233           print_command_lines (uiout, *list->body_list, 0);
234           if (depth)
235             ui_out_spaces (uiout, 2 * depth);
236           ui_out_field_string (uiout, NULL, "end");
237           ui_out_text (uiout, "\n");
238           list = list->next;
239           continue;
240         }
241
242       /* ignore illegal command type and try next */
243       list = list->next;
244     }                           /* while (list) */
245 }
246
247 /* Handle pre-post hooks.  */
248
249 static void
250 clear_hook_in_cleanup (void *data)
251 {
252   struct cmd_list_element *c = data;
253   c->hook_in = 0; /* Allow hook to work again once it is complete */
254 }
255
256 void
257 execute_cmd_pre_hook (struct cmd_list_element *c)
258 {
259   if ((c->hook_pre) && (!c->hook_in))
260     {
261       struct cleanup *cleanups = make_cleanup (clear_hook_in_cleanup, c);
262       c->hook_in = 1; /* Prevent recursive hooking */
263       execute_user_command (c->hook_pre, (char *) 0);
264       do_cleanups (cleanups);
265     }
266 }
267
268 void
269 execute_cmd_post_hook (struct cmd_list_element *c)
270 {
271   if ((c->hook_post) && (!c->hook_in))
272     {
273       struct cleanup *cleanups = make_cleanup (clear_hook_in_cleanup, c);
274       c->hook_in = 1; /* Prevent recursive hooking */
275       execute_user_command (c->hook_post, (char *) 0);
276       do_cleanups (cleanups);
277     }
278 }
279
280 /* Execute the command in CMD.  */
281 static void
282 do_restore_user_call_depth (void * call_depth)
283 {       
284   int * depth = call_depth;
285   (*depth)--;
286   if ((*depth) == 0)
287     in_user_command = 0;
288 }
289
290
291 void
292 execute_user_command (struct cmd_list_element *c, char *args)
293 {
294   struct command_line *cmdlines;
295   struct cleanup *old_chain;
296   enum command_control_type ret;
297   static int user_call_depth = 0;
298   extern int max_user_call_depth;
299
300   old_chain = setup_user_args (args);
301
302   cmdlines = c->user_commands;
303   if (cmdlines == 0)
304     /* Null command */
305     return;
306
307   if (++user_call_depth > max_user_call_depth)
308     error (_("Max user call depth exceeded -- command aborted."));
309
310   make_cleanup (do_restore_user_call_depth, &user_call_depth);
311
312   /* Set the instream to 0, indicating execution of a
313      user-defined function.  */
314   make_cleanup (do_restore_instream_cleanup, instream);
315   instream = (FILE *) 0;
316
317   /* Also set the global in_user_command, so that NULL instream is
318      not confused with Insight.  */
319   in_user_command = 1;
320
321   command_nest_depth++;
322   while (cmdlines)
323     {
324       ret = execute_control_command (cmdlines);
325       if (ret != simple_control && ret != break_control)
326         {
327           warning (_("Error executing canned sequence of commands."));
328           break;
329         }
330       cmdlines = cmdlines->next;
331     }
332   command_nest_depth--;
333   do_cleanups (old_chain);
334 }
335
336 /* This function is called every time GDB prints a prompt.
337    It ensures that errors and the like to not confuse the command tracing.  */
338
339 void
340 reset_command_nest_depth (void)
341 {
342   command_nest_depth = 1;
343
344   /* Just in case.  */
345   suppress_next_print_command_trace = 0;
346 }
347
348 /* Print the command, prefixed with '+' to represent the call depth.
349    This is slightly complicated because this function may be called
350    from execute_command and execute_control_command.  Unfortunately
351    execute_command also prints the top level control commands.
352    In these cases execute_command will call execute_control_command
353    via while_command or if_command.  Inner levels of 'if' and 'while'
354    are dealt with directly.  Therefore we can use these functions
355    to determine whether the command has been printed already or not.  */
356 void
357 print_command_trace (const char *cmd)
358 {
359   int i;
360
361   if (suppress_next_print_command_trace)
362     {
363       suppress_next_print_command_trace = 0;
364       return;
365     }
366
367   if (!source_verbose && !trace_commands)
368     return;
369
370   for (i=0; i < command_nest_depth; i++)
371     printf_filtered ("+");
372
373   printf_filtered ("%s\n", cmd);
374 }
375
376 enum command_control_type
377 execute_control_command (struct command_line *cmd)
378 {
379   struct expression *expr;
380   struct command_line *current;
381   struct cleanup *old_chain = make_cleanup (null_cleanup, 0);
382   struct value *val;
383   struct value *val_mark;
384   int loop;
385   enum command_control_type ret;
386   char *new_line;
387
388   /* Start by assuming failure, if a problem is detected, the code
389      below will simply "break" out of the switch.  */
390   ret = invalid_control;
391
392   switch (cmd->control_type)
393     {
394     case simple_control:
395       /* A simple command, execute it and return.  */
396       new_line = insert_args (cmd->line);
397       if (!new_line)
398         break;
399       make_cleanup (free_current_contents, &new_line);
400       execute_command (new_line, 0);
401       ret = cmd->control_type;
402       break;
403
404     case continue_control:
405       print_command_trace ("loop_continue");
406
407       /* Return for "continue", and "break" so we can either
408          continue the loop at the top, or break out.  */
409       ret = cmd->control_type;
410       break;
411
412     case break_control:
413       print_command_trace ("loop_break");
414
415       /* Return for "continue", and "break" so we can either
416          continue the loop at the top, or break out.  */
417       ret = cmd->control_type;
418       break;
419
420     case while_control:
421       {
422         char *buffer = alloca (strlen (cmd->line) + 7);
423         sprintf (buffer, "while %s", cmd->line);
424         print_command_trace (buffer);
425
426         /* Parse the loop control expression for the while statement.  */
427         new_line = insert_args (cmd->line);
428         if (!new_line)
429           break;
430         make_cleanup (free_current_contents, &new_line);
431         expr = parse_expression (new_line);
432         make_cleanup (free_current_contents, &expr);
433
434         ret = simple_control;
435         loop = 1;
436
437         /* Keep iterating so long as the expression is true.  */
438         while (loop == 1)
439           {
440             int cond_result;
441
442             QUIT;
443
444             /* Evaluate the expression.  */
445             val_mark = value_mark ();
446             val = evaluate_expression (expr);
447             cond_result = value_true (val);
448             value_free_to_mark (val_mark);
449
450             /* If the value is false, then break out of the loop.  */
451             if (!cond_result)
452               break;
453
454             /* Execute the body of the while statement.  */
455             current = *cmd->body_list;
456             while (current)
457               {
458                 command_nest_depth++;
459                 ret = execute_control_command (current);
460                 command_nest_depth--;
461
462                 /* If we got an error, or a "break" command, then stop
463                    looping.  */
464                 if (ret == invalid_control || ret == break_control)
465                   {
466                     loop = 0;
467                     break;
468                   }
469
470                 /* If we got a "continue" command, then restart the loop
471                    at this point.  */
472                 if (ret == continue_control)
473                   break;
474
475                 /* Get the next statement.  */
476                 current = current->next;
477               }
478           }
479
480         /* Reset RET so that we don't recurse the break all the way down.  */
481         if (ret == break_control)
482           ret = simple_control;
483
484         break;
485       }
486
487     case if_control:
488       {
489         char *buffer = alloca (strlen (cmd->line) + 4);
490         sprintf (buffer, "if %s", cmd->line);
491         print_command_trace (buffer);
492
493         new_line = insert_args (cmd->line);
494         if (!new_line)
495           break;
496         make_cleanup (free_current_contents, &new_line);
497         /* Parse the conditional for the if statement.  */
498         expr = parse_expression (new_line);
499         make_cleanup (free_current_contents, &expr);
500
501         current = NULL;
502         ret = simple_control;
503
504         /* Evaluate the conditional.  */
505         val_mark = value_mark ();
506         val = evaluate_expression (expr);
507
508         /* Choose which arm to take commands from based on the value of the
509            conditional expression.  */
510         if (value_true (val))
511           current = *cmd->body_list;
512         else if (cmd->body_count == 2)
513           current = *(cmd->body_list + 1);
514         value_free_to_mark (val_mark);
515
516         /* Execute commands in the given arm.  */
517         while (current)
518           {
519             command_nest_depth++;
520             ret = execute_control_command (current);
521             command_nest_depth--;
522
523             /* If we got an error, get out.  */
524             if (ret != simple_control)
525               break;
526
527             /* Get the next statement in the body.  */
528             current = current->next;
529           }
530
531         break;
532       }
533     case commands_control:
534       {
535         /* Breakpoint commands list, record the commands in the breakpoint's
536            command list and return.  */
537         new_line = insert_args (cmd->line);
538         if (!new_line)
539           break;
540         make_cleanup (free_current_contents, &new_line);
541         ret = commands_from_control_command (new_line, cmd);
542         break;
543       }
544     case python_control:
545       {
546         eval_python_from_control_command (cmd);
547         ret = simple_control;
548         break;
549       }
550
551     default:
552       warning (_("Invalid control type in canned commands structure."));
553       break;
554     }
555
556   do_cleanups (old_chain);
557
558   return ret;
559 }
560
561 /* Like execute_control_command, but first set
562    suppress_next_print_command_trace.   */
563
564 enum command_control_type
565 execute_control_command_untraced (struct command_line *cmd)
566 {
567   suppress_next_print_command_trace = 1;
568   return execute_control_command (cmd);
569 }
570
571
572 /* "while" command support.  Executes a body of statements while the
573    loop condition is nonzero.  */
574
575 void
576 while_command (char *arg, int from_tty)
577 {
578   struct command_line *command = NULL;
579
580   control_level = 1;
581   command = get_command_line (while_control, arg);
582
583   if (command == NULL)
584     return;
585
586   execute_control_command_untraced (command);
587   free_command_lines (&command);
588 }
589
590 /* "if" command support.  Execute either the true or false arm depending
591    on the value of the if conditional.  */
592
593 void
594 if_command (char *arg, int from_tty)
595 {
596   struct command_line *command = NULL;
597
598   control_level = 1;
599   command = get_command_line (if_control, arg);
600
601   if (command == NULL)
602     return;
603
604   execute_control_command_untraced (command);
605   free_command_lines (&command);
606 }
607
608 /* Cleanup */
609 static void
610 arg_cleanup (void *ignore)
611 {
612   struct user_args *oargs = user_args;
613   if (!user_args)
614     internal_error (__FILE__, __LINE__,
615                     _("arg_cleanup called with no user args.\n"));
616
617   user_args = user_args->next;
618   xfree (oargs->command);
619   xfree (oargs);
620 }
621
622 /* Bind the incomming arguments for a user defined command to
623    $arg0, $arg1 ... $argMAXUSERARGS.  */
624
625 static struct cleanup *
626 setup_user_args (char *p)
627 {
628   struct user_args *args;
629   struct cleanup *old_chain;
630   unsigned int arg_count = 0;
631
632   args = (struct user_args *) xmalloc (sizeof (struct user_args));
633   memset (args, 0, sizeof (struct user_args));
634
635   args->next = user_args;
636   user_args = args;
637
638   old_chain = make_cleanup (arg_cleanup, 0/*ignored*/);
639
640   if (p == NULL)
641     return old_chain;
642
643   user_args->command = p = xstrdup (p);
644
645   while (*p)
646     {
647       char *start_arg;
648       int squote = 0;
649       int dquote = 0;
650       int bsquote = 0;
651
652       if (arg_count >= MAXUSERARGS)
653         {
654           error (_("user defined function may only have %d arguments."),
655                  MAXUSERARGS);
656           return old_chain;
657         }
658
659       /* Strip whitespace.  */
660       while (*p == ' ' || *p == '\t')
661         p++;
662
663       /* P now points to an argument.  */
664       start_arg = p;
665       user_args->a[arg_count].arg = p;
666
667       /* Get to the end of this argument.  */
668       while (*p)
669         {
670           if (((*p == ' ' || *p == '\t')) && !squote && !dquote && !bsquote)
671             break;
672           else
673             {
674               if (bsquote)
675                 bsquote = 0;
676               else if (*p == '\\')
677                 bsquote = 1;
678               else if (squote)
679                 {
680                   if (*p == '\'')
681                     squote = 0;
682                 }
683               else if (dquote)
684                 {
685                   if (*p == '"')
686                     dquote = 0;
687                 }
688               else
689                 {
690                   if (*p == '\'')
691                     squote = 1;
692                   else if (*p == '"')
693                     dquote = 1;
694                 }
695               p++;
696             }
697         }
698
699       user_args->a[arg_count].len = p - start_arg;
700       arg_count++;
701       user_args->count++;
702     }
703   return old_chain;
704 }
705
706 /* Given character string P, return a point to the first argument ($arg),
707    or NULL if P contains no arguments.  */
708
709 static char *
710 locate_arg (char *p)
711 {
712   while ((p = strchr (p, '$')))
713     {
714       if (strncmp (p, "$arg", 4) == 0
715           && (isdigit (p[4]) || p[4] == 'c'))
716         return p;
717       p++;
718     }
719   return NULL;
720 }
721
722 /* Insert the user defined arguments stored in user_arg into the $arg
723    arguments found in line, with the updated copy being placed into nline.  */
724
725 static char *
726 insert_args (char *line)
727 {
728   char *p, *save_line, *new_line;
729   unsigned len, i;
730
731   /* If we are not in a user-defined function, treat $argc, $arg0, et
732      cetera as normal convenience variables.  */
733   if (user_args == NULL)
734     return xstrdup (line);
735
736   /* First we need to know how much memory to allocate for the new line.  */
737   save_line = line;
738   len = 0;
739   while ((p = locate_arg (line)))
740     {
741       len += p - line;
742       i = p[4] - '0';
743
744       if (p[4] == 'c')
745         {
746           /* $argc.  Number will be <=10.  */
747           len += user_args->count == 10 ? 2 : 1;
748         }
749       else if (i >= user_args->count)
750         {
751           error (_("Missing argument %d in user function."), i);
752           return NULL;
753         }
754       else
755         {
756           len += user_args->a[i].len;
757         }
758       line = p + 5;
759     }
760
761   /* Don't forget the tail.  */
762   len += strlen (line);
763
764   /* Allocate space for the new line and fill it in.  */
765   new_line = (char *) xmalloc (len + 1);
766   if (new_line == NULL)
767     return NULL;
768
769   /* Restore pointer to beginning of old line.  */
770   line = save_line;
771
772   /* Save pointer to beginning of new line.  */
773   save_line = new_line;
774
775   while ((p = locate_arg (line)))
776     {
777       int i, len;
778
779       memcpy (new_line, line, p - line);
780       new_line += p - line;
781
782       if (p[4] == 'c')
783         {
784           gdb_assert (user_args->count >= 0 && user_args->count <= 10);
785           if (user_args->count == 10)
786             {
787               *(new_line++) = '1';
788               *(new_line++) = '0';
789             }
790           else
791             *(new_line++) = user_args->count + '0';
792         }
793       else
794         {
795           i = p[4] - '0';
796           len = user_args->a[i].len;
797           if (len)
798           {
799             memcpy (new_line, user_args->a[i].arg, len);
800             new_line += len;
801           }
802         }
803       line = p + 5;
804     }
805   /* Don't forget the tail.  */
806   strcpy (new_line, line);
807
808   /* Return a pointer to the beginning of the new line.  */
809   return save_line;
810 }
811
812 \f
813 /* Expand the body_list of COMMAND so that it can hold NEW_LENGTH
814    code bodies.  This is typically used when we encounter an "else"
815    clause for an "if" command.  */
816
817 static void
818 realloc_body_list (struct command_line *command, int new_length)
819 {
820   int n;
821   struct command_line **body_list;
822
823   n = command->body_count;
824
825   /* Nothing to do?  */
826   if (new_length <= n)
827     return;
828
829   body_list = (struct command_line **)
830     xmalloc (sizeof (struct command_line *) * new_length);
831
832   memcpy (body_list, command->body_list, sizeof (struct command_line *) * n);
833   memset (body_list + n, 0, sizeof (struct command_line *) * (new_length - n));
834
835   xfree (command->body_list);
836   command->body_list = body_list;
837   command->body_count = new_length;
838 }
839
840 /* Read one line from the input stream.  If the command is an "end",
841    return such an indication to the caller.  If PARSE_COMMANDS is true,
842    strip leading whitespace (trailing whitespace is always stripped)
843    in the line, attempt to recognize GDB control commands, and also
844    return an indication if the command is an "else" or a nop.
845    Otherwise, only "end" is recognized.  */
846
847 static enum misc_command_type
848 read_next_line (struct command_line **command, int parse_commands)
849 {
850   char *p, *p1, *prompt_ptr, control_prompt[256];
851   int i = 0;
852   int not_handled = 0;
853
854   if (control_level >= 254)
855     error (_("Control nesting too deep!"));
856
857   /* Set a prompt based on the nesting of the control commands.  */
858   if (instream == stdin || (instream == 0 && deprecated_readline_hook != NULL))
859     {
860       for (i = 0; i < control_level; i++)
861         control_prompt[i] = ' ';
862       control_prompt[i] = '>';
863       control_prompt[i + 1] = '\0';
864       prompt_ptr = (char *) &control_prompt[0];
865     }
866   else
867     prompt_ptr = NULL;
868
869   p = command_line_input (prompt_ptr, instream == stdin, "commands");
870
871   /* Not sure what to do here.  */
872   if (p == NULL)
873     return end_command;
874
875   if (parse_commands)
876     {
877       /* Strip leading whitespace.  */
878       while (*p == ' ' || *p == '\t')
879         p++;
880     }
881
882   /* Strip trailing whitespace.  */
883   p1 = p + strlen (p);
884   while (p1 != p && (p1[-1] == ' ' || p1[-1] == '\t'))
885     p1--;
886
887   /* Is this the end of a simple, while, or if control structure?  */
888   if (p1 - p == 3 && !strncmp (p, "end", 3))
889     return end_command;
890
891   if (parse_commands)
892     {
893       /* Blanks and comments don't really do anything, but we need to
894          distinguish them from else, end and other commands which can be
895          executed.  */
896       if (p1 == p || p[0] == '#')
897         return nop_command;
898
899       /* Is the else clause of an if control structure?  */
900       if (p1 - p == 4 && !strncmp (p, "else", 4))
901         return else_command;
902
903       /* Check for while, if, break, continue, etc and build a new command
904          line structure for them.  */
905       if (p1 - p > 5 && !strncmp (p, "while", 5))
906         {
907           char *first_arg;
908           first_arg = p + 5;
909           while (first_arg < p1 && isspace (*first_arg))
910             first_arg++;
911           *command = build_command_line (while_control, first_arg);
912         }
913       else if (p1 - p > 2 && !strncmp (p, "if", 2))
914         {
915           char *first_arg;
916           first_arg = p + 2;
917           while (first_arg < p1 && isspace (*first_arg))
918             first_arg++;
919           *command = build_command_line (if_control, first_arg);
920         }
921       else if (p1 - p >= 8 && !strncmp (p, "commands", 8))
922         {
923           char *first_arg;
924           first_arg = p + 8;
925           while (first_arg < p1 && isspace (*first_arg))
926             first_arg++;
927           *command = build_command_line (commands_control, first_arg);
928         }
929       else if (p1 - p == 6 && !strncmp (p, "python", 6))
930         {
931           /* Note that we ignore the inline "python command" form
932              here.  */
933           *command = build_command_line (python_control, "");
934         }
935       else if (p1 - p == 10 && !strncmp (p, "loop_break", 10))
936         {
937           *command = (struct command_line *)
938             xmalloc (sizeof (struct command_line));
939           (*command)->next = NULL;
940           (*command)->line = NULL;
941           (*command)->control_type = break_control;
942           (*command)->body_count = 0;
943           (*command)->body_list = NULL;
944         }
945       else if (p1 - p == 13 && !strncmp (p, "loop_continue", 13))
946         {
947           *command = (struct command_line *)
948             xmalloc (sizeof (struct command_line));
949           (*command)->next = NULL;
950           (*command)->line = NULL;
951           (*command)->control_type = continue_control;
952           (*command)->body_count = 0;
953           (*command)->body_list = NULL;
954         }
955       else
956         not_handled = 1;
957     }
958
959   if (!parse_commands || not_handled)
960     {
961       /* A normal command.  */
962       *command = (struct command_line *)
963         xmalloc (sizeof (struct command_line));
964       (*command)->next = NULL;
965       (*command)->line = savestring (p, p1 - p);
966       (*command)->control_type = simple_control;
967       (*command)->body_count = 0;
968       (*command)->body_list = NULL;
969     }
970
971   /* Nothing special.  */
972   return ok_command;
973 }
974
975 /* Recursively read in the control structures and create a command_line 
976    structure from them.
977
978    The parent_control parameter is the control structure in which the
979    following commands are nested.  */
980
981 static enum command_control_type
982 recurse_read_control_structure (struct command_line *current_cmd)
983 {
984   int current_body, i;
985   enum misc_command_type val;
986   enum command_control_type ret;
987   struct command_line **body_ptr, *child_tail, *next;
988
989   child_tail = NULL;
990   current_body = 1;
991
992   /* Sanity checks.  */
993   if (current_cmd->control_type == simple_control)
994     error (_("Recursed on a simple control type."));
995
996   if (current_body > current_cmd->body_count)
997     error (_("Allocated body is smaller than this command type needs."));
998
999   /* Read lines from the input stream and build control structures.  */
1000   while (1)
1001     {
1002       dont_repeat ();
1003
1004       next = NULL;
1005       val = read_next_line (&next, current_cmd->control_type != python_control);
1006
1007       /* Just skip blanks and comments.  */
1008       if (val == nop_command)
1009         continue;
1010
1011       if (val == end_command)
1012         {
1013           if (current_cmd->control_type == while_control
1014               || current_cmd->control_type == if_control
1015               || current_cmd->control_type == python_control
1016               || current_cmd->control_type == commands_control)
1017             {
1018               /* Success reading an entire canned sequence of commands.  */
1019               ret = simple_control;
1020               break;
1021             }
1022           else
1023             {
1024               ret = invalid_control;
1025               break;
1026             }
1027         }
1028
1029       /* Not the end of a control structure.  */
1030       if (val == else_command)
1031         {
1032           if (current_cmd->control_type == if_control
1033               && current_body == 1)
1034             {
1035               realloc_body_list (current_cmd, 2);
1036               current_body = 2;
1037               child_tail = NULL;
1038               continue;
1039             }
1040           else
1041             {
1042               ret = invalid_control;
1043               break;
1044             }
1045         }
1046
1047       if (child_tail)
1048         {
1049           child_tail->next = next;
1050         }
1051       else
1052         {
1053           body_ptr = current_cmd->body_list;
1054           for (i = 1; i < current_body; i++)
1055             body_ptr++;
1056
1057           *body_ptr = next;
1058
1059         }
1060
1061       child_tail = next;
1062
1063       /* If the latest line is another control structure, then recurse
1064          on it.  */
1065       if (next->control_type == while_control
1066           || next->control_type == if_control
1067           || next->control_type == python_control
1068           || next->control_type == commands_control)
1069         {
1070           control_level++;
1071           ret = recurse_read_control_structure (next);
1072           control_level--;
1073
1074           if (ret != simple_control)
1075             break;
1076         }
1077     }
1078
1079   dont_repeat ();
1080
1081   return ret;
1082 }
1083
1084 /* Read lines from the input stream and accumulate them in a chain of
1085    struct command_line's, which is then returned.  For input from a
1086    terminal, the special command "end" is used to mark the end of the
1087    input, and is not included in the returned chain of commands.
1088
1089    If PARSE_COMMANDS is true, strip leading whitespace (trailing whitespace
1090    is always stripped) in the line and attempt to recognize GDB control
1091    commands.  Otherwise, only "end" is recognized.  */
1092
1093 #define END_MESSAGE "End with a line saying just \"end\"."
1094
1095 struct command_line *
1096 read_command_lines (char *prompt_arg, int from_tty, int parse_commands)
1097 {
1098   struct command_line *head, *tail, *next;
1099   struct cleanup *old_chain;
1100   enum command_control_type ret;
1101   enum misc_command_type val;
1102
1103   control_level = 0;
1104
1105   if (from_tty && input_from_terminal_p ())
1106     {
1107       if (deprecated_readline_begin_hook)
1108         {
1109           /* Note - intentional to merge messages with no newline */
1110           (*deprecated_readline_begin_hook) ("%s  %s\n", prompt_arg, END_MESSAGE);
1111         }
1112       else
1113         {
1114           printf_unfiltered ("%s\n%s\n", prompt_arg, END_MESSAGE);
1115           gdb_flush (gdb_stdout);
1116         }
1117     }
1118
1119   head = tail = NULL;
1120   old_chain = NULL;
1121
1122   while (1)
1123     {
1124       dont_repeat ();
1125       val = read_next_line (&next, parse_commands);
1126
1127       /* Ignore blank lines or comments.  */
1128       if (val == nop_command)
1129         continue;
1130
1131       if (val == end_command)
1132         {
1133           ret = simple_control;
1134           break;
1135         }
1136
1137       if (val != ok_command)
1138         {
1139           ret = invalid_control;
1140           break;
1141         }
1142
1143       if (next->control_type == while_control
1144           || next->control_type == if_control
1145           || next->control_type == python_control
1146           || next->control_type == commands_control)
1147         {
1148           control_level++;
1149           ret = recurse_read_control_structure (next);
1150           control_level--;
1151
1152           if (ret == invalid_control)
1153             break;
1154         }
1155
1156       if (tail)
1157         {
1158           tail->next = next;
1159         }
1160       else
1161         {
1162           head = next;
1163           old_chain = make_cleanup_free_command_lines (&head);
1164         }
1165       tail = next;
1166     }
1167
1168   dont_repeat ();
1169
1170   if (head)
1171     {
1172       if (ret != invalid_control)
1173         {
1174           discard_cleanups (old_chain);
1175         }
1176       else
1177         do_cleanups (old_chain);
1178     }
1179
1180   if (deprecated_readline_end_hook && from_tty && input_from_terminal_p ())
1181     {
1182       (*deprecated_readline_end_hook) ();
1183     }
1184   return (head);
1185 }
1186
1187 /* Free a chain of struct command_line's.  */
1188
1189 void
1190 free_command_lines (struct command_line **lptr)
1191 {
1192   struct command_line *l = *lptr;
1193   struct command_line *next;
1194   struct command_line **blist;
1195   int i;
1196
1197   while (l)
1198     {
1199       if (l->body_count > 0)
1200         {
1201           blist = l->body_list;
1202           for (i = 0; i < l->body_count; i++, blist++)
1203             free_command_lines (blist);
1204         }
1205       next = l->next;
1206       xfree (l->line);
1207       xfree (l);
1208       l = next;
1209     }
1210   *lptr = NULL;
1211 }
1212
1213 static void
1214 do_free_command_lines_cleanup (void *arg)
1215 {
1216   free_command_lines (arg);
1217 }
1218
1219 struct cleanup *
1220 make_cleanup_free_command_lines (struct command_line **arg)
1221 {
1222   return make_cleanup (do_free_command_lines_cleanup, arg);
1223 }
1224
1225 struct command_line *
1226 copy_command_lines (struct command_line *cmds)
1227 {
1228   struct command_line *result = NULL;
1229
1230   if (cmds)
1231     {
1232       result = (struct command_line *) xmalloc (sizeof (struct command_line));
1233
1234       result->next = copy_command_lines (cmds->next);
1235       result->line = xstrdup (cmds->line);
1236       result->control_type = cmds->control_type;
1237       result->body_count = cmds->body_count;
1238       if (cmds->body_count > 0)
1239         {
1240           int i;
1241
1242           result->body_list = (struct command_line **)
1243             xmalloc (sizeof (struct command_line *) * cmds->body_count);
1244
1245           for (i = 0; i < cmds->body_count; i++)
1246             result->body_list[i] = copy_command_lines (cmds->body_list[i]);
1247         }
1248       else
1249         result->body_list = NULL;
1250     }
1251
1252   return result;
1253 }
1254 \f
1255 /* Validate that *COMNAME is a valid name for a command.  Return the
1256    containing command list, in case it starts with a prefix command.
1257    The prefix must already exist.  *COMNAME is advanced to point after
1258    any prefix, and a NUL character overwrites the space after the
1259    prefix.  */
1260
1261 static struct cmd_list_element **
1262 validate_comname (char **comname)
1263 {
1264   struct cmd_list_element **list = &cmdlist;
1265   char *p, *last_word;
1266
1267   if (*comname == 0)
1268     error_no_arg (_("name of command to define"));
1269
1270   /* Find the last word of the argument.  */
1271   p = *comname + strlen (*comname);
1272   while (p > *comname && isspace (p[-1]))
1273     p--;
1274   while (p > *comname && !isspace (p[-1]))
1275     p--;
1276   last_word = p;
1277
1278   /* Find the corresponding command list.  */
1279   if (last_word != *comname)
1280     {
1281       struct cmd_list_element *c;
1282       char saved_char, *tem = *comname;
1283
1284       /* Separate the prefix and the command.  */
1285       saved_char = last_word[-1];
1286       last_word[-1] = '\0';
1287
1288       c = lookup_cmd (&tem, cmdlist, "", 0, 1);
1289       if (c->prefixlist == NULL)
1290         error (_("\"%s\" is not a prefix command."), *comname);
1291
1292       list = c->prefixlist;
1293       last_word[-1] = saved_char;
1294       *comname = last_word;
1295     }
1296
1297   p = *comname;
1298   while (*p)
1299     {
1300       if (!isalnum (*p) && *p != '-' && *p != '_')
1301         error (_("Junk in argument list: \"%s\""), p);
1302       p++;
1303     }
1304
1305   return list;
1306 }
1307
1308 /* This is just a placeholder in the command data structures.  */
1309 static void
1310 user_defined_command (char *ignore, int from_tty)
1311 {
1312 }
1313
1314 void
1315 define_command (char *comname, int from_tty)
1316 {
1317 #define MAX_TMPBUF 128   
1318   enum cmd_hook_type
1319     {
1320       CMD_NO_HOOK = 0,
1321       CMD_PRE_HOOK,
1322       CMD_POST_HOOK
1323     };
1324   struct command_line *cmds;
1325   struct cmd_list_element *c, *newc, *oldc, *hookc = 0, **list;
1326   char *tem, *tem2, *comfull;
1327   char tmpbuf[MAX_TMPBUF];
1328   int  hook_type      = CMD_NO_HOOK;
1329   int  hook_name_size = 0;
1330    
1331 #define HOOK_STRING     "hook-"
1332 #define HOOK_LEN 5
1333 #define HOOK_POST_STRING "hookpost-"
1334 #define HOOK_POST_LEN    9
1335
1336   comfull = comname;
1337   list = validate_comname (&comname);
1338
1339   /* Look it up, and verify that we got an exact match.  */
1340   tem = comname;
1341   c = lookup_cmd (&tem, *list, "", -1, 1);
1342   if (c && strcmp (comname, c->name) != 0)
1343     c = 0;
1344
1345   if (c)
1346     {
1347       int q;
1348       if (c->class == class_user || c->class == class_alias)
1349         q = query (_("Redefine command \"%s\"? "), c->name);
1350       else
1351         q = query (_("Really redefine built-in command \"%s\"? "), c->name);
1352       if (!q)
1353         error (_("Command \"%s\" not redefined."), c->name);
1354     }
1355
1356   /* If this new command is a hook, then mark the command which it
1357      is hooking.  Note that we allow hooking `help' commands, so that
1358      we can hook the `stop' pseudo-command.  */
1359
1360   if (!strncmp (comname, HOOK_STRING, HOOK_LEN))
1361     {
1362        hook_type      = CMD_PRE_HOOK;
1363        hook_name_size = HOOK_LEN;
1364     }
1365   else if (!strncmp (comname, HOOK_POST_STRING, HOOK_POST_LEN))
1366     {
1367       hook_type      = CMD_POST_HOOK;
1368       hook_name_size = HOOK_POST_LEN;
1369     }
1370    
1371   if (hook_type != CMD_NO_HOOK)
1372     {
1373       /* Look up cmd it hooks, and verify that we got an exact match.  */
1374       tem = comname + hook_name_size;
1375       hookc = lookup_cmd (&tem, *list, "", -1, 0);
1376       if (hookc && strcmp (comname + hook_name_size, hookc->name) != 0)
1377         hookc = 0;
1378       if (!hookc)
1379         {
1380           warning (_("Your new `%s' command does not hook any existing command."),
1381                    comfull);
1382           if (!query ("Proceed? "))
1383             error (_("Not confirmed."));
1384         }
1385     }
1386
1387   comname = savestring (comname, strlen (comname));
1388
1389   /* If the rest of the commands will be case insensitive, this one
1390      should behave in the same manner. */
1391   for (tem = comname; *tem; tem++)
1392     if (isupper (*tem))
1393       *tem = tolower (*tem);
1394
1395   sprintf (tmpbuf, "Type commands for definition of \"%s\".", comfull);
1396   cmds = read_command_lines (tmpbuf, from_tty, 1);
1397
1398   if (c && c->class == class_user)
1399     free_command_lines (&c->user_commands);
1400
1401   newc = add_cmd (comname, class_user, user_defined_command,
1402                   (c && c->class == class_user)
1403                   ? c->doc : savestring ("User-defined.", 13), list);
1404   newc->user_commands = cmds;
1405
1406   /* If this new command is a hook, then mark both commands as being
1407      tied.  */
1408   if (hookc)
1409     {
1410       switch (hook_type)
1411         {
1412         case CMD_PRE_HOOK:
1413           hookc->hook_pre  = newc;  /* Target gets hooked.  */
1414           newc->hookee_pre = hookc; /* We are marked as hooking target cmd. */
1415           break;
1416         case CMD_POST_HOOK:
1417           hookc->hook_post  = newc;  /* Target gets hooked.  */
1418           newc->hookee_post = hookc; /* We are marked as hooking target cmd. */
1419           break;
1420         default:
1421           /* Should never come here as hookc would be 0. */
1422           internal_error (__FILE__, __LINE__, _("bad switch"));
1423         }
1424     }
1425 }
1426
1427 void
1428 document_command (char *comname, int from_tty)
1429 {
1430   struct command_line *doclines;
1431   struct cmd_list_element *c, **list;
1432   char *tem, *comfull;
1433   char tmpbuf[128];
1434
1435   comfull = comname;
1436   list = validate_comname (&comname);
1437
1438   tem = comname;
1439   c = lookup_cmd (&tem, *list, "", 0, 1);
1440
1441   if (c->class != class_user)
1442     error (_("Command \"%s\" is built-in."), comfull);
1443
1444   sprintf (tmpbuf, "Type documentation for \"%s\".", comfull);
1445   doclines = read_command_lines (tmpbuf, from_tty, 0);
1446
1447   if (c->doc)
1448     xfree (c->doc);
1449
1450   {
1451     struct command_line *cl1;
1452     int len = 0;
1453
1454     for (cl1 = doclines; cl1; cl1 = cl1->next)
1455       len += strlen (cl1->line) + 1;
1456
1457     c->doc = (char *) xmalloc (len + 1);
1458     *c->doc = 0;
1459
1460     for (cl1 = doclines; cl1; cl1 = cl1->next)
1461       {
1462         strcat (c->doc, cl1->line);
1463         if (cl1->next)
1464           strcat (c->doc, "\n");
1465       }
1466   }
1467
1468   free_command_lines (&doclines);
1469 }
1470 \f
1471 struct source_cleanup_lines_args
1472 {
1473   int old_line;
1474   char *old_file;
1475 };
1476
1477 static void
1478 source_cleanup_lines (void *args)
1479 {
1480   struct source_cleanup_lines_args *p =
1481   (struct source_cleanup_lines_args *) args;
1482   source_line_number = p->old_line;
1483   source_file_name = p->old_file;
1484 }
1485
1486 struct wrapped_read_command_file_args
1487 {
1488   FILE *stream;
1489 };
1490
1491 static void
1492 wrapped_read_command_file (struct ui_out *uiout, void *data)
1493 {
1494   struct wrapped_read_command_file_args *args = data;
1495   read_command_file (args->stream);
1496 }
1497
1498 /* Used to implement source_command */
1499
1500 void
1501 script_from_file (FILE *stream, char *file)
1502 {
1503   struct cleanup *old_cleanups;
1504   struct source_cleanup_lines_args old_lines;
1505   int needed_length;
1506
1507   if (stream == NULL)
1508     internal_error (__FILE__, __LINE__, _("called with NULL file pointer!"));
1509
1510   old_cleanups = make_cleanup_fclose (stream);
1511
1512   old_lines.old_line = source_line_number;
1513   old_lines.old_file = source_file_name;
1514   make_cleanup (source_cleanup_lines, &old_lines);
1515   source_line_number = 0;
1516   source_file_name = file;
1517   /* This will get set every time we read a line.  So it won't stay "" for
1518      long.  */
1519   error_pre_print = "";
1520
1521   {
1522     struct gdb_exception e;
1523     struct wrapped_read_command_file_args args;
1524     args.stream = stream;
1525     e = catch_exception (uiout, wrapped_read_command_file, &args,
1526                          RETURN_MASK_ERROR);
1527     switch (e.reason)
1528       {
1529       case 0:
1530         break;
1531       case RETURN_ERROR:
1532         /* Re-throw the error, but with the file name information
1533            prepended.  */
1534         throw_error (e.error,
1535                      _("%s:%d: Error in sourced command file:\n%s"),
1536                      source_file_name, source_line_number, e.message);
1537       default:
1538         internal_error (__FILE__, __LINE__, _("bad reason"));
1539       }
1540   }
1541
1542   do_cleanups (old_cleanups);
1543 }
1544
1545 /* Print the definition of user command C to STREAM.  Or, if C is a
1546    prefix command, show the definitions of all user commands under C
1547    (recursively).  PREFIX and NAME combined are the name of the
1548    current command.  */
1549 void
1550 show_user_1 (struct cmd_list_element *c, char *prefix, char *name,
1551              struct ui_file *stream)
1552 {
1553   struct command_line *cmdlines;
1554
1555   if (c->prefixlist != NULL)
1556     {
1557       char *prefixname = c->prefixname;
1558       for (c = *c->prefixlist; c != NULL; c = c->next)
1559         if (c->class == class_user || c->prefixlist != NULL)
1560           show_user_1 (c, prefixname, c->name, gdb_stdout);
1561       return;
1562     }
1563
1564   cmdlines = c->user_commands;
1565   if (!cmdlines)
1566     return;
1567   fprintf_filtered (stream, "User command \"%s%s\":\n", prefix, name);
1568
1569   print_command_lines (uiout, cmdlines, 1);
1570   fputs_filtered ("\n", stream);
1571 }
1572