3 Copyright (C) 2000-2023 Free Software Foundation, Inc.
5 Contributed by Cygnus Solutions (a Red Hat company).
7 This file is part of GDB.
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 3 of the License, or
12 (at your option) any later version.
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/>. */
23 #include "arch-utils.h"
28 #include "gdbthread.h"
31 #include "mi-getopt.h"
32 #include "mi-console.h"
36 #include "gdbsupport/event-loop.h"
37 #include "event-top.h"
38 #include "gdbcore.h" /* For write_memory(). */
43 #include "mi-interp.h"
47 #include "gdbsupport/gdb_splay_tree.h"
48 #include "tracepoint.h"
51 #include "extension.h"
53 #include "observable.h"
54 #include "gdbsupport/gdb_optional.h"
55 #include "gdbsupport/byte-vector.h"
58 #include "gdbsupport/run-time-clock.h"
60 #include "progspace-and-thread.h"
61 #include "gdbsupport/rsp-low.h"
72 static int mi_debug_p;
74 /* This is used to pass the current command timestamp down to
75 continuation routines. */
76 static struct mi_timestamp *current_command_ts;
78 static int do_timings = 0;
81 /* Few commands would like to know if options like --thread-group were
82 explicitly specified. This variable keeps the current parsed
83 command including all option, and make it possible. */
84 static struct mi_parse *current_context;
86 int running_result_record_printed = 1;
88 /* Flag indicating that the target has proceeded since the last
89 command was issued. */
92 static void mi_cmd_execute (struct mi_parse *parse);
94 static void mi_execute_async_cli_command (const char *cli_command,
95 char **argv, int argc);
96 static bool register_changed_p (int regnum, readonly_detached_regcache *,
97 readonly_detached_regcache *);
98 static void output_register (frame_info_ptr, int regnum, int format,
99 int skip_unavailable);
101 /* Controls whether the frontend wants MI in async mode. */
102 static bool mi_async = false;
104 /* The set command writes to this variable. If the inferior is
105 executing, mi_async is *not* updated. */
106 static bool mi_async_1 = false;
109 set_mi_async_command (const char *args, int from_tty,
110 struct cmd_list_element *c)
112 if (have_live_inferiors ())
114 mi_async_1 = mi_async;
115 error (_("Cannot change this setting while the inferior is running."));
118 mi_async = mi_async_1;
122 show_mi_async_command (struct ui_file *file, int from_tty,
123 struct cmd_list_element *c,
127 _("Whether MI is in asynchronous mode is %s.\n"),
131 /* A wrapper for target_can_async_p that takes the MI setting into
137 return mi_async && target_can_async_p ();
140 /* Command implementations. FIXME: Is this libgdb? No. This is the MI
141 layer that calls libgdb. Any operation used in the below should be
144 static void timestamp (struct mi_timestamp *tv);
146 static void print_diff (struct ui_file *file, struct mi_timestamp *start,
147 struct mi_timestamp *end);
150 mi_cmd_gdb_exit (const char *command, char **argv, int argc)
152 struct mi_interp *mi = (struct mi_interp *) current_interpreter ();
154 /* We have to print everything right here because we never return. */
156 gdb_puts (current_token, mi->raw_stdout);
157 gdb_puts ("^exit\n", mi->raw_stdout);
158 mi_out_put (current_uiout, mi->raw_stdout);
159 gdb_flush (mi->raw_stdout);
160 /* FIXME: The function called is not yet a formal libgdb function. */
161 quit_force (NULL, FROM_TTY);
165 mi_cmd_exec_next (const char *command, char **argv, int argc)
167 /* FIXME: Should call a libgdb function, not a cli wrapper. */
168 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
169 mi_execute_async_cli_command ("reverse-next", argv + 1, argc - 1);
171 mi_execute_async_cli_command ("next", argv, argc);
175 mi_cmd_exec_next_instruction (const char *command, char **argv, int argc)
177 /* FIXME: Should call a libgdb function, not a cli wrapper. */
178 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
179 mi_execute_async_cli_command ("reverse-nexti", argv + 1, argc - 1);
181 mi_execute_async_cli_command ("nexti", argv, argc);
185 mi_cmd_exec_step (const char *command, char **argv, int argc)
187 /* FIXME: Should call a libgdb function, not a cli wrapper. */
188 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
189 mi_execute_async_cli_command ("reverse-step", argv + 1, argc - 1);
191 mi_execute_async_cli_command ("step", argv, argc);
195 mi_cmd_exec_step_instruction (const char *command, char **argv, int argc)
197 /* FIXME: Should call a libgdb function, not a cli wrapper. */
198 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
199 mi_execute_async_cli_command ("reverse-stepi", argv + 1, argc - 1);
201 mi_execute_async_cli_command ("stepi", argv, argc);
205 mi_cmd_exec_finish (const char *command, char **argv, int argc)
207 /* FIXME: Should call a libgdb function, not a cli wrapper. */
208 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
209 mi_execute_async_cli_command ("reverse-finish", argv + 1, argc - 1);
211 mi_execute_async_cli_command ("finish", argv, argc);
215 mi_cmd_exec_return (const char *command, char **argv, int argc)
217 /* This command doesn't really execute the target, it just pops the
218 specified number of frames. */
220 /* Call return_command with from_tty argument equal to 0 so as to
221 avoid being queried. */
222 return_command (*argv, 0);
224 /* Call return_command with from_tty argument equal to 0 so as to
225 avoid being queried. */
226 return_command (NULL, 0);
228 /* Because we have called return_command with from_tty = 0, we need
229 to print the frame here. */
230 print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS, 1);
234 mi_cmd_exec_jump (const char *args, char **argv, int argc)
236 /* FIXME: Should call a libgdb function, not a cli wrapper. */
237 mi_execute_async_cli_command ("jump", argv, argc);
241 proceed_thread (struct thread_info *thread, int pid)
243 if (thread->state != THREAD_STOPPED)
246 if (pid != 0 && thread->ptid.pid () != pid)
249 switch_to_thread (thread);
250 clear_proceed_status (0);
251 proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
255 proceed_thread_callback (struct thread_info *thread, void *arg)
257 int pid = *(int *)arg;
259 proceed_thread (thread, pid);
264 exec_continue (char **argv, int argc)
266 prepare_execution_command (current_inferior ()->top_target (), mi_async_p ());
271 /* In non-stop mode, 'resume' always resumes a single thread.
272 Therefore, to resume all threads of the current inferior, or
273 all threads in all inferiors, we need to iterate over
276 See comment on infcmd.c:proceed_thread_callback for rationale. */
277 if (current_context->all || current_context->thread_group != -1)
279 scoped_restore_current_thread restore_thread;
280 scoped_disable_commit_resumed disable_commit_resumed
281 ("MI continue all threads in non-stop");
284 if (!current_context->all)
287 = find_inferior_id (current_context->thread_group);
292 iterate_over_threads (proceed_thread_callback, &pid);
293 disable_commit_resumed.reset_and_commit ();
302 scoped_restore save_multi = make_scoped_restore (&sched_multi);
304 if (current_context->all)
311 /* In all-stop mode, -exec-continue traditionally resumed
312 either all threads, or one thread, depending on the
313 'scheduler-locking' variable. Let's continue to do the
321 exec_reverse_continue (char **argv, int argc)
323 enum exec_direction_kind dir = execution_direction;
325 if (dir == EXEC_REVERSE)
326 error (_("Already in reverse mode."));
328 if (!target_can_execute_reverse ())
329 error (_("Target %s does not support this command."), target_shortname ());
331 scoped_restore save_exec_dir = make_scoped_restore (&execution_direction,
333 exec_continue (argv, argc);
337 mi_cmd_exec_continue (const char *command, char **argv, int argc)
339 if (argc > 0 && strcmp (argv[0], "--reverse") == 0)
340 exec_reverse_continue (argv + 1, argc - 1);
342 exec_continue (argv, argc);
346 interrupt_thread_callback (struct thread_info *thread, void *arg)
348 int pid = *(int *)arg;
350 if (thread->state != THREAD_RUNNING)
353 if (thread->ptid.pid () != pid)
356 target_stop (thread->ptid);
360 /* Interrupt the execution of the target. Note how we must play
361 around with the token variables, in order to display the current
362 token in the result of the interrupt command, and the previous
363 execution token when the target finally stops. See comments in
367 mi_cmd_exec_interrupt (const char *command, char **argv, int argc)
369 /* In all-stop mode, everything stops, so we don't need to try
370 anything specific. */
373 interrupt_target_1 (0);
377 if (current_context->all)
379 /* This will interrupt all threads in all inferiors. */
380 interrupt_target_1 (1);
382 else if (current_context->thread_group != -1)
384 struct inferior *inf = find_inferior_id (current_context->thread_group);
386 scoped_disable_commit_resumed disable_commit_resumed
387 ("interrupting all threads of thread group");
389 iterate_over_threads (interrupt_thread_callback, &inf->pid);
393 /* Interrupt just the current thread -- either explicitly
394 specified via --thread or whatever was current before
395 MI command was sent. */
396 interrupt_target_1 (0);
400 /* Start the execution of the given inferior.
402 START_P indicates whether the program should be stopped when reaching the
403 main subprogram (similar to what the CLI "start" command does). */
406 run_one_inferior (inferior *inf, bool start_p)
408 const char *run_cmd = start_p ? "start" : "run";
409 struct target_ops *run_target = find_run_target ();
410 bool async_p = mi_async && target_can_async_p (run_target);
414 thread_info *tp = any_thread_of_inferior (inf);
416 error (_("Inferior has no threads."));
418 switch_to_thread (tp);
421 switch_to_inferior_no_thread (inf);
422 mi_execute_cli_command (run_cmd, async_p,
423 async_p ? "&" : NULL);
427 mi_cmd_exec_run (const char *command, char **argv, int argc)
431 /* Parse the command options. */
436 static const struct mi_opt opts[] =
438 {"-start", START_OPT, 0},
447 int opt = mi_getopt ("-exec-run", argc, argv, opts, &oind, &oarg);
451 switch ((enum opt) opt)
459 /* This command does not accept any argument. Make sure the user
460 did not provide any. */
462 error (_("Invalid argument: %s"), argv[oind]);
464 if (current_context->all)
466 scoped_restore_current_pspace_and_thread restore_pspace_thread;
468 for (inferior *inf : all_inferiors ())
469 run_one_inferior (inf, start_p);
473 const char *run_cmd = start_p ? "start" : "run";
474 struct target_ops *run_target = find_run_target ();
475 bool async_p = mi_async && target_can_async_p (run_target);
477 mi_execute_cli_command (run_cmd, async_p,
478 async_p ? "&" : NULL);
484 find_thread_of_process (struct thread_info *ti, void *p)
488 if (ti->ptid.pid () == pid && ti->state != THREAD_EXITED)
495 mi_cmd_target_detach (const char *command, char **argv, int argc)
497 if (argc != 0 && argc != 1)
498 error (_("Usage: -target-detach [pid | thread-group]"));
502 struct thread_info *tp;
506 /* First see if we are dealing with a thread-group id. */
509 struct inferior *inf;
510 int id = strtoul (argv[0] + 1, &end, 0);
513 error (_("Invalid syntax of thread-group id '%s'"), argv[0]);
515 inf = find_inferior_id (id);
517 error (_("Non-existent thread-group id '%d'"), id);
523 /* We must be dealing with a pid. */
524 pid = strtol (argv[0], &end, 10);
527 error (_("Invalid identifier '%s'"), argv[0]);
530 /* Pick any thread in the desired process. Current
531 target_detach detaches from the parent of inferior_ptid. */
532 tp = iterate_over_threads (find_thread_of_process, &pid);
534 error (_("Thread group is empty"));
536 switch_to_thread (tp);
539 detach_command (NULL, 0);
543 mi_cmd_target_flash_erase (const char *command, char **argv, int argc)
545 flash_erase_command (NULL, 0);
549 mi_cmd_thread_select (const char *command, char **argv, int argc)
552 error (_("-thread-select: USAGE: threadnum."));
554 int num = value_as_long (parse_and_eval (argv[0]));
555 thread_info *thr = find_thread_global_id (num);
557 error (_("Thread ID %d not known."), num);
559 thread_select (argv[0], thr);
561 print_selected_thread_frame (current_uiout,
562 USER_SELECTED_THREAD | USER_SELECTED_FRAME);
566 mi_cmd_thread_list_ids (const char *command, char **argv, int argc)
569 error (_("-thread-list-ids: No arguments required."));
572 int current_thread = -1;
574 update_thread_list ();
577 ui_out_emit_tuple tuple_emitter (current_uiout, "thread-ids");
579 for (thread_info *tp : all_non_exited_threads ())
581 if (tp->ptid == inferior_ptid)
582 current_thread = tp->global_num;
585 current_uiout->field_signed ("thread-id", tp->global_num);
589 if (current_thread != -1)
590 current_uiout->field_signed ("current-thread-id", current_thread);
591 current_uiout->field_signed ("number-of-threads", num);
595 mi_cmd_thread_info (const char *command, char **argv, int argc)
597 if (argc != 0 && argc != 1)
598 error (_("Invalid MI command"));
600 print_thread_info (current_uiout, argv[0], -1);
603 struct collect_cores_data
610 collect_cores (struct thread_info *ti, void *xdata)
612 struct collect_cores_data *data = (struct collect_cores_data *) xdata;
614 if (ti->ptid.pid () == data->pid)
616 int core = target_core_of_thread (ti->ptid);
619 data->cores.insert (core);
625 struct print_one_inferior_data
628 const std::set<int> *inferiors;
632 print_one_inferior (struct inferior *inferior, bool recurse,
633 const std::set<int> &ids)
635 struct ui_out *uiout = current_uiout;
637 if (ids.empty () || (ids.find (inferior->pid) != ids.end ()))
639 struct collect_cores_data data;
640 ui_out_emit_tuple tuple_emitter (uiout, NULL);
642 uiout->field_fmt ("id", "i%d", inferior->num);
643 uiout->field_string ("type", "process");
644 if (inferior->has_exit_code)
645 uiout->field_string ("exit-code",
646 int_string (inferior->exit_code, 8, 0, 0, 1));
647 if (inferior->pid != 0)
648 uiout->field_signed ("pid", inferior->pid);
650 if (inferior->pspace->exec_filename != nullptr)
652 uiout->field_string ("executable",
653 inferior->pspace->exec_filename.get ());
656 if (inferior->pid != 0)
658 data.pid = inferior->pid;
659 iterate_over_threads (collect_cores, &data);
662 if (!data.cores.empty ())
664 ui_out_emit_list list_emitter (uiout, "cores");
666 for (int b : data.cores)
667 uiout->field_signed (NULL, b);
671 print_thread_info (uiout, NULL, inferior->pid);
675 /* Output a field named 'cores' with a list as the value. The
676 elements of the list are obtained by splitting 'cores' on
680 output_cores (struct ui_out *uiout, const char *field_name, const char *xcores)
682 ui_out_emit_list list_emitter (uiout, field_name);
683 auto cores = make_unique_xstrdup (xcores);
684 char *p = cores.get ();
687 for (p = strtok_r (p, ",", &saveptr); p; p = strtok_r (NULL, ",", &saveptr))
688 uiout->field_string (NULL, p);
692 list_available_thread_groups (const std::set<int> &ids, int recurse)
694 struct ui_out *uiout = current_uiout;
696 /* This keeps a map from integer (pid) to vector of struct osdata_item.
697 The vector contains information about all threads for the given pid. */
698 std::map<int, std::vector<osdata_item>> tree;
700 /* get_osdata will throw if it cannot return data. */
701 std::unique_ptr<osdata> data = get_osdata ("processes");
705 std::unique_ptr<osdata> threads = get_osdata ("threads");
707 for (const osdata_item &item : threads->items)
709 const std::string *pid = get_osdata_column (item, "pid");
710 int pid_i = strtoul (pid->c_str (), NULL, 0);
712 tree[pid_i].push_back (item);
716 ui_out_emit_list list_emitter (uiout, "groups");
718 for (const osdata_item &item : data->items)
720 const std::string *pid = get_osdata_column (item, "pid");
721 const std::string *cmd = get_osdata_column (item, "command");
722 const std::string *user = get_osdata_column (item, "user");
723 const std::string *cores = get_osdata_column (item, "cores");
725 int pid_i = strtoul (pid->c_str (), NULL, 0);
727 /* At present, the target will return all available processes
728 and if information about specific ones was required, we filter
729 undesired processes here. */
730 if (!ids.empty () && ids.find (pid_i) == ids.end ())
733 ui_out_emit_tuple tuple_emitter (uiout, NULL);
735 uiout->field_string ("id", *pid);
736 uiout->field_string ("type", "process");
738 uiout->field_string ("description", *cmd);
740 uiout->field_string ("user", *user);
742 output_cores (uiout, "cores", cores->c_str ());
746 auto n = tree.find (pid_i);
747 if (n != tree.end ())
749 std::vector<osdata_item> &children = n->second;
751 ui_out_emit_list thread_list_emitter (uiout, "threads");
753 for (const osdata_item &child : children)
755 ui_out_emit_tuple inner_tuple_emitter (uiout, NULL);
756 const std::string *tid = get_osdata_column (child, "tid");
757 const std::string *tcore = get_osdata_column (child, "core");
759 uiout->field_string ("id", *tid);
761 uiout->field_string ("core", *tcore);
769 mi_cmd_list_thread_groups (const char *command, char **argv, int argc)
771 struct ui_out *uiout = current_uiout;
778 AVAILABLE_OPT, RECURSE_OPT
780 static const struct mi_opt opts[] =
782 {"-available", AVAILABLE_OPT, 0},
783 {"-recurse", RECURSE_OPT, 1},
792 int opt = mi_getopt ("-list-thread-groups", argc, argv, opts,
797 switch ((enum opt) opt)
803 if (strcmp (oarg, "0") == 0)
805 else if (strcmp (oarg, "1") == 0)
808 error (_("only '0' and '1' are valid values "
809 "for the '--recurse' option"));
814 for (; oind < argc; ++oind)
819 if (*(argv[oind]) != 'i')
820 error (_("invalid syntax of group id '%s'"), argv[oind]);
822 inf = strtoul (argv[oind] + 1, &end, 0);
825 error (_("invalid syntax of group id '%s'"), argv[oind]);
831 list_available_thread_groups (ids, recurse);
833 else if (ids.size () == 1)
835 /* Local thread groups, single id. */
836 int id = *(ids.begin ());
837 struct inferior *inf = find_inferior_id (id);
840 error (_("Non-existent thread group id '%d'"), id);
842 print_thread_info (uiout, NULL, inf->pid);
846 /* Local thread groups. Either no explicit ids -- and we
847 print everything, or several explicit ids. In both cases,
848 we print more than one group, and have to use 'groups'
849 as the top-level element. */
850 ui_out_emit_list list_emitter (uiout, "groups");
851 update_thread_list ();
852 for (inferior *inf : all_inferiors ())
853 print_one_inferior (inf, recurse, ids);
858 mi_cmd_data_list_register_names (const char *command, char **argv, int argc)
860 struct gdbarch *gdbarch;
861 struct ui_out *uiout = current_uiout;
865 /* Note that the test for a valid register must include checking the
866 gdbarch_register_name because gdbarch_num_regs may be allocated
867 for the union of the register sets within a family of related
868 processors. In this case, some entries of gdbarch_register_name
869 will change depending upon the particular processor being
872 gdbarch = get_current_arch ();
873 numregs = gdbarch_num_cooked_regs (gdbarch);
875 ui_out_emit_list list_emitter (uiout, "register-names");
877 if (argc == 0) /* No args, just do all the regs. */
883 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
884 uiout->field_string (NULL, "");
886 uiout->field_string (NULL, gdbarch_register_name (gdbarch, regnum));
890 /* Else, list of register #s, just do listed regs. */
891 for (i = 0; i < argc; i++)
893 regnum = atoi (argv[i]);
894 if (regnum < 0 || regnum >= numregs)
895 error (_("bad register number"));
897 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
898 uiout->field_string (NULL, "");
900 uiout->field_string (NULL, gdbarch_register_name (gdbarch, regnum));
905 mi_cmd_data_list_changed_registers (const char *command, char **argv, int argc)
907 static std::unique_ptr<readonly_detached_regcache> this_regs;
908 struct ui_out *uiout = current_uiout;
909 std::unique_ptr<readonly_detached_regcache> prev_regs;
910 struct gdbarch *gdbarch;
914 /* The last time we visited this function, the current frame's
915 register contents were saved in THIS_REGS. Move THIS_REGS over
916 to PREV_REGS, and refresh THIS_REGS with the now-current register
919 prev_regs = std::move (this_regs);
920 this_regs = frame_save_as_regcache (get_selected_frame (NULL));
922 /* Note that the test for a valid register must include checking the
923 gdbarch_register_name because gdbarch_num_regs may be allocated
924 for the union of the register sets within a family of related
925 processors. In this case, some entries of gdbarch_register_name
926 will change depending upon the particular processor being
929 gdbarch = this_regs->arch ();
930 numregs = gdbarch_num_cooked_regs (gdbarch);
932 ui_out_emit_list list_emitter (uiout, "changed-registers");
936 /* No args, just do all the regs. */
941 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
944 if (register_changed_p (regnum, prev_regs.get (),
946 uiout->field_signed (NULL, regnum);
950 /* Else, list of register #s, just do listed regs. */
951 for (i = 0; i < argc; i++)
953 regnum = atoi (argv[i]);
957 && *gdbarch_register_name (gdbarch, regnum) != '\000')
959 if (register_changed_p (regnum, prev_regs.get (),
961 uiout->field_signed (NULL, regnum);
964 error (_("bad register number"));
969 register_changed_p (int regnum, readonly_detached_regcache *prev_regs,
970 readonly_detached_regcache *this_regs)
972 struct gdbarch *gdbarch = this_regs->arch ();
973 struct value *prev_value, *this_value;
975 /* First time through or after gdbarch change consider all registers
977 if (!prev_regs || prev_regs->arch () != gdbarch)
980 /* Get register contents and compare. */
981 prev_value = prev_regs->cooked_read_value (regnum);
982 this_value = this_regs->cooked_read_value (regnum);
983 gdb_assert (prev_value != NULL);
984 gdb_assert (this_value != NULL);
986 auto ret = !value_contents_eq (prev_value, 0, this_value, 0,
987 register_size (gdbarch, regnum));
989 release_value (prev_value);
990 release_value (this_value);
994 /* Return a list of register number and value pairs. The valid
995 arguments expected are: a letter indicating the format in which to
996 display the registers contents. This can be one of: x
997 (hexadecimal), d (decimal), N (natural), t (binary), o (octal), r
998 (raw). After the format argument there can be a sequence of
999 numbers, indicating which registers to fetch the content of. If
1000 the format is the only argument, a list of all the registers with
1001 their values is returned. */
1004 mi_cmd_data_list_register_values (const char *command, char **argv, int argc)
1006 struct ui_out *uiout = current_uiout;
1007 frame_info_ptr frame;
1008 struct gdbarch *gdbarch;
1009 int regnum, numregs, format;
1011 int skip_unavailable = 0;
1017 static const struct mi_opt opts[] =
1019 {"-skip-unavailable", SKIP_UNAVAILABLE, 0},
1023 /* Note that the test for a valid register must include checking the
1024 gdbarch_register_name because gdbarch_num_regs may be allocated
1025 for the union of the register sets within a family of related
1026 processors. In this case, some entries of gdbarch_register_name
1027 will change depending upon the particular processor being
1033 int opt = mi_getopt ("-data-list-register-values", argc, argv,
1034 opts, &oind, &oarg);
1038 switch ((enum opt) opt)
1040 case SKIP_UNAVAILABLE:
1041 skip_unavailable = 1;
1046 if (argc - oind < 1)
1047 error (_("-data-list-register-values: Usage: "
1048 "-data-list-register-values [--skip-unavailable] <format>"
1049 " [<regnum1>...<regnumN>]"));
1051 format = (int) argv[oind][0];
1053 frame = get_selected_frame (NULL);
1054 gdbarch = get_frame_arch (frame);
1055 numregs = gdbarch_num_cooked_regs (gdbarch);
1057 ui_out_emit_list list_emitter (uiout, "register-values");
1059 if (argc - oind == 1)
1061 /* No args, beside the format: do all the regs. */
1066 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1069 output_register (frame, regnum, format, skip_unavailable);
1073 /* Else, list of register #s, just do listed regs. */
1074 for (i = 1 + oind; i < argc; i++)
1076 regnum = atoi (argv[i]);
1080 && *gdbarch_register_name (gdbarch, regnum) != '\000')
1081 output_register (frame, regnum, format, skip_unavailable);
1083 error (_("bad register number"));
1087 /* Output one register REGNUM's contents in the desired FORMAT. If
1088 SKIP_UNAVAILABLE is true, skip the register if it is
1092 output_register (frame_info_ptr frame, int regnum, int format,
1093 int skip_unavailable)
1095 struct ui_out *uiout = current_uiout;
1096 struct value *val = value_of_register (regnum, frame);
1097 struct value_print_options opts;
1099 if (skip_unavailable && !value_entirely_available (val))
1102 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1103 uiout->field_signed ("number", regnum);
1113 get_formatted_print_options (&opts, format);
1115 common_val_print (val, &stb, 0, &opts, current_language);
1116 uiout->field_stream ("value", stb);
1119 /* Write given values into registers. The registers and values are
1120 given as pairs. The corresponding MI command is
1121 -data-write-register-values <format>
1122 [<regnum1> <value1>...<regnumN> <valueN>] */
1124 mi_cmd_data_write_register_values (const char *command, char **argv, int argc)
1126 struct regcache *regcache;
1127 struct gdbarch *gdbarch;
1130 /* Note that the test for a valid register must include checking the
1131 gdbarch_register_name because gdbarch_num_regs may be allocated
1132 for the union of the register sets within a family of related
1133 processors. In this case, some entries of gdbarch_register_name
1134 will change depending upon the particular processor being
1137 regcache = get_current_regcache ();
1138 gdbarch = regcache->arch ();
1139 numregs = gdbarch_num_cooked_regs (gdbarch);
1142 error (_("-data-write-register-values: Usage: -data-write-register-"
1143 "values <format> [<regnum1> <value1>...<regnumN> <valueN>]"));
1145 if (!target_has_registers ())
1146 error (_("-data-write-register-values: No registers."));
1149 error (_("-data-write-register-values: No regs and values specified."));
1152 error (_("-data-write-register-values: "
1153 "Regs and vals are not in pairs."));
1155 for (i = 1; i < argc; i = i + 2)
1157 int regnum = atoi (argv[i]);
1159 if (regnum >= 0 && regnum < numregs
1160 && *gdbarch_register_name (gdbarch, regnum) != '\0')
1164 /* Get the value as a number. */
1165 value = parse_and_eval_address (argv[i + 1]);
1167 /* Write it down. */
1168 regcache_cooked_write_signed (regcache, regnum, value);
1171 error (_("bad register number"));
1175 /* Evaluate the value of the argument. The argument is an
1176 expression. If the expression contains spaces it needs to be
1177 included in double quotes. */
1180 mi_cmd_data_evaluate_expression (const char *command, char **argv, int argc)
1183 struct value_print_options opts;
1184 struct ui_out *uiout = current_uiout;
1187 error (_("-data-evaluate-expression: "
1188 "Usage: -data-evaluate-expression expression"));
1190 expression_up expr = parse_expression (argv[0]);
1192 val = evaluate_expression (expr.get ());
1196 /* Print the result of the expression evaluation. */
1197 get_user_print_options (&opts);
1199 common_val_print (val, &stb, 0, &opts, current_language);
1201 uiout->field_stream ("value", stb);
1204 /* This is the -data-read-memory command.
1206 ADDR: start address of data to be dumped.
1207 WORD-FORMAT: a char indicating format for the ``word''. See
1209 WORD-SIZE: size of each ``word''; 1,2,4, or 8 bytes.
1210 NR_ROW: Number of rows.
1211 NR_COL: The number of columns (words per row).
1212 ASCHAR: (OPTIONAL) Append an ascii character dump to each row. Use
1213 ASCHAR for unprintable characters.
1215 Reads SIZE*NR_ROW*NR_COL bytes starting at ADDR from memory and
1216 displays them. Returns:
1218 {addr="...",rowN={wordN="..." ,... [,ascii="..."]}, ...}
1221 The number of bytes read is SIZE*ROW*COL. */
1224 mi_cmd_data_read_memory (const char *command, char **argv, int argc)
1226 struct gdbarch *gdbarch = get_current_arch ();
1227 struct ui_out *uiout = current_uiout;
1229 long total_bytes, nr_cols, nr_rows;
1231 struct type *word_type;
1243 static const struct mi_opt opts[] =
1245 {"o", OFFSET_OPT, 1},
1251 int opt = mi_getopt ("-data-read-memory", argc, argv, opts,
1256 switch ((enum opt) opt)
1259 offset = atol (oarg);
1266 if (argc < 5 || argc > 6)
1267 error (_("-data-read-memory: Usage: "
1268 "ADDR WORD-FORMAT WORD-SIZE NR-ROWS NR-COLS [ASCHAR]."));
1270 /* Extract all the arguments. */
1272 /* Start address of the memory dump. */
1273 addr = parse_and_eval_address (argv[0]) + offset;
1274 /* The format character to use when displaying a memory word. See
1275 the ``x'' command. */
1276 word_format = argv[1][0];
1277 /* The size of the memory word. */
1278 word_size = atol (argv[2]);
1282 word_type = builtin_type (gdbarch)->builtin_int8;
1286 word_type = builtin_type (gdbarch)->builtin_int16;
1290 word_type = builtin_type (gdbarch)->builtin_int32;
1294 word_type = builtin_type (gdbarch)->builtin_int64;
1298 word_type = builtin_type (gdbarch)->builtin_int8;
1301 /* The number of rows. */
1302 nr_rows = atol (argv[3]);
1304 error (_("-data-read-memory: invalid number of rows."));
1306 /* Number of bytes per row. */
1307 nr_cols = atol (argv[4]);
1309 error (_("-data-read-memory: invalid number of columns."));
1311 /* The un-printable character when printing ascii. */
1317 /* Create a buffer and read it in. */
1318 total_bytes = word_size * nr_rows * nr_cols;
1320 gdb::byte_vector mbuf (total_bytes);
1322 nr_bytes = target_read (current_inferior ()->top_target (),
1323 TARGET_OBJECT_MEMORY, NULL,
1324 mbuf.data (), addr, total_bytes);
1326 error (_("Unable to read memory."));
1328 /* Output the header information. */
1329 uiout->field_core_addr ("addr", gdbarch, addr);
1330 uiout->field_signed ("nr-bytes", nr_bytes);
1331 uiout->field_signed ("total-bytes", total_bytes);
1332 uiout->field_core_addr ("next-row", gdbarch, addr + word_size * nr_cols);
1333 uiout->field_core_addr ("prev-row", gdbarch, addr - word_size * nr_cols);
1334 uiout->field_core_addr ("next-page", gdbarch, addr + total_bytes);
1335 uiout->field_core_addr ("prev-page", gdbarch, addr - total_bytes);
1337 /* Build the result as a two dimensional table. */
1344 ui_out_emit_list list_emitter (uiout, "memory");
1345 for (row = 0, row_byte = 0;
1347 row++, row_byte += nr_cols * word_size)
1351 struct value_print_options print_opts;
1353 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1354 uiout->field_core_addr ("addr", gdbarch, addr + row_byte);
1355 /* ui_out_field_core_addr_symbolic (uiout, "saddr", addr +
1358 ui_out_emit_list list_data_emitter (uiout, "data");
1359 get_formatted_print_options (&print_opts, word_format);
1360 for (col = 0, col_byte = row_byte;
1362 col++, col_byte += word_size)
1364 if (col_byte + word_size > nr_bytes)
1366 uiout->field_string (NULL, "N/A");
1371 print_scalar_formatted (&mbuf[col_byte], word_type,
1372 &print_opts, word_asize, &stream);
1373 uiout->field_stream (NULL, stream);
1383 for (byte = row_byte;
1384 byte < row_byte + word_size * nr_cols; byte++)
1386 if (byte >= nr_bytes)
1388 else if (mbuf[byte] < 32 || mbuf[byte] > 126)
1389 stream.putc (aschar);
1391 stream.putc (mbuf[byte]);
1393 uiout->field_stream ("ascii", stream);
1400 mi_cmd_data_read_memory_bytes (const char *command, char **argv, int argc)
1402 struct gdbarch *gdbarch = get_current_arch ();
1403 struct ui_out *uiout = current_uiout;
1407 int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
1414 static const struct mi_opt opts[] =
1416 {"o", OFFSET_OPT, 1},
1422 int opt = mi_getopt ("-data-read-memory-bytes", argc, argv, opts,
1426 switch ((enum opt) opt)
1429 offset = atol (oarg);
1437 error (_("Usage: [ -o OFFSET ] ADDR LENGTH."));
1439 addr = parse_and_eval_address (argv[0]) + offset;
1440 length = atol (argv[1]);
1442 std::vector<memory_read_result> result
1443 = read_memory_robust (current_inferior ()->top_target (), addr, length);
1445 if (result.size () == 0)
1446 error (_("Unable to read memory."));
1448 ui_out_emit_list list_emitter (uiout, "memory");
1449 for (const memory_read_result &read_result : result)
1451 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1453 uiout->field_core_addr ("begin", gdbarch, read_result.begin);
1454 uiout->field_core_addr ("offset", gdbarch, read_result.begin - addr);
1455 uiout->field_core_addr ("end", gdbarch, read_result.end);
1457 std::string data = bin2hex (read_result.data.get (),
1458 (read_result.end - read_result.begin)
1460 uiout->field_string ("contents", data);
1464 /* Implementation of the -data-write_memory command.
1466 COLUMN_OFFSET: optional argument. Must be preceded by '-o'. The
1467 offset from the beginning of the memory grid row where the cell to
1469 ADDR: start address of the row in the memory grid where the memory
1470 cell is, if OFFSET_COLUMN is specified. Otherwise, the address of
1471 the location to write to.
1472 FORMAT: a char indicating format for the ``word''. See
1474 WORD_SIZE: size of each ``word''; 1,2,4, or 8 bytes
1475 VALUE: value to be written into the memory address.
1477 Writes VALUE into ADDR + (COLUMN_OFFSET * WORD_SIZE).
1482 mi_cmd_data_write_memory (const char *command, char **argv, int argc)
1484 struct gdbarch *gdbarch = get_current_arch ();
1485 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1488 /* FIXME: ezannoni 2000-02-17 LONGEST could possibly not be big
1489 enough when using a compiler other than GCC. */
1498 static const struct mi_opt opts[] =
1500 {"o", OFFSET_OPT, 1},
1506 int opt = mi_getopt ("-data-write-memory", argc, argv, opts,
1511 switch ((enum opt) opt)
1514 offset = atol (oarg);
1522 error (_("-data-write-memory: Usage: "
1523 "[-o COLUMN_OFFSET] ADDR FORMAT WORD-SIZE VALUE."));
1525 /* Extract all the arguments. */
1526 /* Start address of the memory dump. */
1527 addr = parse_and_eval_address (argv[0]);
1528 /* The size of the memory word. */
1529 word_size = atol (argv[2]);
1531 /* Calculate the real address of the write destination. */
1532 addr += (offset * word_size);
1534 /* Get the value as a number. */
1535 value = parse_and_eval_address (argv[3]);
1536 /* Get the value into an array. */
1537 gdb::byte_vector buffer (word_size);
1538 store_signed_integer (buffer.data (), word_size, byte_order, value);
1539 /* Write it down to memory. */
1540 write_memory_with_notification (addr, buffer.data (), word_size);
1543 /* Implementation of the -data-write-memory-bytes command.
1546 DATA: string of bytes to write at that address
1547 COUNT: number of bytes to be filled (decimal integer). */
1550 mi_cmd_data_write_memory_bytes (const char *command, char **argv, int argc)
1554 size_t len_hex, len_bytes, len_units, i, steps, remaining_units;
1555 long int count_units;
1558 if (argc != 2 && argc != 3)
1559 error (_("Usage: ADDR DATA [COUNT]."));
1561 addr = parse_and_eval_address (argv[0]);
1563 len_hex = strlen (cdata);
1564 unit_size = gdbarch_addressable_memory_unit_size (get_current_arch ());
1566 if (len_hex % (unit_size * 2) != 0)
1567 error (_("Hex-encoded '%s' must represent an integral number of "
1568 "addressable memory units."),
1571 len_bytes = len_hex / 2;
1572 len_units = len_bytes / unit_size;
1575 count_units = strtoul (argv[2], NULL, 10);
1577 count_units = len_units;
1579 gdb::byte_vector databuf (len_bytes);
1581 for (i = 0; i < len_bytes; ++i)
1584 if (sscanf (cdata + i * 2, "%02x", &x) != 1)
1585 error (_("Invalid argument"));
1586 databuf[i] = (gdb_byte) x;
1589 gdb::byte_vector data;
1590 if (len_units < count_units)
1592 /* Pattern is made of less units than count:
1593 repeat pattern to fill memory. */
1594 data = gdb::byte_vector (count_units * unit_size);
1596 /* Number of times the pattern is entirely repeated. */
1597 steps = count_units / len_units;
1598 /* Number of remaining addressable memory units. */
1599 remaining_units = count_units % len_units;
1600 for (i = 0; i < steps; i++)
1601 memcpy (&data[i * len_bytes], &databuf[0], len_bytes);
1603 if (remaining_units > 0)
1604 memcpy (&data[steps * len_bytes], &databuf[0],
1605 remaining_units * unit_size);
1609 /* Pattern is longer than or equal to count:
1610 just copy count addressable memory units. */
1611 data = std::move (databuf);
1614 write_memory_with_notification (addr, data.data (), count_units);
1618 mi_cmd_enable_timings (const char *command, char **argv, int argc)
1624 if (strcmp (argv[0], "yes") == 0)
1626 else if (strcmp (argv[0], "no") == 0)
1637 error (_("-enable-timings: Usage: %s {yes|no}"), command);
1641 mi_cmd_list_features (const char *command, char **argv, int argc)
1645 struct ui_out *uiout = current_uiout;
1647 ui_out_emit_list list_emitter (uiout, "features");
1648 uiout->field_string (NULL, "frozen-varobjs");
1649 uiout->field_string (NULL, "pending-breakpoints");
1650 uiout->field_string (NULL, "thread-info");
1651 uiout->field_string (NULL, "data-read-memory-bytes");
1652 uiout->field_string (NULL, "breakpoint-notifications");
1653 uiout->field_string (NULL, "ada-task-info");
1654 uiout->field_string (NULL, "language-option");
1655 uiout->field_string (NULL, "info-gdb-mi-command");
1656 uiout->field_string (NULL, "undefined-command-error-code");
1657 uiout->field_string (NULL, "exec-run-start-option");
1658 uiout->field_string (NULL, "data-disassemble-a-option");
1660 if (ext_lang_initialized_p (get_ext_lang_defn (EXT_LANG_PYTHON)))
1661 uiout->field_string (NULL, "python");
1666 error (_("-list-features should be passed no arguments"));
1670 mi_cmd_list_target_features (const char *command, char **argv, int argc)
1674 struct ui_out *uiout = current_uiout;
1676 ui_out_emit_list list_emitter (uiout, "features");
1678 uiout->field_string (NULL, "async");
1679 if (target_can_execute_reverse ())
1680 uiout->field_string (NULL, "reverse");
1684 error (_("-list-target-features should be passed no arguments"));
1688 mi_cmd_add_inferior (const char *command, char **argv, int argc)
1690 bool no_connection = false;
1692 /* Parse the command options. */
1697 static const struct mi_opt opts[] =
1699 {"-no-connection", NO_CONNECTION_OPT, 0},
1708 int opt = mi_getopt ("-add-inferior", argc, argv, opts, &oind, &oarg);
1712 switch ((enum opt) opt)
1714 case NO_CONNECTION_OPT:
1715 no_connection = true;
1720 scoped_restore_current_pspace_and_thread restore_pspace_thread;
1722 inferior *inf = add_inferior_with_spaces ();
1724 switch_to_inferior_and_push_target (inf, no_connection,
1725 current_inferior ());
1727 current_uiout->field_fmt ("inferior", "i%d", inf->num);
1729 process_stratum_target *proc_target = inf->process_target ();
1731 if (proc_target != nullptr)
1733 ui_out_emit_tuple tuple_emitter (current_uiout, "connection");
1734 current_uiout->field_unsigned ("number", proc_target->connection_number);
1735 current_uiout->field_string ("name", proc_target->shortname ());
1740 mi_cmd_remove_inferior (const char *command, char **argv, int argc)
1743 struct inferior *inf_to_remove;
1746 error (_("-remove-inferior should be passed a single argument"));
1748 if (sscanf (argv[0], "i%d", &id) != 1)
1749 error (_("the thread group id is syntactically invalid"));
1751 inf_to_remove = find_inferior_id (id);
1752 if (inf_to_remove == NULL)
1753 error (_("the specified thread group does not exist"));
1755 if (inf_to_remove->pid != 0)
1756 error (_("cannot remove an active inferior"));
1758 if (inf_to_remove == current_inferior ())
1760 struct thread_info *tp = 0;
1761 struct inferior *new_inferior = NULL;
1763 for (inferior *inf : all_inferiors ())
1765 if (inf != inf_to_remove)
1769 if (new_inferior == NULL)
1770 error (_("Cannot remove last inferior"));
1772 set_current_inferior (new_inferior);
1773 if (new_inferior->pid != 0)
1774 tp = any_thread_of_inferior (new_inferior);
1776 switch_to_thread (tp);
1778 switch_to_no_thread ();
1779 set_current_program_space (new_inferior->pspace);
1782 delete_inferior (inf_to_remove);
1787 /* Execute a command within a safe environment.
1788 Return <0 for error; >=0 for ok.
1790 args->action will tell mi_execute_command what action
1791 to perform after the given command has executed (display/suppress
1792 prompt, display error). */
1795 captured_mi_execute_command (struct ui_out *uiout, struct mi_parse *context)
1797 struct mi_interp *mi = (struct mi_interp *) command_interp ();
1800 current_command_ts = context->cmd_start;
1802 scoped_restore save_token = make_scoped_restore (¤t_token,
1805 running_result_record_printed = 0;
1807 switch (context->op)
1810 /* A MI command was read from the input stream. */
1812 gdb_printf (gdb_stdlog,
1813 " token=`%s' command=`%s' args=`%s'\n",
1814 context->token, context->command, context->args);
1816 mi_cmd_execute (context);
1818 /* Print the result if there were no errors.
1820 Remember that on the way out of executing a command, you have
1821 to directly use the mi_interp's uiout, since the command
1822 could have reset the interpreter, in which case the current
1823 uiout will most likely crash in the mi_out_* routines. */
1824 if (!running_result_record_printed)
1826 gdb_puts (context->token, mi->raw_stdout);
1827 /* There's no particularly good reason why target-connect results
1828 in not ^done. Should kill ^connected for MI3. */
1829 gdb_puts (strcmp (context->command, "target-select") == 0
1830 ? "^connected" : "^done", mi->raw_stdout);
1831 mi_out_put (uiout, mi->raw_stdout);
1832 mi_out_rewind (uiout);
1833 mi_print_timing_maybe (mi->raw_stdout);
1834 gdb_puts ("\n", mi->raw_stdout);
1837 /* The command does not want anything to be printed. In that
1838 case, the command probably should not have written anything
1839 to uiout, but in case it has written something, discard it. */
1840 mi_out_rewind (uiout);
1847 /* A CLI command was read from the input stream. */
1848 /* This "feature" will be removed as soon as we have a
1849 complete set of mi commands. */
1850 /* Echo the command on the console. */
1851 gdb_printf (gdb_stdlog, "%s\n", context->command);
1852 /* Call the "console" interpreter. */
1853 argv[0] = (char *) INTERP_CONSOLE;
1854 argv[1] = context->command;
1855 mi_cmd_interpreter_exec ("-interpreter-exec", argv, 2);
1857 /* If we changed interpreters, DON'T print out anything. */
1858 if (current_interp_named_p (INTERP_MI)
1859 || current_interp_named_p (INTERP_MI1)
1860 || current_interp_named_p (INTERP_MI2)
1861 || current_interp_named_p (INTERP_MI3)
1862 || current_interp_named_p (INTERP_MI4))
1864 if (!running_result_record_printed)
1866 gdb_puts (context->token, mi->raw_stdout);
1867 gdb_puts ("^done", mi->raw_stdout);
1868 mi_out_put (uiout, mi->raw_stdout);
1869 mi_out_rewind (uiout);
1870 mi_print_timing_maybe (mi->raw_stdout);
1871 gdb_puts ("\n", mi->raw_stdout);
1874 mi_out_rewind (uiout);
1881 /* Print a gdb exception to the MI output stream. */
1884 mi_print_exception (const char *token, const struct gdb_exception &exception)
1886 struct mi_interp *mi = (struct mi_interp *) current_interpreter ();
1888 gdb_puts (token, mi->raw_stdout);
1889 gdb_puts ("^error,msg=\"", mi->raw_stdout);
1890 if (exception.message == NULL)
1891 gdb_puts ("unknown error", mi->raw_stdout);
1893 mi->raw_stdout->putstr (exception.what (), '"');
1894 gdb_puts ("\"", mi->raw_stdout);
1896 switch (exception.error)
1898 case UNDEFINED_COMMAND_ERROR:
1899 gdb_puts (",code=\"undefined-command\"", mi->raw_stdout);
1903 gdb_puts ("\n", mi->raw_stdout);
1907 mi_execute_command (const char *cmd, int from_tty)
1910 std::unique_ptr<struct mi_parse> command;
1912 /* This is to handle EOF (^D). We just quit gdb. */
1913 /* FIXME: we should call some API function here. */
1915 quit_force (NULL, from_tty);
1917 target_log_command (cmd);
1921 command = mi_parse (cmd, &token);
1923 catch (const gdb_exception &exception)
1925 mi_print_exception (token, exception);
1929 if (command != NULL)
1931 command->token = token;
1935 command->cmd_start = new mi_timestamp ();
1936 timestamp (command->cmd_start);
1941 captured_mi_execute_command (current_uiout, command.get ());
1943 catch (const gdb_exception &result)
1945 /* Like in start_event_loop, enable input and force display
1946 of the prompt. Otherwise, any command that calls
1947 async_disable_stdin, and then throws, will leave input
1949 async_enable_stdin ();
1950 current_ui->prompt_state = PROMPT_NEEDED;
1952 /* The command execution failed and error() was called
1954 mi_print_exception (command->token, result);
1955 mi_out_rewind (current_uiout);
1958 bpstat_do_actions ();
1963 /* Captures the current user selected context state, that is the current
1964 thread and frame. Later we can then check if the user selected context
1965 has changed at all. */
1967 struct user_selected_context
1970 user_selected_context ()
1971 : m_previous_ptid (inferior_ptid)
1973 save_selected_frame (&m_previous_frame_id, &m_previous_frame_level);
1976 /* Return true if the user selected context has changed since this object
1978 bool has_changed () const
1980 /* Did the selected thread change? */
1981 if (m_previous_ptid != null_ptid && inferior_ptid != null_ptid
1982 && m_previous_ptid != inferior_ptid)
1985 /* Grab details of the currently selected frame, for comparison. */
1986 frame_id current_frame_id;
1987 int current_frame_level;
1988 save_selected_frame (¤t_frame_id, ¤t_frame_level);
1990 /* Did the selected frame level change? */
1991 if (current_frame_level != m_previous_frame_level)
1994 /* Did the selected frame id change? If the innermost frame is
1995 selected then the level will be -1, and the frame-id will be
1996 null_frame_id. As comparing null_frame_id with itself always
1997 reports not-equal, we only do the equality test if we have something
1998 other than the innermost frame selected. */
1999 if (current_frame_level != -1
2000 && current_frame_id != m_previous_frame_id)
2003 /* Nothing changed! */
2007 /* The previously selected thread. This might be null_ptid if there was
2008 no previously selected thread. */
2009 ptid_t m_previous_ptid;
2011 /* The previously selected frame. If the innermost frame is selected, or
2012 no frame is selected, then the frame_id will be null_frame_id, and the
2013 level will be -1. */
2014 frame_id m_previous_frame_id;
2015 int m_previous_frame_level;
2019 mi_cmd_execute (struct mi_parse *parse)
2021 scoped_value_mark cleanup = prepare_execute_command ();
2023 if (parse->all && parse->thread_group != -1)
2024 error (_("Cannot specify --thread-group together with --all"));
2026 if (parse->all && parse->thread != -1)
2027 error (_("Cannot specify --thread together with --all"));
2029 if (parse->thread_group != -1 && parse->thread != -1)
2030 error (_("Cannot specify --thread together with --thread-group"));
2032 if (parse->frame != -1 && parse->thread == -1)
2033 error (_("Cannot specify --frame without --thread"));
2035 if (parse->thread_group != -1)
2037 struct inferior *inf = find_inferior_id (parse->thread_group);
2038 struct thread_info *tp = 0;
2041 error (_("Invalid thread group for the --thread-group option"));
2043 set_current_inferior (inf);
2044 /* This behaviour means that if --thread-group option identifies
2045 an inferior with multiple threads, then a random one will be
2046 picked. This is not a problem -- frontend should always
2047 provide --thread if it wishes to operate on a specific
2050 tp = any_live_thread_of_inferior (inf);
2052 switch_to_thread (tp);
2054 switch_to_no_thread ();
2055 set_current_program_space (inf->pspace);
2058 user_selected_context current_user_selected_context;
2060 gdb::optional<scoped_restore_current_thread> thread_saver;
2061 if (parse->thread != -1)
2063 thread_info *tp = find_thread_global_id (parse->thread);
2066 error (_("Invalid thread id: %d"), parse->thread);
2068 if (tp->state == THREAD_EXITED)
2069 error (_("Thread id: %d has terminated"), parse->thread);
2071 if (parse->cmd->preserve_user_selected_context ())
2072 thread_saver.emplace ();
2074 switch_to_thread (tp);
2077 gdb::optional<scoped_restore_selected_frame> frame_saver;
2078 if (parse->frame != -1)
2081 int frame = parse->frame;
2083 fid = find_relative_frame (get_current_frame (), &frame);
2086 if (parse->cmd->preserve_user_selected_context ())
2087 frame_saver.emplace ();
2092 error (_("Invalid frame id: %d"), frame);
2095 gdb::optional<scoped_restore_current_language> lang_saver;
2096 if (parse->language != language_unknown)
2098 lang_saver.emplace ();
2099 set_language (parse->language);
2102 current_context = parse;
2104 gdb_assert (parse->cmd != nullptr);
2106 gdb::optional<scoped_restore_tmpl<int>> restore_suppress_notification
2107 = parse->cmd->do_suppress_notification ();
2109 parse->cmd->invoke (parse);
2111 if (!parse->cmd->preserve_user_selected_context ()
2112 && current_user_selected_context.has_changed ())
2113 gdb::observers::user_selected_context_changed.notify
2114 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
2117 /* See mi-main.h. */
2120 mi_execute_cli_command (const char *cmd, bool args_p, const char *args)
2124 std::string run (cmd);
2127 run = run + " " + args;
2129 gdb_assert (args == nullptr);
2132 gdb_printf (gdb_stdlog, "cli=%s run=%s\n",
2135 execute_command (run.c_str (), 0 /* from_tty */ );
2140 mi_execute_async_cli_command (const char *cli_command, char **argv, int argc)
2142 std::string run = cli_command;
2145 run = run + " " + *argv;
2149 execute_command (run.c_str (), 0 /* from_tty */ );
2153 mi_load_progress (const char *section_name,
2154 unsigned long sent_so_far,
2155 unsigned long total_section,
2156 unsigned long total_sent,
2157 unsigned long grand_total)
2159 using namespace std::chrono;
2160 static steady_clock::time_point last_update;
2161 static char *previous_sect_name = NULL;
2163 struct mi_interp *mi = (struct mi_interp *) current_interpreter ();
2165 /* This function is called through deprecated_show_load_progress
2166 which means uiout may not be correct. Fix it for the duration
2167 of this function. */
2169 std::unique_ptr<ui_out> uiout (mi_out_new (current_interpreter ()->name ()));
2170 if (uiout == nullptr)
2173 scoped_restore save_uiout
2174 = make_scoped_restore (¤t_uiout, uiout.get ());
2176 new_section = (previous_sect_name ?
2177 strcmp (previous_sect_name, section_name) : 1);
2180 xfree (previous_sect_name);
2181 previous_sect_name = xstrdup (section_name);
2184 gdb_puts (current_token, mi->raw_stdout);
2185 gdb_puts ("+download", mi->raw_stdout);
2187 ui_out_emit_tuple tuple_emitter (uiout.get (), NULL);
2188 uiout->field_string ("section", section_name);
2189 uiout->field_signed ("section-size", total_section);
2190 uiout->field_signed ("total-size", grand_total);
2192 mi_out_put (uiout.get (), mi->raw_stdout);
2193 gdb_puts ("\n", mi->raw_stdout);
2194 gdb_flush (mi->raw_stdout);
2197 steady_clock::time_point time_now = steady_clock::now ();
2198 if (time_now - last_update > milliseconds (500))
2200 last_update = time_now;
2202 gdb_puts (current_token, mi->raw_stdout);
2203 gdb_puts ("+download", mi->raw_stdout);
2205 ui_out_emit_tuple tuple_emitter (uiout.get (), NULL);
2206 uiout->field_string ("section", section_name);
2207 uiout->field_signed ("section-sent", sent_so_far);
2208 uiout->field_signed ("section-size", total_section);
2209 uiout->field_signed ("total-sent", total_sent);
2210 uiout->field_signed ("total-size", grand_total);
2212 mi_out_put (uiout.get (), mi->raw_stdout);
2213 gdb_puts ("\n", mi->raw_stdout);
2214 gdb_flush (mi->raw_stdout);
2219 timestamp (struct mi_timestamp *tv)
2221 using namespace std::chrono;
2223 tv->wallclock = steady_clock::now ();
2224 run_time_clock::now (tv->utime, tv->stime);
2228 print_diff_now (struct ui_file *file, struct mi_timestamp *start)
2230 struct mi_timestamp now;
2233 print_diff (file, start, &now);
2237 mi_print_timing_maybe (struct ui_file *file)
2239 /* If the command is -enable-timing then do_timings may be true
2240 whilst current_command_ts is not initialized. */
2241 if (do_timings && current_command_ts)
2242 print_diff_now (file, current_command_ts);
2246 print_diff (struct ui_file *file, struct mi_timestamp *start,
2247 struct mi_timestamp *end)
2249 using namespace std::chrono;
2251 duration<double> wallclock = end->wallclock - start->wallclock;
2252 duration<double> utime = end->utime - start->utime;
2253 duration<double> stime = end->stime - start->stime;
2257 ",time={wallclock=\"%0.5f\",user=\"%0.5f\",system=\"%0.5f\"}",
2258 wallclock.count (), utime.count (), stime.count ());
2262 mi_cmd_trace_define_variable (const char *command, char **argv, int argc)
2264 LONGEST initval = 0;
2265 struct trace_state_variable *tsv;
2268 if (argc != 1 && argc != 2)
2269 error (_("Usage: -trace-define-variable VARIABLE [VALUE]"));
2273 error (_("Name of trace variable should start with '$'"));
2275 validate_trace_state_variable_name (name);
2277 tsv = find_trace_state_variable (name);
2279 tsv = create_trace_state_variable (name);
2282 initval = value_as_long (parse_and_eval (argv[1]));
2284 tsv->initial_value = initval;
2288 mi_cmd_trace_list_variables (const char *command, char **argv, int argc)
2291 error (_("-trace-list-variables: no arguments allowed"));
2293 tvariables_info_1 ();
2297 mi_cmd_trace_find (const char *command, char **argv, int argc)
2302 error (_("trace selection mode is required"));
2306 if (strcmp (mode, "none") == 0)
2308 tfind_1 (tfind_number, -1, 0, 0, 0);
2312 check_trace_running (current_trace_status ());
2314 if (strcmp (mode, "frame-number") == 0)
2317 error (_("frame number is required"));
2318 tfind_1 (tfind_number, atoi (argv[1]), 0, 0, 0);
2320 else if (strcmp (mode, "tracepoint-number") == 0)
2323 error (_("tracepoint number is required"));
2324 tfind_1 (tfind_tp, atoi (argv[1]), 0, 0, 0);
2326 else if (strcmp (mode, "pc") == 0)
2329 error (_("PC is required"));
2330 tfind_1 (tfind_pc, 0, parse_and_eval_address (argv[1]), 0, 0);
2332 else if (strcmp (mode, "pc-inside-range") == 0)
2335 error (_("Start and end PC are required"));
2336 tfind_1 (tfind_range, 0, parse_and_eval_address (argv[1]),
2337 parse_and_eval_address (argv[2]), 0);
2339 else if (strcmp (mode, "pc-outside-range") == 0)
2342 error (_("Start and end PC are required"));
2343 tfind_1 (tfind_outside, 0, parse_and_eval_address (argv[1]),
2344 parse_and_eval_address (argv[2]), 0);
2346 else if (strcmp (mode, "line") == 0)
2349 error (_("Line is required"));
2351 std::vector<symtab_and_line> sals
2352 = decode_line_with_current_source (argv[1],
2353 DECODE_LINE_FUNFIRSTLINE);
2354 const symtab_and_line &sal = sals[0];
2356 if (sal.symtab == 0)
2357 error (_("Could not find the specified line"));
2359 CORE_ADDR start_pc, end_pc;
2360 if (sal.line > 0 && find_line_pc_range (sal, &start_pc, &end_pc))
2361 tfind_1 (tfind_range, 0, start_pc, end_pc - 1, 0);
2363 error (_("Could not find the specified line"));
2366 error (_("Invalid mode '%s'"), mode);
2368 if (has_stack_frames () || get_traceframe_number () >= 0)
2369 print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS, 1);
2373 mi_cmd_trace_save (const char *command, char **argv, int argc)
2375 int target_saves = 0;
2376 int generate_ctf = 0;
2383 TARGET_SAVE_OPT, CTF_OPT
2385 static const struct mi_opt opts[] =
2387 {"r", TARGET_SAVE_OPT, 0},
2388 {"ctf", CTF_OPT, 0},
2394 int opt = mi_getopt ("-trace-save", argc, argv, opts,
2399 switch ((enum opt) opt)
2401 case TARGET_SAVE_OPT:
2410 if (argc - oind != 1)
2411 error (_("Exactly one argument required "
2412 "(file in which to save trace data)"));
2414 filename = argv[oind];
2417 trace_save_ctf (filename, target_saves);
2419 trace_save_tfile (filename, target_saves);
2423 mi_cmd_trace_start (const char *command, char **argv, int argc)
2425 start_tracing (NULL);
2429 mi_cmd_trace_status (const char *command, char **argv, int argc)
2431 trace_status_mi (0);
2435 mi_cmd_trace_stop (const char *command, char **argv, int argc)
2437 stop_tracing (NULL);
2438 trace_status_mi (1);
2441 /* Implement the "-ada-task-info" command. */
2444 mi_cmd_ada_task_info (const char *command, char **argv, int argc)
2446 if (argc != 0 && argc != 1)
2447 error (_("Invalid MI command"));
2449 print_ada_task_info (current_uiout, argv[0], current_inferior ());
2452 /* Print EXPRESSION according to VALUES. */
2455 print_variable_or_computed (const char *expression, enum print_values values)
2459 struct ui_out *uiout = current_uiout;
2463 expression_up expr = parse_expression (expression);
2465 if (values == PRINT_SIMPLE_VALUES)
2466 val = evaluate_type (expr.get ());
2468 val = evaluate_expression (expr.get ());
2470 gdb::optional<ui_out_emit_tuple> tuple_emitter;
2471 if (values != PRINT_NO_VALUES)
2472 tuple_emitter.emplace (uiout, nullptr);
2473 uiout->field_string ("name", expression);
2477 case PRINT_SIMPLE_VALUES:
2478 type = check_typedef (value_type (val));
2479 type_print (value_type (val), "", &stb, -1);
2480 uiout->field_stream ("type", stb);
2481 if (type->code () != TYPE_CODE_ARRAY
2482 && type->code () != TYPE_CODE_STRUCT
2483 && type->code () != TYPE_CODE_UNION)
2485 struct value_print_options opts;
2487 get_no_prettyformat_print_options (&opts);
2489 common_val_print (val, &stb, 0, &opts, current_language);
2490 uiout->field_stream ("value", stb);
2493 case PRINT_ALL_VALUES:
2495 struct value_print_options opts;
2497 get_no_prettyformat_print_options (&opts);
2499 common_val_print (val, &stb, 0, &opts, current_language);
2500 uiout->field_stream ("value", stb);
2506 /* Implement the "-trace-frame-collected" command. */
2509 mi_cmd_trace_frame_collected (const char *command, char **argv, int argc)
2511 struct bp_location *tloc;
2513 struct collection_list *clist;
2514 struct collection_list tracepoint_list, stepping_list;
2515 struct traceframe_info *tinfo;
2517 enum print_values var_print_values = PRINT_ALL_VALUES;
2518 enum print_values comp_print_values = PRINT_ALL_VALUES;
2519 int registers_format = 'x';
2520 int memory_contents = 0;
2521 struct ui_out *uiout = current_uiout;
2529 static const struct mi_opt opts[] =
2531 {"-var-print-values", VAR_PRINT_VALUES, 1},
2532 {"-comp-print-values", COMP_PRINT_VALUES, 1},
2533 {"-registers-format", REGISTERS_FORMAT, 1},
2534 {"-memory-contents", MEMORY_CONTENTS, 0},
2541 int opt = mi_getopt ("-trace-frame-collected", argc, argv, opts,
2545 switch ((enum opt) opt)
2547 case VAR_PRINT_VALUES:
2548 var_print_values = mi_parse_print_values (oarg);
2550 case COMP_PRINT_VALUES:
2551 comp_print_values = mi_parse_print_values (oarg);
2553 case REGISTERS_FORMAT:
2554 registers_format = oarg[0];
2556 case MEMORY_CONTENTS:
2557 memory_contents = 1;
2563 error (_("Usage: -trace-frame-collected "
2564 "[--var-print-values PRINT_VALUES] "
2565 "[--comp-print-values PRINT_VALUES] "
2566 "[--registers-format FORMAT]"
2567 "[--memory-contents]"));
2569 /* This throws an error is not inspecting a trace frame. */
2570 tloc = get_traceframe_location (&stepping_frame);
2572 /* This command only makes sense for the current frame, not the
2574 scoped_restore_current_thread restore_thread;
2575 select_frame (get_current_frame ());
2577 encode_actions (tloc, &tracepoint_list, &stepping_list);
2580 clist = &stepping_list;
2582 clist = &tracepoint_list;
2584 tinfo = get_traceframe_info ();
2586 /* Explicitly wholly collected variables. */
2588 ui_out_emit_list list_emitter (uiout, "explicit-variables");
2589 const std::vector<std::string> &wholly_collected
2590 = clist->wholly_collected ();
2591 for (size_t i = 0; i < wholly_collected.size (); i++)
2593 const std::string &str = wholly_collected[i];
2594 print_variable_or_computed (str.c_str (), var_print_values);
2598 /* Computed expressions. */
2600 ui_out_emit_list list_emitter (uiout, "computed-expressions");
2602 const std::vector<std::string> &computed = clist->computed ();
2603 for (size_t i = 0; i < computed.size (); i++)
2605 const std::string &str = computed[i];
2606 print_variable_or_computed (str.c_str (), comp_print_values);
2610 /* Registers. Given pseudo-registers, and that some architectures
2611 (like MIPS) actually hide the raw registers, we don't go through
2612 the trace frame info, but instead consult the register cache for
2613 register availability. */
2615 frame_info_ptr frame;
2616 struct gdbarch *gdbarch;
2620 ui_out_emit_list list_emitter (uiout, "registers");
2622 frame = get_selected_frame (NULL);
2623 gdbarch = get_frame_arch (frame);
2624 numregs = gdbarch_num_cooked_regs (gdbarch);
2626 for (regnum = 0; regnum < numregs; regnum++)
2628 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
2631 output_register (frame, regnum, registers_format, 1);
2635 /* Trace state variables. */
2637 ui_out_emit_list list_emitter (uiout, "tvars");
2639 for (int tvar : tinfo->tvars)
2641 struct trace_state_variable *tsv;
2643 tsv = find_trace_state_variable_by_number (tvar);
2645 ui_out_emit_tuple tuple_emitter (uiout, NULL);
2649 uiout->field_fmt ("name", "$%s", tsv->name.c_str ());
2651 tsv->value_known = target_get_trace_state_variable_value (tsv->number,
2653 uiout->field_signed ("current", tsv->value);
2657 uiout->field_skip ("name");
2658 uiout->field_skip ("current");
2665 std::vector<mem_range> available_memory;
2667 traceframe_available_memory (&available_memory, 0, ULONGEST_MAX);
2669 ui_out_emit_list list_emitter (uiout, "memory");
2671 for (const mem_range &r : available_memory)
2673 struct gdbarch *gdbarch = target_gdbarch ();
2675 ui_out_emit_tuple tuple_emitter (uiout, NULL);
2677 uiout->field_core_addr ("address", gdbarch, r.start);
2678 uiout->field_signed ("length", r.length);
2680 gdb::byte_vector data (r.length);
2682 if (memory_contents)
2684 if (target_read_memory (r.start, data.data (), r.length) == 0)
2686 std::string data_str = bin2hex (data.data (), r.length);
2687 uiout->field_string ("contents", data_str);
2690 uiout->field_skip ("contents");
2696 /* See mi/mi-main.h. */
2699 mi_cmd_fix_multi_location_breakpoint_output (const char *command, char **argv,
2702 fix_multi_location_breakpoint_output_globally = true;
2705 /* See mi/mi-main.h. */
2708 mi_cmd_fix_breakpoint_script_output (const char *command, char **argv, int argc)
2710 fix_breakpoint_script_output_globally = true;
2713 /* Implement the "-complete" command. */
2716 mi_cmd_complete (const char *command, char **argv, int argc)
2719 error (_("Usage: -complete COMMAND"));
2721 if (max_completions == 0)
2722 error (_("max-completions is zero, completion is disabled."));
2724 int quote_char = '\0';
2727 completion_result result = complete (argv[0], &word, "e_char);
2729 std::string arg_prefix (argv[0], word - argv[0]);
2731 struct ui_out *uiout = current_uiout;
2733 if (result.number_matches > 0)
2734 uiout->field_fmt ("completion", "%s%s",
2735 arg_prefix.c_str (),result.match_list[0]);
2738 ui_out_emit_list completions_emitter (uiout, "matches");
2740 if (result.number_matches == 1)
2741 uiout->field_fmt (NULL, "%s%s",
2742 arg_prefix.c_str (), result.match_list[0]);
2745 result.sort_match_list ();
2746 for (size_t i = 0; i < result.number_matches; i++)
2748 uiout->field_fmt (NULL, "%s%s",
2749 arg_prefix.c_str (), result.match_list[i + 1]);
2753 uiout->field_string ("max_completions_reached",
2754 result.number_matches == max_completions ? "1" : "0");
2758 void _initialize_mi_main ();
2760 _initialize_mi_main ()
2762 set_show_commands mi_async_cmds
2763 = add_setshow_boolean_cmd ("mi-async", class_run,
2765 Set whether MI asynchronous mode is enabled."), _("\
2766 Show whether MI asynchronous mode is enabled."), _("\
2767 Tells GDB whether MI should be in asynchronous mode."),
2768 set_mi_async_command,
2769 show_mi_async_command,
2770 &setlist, &showlist);
2772 /* Alias old "target-async" to "mi-async". */
2773 cmd_list_element *set_target_async_cmd
2774 = add_alias_cmd ("target-async", mi_async_cmds.set, class_run, 0, &setlist);
2775 deprecate_cmd (set_target_async_cmd, "set mi-async");
2777 cmd_list_element *show_target_async_cmd
2778 = add_alias_cmd ("target-async", mi_async_cmds.show, class_run, 0,
2780 deprecate_cmd (show_target_async_cmd, "show mi-async");