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