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