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