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