arm, objdump: print obsolote warning when 26-bit set in instructions
[binutils-gdb.git] / gdb / mi / mi-main.c
blobb72cd1b9b82c8af28c003b955bbfd1fe4822d6a1
1 /* MI Command Set.
3 Copyright (C) 2000-2024 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/>. */
22 #include "arch-utils.h"
23 #include "extract-store-integer.h"
24 #include "target.h"
25 #include "inferior.h"
26 #include "infrun.h"
27 #include "top.h"
28 #include "ui.h"
29 #include "gdbthread.h"
30 #include "mi-cmds.h"
31 #include "mi-parse.h"
32 #include "mi-getopt.h"
33 #include "mi-console.h"
34 #include "ui-out.h"
35 #include "mi-out.h"
36 #include "interps.h"
37 #include "gdbsupport/event-loop.h"
38 #include "event-top.h"
39 #include "gdbcore.h"
40 #include "value.h"
41 #include "regcache.h"
42 #include "frame.h"
43 #include "mi-main.h"
44 #include "mi-interp.h"
45 #include "language.h"
46 #include "valprint.h"
47 #include "osdata.h"
48 #include "gdbsupport/gdb_splay_tree.h"
49 #include "tracepoint.h"
50 #include "ada-lang.h"
51 #include "linespec.h"
52 #include "extension.h"
53 #include "cli/cli-cmds.h"
54 #include "observable.h"
55 #include <optional>
56 #include "gdbsupport/byte-vector.h"
58 #include <ctype.h>
59 #include "gdbsupport/run-time-clock.h"
60 #include <chrono>
61 #include "progspace-and-thread.h"
62 #include "gdbsupport/rsp-low.h"
63 #include <algorithm>
64 #include <set>
65 #include <map>
67 enum
69 FROM_TTY = 0
72 /* Debug flag */
73 static int mi_debug_p;
75 /* This is used to pass the current command timestamp down to
76 continuation routines. */
77 static struct mi_timestamp *current_command_ts;
79 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 static void mi_cmd_execute (struct mi_parse *parse);
88 static void mi_execute_async_cli_command (const char *cli_command,
89 const char *const *argv, int argc);
90 static bool register_changed_p (int regnum, readonly_detached_regcache *,
91 readonly_detached_regcache *);
92 static void output_register (const frame_info_ptr &, int regnum, int format,
93 int skip_unavailable);
95 /* Controls whether the frontend wants MI in async mode. */
96 static bool mi_async = false;
98 /* The set command writes to this variable. If the inferior is
99 executing, mi_async is *not* updated. */
100 static bool mi_async_1 = false;
102 static void
103 set_mi_async_command (const char *args, int from_tty,
104 struct cmd_list_element *c)
106 if (have_live_inferiors ())
108 mi_async_1 = mi_async;
109 error (_("Cannot change this setting while the inferior is running."));
112 mi_async = mi_async_1;
115 static void
116 show_mi_async_command (struct ui_file *file, int from_tty,
117 struct cmd_list_element *c,
118 const char *value)
120 gdb_printf (file,
121 _("Whether MI is in asynchronous mode is %s.\n"),
122 value);
125 /* A wrapper for target_can_async_p that takes the MI setting into
126 account. */
129 mi_async_p (void)
131 return mi_async && target_can_async_p ();
134 /* Command implementations. FIXME: Is this libgdb? No. This is the MI
135 layer that calls libgdb. Any operation used in the below should be
136 formalized. */
138 static void timestamp (struct mi_timestamp *tv);
140 static void print_diff (struct ui_file *file, struct mi_timestamp *start,
141 struct mi_timestamp *end);
143 void
144 mi_cmd_gdb_exit (const char *command, const char *const *argv, int argc)
146 struct mi_interp *mi = as_mi_interp (current_interpreter ());
148 /* If the current interpreter is not an MI interpreter, then just
149 don't bother printing anything. This case can arise from using
150 the Python gdb.execute_mi function -- but here the result does
151 not matter, as gdb is about to exit anyway. */
152 if (mi != nullptr)
154 /* We have to print everything right here because we never return. */
155 if (mi->current_token)
156 gdb_puts (mi->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);
161 /* FIXME: The function called is not yet a formal libgdb function. */
162 quit_force (NULL, FROM_TTY);
165 void
166 mi_cmd_exec_next (const char *command, const char *const *argv, int argc)
168 /* FIXME: Should call a libgdb function, not a cli wrapper. */
169 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
170 mi_execute_async_cli_command ("reverse-next", argv + 1, argc - 1);
171 else
172 mi_execute_async_cli_command ("next", argv, argc);
175 void
176 mi_cmd_exec_next_instruction (const char *command, const char *const *argv,
177 int argc)
179 /* FIXME: Should call a libgdb function, not a cli wrapper. */
180 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
181 mi_execute_async_cli_command ("reverse-nexti", argv + 1, argc - 1);
182 else
183 mi_execute_async_cli_command ("nexti", argv, argc);
186 void
187 mi_cmd_exec_step (const char *command, const char *const *argv, int argc)
189 /* FIXME: Should call a libgdb function, not a cli wrapper. */
190 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
191 mi_execute_async_cli_command ("reverse-step", argv + 1, argc - 1);
192 else
193 mi_execute_async_cli_command ("step", argv, argc);
196 void
197 mi_cmd_exec_step_instruction (const char *command, const char *const *argv,
198 int argc)
200 /* FIXME: Should call a libgdb function, not a cli wrapper. */
201 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
202 mi_execute_async_cli_command ("reverse-stepi", argv + 1, argc - 1);
203 else
204 mi_execute_async_cli_command ("stepi", argv, argc);
207 void
208 mi_cmd_exec_finish (const char *command, const char *const *argv, int argc)
210 /* FIXME: Should call a libgdb function, not a cli wrapper. */
211 if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
212 mi_execute_async_cli_command ("reverse-finish", argv + 1, argc - 1);
213 else
214 mi_execute_async_cli_command ("finish", argv, argc);
217 void
218 mi_cmd_exec_return (const char *command, const char *const *argv, int argc)
220 /* This command doesn't really execute the target, it just pops the
221 specified number of frames. */
222 if (argc)
223 /* Call return_command with from_tty argument equal to 0 so as to
224 avoid being queried. */
225 return_command (*argv, 0);
226 else
227 /* Call return_command with from_tty argument equal to 0 so as to
228 avoid being queried. */
229 return_command (NULL, 0);
231 /* Because we have called return_command with from_tty = 0, we need
232 to print the frame here. */
233 print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS, 1);
236 void
237 mi_cmd_exec_jump (const char *args, const char *const *argv, int argc)
239 /* FIXME: Should call a libgdb function, not a cli wrapper. */
240 mi_execute_async_cli_command ("jump", argv, argc);
243 static void
244 proceed_thread (struct thread_info *thread, int pid)
246 if (thread->state != THREAD_STOPPED)
247 return;
249 if (pid != 0 && thread->ptid.pid () != pid)
250 return;
252 switch_to_thread (thread);
253 clear_proceed_status (0);
254 proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
257 static int
258 proceed_thread_callback (struct thread_info *thread, void *arg)
260 int pid = *(int *)arg;
262 proceed_thread (thread, pid);
263 return 0;
266 static void
267 exec_continue (const char *const *argv, int argc)
269 prepare_execution_command (current_inferior ()->top_target (), mi_async_p ());
272 if (non_stop)
274 /* In non-stop mode, 'resume' always resumes a single thread.
275 Therefore, to resume all threads of the current inferior, or
276 all threads in all inferiors, we need to iterate over
277 threads.
279 See comment on infcmd.c:proceed_thread_callback for rationale. */
280 if (current_context->all || current_context->thread_group != -1)
282 scoped_restore_current_thread restore_thread;
283 scoped_disable_commit_resumed disable_commit_resumed
284 ("MI continue all threads in non-stop");
285 int pid = 0;
287 if (!current_context->all)
289 struct inferior *inf
290 = find_inferior_id (current_context->thread_group);
292 pid = inf->pid;
295 iterate_over_threads (proceed_thread_callback, &pid);
296 disable_commit_resumed.reset_and_commit ();
298 else
300 continue_1 (0);
303 else
305 scoped_restore save_multi = make_scoped_restore (&sched_multi);
307 if (current_context->all)
309 sched_multi = 1;
310 continue_1 (0);
312 else
314 /* In all-stop mode, -exec-continue traditionally resumed
315 either all threads, or one thread, depending on the
316 'scheduler-locking' variable. Let's continue to do the
317 same. */
318 continue_1 (1);
323 static void
324 exec_reverse_continue (const char *const *argv, int argc)
326 enum exec_direction_kind dir = execution_direction;
328 if (dir == EXEC_REVERSE)
329 error (_("Already in reverse mode."));
331 if (!target_can_execute_reverse ())
332 error (_("Target %s does not support this command."), target_shortname ());
334 scoped_restore save_exec_dir = make_scoped_restore (&execution_direction,
335 EXEC_REVERSE);
336 exec_continue (argv, argc);
339 void
340 mi_cmd_exec_continue (const char *command, const char *const *argv, int argc)
342 if (argc > 0 && strcmp (argv[0], "--reverse") == 0)
343 exec_reverse_continue (argv + 1, argc - 1);
344 else
345 exec_continue (argv, argc);
348 static int
349 interrupt_thread_callback (struct thread_info *thread, void *arg)
351 int pid = *(int *)arg;
353 if (thread->state != THREAD_RUNNING)
354 return 0;
356 if (thread->ptid.pid () != pid)
357 return 0;
359 target_stop (thread->ptid);
360 return 0;
363 /* Interrupt the execution of the target. Note how we must play
364 around with the token variables, in order to display the current
365 token in the result of the interrupt command, and the previous
366 execution token when the target finally stops. See comments in
367 mi_cmd_execute. */
369 void
370 mi_cmd_exec_interrupt (const char *command, const char *const *argv, int argc)
372 /* In all-stop mode, everything stops, so we don't need to try
373 anything specific. */
374 if (!non_stop)
376 interrupt_target_1 (0);
377 return;
380 if (current_context->all)
382 /* This will interrupt all threads in all inferiors. */
383 interrupt_target_1 (1);
385 else if (current_context->thread_group != -1)
387 struct inferior *inf = find_inferior_id (current_context->thread_group);
389 scoped_disable_commit_resumed disable_commit_resumed
390 ("interrupting all threads of thread group");
392 iterate_over_threads (interrupt_thread_callback, &inf->pid);
394 else
396 /* Interrupt just the current thread -- either explicitly
397 specified via --thread or whatever was current before
398 MI command was sent. */
399 interrupt_target_1 (0);
403 /* Start the execution of the given inferior.
405 START_P indicates whether the program should be stopped when reaching the
406 main subprogram (similar to what the CLI "start" command does). */
408 static void
409 run_one_inferior (inferior *inf, bool start_p)
411 const char *run_cmd = start_p ? "start" : "run";
412 struct target_ops *run_target = find_run_target ();
413 bool async_p = mi_async && target_can_async_p (run_target);
415 if (inf->pid != 0)
417 thread_info *tp = any_thread_of_inferior (inf);
418 if (tp == NULL)
419 error (_("Inferior has no threads."));
421 switch_to_thread (tp);
423 else
424 switch_to_inferior_no_thread (inf);
425 mi_execute_cli_command (run_cmd, async_p,
426 async_p ? "&" : NULL);
429 void
430 mi_cmd_exec_run (const char *command, const char *const *argv, int argc)
432 int start_p = 0;
434 /* Parse the command options. */
435 enum opt
437 START_OPT,
439 static const struct mi_opt opts[] =
441 {"-start", START_OPT, 0},
442 {NULL, 0, 0},
445 int oind = 0;
446 const char *oarg;
448 while (1)
450 int opt = mi_getopt ("-exec-run", argc, argv, opts, &oind, &oarg);
452 if (opt < 0)
453 break;
454 switch ((enum opt) opt)
456 case START_OPT:
457 start_p = 1;
458 break;
462 /* This command does not accept any argument. Make sure the user
463 did not provide any. */
464 if (oind != argc)
465 error (_("Invalid argument: %s"), argv[oind]);
467 if (current_context->all)
469 scoped_restore_current_pspace_and_thread restore_pspace_thread;
471 for (inferior *inf : all_inferiors ())
472 run_one_inferior (inf, start_p);
474 else
476 const char *run_cmd = start_p ? "start" : "run";
477 struct target_ops *run_target = find_run_target ();
478 bool async_p = mi_async && target_can_async_p (run_target);
480 mi_execute_cli_command (run_cmd, async_p,
481 async_p ? "&" : NULL);
486 static int
487 find_thread_of_process (struct thread_info *ti, void *p)
489 int pid = *(int *)p;
491 if (ti->ptid.pid () == pid && ti->state != THREAD_EXITED)
492 return 1;
494 return 0;
497 void
498 mi_cmd_target_detach (const char *command, const char *const *argv, int argc)
500 if (argc != 0 && argc != 1)
501 error (_("Usage: -target-detach [pid | thread-group]"));
503 if (argc == 1)
505 struct thread_info *tp;
506 char *end;
507 int pid;
509 /* First see if we are dealing with a thread-group id. */
510 if (*argv[0] == 'i')
512 struct inferior *inf;
513 int id = strtoul (argv[0] + 1, &end, 0);
515 if (*end != '\0')
516 error (_("Invalid syntax of thread-group id '%s'"), argv[0]);
518 inf = find_inferior_id (id);
519 if (!inf)
520 error (_("Non-existent thread-group id '%d'"), id);
522 pid = inf->pid;
524 else
526 /* We must be dealing with a pid. */
527 pid = strtol (argv[0], &end, 10);
529 if (*end != '\0')
530 error (_("Invalid identifier '%s'"), argv[0]);
533 /* Pick any thread in the desired process. Current
534 target_detach detaches from the parent of inferior_ptid. */
535 tp = iterate_over_threads (find_thread_of_process, &pid);
536 if (!tp)
537 error (_("Thread group is empty"));
539 switch_to_thread (tp);
542 detach_command (NULL, 0);
545 void
546 mi_cmd_target_flash_erase (const char *command, const char *const *argv,
547 int argc)
549 flash_erase_command (NULL, 0);
552 void
553 mi_cmd_thread_select (const char *command, const char *const *argv, int argc)
555 if (argc != 1)
556 error (_("-thread-select: USAGE: threadnum."));
558 int num = value_as_long (parse_and_eval (argv[0]));
559 thread_info *thr = find_thread_global_id (num);
560 if (thr == NULL)
561 error (_("Thread ID %d not known."), num);
563 thread_select (argv[0], thr);
565 print_selected_thread_frame (current_uiout,
566 USER_SELECTED_THREAD | USER_SELECTED_FRAME);
569 void
570 mi_cmd_thread_list_ids (const char *command, const char *const *argv, int argc)
572 if (argc != 0)
573 error (_("-thread-list-ids: No arguments required."));
575 int num = 0;
576 int current_thread = -1;
578 update_thread_list ();
581 ui_out_emit_tuple tuple_emitter (current_uiout, "thread-ids");
583 for (thread_info *tp : all_non_exited_threads ())
585 if (tp->ptid == inferior_ptid)
586 current_thread = tp->global_num;
588 num++;
589 current_uiout->field_signed ("thread-id", tp->global_num);
593 if (current_thread != -1)
594 current_uiout->field_signed ("current-thread-id", current_thread);
595 current_uiout->field_signed ("number-of-threads", num);
598 void
599 mi_cmd_thread_info (const char *command, const char *const *argv, int argc)
601 if (argc != 0 && argc != 1)
602 error (_("Invalid MI command"));
604 print_thread_info (current_uiout, argv[0], -1);
607 struct collect_cores_data
609 int pid;
610 std::set<int> cores;
613 static int
614 collect_cores (struct thread_info *ti, void *xdata)
616 struct collect_cores_data *data = (struct collect_cores_data *) xdata;
618 if (ti->ptid.pid () == data->pid)
620 int core = target_core_of_thread (ti->ptid);
622 if (core != -1)
623 data->cores.insert (core);
626 return 0;
629 struct print_one_inferior_data
631 int recurse;
632 const std::set<int> *inferiors;
635 static void
636 print_one_inferior (struct inferior *inferior, bool recurse,
637 const std::set<int> &ids)
639 struct ui_out *uiout = current_uiout;
641 if (ids.empty () || (ids.find (inferior->pid) != ids.end ()))
643 struct collect_cores_data data;
644 ui_out_emit_tuple tuple_emitter (uiout, NULL);
646 uiout->field_fmt ("id", "i%d", inferior->num);
647 uiout->field_string ("type", "process");
648 if (inferior->has_exit_code)
649 uiout->field_string ("exit-code",
650 int_string (inferior->exit_code, 8, 0, 0, 1));
651 if (inferior->pid != 0)
652 uiout->field_signed ("pid", inferior->pid);
654 if (inferior->pspace->exec_filename () != nullptr)
655 uiout->field_string ("executable", inferior->pspace->exec_filename ());
657 if (inferior->pid != 0)
659 data.pid = inferior->pid;
660 iterate_over_threads (collect_cores, &data);
663 if (!data.cores.empty ())
665 ui_out_emit_list list_emitter (uiout, "cores");
667 for (int b : data.cores)
668 uiout->field_signed (NULL, b);
671 if (recurse)
672 print_thread_info (uiout, NULL, inferior->pid);
676 /* Output a field named 'cores' with a list as the value. The
677 elements of the list are obtained by splitting 'cores' on
678 comma. */
680 static void
681 output_cores (struct ui_out *uiout, const char *field_name, const char *xcores)
683 ui_out_emit_list list_emitter (uiout, field_name);
684 auto cores = make_unique_xstrdup (xcores);
685 char *p = cores.get ();
686 char *saveptr;
688 for (p = strtok_r (p, ",", &saveptr); p; p = strtok_r (NULL, ",", &saveptr))
689 uiout->field_string (NULL, p);
692 static void
693 list_available_thread_groups (const std::set<int> &ids, int recurse)
695 struct ui_out *uiout = current_uiout;
697 /* This keeps a map from integer (pid) to vector of struct osdata_item.
698 The vector contains information about all threads for the given pid. */
699 std::map<int, std::vector<osdata_item>> tree;
701 /* get_osdata will throw if it cannot return data. */
702 std::unique_ptr<osdata> data = get_osdata ("processes");
704 if (recurse)
706 std::unique_ptr<osdata> threads = get_osdata ("threads");
708 for (const osdata_item &item : threads->items)
710 const std::string *pid = get_osdata_column (item, "pid");
711 int pid_i = strtoul (pid->c_str (), NULL, 0);
713 tree[pid_i].push_back (item);
717 ui_out_emit_list list_emitter (uiout, "groups");
719 for (const osdata_item &item : data->items)
721 const std::string *pid = get_osdata_column (item, "pid");
722 const std::string *cmd = get_osdata_column (item, "command");
723 const std::string *user = get_osdata_column (item, "user");
724 const std::string *cores = get_osdata_column (item, "cores");
726 int pid_i = strtoul (pid->c_str (), NULL, 0);
728 /* At present, the target will return all available processes
729 and if information about specific ones was required, we filter
730 undesired processes here. */
731 if (!ids.empty () && ids.find (pid_i) == ids.end ())
732 continue;
734 ui_out_emit_tuple tuple_emitter (uiout, NULL);
736 uiout->field_string ("id", *pid);
737 uiout->field_string ("type", "process");
738 if (cmd)
739 uiout->field_string ("description", *cmd);
740 if (user)
741 uiout->field_string ("user", *user);
742 if (cores)
743 output_cores (uiout, "cores", cores->c_str ());
745 if (recurse)
747 auto n = tree.find (pid_i);
748 if (n != tree.end ())
750 std::vector<osdata_item> &children = n->second;
752 ui_out_emit_list thread_list_emitter (uiout, "threads");
754 for (const osdata_item &child : children)
756 ui_out_emit_tuple inner_tuple_emitter (uiout, NULL);
757 const std::string *tid = get_osdata_column (child, "tid");
758 const std::string *tcore = get_osdata_column (child, "core");
760 uiout->field_string ("id", *tid);
761 if (tcore)
762 uiout->field_string ("core", *tcore);
769 void
770 mi_cmd_list_thread_groups (const char *command, const char *const *argv,
771 int argc)
773 struct ui_out *uiout = current_uiout;
774 int available = 0;
775 int recurse = 0;
776 std::set<int> ids;
778 enum opt
780 AVAILABLE_OPT, RECURSE_OPT
782 static const struct mi_opt opts[] =
784 {"-available", AVAILABLE_OPT, 0},
785 {"-recurse", RECURSE_OPT, 1},
786 { 0, 0, 0 }
789 int oind = 0;
790 const char *oarg;
792 while (1)
794 int opt = mi_getopt ("-list-thread-groups", argc, argv, opts,
795 &oind, &oarg);
797 if (opt < 0)
798 break;
799 switch ((enum opt) opt)
801 case AVAILABLE_OPT:
802 available = 1;
803 break;
804 case RECURSE_OPT:
805 if (strcmp (oarg, "0") == 0)
807 else if (strcmp (oarg, "1") == 0)
808 recurse = 1;
809 else
810 error (_("only '0' and '1' are valid values "
811 "for the '--recurse' option"));
812 break;
816 for (; oind < argc; ++oind)
818 char *end;
819 int inf;
821 if (*(argv[oind]) != 'i')
822 error (_("invalid syntax of group id '%s'"), argv[oind]);
824 inf = strtoul (argv[oind] + 1, &end, 0);
826 if (*end != '\0')
827 error (_("invalid syntax of group id '%s'"), argv[oind]);
828 ids.insert (inf);
831 if (available)
833 list_available_thread_groups (ids, recurse);
835 else if (ids.size () == 1)
837 /* Local thread groups, single id. */
838 int id = *(ids.begin ());
839 struct inferior *inf = find_inferior_id (id);
841 if (!inf)
842 error (_("Non-existent thread group id '%d'"), id);
844 print_thread_info (uiout, NULL, inf->pid);
846 else
848 /* Local thread groups. Either no explicit ids -- and we
849 print everything, or several explicit ids. In both cases,
850 we print more than one group, and have to use 'groups'
851 as the top-level element. */
852 ui_out_emit_list list_emitter (uiout, "groups");
853 update_thread_list ();
854 for (inferior *inf : all_inferiors ())
855 print_one_inferior (inf, recurse, ids);
859 void
860 mi_cmd_data_list_register_names (const char *command, const char *const *argv,
861 int argc)
863 struct gdbarch *gdbarch;
864 struct ui_out *uiout = current_uiout;
865 int regnum, numregs;
866 int i;
868 /* Note that the test for a valid register must include checking the
869 gdbarch_register_name because gdbarch_num_regs may be allocated
870 for the union of the register sets within a family of related
871 processors. In this case, some entries of gdbarch_register_name
872 will change depending upon the particular processor being
873 debugged. */
875 gdbarch = get_current_arch ();
876 numregs = gdbarch_num_cooked_regs (gdbarch);
878 ui_out_emit_list list_emitter (uiout, "register-names");
880 if (argc == 0) /* No args, just do all the regs. */
882 for (regnum = 0;
883 regnum < numregs;
884 regnum++)
886 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
887 uiout->field_string (NULL, "");
888 else
889 uiout->field_string (NULL, gdbarch_register_name (gdbarch, regnum));
893 /* Else, list of register #s, just do listed regs. */
894 for (i = 0; i < argc; i++)
896 regnum = atoi (argv[i]);
897 if (regnum < 0 || regnum >= numregs)
898 error (_("bad register number"));
900 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
901 uiout->field_string (NULL, "");
902 else
903 uiout->field_string (NULL, gdbarch_register_name (gdbarch, regnum));
907 void
908 mi_cmd_data_list_changed_registers (const char *command,
909 const char *const *argv, int argc)
911 static std::unique_ptr<readonly_detached_regcache> this_regs;
912 struct ui_out *uiout = current_uiout;
913 std::unique_ptr<readonly_detached_regcache> prev_regs;
914 struct gdbarch *gdbarch;
915 int regnum, numregs;
916 int i;
918 /* The last time we visited this function, the current frame's
919 register contents were saved in THIS_REGS. Move THIS_REGS over
920 to PREV_REGS, and refresh THIS_REGS with the now-current register
921 contents. */
923 prev_regs = std::move (this_regs);
924 this_regs = frame_save_as_regcache (get_selected_frame (NULL));
926 /* Note that the test for a valid register must include checking the
927 gdbarch_register_name because gdbarch_num_regs may be allocated
928 for the union of the register sets within a family of related
929 processors. In this case, some entries of gdbarch_register_name
930 will change depending upon the particular processor being
931 debugged. */
933 gdbarch = this_regs->arch ();
934 numregs = gdbarch_num_cooked_regs (gdbarch);
936 ui_out_emit_list list_emitter (uiout, "changed-registers");
938 if (argc == 0)
940 /* No args, just do all the regs. */
941 for (regnum = 0;
942 regnum < numregs;
943 regnum++)
945 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
946 continue;
948 if (register_changed_p (regnum, prev_regs.get (),
949 this_regs.get ()))
950 uiout->field_signed (NULL, regnum);
954 /* Else, list of register #s, just do listed regs. */
955 for (i = 0; i < argc; i++)
957 regnum = atoi (argv[i]);
959 if (regnum >= 0
960 && regnum < numregs
961 && *gdbarch_register_name (gdbarch, regnum) != '\000')
963 if (register_changed_p (regnum, prev_regs.get (),
964 this_regs.get ()))
965 uiout->field_signed (NULL, regnum);
967 else
968 error (_("bad register number"));
972 static bool
973 register_changed_p (int regnum, readonly_detached_regcache *prev_regs,
974 readonly_detached_regcache *this_regs)
976 struct gdbarch *gdbarch = this_regs->arch ();
977 struct value *prev_value, *this_value;
979 /* First time through or after gdbarch change consider all registers
980 as changed. */
981 if (!prev_regs || prev_regs->arch () != gdbarch)
982 return true;
984 /* Get register contents and compare. */
985 prev_value = prev_regs->cooked_read_value (regnum);
986 this_value = this_regs->cooked_read_value (regnum);
987 gdb_assert (prev_value != NULL);
988 gdb_assert (this_value != NULL);
990 auto ret = !prev_value->contents_eq (0, this_value, 0,
991 register_size (gdbarch, regnum));
993 release_value (prev_value);
994 release_value (this_value);
995 return ret;
998 /* Return a list of register number and value pairs. The valid
999 arguments expected are: a letter indicating the format in which to
1000 display the registers contents. This can be one of: x
1001 (hexadecimal), d (decimal), N (natural), t (binary), o (octal), r
1002 (raw). After the format argument there can be a sequence of
1003 numbers, indicating which registers to fetch the content of. If
1004 the format is the only argument, a list of all the registers with
1005 their values is returned. */
1007 void
1008 mi_cmd_data_list_register_values (const char *command, const char *const *argv,
1009 int argc)
1011 struct ui_out *uiout = current_uiout;
1012 frame_info_ptr frame;
1013 struct gdbarch *gdbarch;
1014 int regnum, numregs, format;
1015 int i;
1016 int skip_unavailable = 0;
1017 int oind = 0;
1018 enum opt
1020 SKIP_UNAVAILABLE,
1022 static const struct mi_opt opts[] =
1024 {"-skip-unavailable", SKIP_UNAVAILABLE, 0},
1025 { 0, 0, 0 }
1028 /* Note that the test for a valid register must include checking the
1029 gdbarch_register_name because gdbarch_num_regs may be allocated
1030 for the union of the register sets within a family of related
1031 processors. In this case, some entries of gdbarch_register_name
1032 will change depending upon the particular processor being
1033 debugged. */
1035 while (1)
1037 const char *oarg;
1038 int opt = mi_getopt ("-data-list-register-values", argc, argv,
1039 opts, &oind, &oarg);
1041 if (opt < 0)
1042 break;
1043 switch ((enum opt) opt)
1045 case SKIP_UNAVAILABLE:
1046 skip_unavailable = 1;
1047 break;
1051 if (argc - oind < 1)
1052 error (_("-data-list-register-values: Usage: "
1053 "-data-list-register-values [--skip-unavailable] <format>"
1054 " [<regnum1>...<regnumN>]"));
1056 format = (int) argv[oind][0];
1058 frame = get_selected_frame (NULL);
1059 gdbarch = get_frame_arch (frame);
1060 numregs = gdbarch_num_cooked_regs (gdbarch);
1062 ui_out_emit_list list_emitter (uiout, "register-values");
1064 if (argc - oind == 1)
1066 /* No args, beside the format: do all the regs. */
1067 for (regnum = 0;
1068 regnum < numregs;
1069 regnum++)
1071 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1072 continue;
1074 output_register (frame, regnum, format, skip_unavailable);
1078 /* Else, list of register #s, just do listed regs. */
1079 for (i = 1 + oind; i < argc; i++)
1081 regnum = atoi (argv[i]);
1083 if (regnum >= 0
1084 && regnum < numregs
1085 && *gdbarch_register_name (gdbarch, regnum) != '\000')
1086 output_register (frame, regnum, format, skip_unavailable);
1087 else
1088 error (_("bad register number"));
1092 /* Output one register REGNUM's contents in the desired FORMAT. If
1093 SKIP_UNAVAILABLE is true, skip the register if it is
1094 unavailable. */
1096 static void
1097 output_register (const frame_info_ptr &frame, int regnum, int format,
1098 int skip_unavailable)
1100 struct ui_out *uiout = current_uiout;
1101 value *val
1102 = value_of_register (regnum, get_next_frame_sentinel_okay (frame));
1103 struct value_print_options opts;
1105 if (skip_unavailable && !val->entirely_available ())
1106 return;
1108 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1109 uiout->field_signed ("number", regnum);
1111 if (format == 'N')
1112 format = 0;
1114 if (format == 'r')
1115 format = 'z';
1117 string_file stb;
1119 get_formatted_print_options (&opts, format);
1120 opts.deref_ref = true;
1121 common_val_print (val, &stb, 0, &opts, current_language);
1122 uiout->field_stream ("value", stb);
1125 /* Write given values into registers. The registers and values are
1126 given as pairs. The corresponding MI command is
1127 -data-write-register-values <format>
1128 [<regnum1> <value1>...<regnumN> <valueN>] */
1129 void
1130 mi_cmd_data_write_register_values (const char *command,
1131 const char *const *argv, int argc)
1133 struct gdbarch *gdbarch;
1134 int numregs, i;
1136 /* Note that the test for a valid register must include checking the
1137 gdbarch_register_name because gdbarch_num_regs may be allocated
1138 for the union of the register sets within a family of related
1139 processors. In this case, some entries of gdbarch_register_name
1140 will change depending upon the particular processor being
1141 debugged. */
1143 regcache *regcache = get_thread_regcache (inferior_thread ());
1144 gdbarch = regcache->arch ();
1145 numregs = gdbarch_num_cooked_regs (gdbarch);
1147 if (argc == 0)
1148 error (_("-data-write-register-values: Usage: -data-write-register-"
1149 "values <format> [<regnum1> <value1>...<regnumN> <valueN>]"));
1151 if (!target_has_registers ())
1152 error (_("-data-write-register-values: No registers."));
1154 if (!(argc - 1))
1155 error (_("-data-write-register-values: No regs and values specified."));
1157 if ((argc - 1) % 2)
1158 error (_("-data-write-register-values: "
1159 "Regs and vals are not in pairs."));
1161 for (i = 1; i < argc; i = i + 2)
1163 int regnum = atoi (argv[i]);
1165 if (regnum >= 0 && regnum < numregs
1166 && *gdbarch_register_name (gdbarch, regnum) != '\0')
1168 LONGEST value;
1170 /* Get the value as a number. */
1171 value = parse_and_eval_address (argv[i + 1]);
1173 /* Write it down. */
1174 regcache_cooked_write_signed (regcache, regnum, value);
1176 else
1177 error (_("bad register number"));
1181 /* Evaluate the value of the argument. The argument is an
1182 expression. If the expression contains spaces it needs to be
1183 included in double quotes. */
1185 void
1186 mi_cmd_data_evaluate_expression (const char *command, const char *const *argv,
1187 int argc)
1189 struct value *val;
1190 struct value_print_options opts;
1191 struct ui_out *uiout = current_uiout;
1193 if (argc != 1)
1194 error (_("-data-evaluate-expression: "
1195 "Usage: -data-evaluate-expression expression"));
1197 expression_up expr = parse_expression (argv[0]);
1199 val = expr->evaluate ();
1201 string_file stb;
1203 /* Print the result of the expression evaluation. */
1204 get_user_print_options (&opts);
1205 opts.deref_ref = false;
1206 common_val_print (val, &stb, 0, &opts, current_language);
1208 uiout->field_stream ("value", stb);
1211 /* This is the -data-read-memory command.
1213 ADDR: start address of data to be dumped.
1214 WORD-FORMAT: a char indicating format for the ``word''. See
1215 the ``x'' command.
1216 WORD-SIZE: size of each ``word''; 1,2,4, or 8 bytes.
1217 NR_ROW: Number of rows.
1218 NR_COL: The number of columns (words per row).
1219 ASCHAR: (OPTIONAL) Append an ascii character dump to each row. Use
1220 ASCHAR for unprintable characters.
1222 Reads SIZE*NR_ROW*NR_COL bytes starting at ADDR from memory and
1223 displays them. Returns:
1225 {addr="...",rowN={wordN="..." ,... [,ascii="..."]}, ...}
1227 Returns:
1228 The number of bytes read is SIZE*ROW*COL. */
1230 void
1231 mi_cmd_data_read_memory (const char *command, const char *const *argv,
1232 int argc)
1234 struct gdbarch *gdbarch = get_current_arch ();
1235 struct ui_out *uiout = current_uiout;
1236 CORE_ADDR addr;
1237 long total_bytes, nr_cols, nr_rows;
1238 char word_format;
1239 struct type *word_type;
1240 long word_size;
1241 char word_asize;
1242 char aschar;
1243 int nr_bytes;
1244 long offset = 0;
1245 int oind = 0;
1246 const char *oarg;
1247 enum opt
1249 OFFSET_OPT
1251 static const struct mi_opt opts[] =
1253 {"o", OFFSET_OPT, 1},
1254 { 0, 0, 0 }
1257 while (1)
1259 int opt = mi_getopt ("-data-read-memory", argc, argv, opts,
1260 &oind, &oarg);
1262 if (opt < 0)
1263 break;
1264 switch ((enum opt) opt)
1266 case OFFSET_OPT:
1267 offset = atol (oarg);
1268 break;
1271 argv += oind;
1272 argc -= oind;
1274 if (argc < 5 || argc > 6)
1275 error (_("-data-read-memory: Usage: "
1276 "ADDR WORD-FORMAT WORD-SIZE NR-ROWS NR-COLS [ASCHAR]."));
1278 /* Extract all the arguments. */
1280 /* Start address of the memory dump. */
1281 addr = parse_and_eval_address (argv[0]) + offset;
1282 /* The format character to use when displaying a memory word. See
1283 the ``x'' command. */
1284 word_format = argv[1][0];
1285 /* The size of the memory word. */
1286 word_size = atol (argv[2]);
1287 switch (word_size)
1289 case 1:
1290 word_type = builtin_type (gdbarch)->builtin_int8;
1291 word_asize = 'b';
1292 break;
1293 case 2:
1294 word_type = builtin_type (gdbarch)->builtin_int16;
1295 word_asize = 'h';
1296 break;
1297 case 4:
1298 word_type = builtin_type (gdbarch)->builtin_int32;
1299 word_asize = 'w';
1300 break;
1301 case 8:
1302 word_type = builtin_type (gdbarch)->builtin_int64;
1303 word_asize = 'g';
1304 break;
1305 default:
1306 word_type = builtin_type (gdbarch)->builtin_int8;
1307 word_asize = 'b';
1309 /* The number of rows. */
1310 nr_rows = atol (argv[3]);
1311 if (nr_rows <= 0)
1312 error (_("-data-read-memory: invalid number of rows."));
1314 /* Number of bytes per row. */
1315 nr_cols = atol (argv[4]);
1316 if (nr_cols <= 0)
1317 error (_("-data-read-memory: invalid number of columns."));
1319 /* The un-printable character when printing ascii. */
1320 if (argc == 6)
1321 aschar = *argv[5];
1322 else
1323 aschar = 0;
1325 /* Create a buffer and read it in. */
1326 total_bytes = word_size * nr_rows * nr_cols;
1328 gdb::byte_vector mbuf (total_bytes);
1330 nr_bytes = target_read (current_inferior ()->top_target (),
1331 TARGET_OBJECT_MEMORY, NULL,
1332 mbuf.data (), addr, total_bytes);
1333 if (nr_bytes <= 0)
1334 error (_("Unable to read memory."));
1336 /* Output the header information. */
1337 uiout->field_core_addr ("addr", gdbarch, addr);
1338 uiout->field_signed ("nr-bytes", nr_bytes);
1339 uiout->field_signed ("total-bytes", total_bytes);
1340 uiout->field_core_addr ("next-row", gdbarch, addr + word_size * nr_cols);
1341 uiout->field_core_addr ("prev-row", gdbarch, addr - word_size * nr_cols);
1342 uiout->field_core_addr ("next-page", gdbarch, addr + total_bytes);
1343 uiout->field_core_addr ("prev-page", gdbarch, addr - total_bytes);
1345 /* Build the result as a two dimensional table. */
1347 int row;
1348 int row_byte;
1350 string_file stream;
1352 ui_out_emit_list list_emitter (uiout, "memory");
1353 for (row = 0, row_byte = 0;
1354 row < nr_rows;
1355 row++, row_byte += nr_cols * word_size)
1357 int col;
1358 int col_byte;
1359 struct value_print_options print_opts;
1361 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1362 uiout->field_core_addr ("addr", gdbarch, addr + row_byte);
1363 /* ui_out_field_core_addr_symbolic (uiout, "saddr", addr +
1364 row_byte); */
1366 ui_out_emit_list list_data_emitter (uiout, "data");
1367 get_formatted_print_options (&print_opts, word_format);
1368 for (col = 0, col_byte = row_byte;
1369 col < nr_cols;
1370 col++, col_byte += word_size)
1372 if (col_byte + word_size > nr_bytes)
1374 uiout->field_string (NULL, "N/A");
1376 else
1378 stream.clear ();
1379 print_scalar_formatted (&mbuf[col_byte], word_type,
1380 &print_opts, word_asize, &stream);
1381 uiout->field_stream (NULL, stream);
1386 if (aschar)
1388 int byte;
1390 stream.clear ();
1391 for (byte = row_byte;
1392 byte < row_byte + word_size * nr_cols; byte++)
1394 if (byte >= nr_bytes)
1395 stream.putc ('X');
1396 else if (mbuf[byte] < 32 || mbuf[byte] > 126)
1397 stream.putc (aschar);
1398 else
1399 stream.putc (mbuf[byte]);
1401 uiout->field_stream ("ascii", stream);
1407 void
1408 mi_cmd_data_read_memory_bytes (const char *command, const char *const *argv,
1409 int argc)
1411 struct gdbarch *gdbarch = get_current_arch ();
1412 struct ui_out *uiout = current_uiout;
1413 CORE_ADDR addr;
1414 LONGEST length;
1415 long offset = 0;
1416 int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
1417 int oind = 0;
1418 const char *oarg;
1419 enum opt
1421 OFFSET_OPT
1423 static const struct mi_opt opts[] =
1425 {"o", OFFSET_OPT, 1},
1426 { 0, 0, 0 }
1429 while (1)
1431 int opt = mi_getopt ("-data-read-memory-bytes", argc, argv, opts,
1432 &oind, &oarg);
1433 if (opt < 0)
1434 break;
1435 switch ((enum opt) opt)
1437 case OFFSET_OPT:
1438 offset = atol (oarg);
1439 break;
1442 argv += oind;
1443 argc -= oind;
1445 if (argc != 2)
1446 error (_("Usage: [ -o OFFSET ] ADDR LENGTH."));
1448 addr = parse_and_eval_address (argv[0]) + offset;
1449 length = atol (argv[1]);
1451 std::vector<memory_read_result> result
1452 = read_memory_robust (current_inferior ()->top_target (), addr, length);
1454 if (result.size () == 0)
1455 error (_("Unable to read memory."));
1457 ui_out_emit_list list_emitter (uiout, "memory");
1458 for (const memory_read_result &read_result : result)
1460 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1462 uiout->field_core_addr ("begin", gdbarch, read_result.begin);
1463 uiout->field_core_addr ("offset", gdbarch, read_result.begin - addr);
1464 uiout->field_core_addr ("end", gdbarch, read_result.end);
1466 std::string data = bin2hex (read_result.data.get (),
1467 (read_result.end - read_result.begin)
1468 * unit_size);
1469 uiout->field_string ("contents", data);
1473 /* Implementation of the -data-write_memory command.
1475 COLUMN_OFFSET: optional argument. Must be preceded by '-o'. The
1476 offset from the beginning of the memory grid row where the cell to
1477 be written is.
1478 ADDR: start address of the row in the memory grid where the memory
1479 cell is, if OFFSET_COLUMN is specified. Otherwise, the address of
1480 the location to write to.
1481 FORMAT: a char indicating format for the ``word''. See
1482 the ``x'' command.
1483 WORD_SIZE: size of each ``word''; 1,2,4, or 8 bytes
1484 VALUE: value to be written into the memory address.
1486 Writes VALUE into ADDR + (COLUMN_OFFSET * WORD_SIZE).
1488 Prints nothing. */
1490 void
1491 mi_cmd_data_write_memory (const char *command, const char *const *argv,
1492 int argc)
1494 struct gdbarch *gdbarch = get_current_arch ();
1495 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1496 CORE_ADDR addr;
1497 long word_size;
1498 /* FIXME: ezannoni 2000-02-17 LONGEST could possibly not be big
1499 enough when using a compiler other than GCC. */
1500 LONGEST value;
1501 long offset = 0;
1502 int oind = 0;
1503 const char *oarg;
1504 enum opt
1506 OFFSET_OPT
1508 static const struct mi_opt opts[] =
1510 {"o", OFFSET_OPT, 1},
1511 { 0, 0, 0 }
1514 while (1)
1516 int opt = mi_getopt ("-data-write-memory", argc, argv, opts,
1517 &oind, &oarg);
1519 if (opt < 0)
1520 break;
1521 switch ((enum opt) opt)
1523 case OFFSET_OPT:
1524 offset = atol (oarg);
1525 break;
1528 argv += oind;
1529 argc -= oind;
1531 if (argc != 4)
1532 error (_("-data-write-memory: Usage: "
1533 "[-o COLUMN_OFFSET] ADDR FORMAT WORD-SIZE VALUE."));
1535 /* Extract all the arguments. */
1536 /* Start address of the memory dump. */
1537 addr = parse_and_eval_address (argv[0]);
1538 /* The size of the memory word. */
1539 word_size = atol (argv[2]);
1541 /* Calculate the real address of the write destination. */
1542 addr += (offset * word_size);
1544 /* Get the value as a number. */
1545 value = parse_and_eval_address (argv[3]);
1546 /* Get the value into an array. */
1547 gdb::byte_vector buffer (word_size);
1548 store_signed_integer (buffer.data (), word_size, byte_order, value);
1549 /* Write it down to memory. */
1550 write_memory_with_notification (addr, buffer.data (), word_size);
1553 /* Implementation of the -data-write-memory-bytes command.
1555 ADDR: start address
1556 DATA: string of bytes to write at that address
1557 COUNT: number of bytes to be filled (decimal integer). */
1559 void
1560 mi_cmd_data_write_memory_bytes (const char *command, const char *const *argv,
1561 int argc)
1563 CORE_ADDR addr;
1564 const char *cdata;
1565 size_t len_hex, len_bytes, len_units, i, steps, remaining_units;
1566 long int count_units;
1567 int unit_size;
1569 if (argc != 2 && argc != 3)
1570 error (_("Usage: ADDR DATA [COUNT]."));
1572 addr = parse_and_eval_address (argv[0]);
1573 cdata = argv[1];
1574 len_hex = strlen (cdata);
1575 unit_size = gdbarch_addressable_memory_unit_size (get_current_arch ());
1577 if (len_hex % (unit_size * 2) != 0)
1578 error (_("Hex-encoded '%s' must represent an integral number of "
1579 "addressable memory units."),
1580 cdata);
1582 len_bytes = len_hex / 2;
1583 len_units = len_bytes / unit_size;
1585 if (argc == 3)
1586 count_units = strtoul (argv[2], NULL, 10);
1587 else
1588 count_units = len_units;
1590 gdb::byte_vector databuf (len_bytes);
1592 for (i = 0; i < len_bytes; ++i)
1594 int x;
1595 if (sscanf (cdata + i * 2, "%02x", &x) != 1)
1596 error (_("Invalid argument"));
1597 databuf[i] = (gdb_byte) x;
1600 gdb::byte_vector data;
1601 if (len_units < count_units)
1603 /* Pattern is made of less units than count:
1604 repeat pattern to fill memory. */
1605 data = gdb::byte_vector (count_units * unit_size);
1607 /* Number of times the pattern is entirely repeated. */
1608 steps = count_units / len_units;
1609 /* Number of remaining addressable memory units. */
1610 remaining_units = count_units % len_units;
1611 for (i = 0; i < steps; i++)
1612 memcpy (&data[i * len_bytes], &databuf[0], len_bytes);
1614 if (remaining_units > 0)
1615 memcpy (&data[steps * len_bytes], &databuf[0],
1616 remaining_units * unit_size);
1618 else
1620 /* Pattern is longer than or equal to count:
1621 just copy count addressable memory units. */
1622 data = std::move (databuf);
1625 write_memory_with_notification (addr, data.data (), count_units);
1628 void
1629 mi_cmd_enable_timings (const char *command, const char *const *argv, int argc)
1631 if (argc == 0)
1632 do_timings = 1;
1633 else if (argc == 1)
1635 if (strcmp (argv[0], "yes") == 0)
1636 do_timings = 1;
1637 else if (strcmp (argv[0], "no") == 0)
1638 do_timings = 0;
1639 else
1640 goto usage_error;
1642 else
1643 goto usage_error;
1645 return;
1647 usage_error:
1648 error (_("-enable-timings: Usage: %s {yes|no}"), command);
1651 void
1652 mi_cmd_list_features (const char *command, const char *const *argv, int argc)
1654 if (argc == 0)
1656 struct ui_out *uiout = current_uiout;
1658 ui_out_emit_list list_emitter (uiout, "features");
1659 uiout->field_string (NULL, "frozen-varobjs");
1660 uiout->field_string (NULL, "pending-breakpoints");
1661 uiout->field_string (NULL, "thread-info");
1662 uiout->field_string (NULL, "data-read-memory-bytes");
1663 uiout->field_string (NULL, "breakpoint-notifications");
1664 uiout->field_string (NULL, "ada-task-info");
1665 uiout->field_string (NULL, "language-option");
1666 uiout->field_string (NULL, "info-gdb-mi-command");
1667 uiout->field_string (NULL, "undefined-command-error-code");
1668 uiout->field_string (NULL, "exec-run-start-option");
1669 uiout->field_string (NULL, "data-disassemble-a-option");
1670 uiout->field_string (NULL, "simple-values-ref-types");
1672 if (ext_lang_initialized_p (get_ext_lang_defn (EXT_LANG_PYTHON)))
1673 uiout->field_string (NULL, "python");
1675 return;
1678 error (_("-list-features should be passed no arguments"));
1681 void
1682 mi_cmd_list_target_features (const char *command, const char *const *argv,
1683 int argc)
1685 if (argc == 0)
1687 struct ui_out *uiout = current_uiout;
1689 ui_out_emit_list list_emitter (uiout, "features");
1690 if (mi_async_p ())
1691 uiout->field_string (NULL, "async");
1692 if (target_can_execute_reverse ())
1693 uiout->field_string (NULL, "reverse");
1694 return;
1697 error (_("-list-target-features should be passed no arguments"));
1700 void
1701 mi_cmd_add_inferior (const char *command, const char *const *argv, int argc)
1703 bool no_connection = false;
1705 /* Parse the command options. */
1706 enum opt
1708 NO_CONNECTION_OPT,
1710 static const struct mi_opt opts[] =
1712 {"-no-connection", NO_CONNECTION_OPT, 0},
1713 {NULL, 0, 0},
1716 int oind = 0;
1717 const char *oarg;
1719 while (1)
1721 int opt = mi_getopt ("-add-inferior", argc, argv, opts, &oind, &oarg);
1723 if (opt < 0)
1724 break;
1725 switch ((enum opt) opt)
1727 case NO_CONNECTION_OPT:
1728 no_connection = true;
1729 break;
1733 scoped_restore_current_pspace_and_thread restore_pspace_thread;
1735 inferior *inf = add_inferior_with_spaces ();
1737 switch_to_inferior_and_push_target (inf, no_connection,
1738 current_inferior ());
1740 current_uiout->field_fmt ("inferior", "i%d", inf->num);
1742 process_stratum_target *proc_target = inf->process_target ();
1744 if (proc_target != nullptr)
1746 ui_out_emit_tuple tuple_emitter (current_uiout, "connection");
1747 current_uiout->field_unsigned ("number", proc_target->connection_number);
1748 current_uiout->field_string ("name", proc_target->shortname ());
1752 void
1753 mi_cmd_remove_inferior (const char *command, const char *const *argv, int argc)
1755 int id;
1756 struct inferior *inf_to_remove;
1758 if (argc != 1)
1759 error (_("-remove-inferior should be passed a single argument"));
1761 id = mi_parse_thread_group_id (argv[0]);
1763 inf_to_remove = find_inferior_id (id);
1764 if (inf_to_remove == NULL)
1765 error (_("the specified thread group does not exist"));
1767 if (inf_to_remove->pid != 0)
1768 error (_("cannot remove an active inferior"));
1770 if (inf_to_remove == current_inferior ())
1772 struct thread_info *tp = 0;
1773 struct inferior *new_inferior = NULL;
1775 for (inferior *inf : all_inferiors ())
1777 if (inf != inf_to_remove)
1778 new_inferior = inf;
1781 if (new_inferior == NULL)
1782 error (_("Cannot remove last inferior"));
1784 set_current_inferior (new_inferior);
1785 if (new_inferior->pid != 0)
1786 tp = any_thread_of_inferior (new_inferior);
1787 if (tp != NULL)
1788 switch_to_thread (tp);
1789 else
1790 switch_to_no_thread ();
1791 set_current_program_space (new_inferior->pspace);
1794 delete_inferior (inf_to_remove);
1799 /* Execute a command within a safe environment.
1800 Return <0 for error; >=0 for ok.
1802 args->action will tell mi_execute_command what action
1803 to perform after the given command has executed (display/suppress
1804 prompt, display error). */
1806 static void
1807 captured_mi_execute_command (struct mi_interp *mi, struct ui_out *uiout,
1808 struct mi_parse *context)
1810 if (do_timings)
1811 current_command_ts = context->cmd_start;
1813 scoped_restore save_token
1814 = make_scoped_restore (&mi->current_token, context->token.c_str ());
1816 mi->running_result_record_printed = 0;
1817 mi->mi_proceeded = 0;
1818 switch (context->op)
1820 case MI_COMMAND:
1821 /* A MI command was read from the input stream. */
1822 if (mi_debug_p)
1823 gdb_printf (gdb_stdlog,
1824 " token=`%s' command=`%s' args=`%s'\n",
1825 context->token.c_str (), context->command.get (),
1826 context->args ());
1828 mi_cmd_execute (context);
1830 /* Print the result if there were no errors.
1832 Remember that on the way out of executing a command, you have
1833 to directly use the mi_interp's uiout, since the command
1834 could have reset the interpreter, in which case the current
1835 uiout will most likely crash in the mi_out_* routines. */
1836 if (!mi->running_result_record_printed)
1838 gdb_puts (context->token.c_str (), mi->raw_stdout);
1839 /* There's no particularly good reason why target-connect results
1840 in not ^done. Should kill ^connected for MI3. */
1841 gdb_puts (strcmp (context->command.get (), "target-select") == 0
1842 ? "^connected" : "^done", mi->raw_stdout);
1843 mi_out_put (uiout, mi->raw_stdout);
1844 mi_out_rewind (uiout);
1845 mi_print_timing_maybe (mi->raw_stdout);
1846 gdb_puts ("\n", mi->raw_stdout);
1848 else
1849 /* The command does not want anything to be printed. In that
1850 case, the command probably should not have written anything
1851 to uiout, but in case it has written something, discard it. */
1852 mi_out_rewind (uiout);
1853 break;
1855 case CLI_COMMAND:
1857 const char *argv[2];
1859 /* A CLI command was read from the input stream. */
1860 /* This "feature" will be removed as soon as we have a
1861 complete set of mi commands. */
1862 /* Echo the command on the console. */
1863 gdb_printf (gdb_stdlog, "%s\n", context->command.get ());
1864 /* Call the "console" interpreter. */
1865 argv[0] = INTERP_CONSOLE;
1866 argv[1] = context->command.get ();
1867 mi_cmd_interpreter_exec ("-interpreter-exec", argv, 2);
1869 /* If we changed interpreters, DON'T print out anything. */
1870 if (current_interp_named_p (INTERP_MI)
1871 || current_interp_named_p (INTERP_MI2)
1872 || current_interp_named_p (INTERP_MI3)
1873 || current_interp_named_p (INTERP_MI4))
1875 if (!mi->running_result_record_printed)
1877 gdb_puts (context->token.c_str (), mi->raw_stdout);
1878 gdb_puts ("^done", mi->raw_stdout);
1879 mi_out_put (uiout, mi->raw_stdout);
1880 mi_out_rewind (uiout);
1881 mi_print_timing_maybe (mi->raw_stdout);
1882 gdb_puts ("\n", mi->raw_stdout);
1884 else
1885 mi_out_rewind (uiout);
1887 break;
1892 /* Print a gdb exception to the MI output stream. */
1894 static void
1895 mi_print_exception (struct mi_interp *mi, const char *token,
1896 const struct gdb_exception &exception)
1898 gdb_puts (token, mi->raw_stdout);
1899 gdb_puts ("^error,msg=\"", mi->raw_stdout);
1900 if (exception.message == NULL)
1901 gdb_puts ("unknown error", mi->raw_stdout);
1902 else
1903 mi->raw_stdout->putstr (exception.what (), '"');
1904 gdb_puts ("\"", mi->raw_stdout);
1906 switch (exception.error)
1908 case UNDEFINED_COMMAND_ERROR:
1909 gdb_puts (",code=\"undefined-command\"", mi->raw_stdout);
1910 break;
1913 gdb_puts ("\n", mi->raw_stdout);
1916 void
1917 mi_execute_command (const char *cmd, int from_tty)
1919 std::string token;
1920 std::unique_ptr<struct mi_parse> command;
1922 /* This is to handle EOF (^D). We just quit gdb. */
1923 /* FIXME: we should call some API function here. */
1924 if (cmd == 0)
1925 quit_force (NULL, from_tty);
1927 target_log_command (cmd);
1929 struct mi_interp *mi
1930 = gdb::checked_static_cast<mi_interp *> (command_interp ());
1933 command = std::make_unique<mi_parse> (cmd, &token);
1935 catch (const gdb_exception &exception)
1937 mi_print_exception (mi, token.c_str (), exception);
1940 if (command != NULL)
1942 command->token = std::move (token);
1944 if (do_timings)
1946 command->cmd_start = new mi_timestamp ();
1947 timestamp (command->cmd_start);
1952 captured_mi_execute_command (mi, current_uiout, command.get ());
1954 catch (const gdb_exception &result)
1956 /* Like in start_event_loop, enable input and force display
1957 of the prompt. Otherwise, any command that calls
1958 async_disable_stdin, and then throws, will leave input
1959 disabled. */
1960 async_enable_stdin ();
1961 current_ui->prompt_state = PROMPT_NEEDED;
1963 /* The command execution failed and error() was called
1964 somewhere. */
1965 mi_print_exception (mi, command->token.c_str (), result);
1966 mi_out_rewind (current_uiout);
1968 /* Throw to a higher level catch for SIGTERM sent to GDB. */
1969 if (result.reason == RETURN_FORCED_QUIT)
1970 throw;
1973 bpstat_do_actions ();
1978 /* See mi-cmds.h. */
1980 void
1981 mi_execute_command (mi_parse *context)
1983 if (context->op != MI_COMMAND)
1984 error (_("Command is not an MI command"));
1986 mi_interp *mi = as_mi_interp (current_interpreter ());
1988 /* The current interpreter may not be MI, for instance when using
1989 the Python gdb.execute_mi function. */
1990 if (mi != nullptr)
1991 scoped_restore save_token = make_scoped_restore (&mi->current_token,
1992 context->token.c_str ());
1994 scoped_restore save_debug = make_scoped_restore (&mi_debug_p, 0);
1996 mi_cmd_execute (context);
1999 /* Captures the current user selected context state, that is the current
2000 thread and frame. Later we can then check if the user selected context
2001 has changed at all. */
2003 struct user_selected_context
2005 /* Constructor. */
2006 user_selected_context ()
2007 : m_previous_ptid (inferior_ptid)
2009 save_selected_frame (&m_previous_frame_id, &m_previous_frame_level);
2012 /* Return true if the user selected context has changed since this object
2013 was created. */
2014 bool has_changed () const
2016 /* Did the selected thread change? */
2017 if (m_previous_ptid != null_ptid && inferior_ptid != null_ptid
2018 && m_previous_ptid != inferior_ptid)
2019 return true;
2021 /* Grab details of the currently selected frame, for comparison. */
2022 frame_id current_frame_id;
2023 int current_frame_level;
2024 save_selected_frame (&current_frame_id, &current_frame_level);
2026 /* Did the selected frame level change? */
2027 if (current_frame_level != m_previous_frame_level)
2028 return true;
2030 /* Did the selected frame id change? If the innermost frame is
2031 selected then the level will be -1, and the frame-id will be
2032 null_frame_id. As comparing null_frame_id with itself always
2033 reports not-equal, we only do the equality test if we have something
2034 other than the innermost frame selected. */
2035 if (current_frame_level != -1
2036 && current_frame_id != m_previous_frame_id)
2037 return true;
2039 /* Nothing changed! */
2040 return false;
2042 private:
2043 /* The previously selected thread. This might be null_ptid if there was
2044 no previously selected thread. */
2045 ptid_t m_previous_ptid;
2047 /* The previously selected frame. If the innermost frame is selected, or
2048 no frame is selected, then the frame_id will be null_frame_id, and the
2049 level will be -1. */
2050 frame_id m_previous_frame_id;
2051 int m_previous_frame_level;
2054 static void
2055 mi_cmd_execute (struct mi_parse *parse)
2057 scoped_value_mark cleanup = prepare_execute_command ();
2059 if (parse->all && parse->thread_group != -1)
2060 error (_("Cannot specify --thread-group together with --all"));
2062 if (parse->all && parse->thread != -1)
2063 error (_("Cannot specify --thread together with --all"));
2065 if (parse->thread_group != -1 && parse->thread != -1)
2066 error (_("Cannot specify --thread together with --thread-group"));
2068 if (parse->frame != -1 && parse->thread == -1)
2069 error (_("Cannot specify --frame without --thread"));
2071 if (parse->thread_group != -1)
2073 struct inferior *inf = find_inferior_id (parse->thread_group);
2074 struct thread_info *tp = 0;
2076 if (!inf)
2077 error (_("Invalid thread group for the --thread-group option"));
2079 set_current_inferior (inf);
2080 /* This behaviour means that if --thread-group option identifies
2081 an inferior with multiple threads, then a random one will be
2082 picked. This is not a problem -- frontend should always
2083 provide --thread if it wishes to operate on a specific
2084 thread. */
2085 if (inf->pid != 0)
2086 tp = any_live_thread_of_inferior (inf);
2087 if (tp != NULL)
2088 switch_to_thread (tp);
2089 else
2090 switch_to_no_thread ();
2091 set_current_program_space (inf->pspace);
2094 user_selected_context current_user_selected_context;
2096 std::optional<scoped_restore_current_thread> thread_saver;
2097 if (parse->thread != -1)
2099 thread_info *tp = find_thread_global_id (parse->thread);
2101 if (tp == NULL)
2102 error (_("Invalid thread id: %d"), parse->thread);
2104 if (tp->state == THREAD_EXITED)
2105 error (_("Thread id: %d has terminated"), parse->thread);
2107 if (parse->cmd->preserve_user_selected_context ())
2108 thread_saver.emplace ();
2110 switch_to_thread (tp);
2113 std::optional<scoped_restore_selected_frame> frame_saver;
2114 if (parse->frame != -1)
2116 frame_info_ptr fid;
2117 int frame = parse->frame;
2119 fid = find_relative_frame (get_current_frame (), &frame);
2120 if (frame == 0)
2122 if (parse->cmd->preserve_user_selected_context ())
2123 frame_saver.emplace ();
2125 select_frame (fid);
2127 else
2128 error (_("Invalid frame id: %d"), frame);
2131 std::optional<scoped_restore_current_language> lang_saver;
2132 if (parse->language != language_unknown)
2133 lang_saver.emplace (parse->language);
2135 current_context = parse;
2137 gdb_assert (parse->cmd != nullptr);
2139 std::optional<scoped_restore_tmpl<int>> restore_suppress_notification
2140 = parse->cmd->do_suppress_notification ();
2142 parse->cmd->invoke (parse);
2144 if (!parse->cmd->preserve_user_selected_context ()
2145 && current_user_selected_context.has_changed ())
2146 interps_notify_user_selected_context_changed
2147 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
2150 /* See mi-main.h. */
2152 void
2153 mi_execute_cli_command (const char *cmd, bool args_p, const char *args)
2155 if (cmd != nullptr)
2157 std::string run (cmd);
2159 if (args_p)
2160 run = run + " " + args;
2161 else
2162 gdb_assert (args == nullptr);
2164 if (mi_debug_p)
2165 gdb_printf (gdb_stdlog, "cli=%s run=%s\n",
2166 cmd, run.c_str ());
2168 execute_command (run.c_str (), 0 /* from_tty */ );
2172 void
2173 mi_execute_async_cli_command (const char *cli_command, const char *const *argv,
2174 int argc)
2176 std::string run = cli_command;
2178 if (argc)
2179 run = run + " " + *argv;
2180 if (mi_async_p ())
2181 run += "&";
2183 execute_command (run.c_str (), 0 /* from_tty */ );
2186 void
2187 mi_load_progress (const char *section_name,
2188 unsigned long sent_so_far,
2189 unsigned long total_section,
2190 unsigned long total_sent,
2191 unsigned long grand_total)
2193 using namespace std::chrono;
2194 static steady_clock::time_point last_update;
2195 static char *previous_sect_name = NULL;
2196 int new_section;
2197 struct mi_interp *mi = as_mi_interp (current_interpreter ());
2199 /* If the current interpreter is not an MI interpreter, then just
2200 don't bother printing anything. */
2201 if (mi == nullptr)
2202 return;
2204 /* This function is called through deprecated_show_load_progress
2205 which means uiout may not be correct. Fix it for the duration
2206 of this function. */
2208 auto uiout = mi_out_new (current_interpreter ()->name ());
2209 if (uiout == nullptr)
2210 return;
2212 scoped_restore save_uiout
2213 = make_scoped_restore (&current_uiout, uiout.get ());
2215 new_section = (previous_sect_name ?
2216 strcmp (previous_sect_name, section_name) : 1);
2217 if (new_section)
2219 xfree (previous_sect_name);
2220 previous_sect_name = xstrdup (section_name);
2222 if (mi->current_token)
2223 gdb_puts (mi->current_token, mi->raw_stdout);
2224 gdb_puts ("+download", mi->raw_stdout);
2226 ui_out_emit_tuple tuple_emitter (uiout.get (), NULL);
2227 uiout->field_string ("section", section_name);
2228 uiout->field_signed ("section-size", total_section);
2229 uiout->field_signed ("total-size", grand_total);
2231 mi_out_put (uiout.get (), mi->raw_stdout);
2232 gdb_puts ("\n", mi->raw_stdout);
2233 gdb_flush (mi->raw_stdout);
2236 steady_clock::time_point time_now = steady_clock::now ();
2237 if (time_now - last_update > milliseconds (500))
2239 last_update = time_now;
2240 if (mi->current_token)
2241 gdb_puts (mi->current_token, mi->raw_stdout);
2242 gdb_puts ("+download", mi->raw_stdout);
2244 ui_out_emit_tuple tuple_emitter (uiout.get (), NULL);
2245 uiout->field_string ("section", section_name);
2246 uiout->field_signed ("section-sent", sent_so_far);
2247 uiout->field_signed ("section-size", total_section);
2248 uiout->field_signed ("total-sent", total_sent);
2249 uiout->field_signed ("total-size", grand_total);
2251 mi_out_put (uiout.get (), mi->raw_stdout);
2252 gdb_puts ("\n", mi->raw_stdout);
2253 gdb_flush (mi->raw_stdout);
2257 static void
2258 timestamp (struct mi_timestamp *tv)
2260 using namespace std::chrono;
2262 tv->wallclock = steady_clock::now ();
2263 run_time_clock::now (tv->utime, tv->stime);
2266 static void
2267 print_diff_now (struct ui_file *file, struct mi_timestamp *start)
2269 struct mi_timestamp now;
2271 timestamp (&now);
2272 print_diff (file, start, &now);
2275 void
2276 mi_print_timing_maybe (struct ui_file *file)
2278 /* If the command is -enable-timing then do_timings may be true
2279 whilst current_command_ts is not initialized. */
2280 if (do_timings && current_command_ts)
2281 print_diff_now (file, current_command_ts);
2284 static void
2285 print_diff (struct ui_file *file, struct mi_timestamp *start,
2286 struct mi_timestamp *end)
2288 using namespace std::chrono;
2290 duration<double> wallclock = end->wallclock - start->wallclock;
2291 duration<double> utime = end->utime - start->utime;
2292 duration<double> stime = end->stime - start->stime;
2294 gdb_printf
2295 (file,
2296 ",time={wallclock=\"%0.5f\",user=\"%0.5f\",system=\"%0.5f\"}",
2297 wallclock.count (), utime.count (), stime.count ());
2300 void
2301 mi_cmd_trace_define_variable (const char *command, const char *const *argv,
2302 int argc)
2304 LONGEST initval = 0;
2305 struct trace_state_variable *tsv;
2306 const char *name;
2308 if (argc != 1 && argc != 2)
2309 error (_("Usage: -trace-define-variable VARIABLE [VALUE]"));
2311 name = argv[0];
2312 if (*name++ != '$')
2313 error (_("Name of trace variable should start with '$'"));
2315 validate_trace_state_variable_name (name);
2317 tsv = find_trace_state_variable (name);
2318 if (!tsv)
2319 tsv = create_trace_state_variable (name);
2321 if (argc == 2)
2322 initval = value_as_long (parse_and_eval (argv[1]));
2324 tsv->initial_value = initval;
2327 void
2328 mi_cmd_trace_list_variables (const char *command, const char *const *argv,
2329 int argc)
2331 if (argc != 0)
2332 error (_("-trace-list-variables: no arguments allowed"));
2334 tvariables_info_1 ();
2337 void
2338 mi_cmd_trace_find (const char *command, const char *const *argv, int argc)
2340 const char *mode;
2342 if (argc == 0)
2343 error (_("trace selection mode is required"));
2345 mode = argv[0];
2347 if (strcmp (mode, "none") == 0)
2349 tfind_1 (tfind_number, -1, 0, 0, 0);
2350 return;
2353 check_trace_running (current_trace_status ());
2355 if (strcmp (mode, "frame-number") == 0)
2357 if (argc != 2)
2358 error (_("frame number is required"));
2359 tfind_1 (tfind_number, atoi (argv[1]), 0, 0, 0);
2361 else if (strcmp (mode, "tracepoint-number") == 0)
2363 if (argc != 2)
2364 error (_("tracepoint number is required"));
2365 tfind_1 (tfind_tp, atoi (argv[1]), 0, 0, 0);
2367 else if (strcmp (mode, "pc") == 0)
2369 if (argc != 2)
2370 error (_("PC is required"));
2371 tfind_1 (tfind_pc, 0, parse_and_eval_address (argv[1]), 0, 0);
2373 else if (strcmp (mode, "pc-inside-range") == 0)
2375 if (argc != 3)
2376 error (_("Start and end PC are required"));
2377 tfind_1 (tfind_range, 0, parse_and_eval_address (argv[1]),
2378 parse_and_eval_address (argv[2]), 0);
2380 else if (strcmp (mode, "pc-outside-range") == 0)
2382 if (argc != 3)
2383 error (_("Start and end PC are required"));
2384 tfind_1 (tfind_outside, 0, parse_and_eval_address (argv[1]),
2385 parse_and_eval_address (argv[2]), 0);
2387 else if (strcmp (mode, "line") == 0)
2389 if (argc != 2)
2390 error (_("Line is required"));
2392 std::vector<symtab_and_line> sals
2393 = decode_line_with_current_source (argv[1],
2394 DECODE_LINE_FUNFIRSTLINE);
2395 const symtab_and_line &sal = sals[0];
2397 if (sal.symtab == 0)
2398 error (_("Could not find the specified line"));
2400 CORE_ADDR start_pc, end_pc;
2401 if (sal.line > 0 && find_line_pc_range (sal, &start_pc, &end_pc))
2402 tfind_1 (tfind_range, 0, start_pc, end_pc - 1, 0);
2403 else
2404 error (_("Could not find the specified line"));
2406 else
2407 error (_("Invalid mode '%s'"), mode);
2409 if (has_stack_frames () || get_traceframe_number () >= 0)
2410 print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS, 1);
2413 void
2414 mi_cmd_trace_save (const char *command, const char *const *argv, int argc)
2416 int target_saves = 0;
2417 int generate_ctf = 0;
2418 const char *filename;
2419 int oind = 0;
2420 const char *oarg;
2422 enum opt
2424 TARGET_SAVE_OPT, CTF_OPT
2426 static const struct mi_opt opts[] =
2428 {"r", TARGET_SAVE_OPT, 0},
2429 {"ctf", CTF_OPT, 0},
2430 { 0, 0, 0 }
2433 while (1)
2435 int opt = mi_getopt ("-trace-save", argc, argv, opts,
2436 &oind, &oarg);
2438 if (opt < 0)
2439 break;
2440 switch ((enum opt) opt)
2442 case TARGET_SAVE_OPT:
2443 target_saves = 1;
2444 break;
2445 case CTF_OPT:
2446 generate_ctf = 1;
2447 break;
2451 if (argc - oind != 1)
2452 error (_("Exactly one argument required "
2453 "(file in which to save trace data)"));
2455 filename = argv[oind];
2457 if (generate_ctf)
2458 trace_save_ctf (filename, target_saves);
2459 else
2460 trace_save_tfile (filename, target_saves);
2463 void
2464 mi_cmd_trace_start (const char *command, const char *const *argv, int argc)
2466 start_tracing (NULL);
2469 void
2470 mi_cmd_trace_status (const char *command, const char *const *argv, int argc)
2472 trace_status_mi (0);
2475 void
2476 mi_cmd_trace_stop (const char *command, const char *const *argv, int argc)
2478 stop_tracing (NULL);
2479 trace_status_mi (1);
2482 /* Implement the "-ada-task-info" command. */
2484 void
2485 mi_cmd_ada_task_info (const char *command, const char *const *argv, int argc)
2487 if (argc != 0 && argc != 1)
2488 error (_("Invalid MI command"));
2490 print_ada_task_info (current_uiout, argv[0], current_inferior ());
2493 /* Print EXPRESSION according to VALUES. */
2495 static void
2496 print_variable_or_computed (const char *expression, enum print_values values)
2498 struct value *val;
2499 struct ui_out *uiout = current_uiout;
2501 string_file stb;
2503 expression_up expr = parse_expression (expression);
2505 if (values == PRINT_SIMPLE_VALUES)
2506 val = expr->evaluate_type ();
2507 else
2508 val = expr->evaluate ();
2510 std::optional<ui_out_emit_tuple> tuple_emitter;
2511 if (values != PRINT_NO_VALUES)
2512 tuple_emitter.emplace (uiout, nullptr);
2513 uiout->field_string ("name", expression);
2515 switch (values)
2517 case PRINT_SIMPLE_VALUES:
2518 type_print (val->type (), "", &stb, -1);
2519 uiout->field_stream ("type", stb);
2520 if (mi_simple_type_p (val->type ()))
2522 struct value_print_options opts;
2524 get_no_prettyformat_print_options (&opts);
2525 opts.deref_ref = true;
2526 common_val_print (val, &stb, 0, &opts, current_language);
2527 uiout->field_stream ("value", stb);
2529 break;
2530 case PRINT_ALL_VALUES:
2532 struct value_print_options opts;
2534 get_no_prettyformat_print_options (&opts);
2535 opts.deref_ref = true;
2536 common_val_print (val, &stb, 0, &opts, current_language);
2537 uiout->field_stream ("value", stb);
2539 break;
2543 /* Implement the "-trace-frame-collected" command. */
2545 void
2546 mi_cmd_trace_frame_collected (const char *command, const char *const *argv,
2547 int argc)
2549 struct bp_location *tloc;
2550 int stepping_frame;
2551 struct collection_list *clist;
2552 struct collection_list tracepoint_list, stepping_list;
2553 struct traceframe_info *tinfo;
2554 int oind = 0;
2555 enum print_values var_print_values = PRINT_ALL_VALUES;
2556 enum print_values comp_print_values = PRINT_ALL_VALUES;
2557 int registers_format = 'x';
2558 int memory_contents = 0;
2559 struct ui_out *uiout = current_uiout;
2560 enum opt
2562 VAR_PRINT_VALUES,
2563 COMP_PRINT_VALUES,
2564 REGISTERS_FORMAT,
2565 MEMORY_CONTENTS,
2567 static const struct mi_opt opts[] =
2569 {"-var-print-values", VAR_PRINT_VALUES, 1},
2570 {"-comp-print-values", COMP_PRINT_VALUES, 1},
2571 {"-registers-format", REGISTERS_FORMAT, 1},
2572 {"-memory-contents", MEMORY_CONTENTS, 0},
2573 { 0, 0, 0 }
2576 while (1)
2578 const char *oarg;
2579 int opt = mi_getopt ("-trace-frame-collected", argc, argv, opts,
2580 &oind, &oarg);
2581 if (opt < 0)
2582 break;
2583 switch ((enum opt) opt)
2585 case VAR_PRINT_VALUES:
2586 var_print_values = mi_parse_print_values (oarg);
2587 break;
2588 case COMP_PRINT_VALUES:
2589 comp_print_values = mi_parse_print_values (oarg);
2590 break;
2591 case REGISTERS_FORMAT:
2592 registers_format = oarg[0];
2593 break;
2594 case MEMORY_CONTENTS:
2595 memory_contents = 1;
2596 break;
2600 if (oind != argc)
2601 error (_("Usage: -trace-frame-collected "
2602 "[--var-print-values PRINT_VALUES] "
2603 "[--comp-print-values PRINT_VALUES] "
2604 "[--registers-format FORMAT]"
2605 "[--memory-contents]"));
2607 /* This throws an error is not inspecting a trace frame. */
2608 tloc = get_traceframe_location (&stepping_frame);
2610 /* This command only makes sense for the current frame, not the
2611 selected frame. */
2612 scoped_restore_current_thread restore_thread;
2613 select_frame (get_current_frame ());
2615 encode_actions (tloc, &tracepoint_list, &stepping_list);
2617 if (stepping_frame)
2618 clist = &stepping_list;
2619 else
2620 clist = &tracepoint_list;
2622 tinfo = get_traceframe_info ();
2624 /* Explicitly wholly collected variables. */
2626 ui_out_emit_list list_emitter (uiout, "explicit-variables");
2627 const std::vector<std::string> &wholly_collected
2628 = clist->wholly_collected ();
2629 for (size_t i = 0; i < wholly_collected.size (); i++)
2631 const std::string &str = wholly_collected[i];
2632 print_variable_or_computed (str.c_str (), var_print_values);
2636 /* Computed expressions. */
2638 ui_out_emit_list list_emitter (uiout, "computed-expressions");
2640 const std::vector<std::string> &computed = clist->computed ();
2641 for (size_t i = 0; i < computed.size (); i++)
2643 const std::string &str = computed[i];
2644 print_variable_or_computed (str.c_str (), comp_print_values);
2648 /* Registers. Given pseudo-registers, and that some architectures
2649 (like MIPS) actually hide the raw registers, we don't go through
2650 the trace frame info, but instead consult the register cache for
2651 register availability. */
2653 frame_info_ptr frame;
2654 struct gdbarch *gdbarch;
2655 int regnum;
2656 int numregs;
2658 ui_out_emit_list list_emitter (uiout, "registers");
2660 frame = get_selected_frame (NULL);
2661 gdbarch = get_frame_arch (frame);
2662 numregs = gdbarch_num_cooked_regs (gdbarch);
2664 for (regnum = 0; regnum < numregs; regnum++)
2666 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
2667 continue;
2669 output_register (frame, regnum, registers_format, 1);
2673 /* Trace state variables. */
2675 ui_out_emit_list list_emitter (uiout, "tvars");
2677 for (int tvar : tinfo->tvars)
2679 struct trace_state_variable *tsv;
2681 tsv = find_trace_state_variable_by_number (tvar);
2683 ui_out_emit_tuple tuple_emitter (uiout, NULL);
2685 if (tsv != NULL)
2687 uiout->field_fmt ("name", "$%s", tsv->name.c_str ());
2689 tsv->value_known = target_get_trace_state_variable_value (tsv->number,
2690 &tsv->value);
2691 uiout->field_signed ("current", tsv->value);
2693 else
2695 uiout->field_skip ("name");
2696 uiout->field_skip ("current");
2701 /* Memory. */
2703 std::vector<mem_range> available_memory;
2705 traceframe_available_memory (&available_memory, 0, ULONGEST_MAX);
2707 ui_out_emit_list list_emitter (uiout, "memory");
2709 for (const mem_range &r : available_memory)
2711 gdbarch *gdbarch = current_inferior ()->arch ();
2713 ui_out_emit_tuple tuple_emitter (uiout, NULL);
2715 uiout->field_core_addr ("address", gdbarch, r.start);
2716 uiout->field_signed ("length", r.length);
2718 gdb::byte_vector data (r.length);
2720 if (memory_contents)
2722 if (target_read_memory (r.start, data.data (), r.length) == 0)
2724 std::string data_str = bin2hex (data.data (), r.length);
2725 uiout->field_string ("contents", data_str);
2727 else
2728 uiout->field_skip ("contents");
2734 /* See mi/mi-main.h. */
2736 void
2737 mi_cmd_fix_multi_location_breakpoint_output (const char *command,
2738 const char *const *argv,
2739 int argc)
2741 fix_multi_location_breakpoint_output_globally = true;
2744 /* See mi/mi-main.h. */
2746 void
2747 mi_cmd_fix_breakpoint_script_output (const char *command,
2748 const char *const *argv, int argc)
2750 fix_breakpoint_script_output_globally = true;
2753 /* Implement the "-complete" command. */
2755 void
2756 mi_cmd_complete (const char *command, const char *const *argv, int argc)
2758 if (argc != 1)
2759 error (_("Usage: -complete COMMAND"));
2761 if (max_completions == 0)
2762 error (_("max-completions is zero, completion is disabled."));
2764 int quote_char = '\0';
2765 const char *word;
2767 completion_result result = complete (argv[0], &word, &quote_char);
2769 std::string arg_prefix (argv[0], word - argv[0]);
2771 struct ui_out *uiout = current_uiout;
2773 if (result.number_matches > 0)
2774 uiout->field_fmt ("completion", "%s%s",
2775 arg_prefix.c_str (),result.match_list[0]);
2778 ui_out_emit_list completions_emitter (uiout, "matches");
2780 if (result.number_matches == 1)
2781 uiout->field_fmt (NULL, "%s%s",
2782 arg_prefix.c_str (), result.match_list[0]);
2783 else
2785 result.sort_match_list ();
2786 for (size_t i = 0; i < result.number_matches; i++)
2788 uiout->field_fmt (NULL, "%s%s",
2789 arg_prefix.c_str (), result.match_list[i + 1]);
2793 uiout->field_string ("max_completions_reached",
2794 result.number_matches == max_completions ? "1" : "0");
2797 /* See mi-main.h. */
2799 mi_parse_thread_group_id (const char *id)
2801 if (*id != 'i')
2802 error (_("thread group id should start with an 'i'"));
2804 char *end;
2805 long num = strtol (id + 1, &end, 10);
2807 if (*end != '\0' || num > INT_MAX)
2808 error (_("invalid thread group id '%s'"), id);
2810 return (int) num;
2813 void _initialize_mi_main ();
2814 void
2815 _initialize_mi_main ()
2817 set_show_commands mi_async_cmds
2818 = add_setshow_boolean_cmd ("mi-async", class_run,
2819 &mi_async_1, _("\
2820 Set whether MI asynchronous mode is enabled."), _("\
2821 Show whether MI asynchronous mode is enabled."), _("\
2822 Tells GDB whether MI should be in asynchronous mode."),
2823 set_mi_async_command,
2824 show_mi_async_command,
2825 &setlist, &showlist);
2827 /* Alias old "target-async" to "mi-async". */
2828 cmd_list_element *set_target_async_cmd
2829 = add_alias_cmd ("target-async", mi_async_cmds.set, class_run, 0, &setlist);
2830 deprecate_cmd (set_target_async_cmd, "set mi-async");
2832 cmd_list_element *show_target_async_cmd
2833 = add_alias_cmd ("target-async", mi_async_cmds.show, class_run, 0,
2834 &showlist);
2835 deprecate_cmd (show_target_async_cmd, "show mi-async");