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