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