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