gdb/cli/cli-script.c - gdb

Global variables defined

Data types defined

Functions defined

Macros defined

Source code

  1. /* GDB CLI command scripting.

  2.    Copyright (C) 1986-2015 Free Software Foundation, Inc.

  3.    This file is part of GDB.

  4.    This program is free software; you can redistribute it and/or modify
  5.    it under the terms of the GNU General Public License as published by
  6.    the Free Software Foundation; either version 3 of the License, or
  7.    (at your option) any later version.

  8.    This program is distributed in the hope that it will be useful,
  9.    but WITHOUT ANY WARRANTY; without even the implied warranty of
  10.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11.    GNU General Public License for more details.

  12.    You should have received a copy of the GNU General Public License
  13.    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */

  14. #include "defs.h"
  15. #include "value.h"
  16. #include "language.h"                /* For value_true */
  17. #include <ctype.h>

  18. #include "ui-out.h"
  19. #include "top.h"
  20. #include "breakpoint.h"
  21. #include "cli/cli-cmds.h"
  22. #include "cli/cli-decode.h"
  23. #include "cli/cli-script.h"

  24. #include "extension.h"
  25. #include "interps.h"
  26. #include "compile/compile.h"

  27. /* Prototypes for local functions.  */

  28. static enum command_control_type
  29. recurse_read_control_structure (char * (*read_next_line_func) (void),
  30.                                 struct command_line *current_cmd,
  31.                                 void (*validator)(char *, void *),
  32.                                 void *closure);

  33. static char *insert_args (char *line);

  34. static struct cleanup * setup_user_args (char *p);

  35. static char *read_next_line (void);

  36. /* Level of control structure when reading.  */
  37. static int control_level;

  38. /* Level of control structure when executing.  */
  39. static int command_nest_depth = 1;

  40. /* This is to prevent certain commands being printed twice.  */
  41. static int suppress_next_print_command_trace = 0;

  42. /* Structure for arguments to user defined functions.  */
  43. #define MAXUSERARGS 10
  44. struct user_args
  45.   {
  46.     struct user_args *next;
  47.     /* It is necessary to store a malloced copy of the command line to
  48.        ensure that the arguments are not overwritten before they are
  49.        used.  */
  50.     char *command;
  51.     struct
  52.       {
  53.         char *arg;
  54.         int len;
  55.       }
  56.     a[MAXUSERARGS];
  57.     int count;
  58.   }
  59. *user_args;


  60. /* Return non-zero if TYPE is a multi-line command (i.e., is terminated
  61.    by "end").  */

  62. static int
  63. multi_line_command_p (enum command_control_type type)
  64. {
  65.   switch (type)
  66.     {
  67.     case if_control:
  68.     case while_control:
  69.     case while_stepping_control:
  70.     case commands_control:
  71.     case compile_control:
  72.     case python_control:
  73.     case guile_control:
  74.       return 1;
  75.     default:
  76.       return 0;
  77.     }
  78. }

  79. /* Allocate, initialize a new command line structure for one of the
  80.    control commands (if/while).  */

  81. static struct command_line *
  82. build_command_line (enum command_control_type type, char *args)
  83. {
  84.   struct command_line *cmd;

  85.   if (args == NULL && (type == if_control || type == while_control))
  86.     error (_("if/while commands require arguments."));
  87.   gdb_assert (args != NULL);

  88.   cmd = (struct command_line *) xmalloc (sizeof (struct command_line));
  89.   cmd->next = NULL;
  90.   cmd->control_type = type;

  91.   cmd->body_count = 1;
  92.   cmd->body_list
  93.     = (struct command_line **) xmalloc (sizeof (struct command_line *)
  94.                                         * cmd->body_count);
  95.   memset (cmd->body_list, 0, sizeof (struct command_line *) * cmd->body_count);
  96.   cmd->line = xstrdup (args);

  97.   return cmd;
  98. }

  99. /* Build and return a new command structure for the control commands
  100.    such as "if" and "while".  */

  101. struct command_line *
  102. get_command_line (enum command_control_type type, char *arg)
  103. {
  104.   struct command_line *cmd;
  105.   struct cleanup *old_chain = NULL;

  106.   /* Allocate and build a new command line structure.  */
  107.   cmd = build_command_line (type, arg);

  108.   old_chain = make_cleanup_free_command_lines (&cmd);

  109.   /* Read in the body of this command.  */
  110.   if (recurse_read_control_structure (read_next_line, cmd, 0, 0)
  111.       == invalid_control)
  112.     {
  113.       warning (_("Error reading in canned sequence of commands."));
  114.       do_cleanups (old_chain);
  115.       return NULL;
  116.     }

  117.   discard_cleanups (old_chain);
  118.   return cmd;
  119. }

  120. /* Recursively print a command (including full control structures).  */

  121. void
  122. print_command_lines (struct ui_out *uiout, struct command_line *cmd,
  123.                      unsigned int depth)
  124. {
  125.   struct command_line *list;

  126.   list = cmd;
  127.   while (list)
  128.     {
  129.       if (depth)
  130.         ui_out_spaces (uiout, 2 * depth);

  131.       /* A simple command, print it and continue.  */
  132.       if (list->control_type == simple_control)
  133.         {
  134.           ui_out_field_string (uiout, NULL, list->line);
  135.           ui_out_text (uiout, "\n");
  136.           list = list->next;
  137.           continue;
  138.         }

  139.       /* loop_continue to jump to the start of a while loop, print it
  140.          and continue. */
  141.       if (list->control_type == continue_control)
  142.         {
  143.           ui_out_field_string (uiout, NULL, "loop_continue");
  144.           ui_out_text (uiout, "\n");
  145.           list = list->next;
  146.           continue;
  147.         }

  148.       /* loop_break to break out of a while loop, print it and
  149.          continue.  */
  150.       if (list->control_type == break_control)
  151.         {
  152.           ui_out_field_string (uiout, NULL, "loop_break");
  153.           ui_out_text (uiout, "\n");
  154.           list = list->next;
  155.           continue;
  156.         }

  157.       /* A while command.  Recursively print its subcommands and
  158.          continue.  */
  159.       if (list->control_type == while_control
  160.           || list->control_type == while_stepping_control)
  161.         {
  162.           /* For while-stepping, the line includes the 'while-stepping'
  163.              token.  See comment in process_next_line for explanation.
  164.              Here, take care not print 'while-stepping' twice.  */
  165.           if (list->control_type == while_control)
  166.             ui_out_field_fmt (uiout, NULL, "while %s", list->line);
  167.           else
  168.             ui_out_field_string (uiout, NULL, list->line);
  169.           ui_out_text (uiout, "\n");
  170.           print_command_lines (uiout, *list->body_list, depth + 1);
  171.           if (depth)
  172.             ui_out_spaces (uiout, 2 * depth);
  173.           ui_out_field_string (uiout, NULL, "end");
  174.           ui_out_text (uiout, "\n");
  175.           list = list->next;
  176.           continue;
  177.         }

  178.       /* An if command.  Recursively print both arms before
  179.          continueing.  */
  180.       if (list->control_type == if_control)
  181.         {
  182.           ui_out_field_fmt (uiout, NULL, "if %s", list->line);
  183.           ui_out_text (uiout, "\n");
  184.           /* The true arm.  */
  185.           print_command_lines (uiout, list->body_list[0], depth + 1);

  186.           /* Show the false arm if it exists.  */
  187.           if (list->body_count == 2)
  188.             {
  189.               if (depth)
  190.                 ui_out_spaces (uiout, 2 * depth);
  191.               ui_out_field_string (uiout, NULL, "else");
  192.               ui_out_text (uiout, "\n");
  193.               print_command_lines (uiout, list->body_list[1], depth + 1);
  194.             }

  195.           if (depth)
  196.             ui_out_spaces (uiout, 2 * depth);
  197.           ui_out_field_string (uiout, NULL, "end");
  198.           ui_out_text (uiout, "\n");
  199.           list = list->next;
  200.           continue;
  201.         }

  202.       /* A commands command.  Print the breakpoint commands and
  203.          continue.  */
  204.       if (list->control_type == commands_control)
  205.         {
  206.           if (*(list->line))
  207.             ui_out_field_fmt (uiout, NULL, "commands %s", list->line);
  208.           else
  209.             ui_out_field_string (uiout, NULL, "commands");
  210.           ui_out_text (uiout, "\n");
  211.           print_command_lines (uiout, *list->body_list, depth + 1);
  212.           if (depth)
  213.             ui_out_spaces (uiout, 2 * depth);
  214.           ui_out_field_string (uiout, NULL, "end");
  215.           ui_out_text (uiout, "\n");
  216.           list = list->next;
  217.           continue;
  218.         }

  219.       if (list->control_type == python_control)
  220.         {
  221.           ui_out_field_string (uiout, NULL, "python");
  222.           ui_out_text (uiout, "\n");
  223.           /* Don't indent python code at all.  */
  224.           print_command_lines (uiout, *list->body_list, 0);
  225.           if (depth)
  226.             ui_out_spaces (uiout, 2 * depth);
  227.           ui_out_field_string (uiout, NULL, "end");
  228.           ui_out_text (uiout, "\n");
  229.           list = list->next;
  230.           continue;
  231.         }

  232.       if (list->control_type == compile_control)
  233.         {
  234.           ui_out_field_string (uiout, NULL, "compile expression");
  235.           ui_out_text (uiout, "\n");
  236.           print_command_lines (uiout, *list->body_list, 0);
  237.           if (depth)
  238.             ui_out_spaces (uiout, 2 * depth);
  239.           ui_out_field_string (uiout, NULL, "end");
  240.           ui_out_text (uiout, "\n");
  241.           list = list->next;
  242.           continue;
  243.         }

  244.       if (list->control_type == guile_control)
  245.         {
  246.           ui_out_field_string (uiout, NULL, "guile");
  247.           ui_out_text (uiout, "\n");
  248.           print_command_lines (uiout, *list->body_list, depth + 1);
  249.           if (depth)
  250.             ui_out_spaces (uiout, 2 * depth);
  251.           ui_out_field_string (uiout, NULL, "end");
  252.           ui_out_text (uiout, "\n");
  253.           list = list->next;
  254.           continue;
  255.         }

  256.       /* Ignore illegal command type and try next.  */
  257.       list = list->next;
  258.     }                                /* while (list) */
  259. }

  260. /* Handle pre-post hooks.  */

  261. static void
  262. clear_hook_in_cleanup (void *data)
  263. {
  264.   struct cmd_list_element *c = data;

  265.   c->hook_in = 0; /* Allow hook to work again once it is complete.  */
  266. }

  267. void
  268. execute_cmd_pre_hook (struct cmd_list_element *c)
  269. {
  270.   if ((c->hook_pre) && (!c->hook_in))
  271.     {
  272.       struct cleanup *cleanups = make_cleanup (clear_hook_in_cleanup, c);
  273.       c->hook_in = 1; /* Prevent recursive hooking.  */
  274.       execute_user_command (c->hook_pre, (char *) 0);
  275.       do_cleanups (cleanups);
  276.     }
  277. }

  278. void
  279. execute_cmd_post_hook (struct cmd_list_element *c)
  280. {
  281.   if ((c->hook_post) && (!c->hook_in))
  282.     {
  283.       struct cleanup *cleanups = make_cleanup (clear_hook_in_cleanup, c);

  284.       c->hook_in = 1; /* Prevent recursive hooking.  */
  285.       execute_user_command (c->hook_post, (char *) 0);
  286.       do_cleanups (cleanups);
  287.     }
  288. }

  289. /* Execute the command in CMD.  */
  290. static void
  291. do_restore_user_call_depth (void * call_depth)
  292. {
  293.   int *depth = call_depth;

  294.   (*depth)--;
  295.   if ((*depth) == 0)
  296.     in_user_command = 0;
  297. }


  298. void
  299. execute_user_command (struct cmd_list_element *c, char *args)
  300. {
  301.   struct command_line *cmdlines;
  302.   struct cleanup *old_chain;
  303.   enum command_control_type ret;
  304.   static int user_call_depth = 0;
  305.   extern unsigned int max_user_call_depth;

  306.   cmdlines = c->user_commands;
  307.   if (cmdlines == 0)
  308.     /* Null command */
  309.     return;

  310.   old_chain = setup_user_args (args);

  311.   if (++user_call_depth > max_user_call_depth)
  312.     error (_("Max user call depth exceeded -- command aborted."));

  313.   make_cleanup (do_restore_user_call_depth, &user_call_depth);

  314.   /* Set the instream to 0, indicating execution of a
  315.      user-defined function.  */
  316.   make_cleanup (do_restore_instream_cleanup, instream);
  317.   instream = (FILE *) 0;

  318.   /* Also set the global in_user_command, so that NULL instream is
  319.      not confused with Insight.  */
  320.   in_user_command = 1;

  321.   make_cleanup_restore_integer (&interpreter_async);
  322.   interpreter_async = 0;

  323.   command_nest_depth++;
  324.   while (cmdlines)
  325.     {
  326.       ret = execute_control_command (cmdlines);
  327.       if (ret != simple_control && ret != break_control)
  328.         {
  329.           warning (_("Error executing canned sequence of commands."));
  330.           break;
  331.         }
  332.       cmdlines = cmdlines->next;
  333.     }
  334.   command_nest_depth--;
  335.   do_cleanups (old_chain);
  336. }

  337. /* This function is called every time GDB prints a prompt.  It ensures
  338.    that errors and the like do not confuse the command tracing.  */

  339. void
  340. reset_command_nest_depth (void)
  341. {
  342.   command_nest_depth = 1;

  343.   /* Just in case.  */
  344.   suppress_next_print_command_trace = 0;
  345. }

  346. /* Print the command, prefixed with '+' to represent the call depth.
  347.    This is slightly complicated because this function may be called
  348.    from execute_command and execute_control_command.  Unfortunately
  349.    execute_command also prints the top level control commands.
  350.    In these cases execute_command will call execute_control_command
  351.    via while_command or if_commandInner levels of 'if' and 'while'
  352.    are dealt with directly.  Therefore we can use these functions
  353.    to determine whether the command has been printed already or not.  */
  354. void
  355. print_command_trace (const char *cmd)
  356. {
  357.   int i;

  358.   if (suppress_next_print_command_trace)
  359.     {
  360.       suppress_next_print_command_trace = 0;
  361.       return;
  362.     }

  363.   if (!source_verbose && !trace_commands)
  364.     return;

  365.   for (i=0; i < command_nest_depth; i++)
  366.     printf_filtered ("+");

  367.   printf_filtered ("%s\n", cmd);
  368. }

  369. enum command_control_type
  370. execute_control_command (struct command_line *cmd)
  371. {
  372.   struct expression *expr;
  373.   struct command_line *current;
  374.   struct cleanup *old_chain = make_cleanup (null_cleanup, 0);
  375.   struct value *val;
  376.   struct value *val_mark;
  377.   int loop;
  378.   enum command_control_type ret;
  379.   char *new_line;

  380.   /* Start by assuming failure, if a problem is detected, the code
  381.      below will simply "break" out of the switch.  */
  382.   ret = invalid_control;

  383.   switch (cmd->control_type)
  384.     {
  385.     case simple_control:
  386.       /* A simple command, execute it and return.  */
  387.       new_line = insert_args (cmd->line);
  388.       if (!new_line)
  389.         break;
  390.       make_cleanup (free_current_contents, &new_line);
  391.       execute_command (new_line, 0);
  392.       ret = cmd->control_type;
  393.       break;

  394.     case continue_control:
  395.       print_command_trace ("loop_continue");

  396.       /* Return for "continue", and "break" so we can either
  397.          continue the loop at the top, or break out.  */
  398.       ret = cmd->control_type;
  399.       break;

  400.     case break_control:
  401.       print_command_trace ("loop_break");

  402.       /* Return for "continue", and "break" so we can either
  403.          continue the loop at the top, or break out.  */
  404.       ret = cmd->control_type;
  405.       break;

  406.     case while_control:
  407.       {
  408.         int len = strlen (cmd->line) + 7;
  409.         char *buffer = alloca (len);

  410.         xsnprintf (buffer, len, "while %s", cmd->line);
  411.         print_command_trace (buffer);

  412.         /* Parse the loop control expression for the while statement.  */
  413.         new_line = insert_args (cmd->line);
  414.         if (!new_line)
  415.           break;
  416.         make_cleanup (free_current_contents, &new_line);
  417.         expr = parse_expression (new_line);
  418.         make_cleanup (free_current_contents, &expr);

  419.         ret = simple_control;
  420.         loop = 1;

  421.         /* Keep iterating so long as the expression is true.  */
  422.         while (loop == 1)
  423.           {
  424.             int cond_result;

  425.             QUIT;

  426.             /* Evaluate the expression.  */
  427.             val_mark = value_mark ();
  428.             val = evaluate_expression (expr);
  429.             cond_result = value_true (val);
  430.             value_free_to_mark (val_mark);

  431.             /* If the value is false, then break out of the loop.  */
  432.             if (!cond_result)
  433.               break;

  434.             /* Execute the body of the while statement.  */
  435.             current = *cmd->body_list;
  436.             while (current)
  437.               {
  438.                 command_nest_depth++;
  439.                 ret = execute_control_command (current);
  440.                 command_nest_depth--;

  441.                 /* If we got an error, or a "break" command, then stop
  442.                    looping.  */
  443.                 if (ret == invalid_control || ret == break_control)
  444.                   {
  445.                     loop = 0;
  446.                     break;
  447.                   }

  448.                 /* If we got a "continue" command, then restart the loop
  449.                    at this point.  */
  450.                 if (ret == continue_control)
  451.                   break;

  452.                 /* Get the next statement.  */
  453.                 current = current->next;
  454.               }
  455.           }

  456.         /* Reset RET so that we don't recurse the break all the way down.  */
  457.         if (ret == break_control)
  458.           ret = simple_control;

  459.         break;
  460.       }

  461.     case if_control:
  462.       {
  463.         int len = strlen (cmd->line) + 4;
  464.         char *buffer = alloca (len);

  465.         xsnprintf (buffer, len, "if %s", cmd->line);
  466.         print_command_trace (buffer);

  467.         new_line = insert_args (cmd->line);
  468.         if (!new_line)
  469.           break;
  470.         make_cleanup (free_current_contents, &new_line);
  471.         /* Parse the conditional for the if statement.  */
  472.         expr = parse_expression (new_line);
  473.         make_cleanup (free_current_contents, &expr);

  474.         current = NULL;
  475.         ret = simple_control;

  476.         /* Evaluate the conditional.  */
  477.         val_mark = value_mark ();
  478.         val = evaluate_expression (expr);

  479.         /* Choose which arm to take commands from based on the value
  480.            of the conditional expression.  */
  481.         if (value_true (val))
  482.           current = *cmd->body_list;
  483.         else if (cmd->body_count == 2)
  484.           current = *(cmd->body_list + 1);
  485.         value_free_to_mark (val_mark);

  486.         /* Execute commands in the given arm.  */
  487.         while (current)
  488.           {
  489.             command_nest_depth++;
  490.             ret = execute_control_command (current);
  491.             command_nest_depth--;

  492.             /* If we got an error, get out.  */
  493.             if (ret != simple_control)
  494.               break;

  495.             /* Get the next statement in the body.  */
  496.             current = current->next;
  497.           }

  498.         break;
  499.       }

  500.     case commands_control:
  501.       {
  502.         /* Breakpoint commands list, record the commands in the
  503.            breakpoint's command list and return.  */
  504.         new_line = insert_args (cmd->line);
  505.         if (!new_line)
  506.           break;
  507.         make_cleanup (free_current_contents, &new_line);
  508.         ret = commands_from_control_command (new_line, cmd);
  509.         break;
  510.       }

  511.     case compile_control:
  512.       eval_compile_command (cmd, NULL, cmd->control_u.compile.scope);
  513.       ret = simple_control;
  514.       break;

  515.     case python_control:
  516.     case guile_control:
  517.       {
  518.         eval_ext_lang_from_control_command (cmd);
  519.         ret = simple_control;
  520.         break;
  521.       }

  522.     default:
  523.       warning (_("Invalid control type in canned commands structure."));
  524.       break;
  525.     }

  526.   do_cleanups (old_chain);

  527.   return ret;
  528. }

  529. /* Like execute_control_command, but first set
  530.    suppress_next_print_command_trace.  */

  531. enum command_control_type
  532. execute_control_command_untraced (struct command_line *cmd)
  533. {
  534.   suppress_next_print_command_trace = 1;
  535.   return execute_control_command (cmd);
  536. }


  537. /* "while" command support.  Executes a body of statements while the
  538.    loop condition is nonzero.  */

  539. static void
  540. while_command (char *arg, int from_tty)
  541. {
  542.   struct command_line *command = NULL;
  543.   struct cleanup *old_chain;

  544.   control_level = 1;
  545.   command = get_command_line (while_control, arg);

  546.   if (command == NULL)
  547.     return;

  548.   old_chain = make_cleanup_restore_integer (&interpreter_async);
  549.   interpreter_async = 0;

  550.   execute_control_command_untraced (command);
  551.   free_command_lines (&command);

  552.   do_cleanups (old_chain);
  553. }

  554. /* "if" command support.  Execute either the true or false arm depending
  555.    on the value of the if conditional.  */

  556. static void
  557. if_command (char *arg, int from_tty)
  558. {
  559.   struct command_line *command = NULL;
  560.   struct cleanup *old_chain;

  561.   control_level = 1;
  562.   command = get_command_line (if_control, arg);

  563.   if (command == NULL)
  564.     return;

  565.   old_chain = make_cleanup_restore_integer (&interpreter_async);
  566.   interpreter_async = 0;

  567.   execute_control_command_untraced (command);
  568.   free_command_lines (&command);

  569.   do_cleanups (old_chain);
  570. }

  571. /* Cleanup */
  572. static void
  573. arg_cleanup (void *ignore)
  574. {
  575.   struct user_args *oargs = user_args;

  576.   if (!user_args)
  577.     internal_error (__FILE__, __LINE__,
  578.                     _("arg_cleanup called with no user args.\n"));

  579.   user_args = user_args->next;
  580.   xfree (oargs->command);
  581.   xfree (oargs);
  582. }

  583. /* Bind the incomming arguments for a user defined command to
  584.    $arg0, $arg1 ... $argMAXUSERARGS.  */

  585. static struct cleanup *
  586. setup_user_args (char *p)
  587. {
  588.   struct user_args *args;
  589.   struct cleanup *old_chain;
  590.   unsigned int arg_count = 0;

  591.   args = (struct user_args *) xmalloc (sizeof (struct user_args));
  592.   memset (args, 0, sizeof (struct user_args));

  593.   args->next = user_args;
  594.   user_args = args;

  595.   old_chain = make_cleanup (arg_cleanup, 0/*ignored*/);

  596.   if (p == NULL)
  597.     return old_chain;

  598.   user_args->command = p = xstrdup (p);

  599.   while (*p)
  600.     {
  601.       char *start_arg;
  602.       int squote = 0;
  603.       int dquote = 0;
  604.       int bsquote = 0;

  605.       if (arg_count >= MAXUSERARGS)
  606.         error (_("user defined function may only have %d arguments."),
  607.                MAXUSERARGS);

  608.       /* Strip whitespace.  */
  609.       while (*p == ' ' || *p == '\t')
  610.         p++;

  611.       /* P now points to an argument.  */
  612.       start_arg = p;
  613.       user_args->a[arg_count].arg = p;

  614.       /* Get to the end of this argument.  */
  615.       while (*p)
  616.         {
  617.           if (((*p == ' ' || *p == '\t')) && !squote && !dquote && !bsquote)
  618.             break;
  619.           else
  620.             {
  621.               if (bsquote)
  622.                 bsquote = 0;
  623.               else if (*p == '\\')
  624.                 bsquote = 1;
  625.               else if (squote)
  626.                 {
  627.                   if (*p == '\'')
  628.                     squote = 0;
  629.                 }
  630.               else if (dquote)
  631.                 {
  632.                   if (*p == '"')
  633.                     dquote = 0;
  634.                 }
  635.               else
  636.                 {
  637.                   if (*p == '\'')
  638.                     squote = 1;
  639.                   else if (*p == '"')
  640.                     dquote = 1;
  641.                 }
  642.               p++;
  643.             }
  644.         }

  645.       user_args->a[arg_count].len = p - start_arg;
  646.       arg_count++;
  647.       user_args->count++;
  648.     }
  649.   return old_chain;
  650. }

  651. /* Given character string P, return a point to the first argument
  652.    ($arg), or NULL if P contains no arguments.  */

  653. static char *
  654. locate_arg (char *p)
  655. {
  656.   while ((p = strchr (p, '$')))
  657.     {
  658.       if (strncmp (p, "$arg", 4) == 0
  659.           && (isdigit (p[4]) || p[4] == 'c'))
  660.         return p;
  661.       p++;
  662.     }
  663.   return NULL;
  664. }

  665. /* Insert the user defined arguments stored in user_arg into the $arg
  666.    arguments found in line, with the updated copy being placed into
  667.    nline.  */

  668. static char *
  669. insert_args (char *line)
  670. {
  671.   char *p, *save_line, *new_line;
  672.   unsigned len, i;

  673.   /* If we are not in a user-defined function, treat $argc, $arg0, et
  674.      cetera as normal convenience variables.  */
  675.   if (user_args == NULL)
  676.     return xstrdup (line);

  677.   /* First we need to know how much memory to allocate for the new
  678.      line.  */
  679.   save_line = line;
  680.   len = 0;
  681.   while ((p = locate_arg (line)))
  682.     {
  683.       len += p - line;
  684.       i = p[4] - '0';

  685.       if (p[4] == 'c')
  686.         {
  687.           /* $argc.  Number will be <=10.  */
  688.           len += user_args->count == 10 ? 2 : 1;
  689.         }
  690.       else if (i >= user_args->count)
  691.         {
  692.           error (_("Missing argument %d in user function."), i);
  693.           return NULL;
  694.         }
  695.       else
  696.         {
  697.           len += user_args->a[i].len;
  698.         }
  699.       line = p + 5;
  700.     }

  701.   /* Don't forget the tail.  */
  702.   len += strlen (line);

  703.   /* Allocate space for the new line and fill it in.  */
  704.   new_line = (char *) xmalloc (len + 1);
  705.   if (new_line == NULL)
  706.     return NULL;

  707.   /* Restore pointer to beginning of old line.  */
  708.   line = save_line;

  709.   /* Save pointer to beginning of new line.  */
  710.   save_line = new_line;

  711.   while ((p = locate_arg (line)))
  712.     {
  713.       int i, len;

  714.       memcpy (new_line, line, p - line);
  715.       new_line += p - line;

  716.       if (p[4] == 'c')
  717.         {
  718.           gdb_assert (user_args->count >= 0 && user_args->count <= 10);
  719.           if (user_args->count == 10)
  720.             {
  721.               *(new_line++) = '1';
  722.               *(new_line++) = '0';
  723.             }
  724.           else
  725.             *(new_line++) = user_args->count + '0';
  726.         }
  727.       else
  728.         {
  729.           i = p[4] - '0';
  730.           len = user_args->a[i].len;
  731.           if (len)
  732.             {
  733.               memcpy (new_line, user_args->a[i].arg, len);
  734.               new_line += len;
  735.             }
  736.         }
  737.       line = p + 5;
  738.     }
  739.   /* Don't forget the tail.  */
  740.   strcpy (new_line, line);

  741.   /* Return a pointer to the beginning of the new line.  */
  742.   return save_line;
  743. }


  744. /* Expand the body_list of COMMAND so that it can hold NEW_LENGTH
  745.    code bodies.  This is typically used when we encounter an "else"
  746.    clause for an "if" command.  */

  747. static void
  748. realloc_body_list (struct command_line *command, int new_length)
  749. {
  750.   int n;
  751.   struct command_line **body_list;

  752.   n = command->body_count;

  753.   /* Nothing to do?  */
  754.   if (new_length <= n)
  755.     return;

  756.   body_list = (struct command_line **)
  757.     xmalloc (sizeof (struct command_line *) * new_length);

  758.   memcpy (body_list, command->body_list, sizeof (struct command_line *) * n);
  759.   memset (body_list + n, 0, sizeof (struct command_line *) * (new_length - n));

  760.   xfree (command->body_list);
  761.   command->body_list = body_list;
  762.   command->body_count = new_length;
  763. }

  764. /* Read next line from stdout.  Passed to read_command_line_1 and
  765.    recurse_read_control_structure whenever we need to read commands
  766.    from stdout.  */

  767. static char *
  768. read_next_line (void)
  769. {
  770.   char *prompt_ptr, control_prompt[256];
  771.   int i = 0;

  772.   if (control_level >= 254)
  773.     error (_("Control nesting too deep!"));

  774.   /* Set a prompt based on the nesting of the control commands.  */
  775.   if (instream == stdin || (instream == 0 && deprecated_readline_hook != NULL))
  776.     {
  777.       for (i = 0; i < control_level; i++)
  778.         control_prompt[i] = ' ';
  779.       control_prompt[i] = '>';
  780.       control_prompt[i + 1] = '\0';
  781.       prompt_ptr = (char *) &control_prompt[0];
  782.     }
  783.   else
  784.     prompt_ptr = NULL;

  785.   return command_line_input (prompt_ptr, instream == stdin, "commands");
  786. }

  787. /* Process one input line.  If the command is an "end", return such an
  788.    indication to the caller.  If PARSE_COMMANDS is true, strip leading
  789.    whitespace (trailing whitespace is always stripped) in the line,
  790.    attempt to recognize GDB control commands, and also return an
  791.    indication if the command is an "else" or a nop.

  792.    Otherwise, only "end" is recognized.  */

  793. static enum misc_command_type
  794. process_next_line (char *p, struct command_line **command, int parse_commands,
  795.                    void (*validator)(char *, void *), void *closure)
  796. {
  797.   char *p_end;
  798.   char *p_start;
  799.   int not_handled = 0;

  800.   /* Not sure what to do here.  */
  801.   if (p == NULL)
  802.     return end_command;

  803.   /* Strip trailing whitespace.  */
  804.   p_end = p + strlen (p);
  805.   while (p_end > p && (p_end[-1] == ' ' || p_end[-1] == '\t'))
  806.     p_end--;

  807.   p_start = p;
  808.   /* Strip leading whitespace.  */
  809.   while (p_start < p_end && (*p_start == ' ' || *p_start == '\t'))
  810.     p_start++;

  811.   /* 'end' is always recognized, regardless of parse_commands value.
  812.      We also permit whitespace before end and after.  */
  813.   if (p_end - p_start == 3 && !strncmp (p_start, "end", 3))
  814.     return end_command;

  815.   if (parse_commands)
  816.     {
  817.       /* If commands are parsed, we skip initial spaces.  Otherwise,
  818.          which is the case for Python commands and documentation
  819.          (see the 'document' command), spaces are preserved.  */
  820.       p = p_start;

  821.       /* Blanks and comments don't really do anything, but we need to
  822.          distinguish them from else, end and other commands which can
  823.          be executed.  */
  824.       if (p_end == p || p[0] == '#')
  825.         return nop_command;

  826.       /* Is the else clause of an if control structure?  */
  827.       if (p_end - p == 4 && !strncmp (p, "else", 4))
  828.         return else_command;

  829.       /* Check for while, if, break, continue, etc and build a new
  830.          command line structure for them.  */
  831.       if ((p_end - p >= 14 && !strncmp (p, "while-stepping", 14))
  832.           || (p_end - p >= 8 && !strncmp (p, "stepping", 8))
  833.           || (p_end - p >= 2 && !strncmp (p, "ws", 2)))
  834.         {
  835.           /* Because validate_actionline and encode_action lookup
  836.              command's line as command, we need the line to
  837.              include 'while-stepping'.

  838.              For 'ws' alias, the command will have 'ws', not expanded
  839.              to 'while-stepping'.  This is intentional -- we don't
  840.              really want frontend to send a command list with 'ws',
  841.              and next break-info returning command line with
  842.              'while-stepping'.  This should work, but might cause the
  843.              breakpoint to be marked as changed while it's actually
  844.              not.  */
  845.           *command = build_command_line (while_stepping_control, p);
  846.         }
  847.       else if (p_end - p > 5 && !strncmp (p, "while", 5))
  848.         {
  849.           char *first_arg;

  850.           first_arg = p + 5;
  851.           while (first_arg < p_end && isspace (*first_arg))
  852.             first_arg++;
  853.           *command = build_command_line (while_control, first_arg);
  854.         }
  855.       else if (p_end - p > 2 && !strncmp (p, "if", 2))
  856.         {
  857.           char *first_arg;

  858.           first_arg = p + 2;
  859.           while (first_arg < p_end && isspace (*first_arg))
  860.             first_arg++;
  861.           *command = build_command_line (if_control, first_arg);
  862.         }
  863.       else if (p_end - p >= 8 && !strncmp (p, "commands", 8))
  864.         {
  865.           char *first_arg;

  866.           first_arg = p + 8;
  867.           while (first_arg < p_end && isspace (*first_arg))
  868.             first_arg++;
  869.           *command = build_command_line (commands_control, first_arg);
  870.         }
  871.       else if (p_end - p == 6 && !strncmp (p, "python", 6))
  872.         {
  873.           /* Note that we ignore the inline "python command" form
  874.              here.  */
  875.           *command = build_command_line (python_control, "");
  876.         }
  877.       else if (p_end - p == 6 && !strncmp (p, "compile", 7))
  878.         {
  879.           /* Note that we ignore the inline "compile command" form
  880.              here.  */
  881.           *command = build_command_line (compile_control, "");
  882.           (*command)->control_u.compile.scope = COMPILE_I_INVALID_SCOPE;
  883.         }

  884.       else if (p_end - p == 5 && !strncmp (p, "guile", 5))
  885.         {
  886.           /* Note that we ignore the inline "guile command" form here.  */
  887.           *command = build_command_line (guile_control, "");
  888.         }
  889.       else if (p_end - p == 10 && !strncmp (p, "loop_break", 10))
  890.         {
  891.           *command = (struct command_line *)
  892.             xmalloc (sizeof (struct command_line));
  893.           (*command)->next = NULL;
  894.           (*command)->line = NULL;
  895.           (*command)->control_type = break_control;
  896.           (*command)->body_count = 0;
  897.           (*command)->body_list = NULL;
  898.         }
  899.       else if (p_end - p == 13 && !strncmp (p, "loop_continue", 13))
  900.         {
  901.           *command = (struct command_line *)
  902.             xmalloc (sizeof (struct command_line));
  903.           (*command)->next = NULL;
  904.           (*command)->line = NULL;
  905.           (*command)->control_type = continue_control;
  906.           (*command)->body_count = 0;
  907.           (*command)->body_list = NULL;
  908.         }
  909.       else
  910.         not_handled = 1;
  911.     }

  912.   if (!parse_commands || not_handled)
  913.     {
  914.       /* A normal command.  */
  915.       *command = (struct command_line *)
  916.         xmalloc (sizeof (struct command_line));
  917.       (*command)->next = NULL;
  918.       (*command)->line = savestring (p, p_end - p);
  919.       (*command)->control_type = simple_control;
  920.       (*command)->body_count = 0;
  921.       (*command)->body_list = NULL;
  922.     }

  923.   if (validator)
  924.     {
  925.       volatile struct gdb_exception ex;

  926.       TRY_CATCH (ex, RETURN_MASK_ALL)
  927.         {
  928.           validator ((*command)->line, closure);
  929.         }
  930.       if (ex.reason < 0)
  931.         {
  932.           xfree (*command);
  933.           throw_exception (ex);
  934.         }
  935.     }

  936.   /* Nothing special.  */
  937.   return ok_command;
  938. }

  939. /* Recursively read in the control structures and create a
  940.    command_line structure from them.  Use read_next_line_func to
  941.    obtain lines of the command.  */

  942. static enum command_control_type
  943. recurse_read_control_structure (char * (*read_next_line_func) (void),
  944.                                 struct command_line *current_cmd,
  945.                                 void (*validator)(char *, void *),
  946.                                 void *closure)
  947. {
  948.   int current_body, i;
  949.   enum misc_command_type val;
  950.   enum command_control_type ret;
  951.   struct command_line **body_ptr, *child_tail, *next;

  952.   child_tail = NULL;
  953.   current_body = 1;

  954.   /* Sanity checks.  */
  955.   if (current_cmd->control_type == simple_control)
  956.     error (_("Recursed on a simple control type."));

  957.   if (current_body > current_cmd->body_count)
  958.     error (_("Allocated body is smaller than this command type needs."));

  959.   /* Read lines from the input stream and build control structures.  */
  960.   while (1)
  961.     {
  962.       dont_repeat ();

  963.       next = NULL;
  964.       val = process_next_line (read_next_line_func (), &next,
  965.                                current_cmd->control_type != python_control
  966.                                && current_cmd->control_type != guile_control
  967.                                && current_cmd->control_type != compile_control,
  968.                                validator, closure);

  969.       /* Just skip blanks and comments.  */
  970.       if (val == nop_command)
  971.         continue;

  972.       if (val == end_command)
  973.         {
  974.           if (multi_line_command_p (current_cmd->control_type))
  975.             {
  976.               /* Success reading an entire canned sequence of commands.  */
  977.               ret = simple_control;
  978.               break;
  979.             }
  980.           else
  981.             {
  982.               ret = invalid_control;
  983.               break;
  984.             }
  985.         }

  986.       /* Not the end of a control structure.  */
  987.       if (val == else_command)
  988.         {
  989.           if (current_cmd->control_type == if_control
  990.               && current_body == 1)
  991.             {
  992.               realloc_body_list (current_cmd, 2);
  993.               current_body = 2;
  994.               child_tail = NULL;
  995.               continue;
  996.             }
  997.           else
  998.             {
  999.               ret = invalid_control;
  1000.               break;
  1001.             }
  1002.         }

  1003.       if (child_tail)
  1004.         {
  1005.           child_tail->next = next;
  1006.         }
  1007.       else
  1008.         {
  1009.           body_ptr = current_cmd->body_list;
  1010.           for (i = 1; i < current_body; i++)
  1011.             body_ptr++;

  1012.           *body_ptr = next;

  1013.         }

  1014.       child_tail = next;

  1015.       /* If the latest line is another control structure, then recurse
  1016.          on it.  */
  1017.       if (multi_line_command_p (next->control_type))
  1018.         {
  1019.           control_level++;
  1020.           ret = recurse_read_control_structure (read_next_line_func, next,
  1021.                                                 validator, closure);
  1022.           control_level--;

  1023.           if (ret != simple_control)
  1024.             break;
  1025.         }
  1026.     }

  1027.   dont_repeat ();

  1028.   return ret;
  1029. }

  1030. static void
  1031. restore_interp (void *arg)
  1032. {
  1033.   interp_set_temp (interp_name ((struct interp *)arg));
  1034. }

  1035. /* Read lines from the input stream and accumulate them in a chain of
  1036.    struct command_line's, which is then returned.  For input from a
  1037.    terminal, the special command "end" is used to mark the end of the
  1038.    input, and is not included in the returned chain of commands.

  1039.    If PARSE_COMMANDS is true, strip leading whitespace (trailing whitespace
  1040.    is always stripped) in the line and attempt to recognize GDB control
  1041.    commands.  Otherwise, only "end" is recognized.  */

  1042. #define END_MESSAGE "End with a line saying just \"end\"."

  1043. struct command_line *
  1044. read_command_lines (char *prompt_arg, int from_tty, int parse_commands,
  1045.                     void (*validator)(char *, void *), void *closure)
  1046. {
  1047.   struct command_line *head;

  1048.   if (from_tty && input_from_terminal_p ())
  1049.     {
  1050.       if (deprecated_readline_begin_hook)
  1051.         {
  1052.           /* Note - intentional to merge messages with no newline.  */
  1053.           (*deprecated_readline_begin_hook) ("%s  %s\n", prompt_arg,
  1054.                                              END_MESSAGE);
  1055.         }
  1056.       else
  1057.         {
  1058.           printf_unfiltered ("%s\n%s\n", prompt_arg, END_MESSAGE);
  1059.           gdb_flush (gdb_stdout);
  1060.         }
  1061.     }


  1062.   /* Reading commands assumes the CLI behavior, so temporarily
  1063.      override the current interpreter with CLI.  */
  1064.   if (current_interp_named_p (INTERP_CONSOLE))
  1065.     head = read_command_lines_1 (read_next_line, parse_commands,
  1066.                                  validator, closure);
  1067.   else
  1068.     {
  1069.       struct interp *old_interp = interp_set_temp (INTERP_CONSOLE);
  1070.       struct cleanup *old_chain = make_cleanup (restore_interp, old_interp);

  1071.       head = read_command_lines_1 (read_next_line, parse_commands,
  1072.                                    validator, closure);
  1073.       do_cleanups (old_chain);
  1074.     }

  1075.   if (deprecated_readline_end_hook && from_tty && input_from_terminal_p ())
  1076.     {
  1077.       (*deprecated_readline_end_hook) ();
  1078.     }
  1079.   return (head);
  1080. }

  1081. /* Act the same way as read_command_lines, except that each new line is
  1082.    obtained using READ_NEXT_LINE_FUNC.  */

  1083. struct command_line *
  1084. read_command_lines_1 (char * (*read_next_line_func) (void), int parse_commands,
  1085.                       void (*validator)(char *, void *), void *closure)
  1086. {
  1087.   struct command_line *head, *tail, *next;
  1088.   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
  1089.   enum command_control_type ret;
  1090.   enum misc_command_type val;

  1091.   control_level = 0;
  1092.   head = tail = NULL;

  1093.   while (1)
  1094.     {
  1095.       dont_repeat ();
  1096.       val = process_next_line (read_next_line_func (), &next, parse_commands,
  1097.                                validator, closure);

  1098.       /* Ignore blank lines or comments.  */
  1099.       if (val == nop_command)
  1100.         continue;

  1101.       if (val == end_command)
  1102.         {
  1103.           ret = simple_control;
  1104.           break;
  1105.         }

  1106.       if (val != ok_command)
  1107.         {
  1108.           ret = invalid_control;
  1109.           break;
  1110.         }

  1111.       if (multi_line_command_p (next->control_type))
  1112.         {
  1113.           control_level++;
  1114.           ret = recurse_read_control_structure (read_next_line_func, next,
  1115.                                                 validator, closure);
  1116.           control_level--;

  1117.           if (ret == invalid_control)
  1118.             break;
  1119.         }

  1120.       if (tail)
  1121.         {
  1122.           tail->next = next;
  1123.         }
  1124.       else
  1125.         {
  1126.           head = next;
  1127.           make_cleanup_free_command_lines (&head);
  1128.         }
  1129.       tail = next;
  1130.     }

  1131.   dont_repeat ();

  1132.   if (ret != invalid_control)
  1133.     discard_cleanups (old_chain);
  1134.   else
  1135.     do_cleanups (old_chain);

  1136.   return head;
  1137. }

  1138. /* Free a chain of struct command_line's.  */

  1139. void
  1140. free_command_lines (struct command_line **lptr)
  1141. {
  1142.   struct command_line *l = *lptr;
  1143.   struct command_line *next;
  1144.   struct command_line **blist;
  1145.   int i;

  1146.   while (l)
  1147.     {
  1148.       if (l->body_count > 0)
  1149.         {
  1150.           blist = l->body_list;
  1151.           for (i = 0; i < l->body_count; i++, blist++)
  1152.             free_command_lines (blist);
  1153.         }
  1154.       next = l->next;
  1155.       xfree (l->line);
  1156.       xfree (l);
  1157.       l = next;
  1158.     }
  1159.   *lptr = NULL;
  1160. }

  1161. static void
  1162. do_free_command_lines_cleanup (void *arg)
  1163. {
  1164.   free_command_lines (arg);
  1165. }

  1166. struct cleanup *
  1167. make_cleanup_free_command_lines (struct command_line **arg)
  1168. {
  1169.   return make_cleanup (do_free_command_lines_cleanup, arg);
  1170. }

  1171. struct command_line *
  1172. copy_command_lines (struct command_line *cmds)
  1173. {
  1174.   struct command_line *result = NULL;

  1175.   if (cmds)
  1176.     {
  1177.       result = (struct command_line *) xmalloc (sizeof (struct command_line));

  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.           result->body_list = (struct command_line **)
  1186.             xmalloc (sizeof (struct command_line *) * cmds->body_count);

  1187.           for (i = 0; i < cmds->body_count; i++)
  1188.             result->body_list[i] = copy_command_lines (cmds->body_list[i]);
  1189.         }
  1190.       else
  1191.         result->body_list = NULL;
  1192.     }

  1193.   return result;
  1194. }

  1195. /* Validate that *COMNAME is a valid name for a command.  Return the
  1196.    containing command list, in case it starts with a prefix command.
  1197.    The prefix must already exist.  *COMNAME is advanced to point after
  1198.    any prefix, and a NUL character overwrites the space after the
  1199.    prefix.  */

  1200. static struct cmd_list_element **
  1201. validate_comname (char **comname)
  1202. {
  1203.   struct cmd_list_element **list = &cmdlist;
  1204.   char *p, *last_word;

  1205.   if (*comname == 0)
  1206.     error_no_arg (_("name of command to define"));

  1207.   /* Find the last word of the argument.  */
  1208.   p = *comname + strlen (*comname);
  1209.   while (p > *comname && isspace (p[-1]))
  1210.     p--;
  1211.   while (p > *comname && !isspace (p[-1]))
  1212.     p--;
  1213.   last_word = p;

  1214.   /* Find the corresponding command list.  */
  1215.   if (last_word != *comname)
  1216.     {
  1217.       struct cmd_list_element *c;
  1218.       char saved_char;
  1219.       const char *tem = *comname;

  1220.       /* Separate the prefix and the command.  */
  1221.       saved_char = last_word[-1];
  1222.       last_word[-1] = '\0';

  1223.       c = lookup_cmd (&tem, cmdlist, "", 0, 1);
  1224.       if (c->prefixlist == NULL)
  1225.         error (_("\"%s\" is not a prefix command."), *comname);

  1226.       list = c->prefixlist;
  1227.       last_word[-1] = saved_char;
  1228.       *comname = last_word;
  1229.     }

  1230.   p = *comname;
  1231.   while (*p)
  1232.     {
  1233.       if (!isalnum (*p) && *p != '-' && *p != '_')
  1234.         error (_("Junk in argument list: \"%s\""), p);
  1235.       p++;
  1236.     }

  1237.   return list;
  1238. }

  1239. /* This is just a placeholder in the command data structures.  */
  1240. static void
  1241. user_defined_command (char *ignore, int from_tty)
  1242. {
  1243. }

  1244. static void
  1245. define_command (char *comname, int from_tty)
  1246. {
  1247. #define MAX_TMPBUF 128
  1248.   enum cmd_hook_type
  1249.     {
  1250.       CMD_NO_HOOK = 0,
  1251.       CMD_PRE_HOOK,
  1252.       CMD_POST_HOOK
  1253.     };
  1254.   struct command_line *cmds;
  1255.   struct cmd_list_element *c, *newc, *hookc = 0, **list;
  1256.   char *tem, *comfull;
  1257.   const char *tem_c;
  1258.   char tmpbuf[MAX_TMPBUF];
  1259.   int  hook_type      = CMD_NO_HOOK;
  1260.   int  hook_name_size = 0;

  1261. #define        HOOK_STRING        "hook-"
  1262. #define        HOOK_LEN 5
  1263. #define HOOK_POST_STRING "hookpost-"
  1264. #define HOOK_POST_LEN    9

  1265.   comfull = comname;
  1266.   list = validate_comname (&comname);

  1267.   /* Look it up, and verify that we got an exact match.  */
  1268.   tem_c = comname;
  1269.   c = lookup_cmd (&tem_c, *list, "", -1, 1);
  1270.   if (c && strcmp (comname, c->name) != 0)
  1271.     c = 0;

  1272.   if (c)
  1273.     {
  1274.       int q;

  1275.       if (c->class == class_user || c->class == class_alias)
  1276.         q = query (_("Redefine command \"%s\"? "), c->name);
  1277.       else
  1278.         q = query (_("Really redefine built-in command \"%s\"? "), c->name);
  1279.       if (!q)
  1280.         error (_("Command \"%s\" not redefined."), c->name);
  1281.     }

  1282.   /* If this new command is a hook, then mark the command which it
  1283.      is hooking.  Note that we allow hooking `help' commands, so that
  1284.      we can hook the `stop' pseudo-command.  */

  1285.   if (!strncmp (comname, HOOK_STRING, HOOK_LEN))
  1286.     {
  1287.        hook_type      = CMD_PRE_HOOK;
  1288.        hook_name_size = HOOK_LEN;
  1289.     }
  1290.   else if (!strncmp (comname, HOOK_POST_STRING, HOOK_POST_LEN))
  1291.     {
  1292.       hook_type      = CMD_POST_HOOK;
  1293.       hook_name_size = HOOK_POST_LEN;
  1294.     }

  1295.   if (hook_type != CMD_NO_HOOK)
  1296.     {
  1297.       /* Look up cmd it hooks, and verify that we got an exact match.  */
  1298.       tem_c = comname + hook_name_size;
  1299.       hookc = lookup_cmd (&tem_c, *list, "", -1, 0);
  1300.       if (hookc && strcmp (comname + hook_name_size, hookc->name) != 0)
  1301.         hookc = 0;
  1302.       if (!hookc)
  1303.         {
  1304.           warning (_("Your new `%s' command does not "
  1305.                      "hook any existing command."),
  1306.                    comfull);
  1307.           if (!query (_("Proceed? ")))
  1308.             error (_("Not confirmed."));
  1309.         }
  1310.     }

  1311.   comname = xstrdup (comname);

  1312.   /* If the rest of the commands will be case insensitive, this one
  1313.      should behave in the same manner.  */
  1314.   for (tem = comname; *tem; tem++)
  1315.     if (isupper (*tem))
  1316.       *tem = tolower (*tem);

  1317.   xsnprintf (tmpbuf, sizeof (tmpbuf),
  1318.              "Type commands for definition of \"%s\".", comfull);
  1319.   cmds = read_command_lines (tmpbuf, from_tty, 1, 0, 0);

  1320.   if (c && c->class == class_user)
  1321.     free_command_lines (&c->user_commands);

  1322.   newc = add_cmd (comname, class_user, user_defined_command,
  1323.                   (c && c->class == class_user)
  1324.                   ? c->doc : xstrdup ("User-defined."), list);
  1325.   newc->user_commands = cmds;

  1326.   /* If this new command is a hook, then mark both commands as being
  1327.      tied.  */
  1328.   if (hookc)
  1329.     {
  1330.       switch (hook_type)
  1331.         {
  1332.         case CMD_PRE_HOOK:
  1333.           hookc->hook_pre  = newc;  /* Target gets hooked.  */
  1334.           newc->hookee_pre = hookc; /* We are marked as hooking target cmd.  */
  1335.           break;
  1336.         case CMD_POST_HOOK:
  1337.           hookc->hook_post  = newc;  /* Target gets hooked.  */
  1338.           newc->hookee_post = hookc; /* We are marked as hooking
  1339.                                         target cmd.  */
  1340.           break;
  1341.         default:
  1342.           /* Should never come here as hookc would be 0.  */
  1343.           internal_error (__FILE__, __LINE__, _("bad switch"));
  1344.         }
  1345.     }
  1346. }

  1347. static void
  1348. document_command (char *comname, int from_tty)
  1349. {
  1350.   struct command_line *doclines;
  1351.   struct cmd_list_element *c, **list;
  1352.   const char *tem;
  1353.   char *comfull;
  1354.   char tmpbuf[128];

  1355.   comfull = comname;
  1356.   list = validate_comname (&comname);

  1357.   tem = comname;
  1358.   c = lookup_cmd (&tem, *list, "", 0, 1);

  1359.   if (c->class != class_user)
  1360.     error (_("Command \"%s\" is built-in."), comfull);

  1361.   xsnprintf (tmpbuf, sizeof (tmpbuf), "Type documentation for \"%s\".",
  1362.              comfull);
  1363.   doclines = read_command_lines (tmpbuf, from_tty, 0, 0, 0);

  1364.   if (c->doc)
  1365.     xfree ((char *) c->doc);

  1366.   {
  1367.     struct command_line *cl1;
  1368.     int len = 0;
  1369.     char *doc;

  1370.     for (cl1 = doclines; cl1; cl1 = cl1->next)
  1371.       len += strlen (cl1->line) + 1;

  1372.     doc = (char *) xmalloc (len + 1);
  1373.     *doc = 0;

  1374.     for (cl1 = doclines; cl1; cl1 = cl1->next)
  1375.       {
  1376.         strcat (doc, cl1->line);
  1377.         if (cl1->next)
  1378.           strcat (doc, "\n");
  1379.       }

  1380.     c->doc = doc;
  1381.   }

  1382.   free_command_lines (&doclines);
  1383. }

  1384. struct source_cleanup_lines_args
  1385. {
  1386.   int old_line;
  1387.   const char *old_file;
  1388. };

  1389. static void
  1390. source_cleanup_lines (void *args)
  1391. {
  1392.   struct source_cleanup_lines_args *p =
  1393.     (struct source_cleanup_lines_args *) args;

  1394.   source_line_number = p->old_line;
  1395.   source_file_name = p->old_file;
  1396. }

  1397. /* Used to implement source_command.  */

  1398. void
  1399. script_from_file (FILE *stream, const char *file)
  1400. {
  1401.   struct cleanup *old_cleanups;
  1402.   struct source_cleanup_lines_args old_lines;

  1403.   if (stream == NULL)
  1404.     internal_error (__FILE__, __LINE__, _("called with NULL file pointer!"));

  1405.   old_lines.old_line = source_line_number;
  1406.   old_lines.old_file = source_file_name;
  1407.   old_cleanups = make_cleanup (source_cleanup_lines, &old_lines);
  1408.   source_line_number = 0;
  1409.   source_file_name = file;

  1410.   make_cleanup_restore_integer (&interpreter_async);
  1411.   interpreter_async = 0;

  1412.   {
  1413.     volatile struct gdb_exception e;

  1414.     TRY_CATCH (e, RETURN_MASK_ERROR)
  1415.       {
  1416.         read_command_file (stream);
  1417.       }
  1418.     switch (e.reason)
  1419.       {
  1420.       case 0:
  1421.         break;
  1422.       case RETURN_ERROR:
  1423.         /* Re-throw the error, but with the file name information
  1424.            prepended.  */
  1425.         throw_error (e.error,
  1426.                      _("%s:%d: Error in sourced command file:\n%s"),
  1427.                      source_file_name, source_line_number, e.message);
  1428.       default:
  1429.         internal_error (__FILE__, __LINE__, _("bad reason"));
  1430.       }
  1431.   }

  1432.   do_cleanups (old_cleanups);
  1433. }

  1434. /* Print the definition of user command C to STREAM.  Or, if C is a
  1435.    prefix command, show the definitions of all user commands under C
  1436.    (recursively).  PREFIX and NAME combined are the name of the
  1437.    current command.  */
  1438. void
  1439. show_user_1 (struct cmd_list_element *c, const char *prefix, const char *name,
  1440.              struct ui_file *stream)
  1441. {
  1442.   struct command_line *cmdlines;

  1443.   if (c->prefixlist != NULL)
  1444.     {
  1445.       const char *prefixname = c->prefixname;

  1446.       for (c = *c->prefixlist; c != NULL; c = c->next)
  1447.         if (c->class == class_user || c->prefixlist != NULL)
  1448.           show_user_1 (c, prefixname, c->name, gdb_stdout);
  1449.       return;
  1450.     }

  1451.   cmdlines = c->user_commands;
  1452.   fprintf_filtered (stream, "User command \"%s%s\":\n", prefix, name);

  1453.   if (!cmdlines)
  1454.     return;
  1455.   print_command_lines (current_uiout, cmdlines, 1);
  1456.   fputs_filtered ("\n", stream);
  1457. }



  1458. initialize_file_ftype _initialize_cli_script;

  1459. void
  1460. _initialize_cli_script (void)
  1461. {
  1462.   add_com ("document", class_support, document_command, _("\
  1463. Document a user-defined command.\n\
  1464. Give command name as argument.  Give documentation on following lines.\n\
  1465. End with a line of just \"end\"."));
  1466.   add_com ("define", class_support, define_command, _("\
  1467. Define a new command name.  Command name is argument.\n\
  1468. Definition appears on following lines, one command per line.\n\
  1469. End with a line of just \"end\".\n\
  1470. Use the \"document\" command to give documentation for the new command.\n\
  1471. Commands defined in this way may have up to ten arguments."));

  1472.   add_com ("while", class_support, while_command, _("\
  1473. Execute nested commands WHILE the conditional expression is non zero.\n\
  1474. The conditional expression must follow the word `while' and must in turn be\n\
  1475. followed by a new line.  The nested commands must be entered one per line,\n\
  1476. and should be terminated by the word `end'."));

  1477.   add_com ("if", class_support, if_command, _("\
  1478. Execute nested commands once IF the conditional expression is non zero.\n\
  1479. The conditional expression must follow the word `if' and must in turn be\n\
  1480. followed by a new line.  The nested commands must be entered one per line,\n\
  1481. and should be terminated by the word 'else' or `end'.  If an else clause\n\
  1482. is used, the same rules apply to its nested commands as to the first ones."));
  1483. }