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