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