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