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