]> git.ipfire.org Git - thirdparty/binutils-gdb.git/blob - gdb/mi/mi-main.c
944c9116731fc5e24c4ecbe266c0f0eec4643eaa
[thirdparty/binutils-gdb.git] / gdb / mi / mi-main.c
1 /* MI Command Set.
2
3 Copyright (C) 2000-2023 Free Software Foundation, Inc.
4
5 Contributed by Cygnus Solutions (a Red Hat company).
6
7 This file is part of GDB.
8
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.
13
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.
18
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/>. */
21
22 #include "defs.h"
23 #include "arch-utils.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 "gdbcmd.h"
54 #include "observable.h"
55 #include "gdbsupport/gdb_optional.h"
56 #include "gdbsupport/byte-vector.h"
57
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>
66
67 enum
68 {
69 FROM_TTY = 0
70 };
71
72 /* Debug flag */
73 static int mi_debug_p;
74
75 /* This is used to pass the current command timestamp down to
76 continuation routines. */
77 static struct mi_timestamp *current_command_ts;
78
79 static int do_timings = 0;
80
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;
85
86 static void mi_cmd_execute (struct mi_parse *parse);
87
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 (frame_info_ptr, int regnum, int format,
93 int skip_unavailable);
94
95 /* Controls whether the frontend wants MI in async mode. */
96 static bool mi_async = false;
97
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;
101
102 static void
103 set_mi_async_command (const char *args, int from_tty,
104 struct cmd_list_element *c)
105 {
106 if (have_live_inferiors ())
107 {
108 mi_async_1 = mi_async;
109 error (_("Cannot change this setting while the inferior is running."));
110 }
111
112 mi_async = mi_async_1;
113 }
114
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)
119 {
120 gdb_printf (file,
121 _("Whether MI is in asynchronous mode is %s.\n"),
122 value);
123 }
124
125 /* A wrapper for target_can_async_p that takes the MI setting into
126 account. */
127
128 int
129 mi_async_p (void)
130 {
131 return mi_async && target_can_async_p ();
132 }
133
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. */
137
138 static void timestamp (struct mi_timestamp *tv);
139
140 static void print_diff (struct ui_file *file, struct mi_timestamp *start,
141 struct mi_timestamp *end);
142
143 void
144 mi_cmd_gdb_exit (const char *command, const char *const *argv, int argc)
145 {
146 struct mi_interp *mi = as_mi_interp (current_interpreter ());
147
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)
153 {
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);
160 }
161 /* FIXME: The function called is not yet a formal libgdb function. */
162 quit_force (NULL, FROM_TTY);
163 }
164
165 void
166 mi_cmd_exec_next (const char *command, const char *const *argv, int argc)
167 {
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);
173 }
174
175 void
176 mi_cmd_exec_next_instruction (const char *command, const char *const *argv,
177 int argc)
178 {
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);
184 }
185
186 void
187 mi_cmd_exec_step (const char *command, const char *const *argv, int argc)
188 {
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);
194 }
195
196 void
197 mi_cmd_exec_step_instruction (const char *command, const char *const *argv,
198 int argc)
199 {
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);
205 }
206
207 void
208 mi_cmd_exec_finish (const char *command, const char *const *argv, int argc)
209 {
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);
215 }
216
217 void
218 mi_cmd_exec_return (const char *command, const char *const *argv, int argc)
219 {
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);
230
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);
234 }
235
236 void
237 mi_cmd_exec_jump (const char *args, const char *const *argv, int argc)
238 {
239 /* FIXME: Should call a libgdb function, not a cli wrapper. */
240 mi_execute_async_cli_command ("jump", argv, argc);
241 }
242
243 static void
244 proceed_thread (struct thread_info *thread, int pid)
245 {
246 if (thread->state != THREAD_STOPPED)
247 return;
248
249 if (pid != 0 && thread->ptid.pid () != pid)
250 return;
251
252 switch_to_thread (thread);
253 clear_proceed_status (0);
254 proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
255 }
256
257 static int
258 proceed_thread_callback (struct thread_info *thread, void *arg)
259 {
260 int pid = *(int *)arg;
261
262 proceed_thread (thread, pid);
263 return 0;
264 }
265
266 static void
267 exec_continue (const char *const *argv, int argc)
268 {
269 prepare_execution_command (current_inferior ()->top_target (), mi_async_p ());
270
271
272 if (non_stop)
273 {
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.
278
279 See comment on infcmd.c:proceed_thread_callback for rationale. */
280 if (current_context->all || current_context->thread_group != -1)
281 {
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;
286
287 if (!current_context->all)
288 {
289 struct inferior *inf
290 = find_inferior_id (current_context->thread_group);
291
292 pid = inf->pid;
293 }
294
295 iterate_over_threads (proceed_thread_callback, &pid);
296 disable_commit_resumed.reset_and_commit ();
297 }
298 else
299 {
300 continue_1 (0);
301 }
302 }
303 else
304 {
305 scoped_restore save_multi = make_scoped_restore (&sched_multi);
306
307 if (current_context->all)
308 {
309 sched_multi = 1;
310 continue_1 (0);
311 }
312 else
313 {
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);
319 }
320 }
321 }
322
323 static void
324 exec_reverse_continue (const char *const *argv, int argc)
325 {
326 enum exec_direction_kind dir = execution_direction;
327
328 if (dir == EXEC_REVERSE)
329 error (_("Already in reverse mode."));
330
331 if (!target_can_execute_reverse ())
332 error (_("Target %s does not support this command."), target_shortname ());
333
334 scoped_restore save_exec_dir = make_scoped_restore (&execution_direction,
335 EXEC_REVERSE);
336 exec_continue (argv, argc);
337 }
338
339 void
340 mi_cmd_exec_continue (const char *command, const char *const *argv, int argc)
341 {
342 if (argc > 0 && strcmp (argv[0], "--reverse") == 0)
343 exec_reverse_continue (argv + 1, argc - 1);
344 else
345 exec_continue (argv, argc);
346 }
347
348 static int
349 interrupt_thread_callback (struct thread_info *thread, void *arg)
350 {
351 int pid = *(int *)arg;
352
353 if (thread->state != THREAD_RUNNING)
354 return 0;
355
356 if (thread->ptid.pid () != pid)
357 return 0;
358
359 target_stop (thread->ptid);
360 return 0;
361 }
362
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. */
368
369 void
370 mi_cmd_exec_interrupt (const char *command, const char *const *argv, int argc)
371 {
372 /* In all-stop mode, everything stops, so we don't need to try
373 anything specific. */
374 if (!non_stop)
375 {
376 interrupt_target_1 (0);
377 return;
378 }
379
380 if (current_context->all)
381 {
382 /* This will interrupt all threads in all inferiors. */
383 interrupt_target_1 (1);
384 }
385 else if (current_context->thread_group != -1)
386 {
387 struct inferior *inf = find_inferior_id (current_context->thread_group);
388
389 scoped_disable_commit_resumed disable_commit_resumed
390 ("interrupting all threads of thread group");
391
392 iterate_over_threads (interrupt_thread_callback, &inf->pid);
393 }
394 else
395 {
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);
400 }
401 }
402
403 /* Start the execution of the given inferior.
404
405 START_P indicates whether the program should be stopped when reaching the
406 main subprogram (similar to what the CLI "start" command does). */
407
408 static void
409 run_one_inferior (inferior *inf, bool start_p)
410 {
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);
414
415 if (inf->pid != 0)
416 {
417 thread_info *tp = any_thread_of_inferior (inf);
418 if (tp == NULL)
419 error (_("Inferior has no threads."));
420
421 switch_to_thread (tp);
422 }
423 else
424 switch_to_inferior_no_thread (inf);
425 mi_execute_cli_command (run_cmd, async_p,
426 async_p ? "&" : NULL);
427 }
428
429 void
430 mi_cmd_exec_run (const char *command, const char *const *argv, int argc)
431 {
432 int start_p = 0;
433
434 /* Parse the command options. */
435 enum opt
436 {
437 START_OPT,
438 };
439 static const struct mi_opt opts[] =
440 {
441 {"-start", START_OPT, 0},
442 {NULL, 0, 0},
443 };
444
445 int oind = 0;
446 const char *oarg;
447
448 while (1)
449 {
450 int opt = mi_getopt ("-exec-run", argc, argv, opts, &oind, &oarg);
451
452 if (opt < 0)
453 break;
454 switch ((enum opt) opt)
455 {
456 case START_OPT:
457 start_p = 1;
458 break;
459 }
460 }
461
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]);
466
467 if (current_context->all)
468 {
469 scoped_restore_current_pspace_and_thread restore_pspace_thread;
470
471 for (inferior *inf : all_inferiors ())
472 run_one_inferior (inf, start_p);
473 }
474 else
475 {
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);
479
480 mi_execute_cli_command (run_cmd, async_p,
481 async_p ? "&" : NULL);
482 }
483 }
484
485
486 static int
487 find_thread_of_process (struct thread_info *ti, void *p)
488 {
489 int pid = *(int *)p;
490
491 if (ti->ptid.pid () == pid && ti->state != THREAD_EXITED)
492 return 1;
493
494 return 0;
495 }
496
497 void
498 mi_cmd_target_detach (const char *command, const char *const *argv, int argc)
499 {
500 if (argc != 0 && argc != 1)
501 error (_("Usage: -target-detach [pid | thread-group]"));
502
503 if (argc == 1)
504 {
505 struct thread_info *tp;
506 char *end;
507 int pid;
508
509 /* First see if we are dealing with a thread-group id. */
510 if (*argv[0] == 'i')
511 {
512 struct inferior *inf;
513 int id = strtoul (argv[0] + 1, &end, 0);
514
515 if (*end != '\0')
516 error (_("Invalid syntax of thread-group id '%s'"), argv[0]);
517
518 inf = find_inferior_id (id);
519 if (!inf)
520 error (_("Non-existent thread-group id '%d'"), id);
521
522 pid = inf->pid;
523 }
524 else
525 {
526 /* We must be dealing with a pid. */
527 pid = strtol (argv[0], &end, 10);
528
529 if (*end != '\0')
530 error (_("Invalid identifier '%s'"), argv[0]);
531 }
532
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"));
538
539 switch_to_thread (tp);
540 }
541
542 detach_command (NULL, 0);
543 }
544
545 void
546 mi_cmd_target_flash_erase (const char *command, const char *const *argv,
547 int argc)
548 {
549 flash_erase_command (NULL, 0);
550 }
551
552 void
553 mi_cmd_thread_select (const char *command, const char *const *argv, int argc)
554 {
555 if (argc != 1)
556 error (_("-thread-select: USAGE: threadnum."));
557
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);
562
563 thread_select (argv[0], thr);
564
565 print_selected_thread_frame (current_uiout,
566 USER_SELECTED_THREAD | USER_SELECTED_FRAME);
567 }
568
569 void
570 mi_cmd_thread_list_ids (const char *command, const char *const *argv, int argc)
571 {
572 if (argc != 0)
573 error (_("-thread-list-ids: No arguments required."));
574
575 int num = 0;
576 int current_thread = -1;
577
578 update_thread_list ();
579
580 {
581 ui_out_emit_tuple tuple_emitter (current_uiout, "thread-ids");
582
583 for (thread_info *tp : all_non_exited_threads ())
584 {
585 if (tp->ptid == inferior_ptid)
586 current_thread = tp->global_num;
587
588 num++;
589 current_uiout->field_signed ("thread-id", tp->global_num);
590 }
591 }
592
593 if (current_thread != -1)
594 current_uiout->field_signed ("current-thread-id", current_thread);
595 current_uiout->field_signed ("number-of-threads", num);
596 }
597
598 void
599 mi_cmd_thread_info (const char *command, const char *const *argv, int argc)
600 {
601 if (argc != 0 && argc != 1)
602 error (_("Invalid MI command"));
603
604 print_thread_info (current_uiout, argv[0], -1);
605 }
606
607 struct collect_cores_data
608 {
609 int pid;
610 std::set<int> cores;
611 };
612
613 static int
614 collect_cores (struct thread_info *ti, void *xdata)
615 {
616 struct collect_cores_data *data = (struct collect_cores_data *) xdata;
617
618 if (ti->ptid.pid () == data->pid)
619 {
620 int core = target_core_of_thread (ti->ptid);
621
622 if (core != -1)
623 data->cores.insert (core);
624 }
625
626 return 0;
627 }
628
629 struct print_one_inferior_data
630 {
631 int recurse;
632 const std::set<int> *inferiors;
633 };
634
635 static void
636 print_one_inferior (struct inferior *inferior, bool recurse,
637 const std::set<int> &ids)
638 {
639 struct ui_out *uiout = current_uiout;
640
641 if (ids.empty () || (ids.find (inferior->pid) != ids.end ()))
642 {
643 struct collect_cores_data data;
644 ui_out_emit_tuple tuple_emitter (uiout, NULL);
645
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);
653
654 if (inferior->pspace->exec_filename != nullptr)
655 {
656 uiout->field_string ("executable",
657 inferior->pspace->exec_filename.get ());
658 }
659
660 if (inferior->pid != 0)
661 {
662 data.pid = inferior->pid;
663 iterate_over_threads (collect_cores, &data);
664 }
665
666 if (!data.cores.empty ())
667 {
668 ui_out_emit_list list_emitter (uiout, "cores");
669
670 for (int b : data.cores)
671 uiout->field_signed (NULL, b);
672 }
673
674 if (recurse)
675 print_thread_info (uiout, NULL, inferior->pid);
676 }
677 }
678
679 /* Output a field named 'cores' with a list as the value. The
680 elements of the list are obtained by splitting 'cores' on
681 comma. */
682
683 static void
684 output_cores (struct ui_out *uiout, const char *field_name, const char *xcores)
685 {
686 ui_out_emit_list list_emitter (uiout, field_name);
687 auto cores = make_unique_xstrdup (xcores);
688 char *p = cores.get ();
689 char *saveptr;
690
691 for (p = strtok_r (p, ",", &saveptr); p; p = strtok_r (NULL, ",", &saveptr))
692 uiout->field_string (NULL, p);
693 }
694
695 static void
696 list_available_thread_groups (const std::set<int> &ids, int recurse)
697 {
698 struct ui_out *uiout = current_uiout;
699
700 /* This keeps a map from integer (pid) to vector of struct osdata_item.
701 The vector contains information about all threads for the given pid. */
702 std::map<int, std::vector<osdata_item>> tree;
703
704 /* get_osdata will throw if it cannot return data. */
705 std::unique_ptr<osdata> data = get_osdata ("processes");
706
707 if (recurse)
708 {
709 std::unique_ptr<osdata> threads = get_osdata ("threads");
710
711 for (const osdata_item &item : threads->items)
712 {
713 const std::string *pid = get_osdata_column (item, "pid");
714 int pid_i = strtoul (pid->c_str (), NULL, 0);
715
716 tree[pid_i].push_back (item);
717 }
718 }
719
720 ui_out_emit_list list_emitter (uiout, "groups");
721
722 for (const osdata_item &item : data->items)
723 {
724 const std::string *pid = get_osdata_column (item, "pid");
725 const std::string *cmd = get_osdata_column (item, "command");
726 const std::string *user = get_osdata_column (item, "user");
727 const std::string *cores = get_osdata_column (item, "cores");
728
729 int pid_i = strtoul (pid->c_str (), NULL, 0);
730
731 /* At present, the target will return all available processes
732 and if information about specific ones was required, we filter
733 undesired processes here. */
734 if (!ids.empty () && ids.find (pid_i) == ids.end ())
735 continue;
736
737 ui_out_emit_tuple tuple_emitter (uiout, NULL);
738
739 uiout->field_string ("id", *pid);
740 uiout->field_string ("type", "process");
741 if (cmd)
742 uiout->field_string ("description", *cmd);
743 if (user)
744 uiout->field_string ("user", *user);
745 if (cores)
746 output_cores (uiout, "cores", cores->c_str ());
747
748 if (recurse)
749 {
750 auto n = tree.find (pid_i);
751 if (n != tree.end ())
752 {
753 std::vector<osdata_item> &children = n->second;
754
755 ui_out_emit_list thread_list_emitter (uiout, "threads");
756
757 for (const osdata_item &child : children)
758 {
759 ui_out_emit_tuple inner_tuple_emitter (uiout, NULL);
760 const std::string *tid = get_osdata_column (child, "tid");
761 const std::string *tcore = get_osdata_column (child, "core");
762
763 uiout->field_string ("id", *tid);
764 if (tcore)
765 uiout->field_string ("core", *tcore);
766 }
767 }
768 }
769 }
770 }
771
772 void
773 mi_cmd_list_thread_groups (const char *command, const char *const *argv,
774 int argc)
775 {
776 struct ui_out *uiout = current_uiout;
777 int available = 0;
778 int recurse = 0;
779 std::set<int> ids;
780
781 enum opt
782 {
783 AVAILABLE_OPT, RECURSE_OPT
784 };
785 static const struct mi_opt opts[] =
786 {
787 {"-available", AVAILABLE_OPT, 0},
788 {"-recurse", RECURSE_OPT, 1},
789 { 0, 0, 0 }
790 };
791
792 int oind = 0;
793 const char *oarg;
794
795 while (1)
796 {
797 int opt = mi_getopt ("-list-thread-groups", argc, argv, opts,
798 &oind, &oarg);
799
800 if (opt < 0)
801 break;
802 switch ((enum opt) opt)
803 {
804 case AVAILABLE_OPT:
805 available = 1;
806 break;
807 case RECURSE_OPT:
808 if (strcmp (oarg, "0") == 0)
809 ;
810 else if (strcmp (oarg, "1") == 0)
811 recurse = 1;
812 else
813 error (_("only '0' and '1' are valid values "
814 "for the '--recurse' option"));
815 break;
816 }
817 }
818
819 for (; oind < argc; ++oind)
820 {
821 char *end;
822 int inf;
823
824 if (*(argv[oind]) != 'i')
825 error (_("invalid syntax of group id '%s'"), argv[oind]);
826
827 inf = strtoul (argv[oind] + 1, &end, 0);
828
829 if (*end != '\0')
830 error (_("invalid syntax of group id '%s'"), argv[oind]);
831 ids.insert (inf);
832 }
833
834 if (available)
835 {
836 list_available_thread_groups (ids, recurse);
837 }
838 else if (ids.size () == 1)
839 {
840 /* Local thread groups, single id. */
841 int id = *(ids.begin ());
842 struct inferior *inf = find_inferior_id (id);
843
844 if (!inf)
845 error (_("Non-existent thread group id '%d'"), id);
846
847 print_thread_info (uiout, NULL, inf->pid);
848 }
849 else
850 {
851 /* Local thread groups. Either no explicit ids -- and we
852 print everything, or several explicit ids. In both cases,
853 we print more than one group, and have to use 'groups'
854 as the top-level element. */
855 ui_out_emit_list list_emitter (uiout, "groups");
856 update_thread_list ();
857 for (inferior *inf : all_inferiors ())
858 print_one_inferior (inf, recurse, ids);
859 }
860 }
861
862 void
863 mi_cmd_data_list_register_names (const char *command, const char *const *argv,
864 int argc)
865 {
866 struct gdbarch *gdbarch;
867 struct ui_out *uiout = current_uiout;
868 int regnum, numregs;
869 int i;
870
871 /* Note that the test for a valid register must include checking the
872 gdbarch_register_name because gdbarch_num_regs may be allocated
873 for the union of the register sets within a family of related
874 processors. In this case, some entries of gdbarch_register_name
875 will change depending upon the particular processor being
876 debugged. */
877
878 gdbarch = get_current_arch ();
879 numregs = gdbarch_num_cooked_regs (gdbarch);
880
881 ui_out_emit_list list_emitter (uiout, "register-names");
882
883 if (argc == 0) /* No args, just do all the regs. */
884 {
885 for (regnum = 0;
886 regnum < numregs;
887 regnum++)
888 {
889 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
890 uiout->field_string (NULL, "");
891 else
892 uiout->field_string (NULL, gdbarch_register_name (gdbarch, regnum));
893 }
894 }
895
896 /* Else, list of register #s, just do listed regs. */
897 for (i = 0; i < argc; i++)
898 {
899 regnum = atoi (argv[i]);
900 if (regnum < 0 || regnum >= numregs)
901 error (_("bad register number"));
902
903 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
904 uiout->field_string (NULL, "");
905 else
906 uiout->field_string (NULL, gdbarch_register_name (gdbarch, regnum));
907 }
908 }
909
910 void
911 mi_cmd_data_list_changed_registers (const char *command,
912 const char *const *argv, int argc)
913 {
914 static std::unique_ptr<readonly_detached_regcache> this_regs;
915 struct ui_out *uiout = current_uiout;
916 std::unique_ptr<readonly_detached_regcache> prev_regs;
917 struct gdbarch *gdbarch;
918 int regnum, numregs;
919 int i;
920
921 /* The last time we visited this function, the current frame's
922 register contents were saved in THIS_REGS. Move THIS_REGS over
923 to PREV_REGS, and refresh THIS_REGS with the now-current register
924 contents. */
925
926 prev_regs = std::move (this_regs);
927 this_regs = frame_save_as_regcache (get_selected_frame (NULL));
928
929 /* Note that the test for a valid register must include checking the
930 gdbarch_register_name because gdbarch_num_regs may be allocated
931 for the union of the register sets within a family of related
932 processors. In this case, some entries of gdbarch_register_name
933 will change depending upon the particular processor being
934 debugged. */
935
936 gdbarch = this_regs->arch ();
937 numregs = gdbarch_num_cooked_regs (gdbarch);
938
939 ui_out_emit_list list_emitter (uiout, "changed-registers");
940
941 if (argc == 0)
942 {
943 /* No args, just do all the regs. */
944 for (regnum = 0;
945 regnum < numregs;
946 regnum++)
947 {
948 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
949 continue;
950
951 if (register_changed_p (regnum, prev_regs.get (),
952 this_regs.get ()))
953 uiout->field_signed (NULL, regnum);
954 }
955 }
956
957 /* Else, list of register #s, just do listed regs. */
958 for (i = 0; i < argc; i++)
959 {
960 regnum = atoi (argv[i]);
961
962 if (regnum >= 0
963 && regnum < numregs
964 && *gdbarch_register_name (gdbarch, regnum) != '\000')
965 {
966 if (register_changed_p (regnum, prev_regs.get (),
967 this_regs.get ()))
968 uiout->field_signed (NULL, regnum);
969 }
970 else
971 error (_("bad register number"));
972 }
973 }
974
975 static bool
976 register_changed_p (int regnum, readonly_detached_regcache *prev_regs,
977 readonly_detached_regcache *this_regs)
978 {
979 struct gdbarch *gdbarch = this_regs->arch ();
980 struct value *prev_value, *this_value;
981
982 /* First time through or after gdbarch change consider all registers
983 as changed. */
984 if (!prev_regs || prev_regs->arch () != gdbarch)
985 return true;
986
987 /* Get register contents and compare. */
988 prev_value = prev_regs->cooked_read_value (regnum);
989 this_value = this_regs->cooked_read_value (regnum);
990 gdb_assert (prev_value != NULL);
991 gdb_assert (this_value != NULL);
992
993 auto ret = !prev_value->contents_eq (0, this_value, 0,
994 register_size (gdbarch, regnum));
995
996 release_value (prev_value);
997 release_value (this_value);
998 return ret;
999 }
1000
1001 /* Return a list of register number and value pairs. The valid
1002 arguments expected are: a letter indicating the format in which to
1003 display the registers contents. This can be one of: x
1004 (hexadecimal), d (decimal), N (natural), t (binary), o (octal), r
1005 (raw). After the format argument there can be a sequence of
1006 numbers, indicating which registers to fetch the content of. If
1007 the format is the only argument, a list of all the registers with
1008 their values is returned. */
1009
1010 void
1011 mi_cmd_data_list_register_values (const char *command, const char *const *argv,
1012 int argc)
1013 {
1014 struct ui_out *uiout = current_uiout;
1015 frame_info_ptr frame;
1016 struct gdbarch *gdbarch;
1017 int regnum, numregs, format;
1018 int i;
1019 int skip_unavailable = 0;
1020 int oind = 0;
1021 enum opt
1022 {
1023 SKIP_UNAVAILABLE,
1024 };
1025 static const struct mi_opt opts[] =
1026 {
1027 {"-skip-unavailable", SKIP_UNAVAILABLE, 0},
1028 { 0, 0, 0 }
1029 };
1030
1031 /* Note that the test for a valid register must include checking the
1032 gdbarch_register_name because gdbarch_num_regs may be allocated
1033 for the union of the register sets within a family of related
1034 processors. In this case, some entries of gdbarch_register_name
1035 will change depending upon the particular processor being
1036 debugged. */
1037
1038 while (1)
1039 {
1040 const char *oarg;
1041 int opt = mi_getopt ("-data-list-register-values", argc, argv,
1042 opts, &oind, &oarg);
1043
1044 if (opt < 0)
1045 break;
1046 switch ((enum opt) opt)
1047 {
1048 case SKIP_UNAVAILABLE:
1049 skip_unavailable = 1;
1050 break;
1051 }
1052 }
1053
1054 if (argc - oind < 1)
1055 error (_("-data-list-register-values: Usage: "
1056 "-data-list-register-values [--skip-unavailable] <format>"
1057 " [<regnum1>...<regnumN>]"));
1058
1059 format = (int) argv[oind][0];
1060
1061 frame = get_selected_frame (NULL);
1062 gdbarch = get_frame_arch (frame);
1063 numregs = gdbarch_num_cooked_regs (gdbarch);
1064
1065 ui_out_emit_list list_emitter (uiout, "register-values");
1066
1067 if (argc - oind == 1)
1068 {
1069 /* No args, beside the format: do all the regs. */
1070 for (regnum = 0;
1071 regnum < numregs;
1072 regnum++)
1073 {
1074 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
1075 continue;
1076
1077 output_register (frame, regnum, format, skip_unavailable);
1078 }
1079 }
1080
1081 /* Else, list of register #s, just do listed regs. */
1082 for (i = 1 + oind; i < argc; i++)
1083 {
1084 regnum = atoi (argv[i]);
1085
1086 if (regnum >= 0
1087 && regnum < numregs
1088 && *gdbarch_register_name (gdbarch, regnum) != '\000')
1089 output_register (frame, regnum, format, skip_unavailable);
1090 else
1091 error (_("bad register number"));
1092 }
1093 }
1094
1095 /* Output one register REGNUM's contents in the desired FORMAT. If
1096 SKIP_UNAVAILABLE is true, skip the register if it is
1097 unavailable. */
1098
1099 static void
1100 output_register (frame_info_ptr frame, int regnum, int format,
1101 int skip_unavailable)
1102 {
1103 struct ui_out *uiout = current_uiout;
1104 struct value *val = value_of_register (regnum, frame);
1105 struct value_print_options opts;
1106
1107 if (skip_unavailable && !val->entirely_available ())
1108 return;
1109
1110 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1111 uiout->field_signed ("number", regnum);
1112
1113 if (format == 'N')
1114 format = 0;
1115
1116 if (format == 'r')
1117 format = 'z';
1118
1119 string_file stb;
1120
1121 get_formatted_print_options (&opts, format);
1122 opts.deref_ref = true;
1123 common_val_print (val, &stb, 0, &opts, current_language);
1124 uiout->field_stream ("value", stb);
1125 }
1126
1127 /* Write given values into registers. The registers and values are
1128 given as pairs. The corresponding MI command is
1129 -data-write-register-values <format>
1130 [<regnum1> <value1>...<regnumN> <valueN>] */
1131 void
1132 mi_cmd_data_write_register_values (const char *command,
1133 const char *const *argv, int argc)
1134 {
1135 struct regcache *regcache;
1136 struct gdbarch *gdbarch;
1137 int numregs, i;
1138
1139 /* Note that the test for a valid register must include checking the
1140 gdbarch_register_name because gdbarch_num_regs may be allocated
1141 for the union of the register sets within a family of related
1142 processors. In this case, some entries of gdbarch_register_name
1143 will change depending upon the particular processor being
1144 debugged. */
1145
1146 regcache = get_current_regcache ();
1147 gdbarch = regcache->arch ();
1148 numregs = gdbarch_num_cooked_regs (gdbarch);
1149
1150 if (argc == 0)
1151 error (_("-data-write-register-values: Usage: -data-write-register-"
1152 "values <format> [<regnum1> <value1>...<regnumN> <valueN>]"));
1153
1154 if (!target_has_registers ())
1155 error (_("-data-write-register-values: No registers."));
1156
1157 if (!(argc - 1))
1158 error (_("-data-write-register-values: No regs and values specified."));
1159
1160 if ((argc - 1) % 2)
1161 error (_("-data-write-register-values: "
1162 "Regs and vals are not in pairs."));
1163
1164 for (i = 1; i < argc; i = i + 2)
1165 {
1166 int regnum = atoi (argv[i]);
1167
1168 if (regnum >= 0 && regnum < numregs
1169 && *gdbarch_register_name (gdbarch, regnum) != '\0')
1170 {
1171 LONGEST value;
1172
1173 /* Get the value as a number. */
1174 value = parse_and_eval_address (argv[i + 1]);
1175
1176 /* Write it down. */
1177 regcache_cooked_write_signed (regcache, regnum, value);
1178 }
1179 else
1180 error (_("bad register number"));
1181 }
1182 }
1183
1184 /* Evaluate the value of the argument. The argument is an
1185 expression. If the expression contains spaces it needs to be
1186 included in double quotes. */
1187
1188 void
1189 mi_cmd_data_evaluate_expression (const char *command, const char *const *argv,
1190 int argc)
1191 {
1192 struct value *val;
1193 struct value_print_options opts;
1194 struct ui_out *uiout = current_uiout;
1195
1196 if (argc != 1)
1197 error (_("-data-evaluate-expression: "
1198 "Usage: -data-evaluate-expression expression"));
1199
1200 expression_up expr = parse_expression (argv[0]);
1201
1202 val = expr->evaluate ();
1203
1204 string_file stb;
1205
1206 /* Print the result of the expression evaluation. */
1207 get_user_print_options (&opts);
1208 opts.deref_ref = false;
1209 common_val_print (val, &stb, 0, &opts, current_language);
1210
1211 uiout->field_stream ("value", stb);
1212 }
1213
1214 /* This is the -data-read-memory command.
1215
1216 ADDR: start address of data to be dumped.
1217 WORD-FORMAT: a char indicating format for the ``word''. See
1218 the ``x'' command.
1219 WORD-SIZE: size of each ``word''; 1,2,4, or 8 bytes.
1220 NR_ROW: Number of rows.
1221 NR_COL: The number of columns (words per row).
1222 ASCHAR: (OPTIONAL) Append an ascii character dump to each row. Use
1223 ASCHAR for unprintable characters.
1224
1225 Reads SIZE*NR_ROW*NR_COL bytes starting at ADDR from memory and
1226 displays them. Returns:
1227
1228 {addr="...",rowN={wordN="..." ,... [,ascii="..."]}, ...}
1229
1230 Returns:
1231 The number of bytes read is SIZE*ROW*COL. */
1232
1233 void
1234 mi_cmd_data_read_memory (const char *command, const char *const *argv,
1235 int argc)
1236 {
1237 struct gdbarch *gdbarch = get_current_arch ();
1238 struct ui_out *uiout = current_uiout;
1239 CORE_ADDR addr;
1240 long total_bytes, nr_cols, nr_rows;
1241 char word_format;
1242 struct type *word_type;
1243 long word_size;
1244 char word_asize;
1245 char aschar;
1246 int nr_bytes;
1247 long offset = 0;
1248 int oind = 0;
1249 const char *oarg;
1250 enum opt
1251 {
1252 OFFSET_OPT
1253 };
1254 static const struct mi_opt opts[] =
1255 {
1256 {"o", OFFSET_OPT, 1},
1257 { 0, 0, 0 }
1258 };
1259
1260 while (1)
1261 {
1262 int opt = mi_getopt ("-data-read-memory", argc, argv, opts,
1263 &oind, &oarg);
1264
1265 if (opt < 0)
1266 break;
1267 switch ((enum opt) opt)
1268 {
1269 case OFFSET_OPT:
1270 offset = atol (oarg);
1271 break;
1272 }
1273 }
1274 argv += oind;
1275 argc -= oind;
1276
1277 if (argc < 5 || argc > 6)
1278 error (_("-data-read-memory: Usage: "
1279 "ADDR WORD-FORMAT WORD-SIZE NR-ROWS NR-COLS [ASCHAR]."));
1280
1281 /* Extract all the arguments. */
1282
1283 /* Start address of the memory dump. */
1284 addr = parse_and_eval_address (argv[0]) + offset;
1285 /* The format character to use when displaying a memory word. See
1286 the ``x'' command. */
1287 word_format = argv[1][0];
1288 /* The size of the memory word. */
1289 word_size = atol (argv[2]);
1290 switch (word_size)
1291 {
1292 case 1:
1293 word_type = builtin_type (gdbarch)->builtin_int8;
1294 word_asize = 'b';
1295 break;
1296 case 2:
1297 word_type = builtin_type (gdbarch)->builtin_int16;
1298 word_asize = 'h';
1299 break;
1300 case 4:
1301 word_type = builtin_type (gdbarch)->builtin_int32;
1302 word_asize = 'w';
1303 break;
1304 case 8:
1305 word_type = builtin_type (gdbarch)->builtin_int64;
1306 word_asize = 'g';
1307 break;
1308 default:
1309 word_type = builtin_type (gdbarch)->builtin_int8;
1310 word_asize = 'b';
1311 }
1312 /* The number of rows. */
1313 nr_rows = atol (argv[3]);
1314 if (nr_rows <= 0)
1315 error (_("-data-read-memory: invalid number of rows."));
1316
1317 /* Number of bytes per row. */
1318 nr_cols = atol (argv[4]);
1319 if (nr_cols <= 0)
1320 error (_("-data-read-memory: invalid number of columns."));
1321
1322 /* The un-printable character when printing ascii. */
1323 if (argc == 6)
1324 aschar = *argv[5];
1325 else
1326 aschar = 0;
1327
1328 /* Create a buffer and read it in. */
1329 total_bytes = word_size * nr_rows * nr_cols;
1330
1331 gdb::byte_vector mbuf (total_bytes);
1332
1333 nr_bytes = target_read (current_inferior ()->top_target (),
1334 TARGET_OBJECT_MEMORY, NULL,
1335 mbuf.data (), addr, total_bytes);
1336 if (nr_bytes <= 0)
1337 error (_("Unable to read memory."));
1338
1339 /* Output the header information. */
1340 uiout->field_core_addr ("addr", gdbarch, addr);
1341 uiout->field_signed ("nr-bytes", nr_bytes);
1342 uiout->field_signed ("total-bytes", total_bytes);
1343 uiout->field_core_addr ("next-row", gdbarch, addr + word_size * nr_cols);
1344 uiout->field_core_addr ("prev-row", gdbarch, addr - word_size * nr_cols);
1345 uiout->field_core_addr ("next-page", gdbarch, addr + total_bytes);
1346 uiout->field_core_addr ("prev-page", gdbarch, addr - total_bytes);
1347
1348 /* Build the result as a two dimensional table. */
1349 {
1350 int row;
1351 int row_byte;
1352
1353 string_file stream;
1354
1355 ui_out_emit_list list_emitter (uiout, "memory");
1356 for (row = 0, row_byte = 0;
1357 row < nr_rows;
1358 row++, row_byte += nr_cols * word_size)
1359 {
1360 int col;
1361 int col_byte;
1362 struct value_print_options print_opts;
1363
1364 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1365 uiout->field_core_addr ("addr", gdbarch, addr + row_byte);
1366 /* ui_out_field_core_addr_symbolic (uiout, "saddr", addr +
1367 row_byte); */
1368 {
1369 ui_out_emit_list list_data_emitter (uiout, "data");
1370 get_formatted_print_options (&print_opts, word_format);
1371 for (col = 0, col_byte = row_byte;
1372 col < nr_cols;
1373 col++, col_byte += word_size)
1374 {
1375 if (col_byte + word_size > nr_bytes)
1376 {
1377 uiout->field_string (NULL, "N/A");
1378 }
1379 else
1380 {
1381 stream.clear ();
1382 print_scalar_formatted (&mbuf[col_byte], word_type,
1383 &print_opts, word_asize, &stream);
1384 uiout->field_stream (NULL, stream);
1385 }
1386 }
1387 }
1388
1389 if (aschar)
1390 {
1391 int byte;
1392
1393 stream.clear ();
1394 for (byte = row_byte;
1395 byte < row_byte + word_size * nr_cols; byte++)
1396 {
1397 if (byte >= nr_bytes)
1398 stream.putc ('X');
1399 else if (mbuf[byte] < 32 || mbuf[byte] > 126)
1400 stream.putc (aschar);
1401 else
1402 stream.putc (mbuf[byte]);
1403 }
1404 uiout->field_stream ("ascii", stream);
1405 }
1406 }
1407 }
1408 }
1409
1410 void
1411 mi_cmd_data_read_memory_bytes (const char *command, const char *const *argv,
1412 int argc)
1413 {
1414 struct gdbarch *gdbarch = get_current_arch ();
1415 struct ui_out *uiout = current_uiout;
1416 CORE_ADDR addr;
1417 LONGEST length;
1418 long offset = 0;
1419 int unit_size = gdbarch_addressable_memory_unit_size (gdbarch);
1420 int oind = 0;
1421 const char *oarg;
1422 enum opt
1423 {
1424 OFFSET_OPT
1425 };
1426 static const struct mi_opt opts[] =
1427 {
1428 {"o", OFFSET_OPT, 1},
1429 { 0, 0, 0 }
1430 };
1431
1432 while (1)
1433 {
1434 int opt = mi_getopt ("-data-read-memory-bytes", argc, argv, opts,
1435 &oind, &oarg);
1436 if (opt < 0)
1437 break;
1438 switch ((enum opt) opt)
1439 {
1440 case OFFSET_OPT:
1441 offset = atol (oarg);
1442 break;
1443 }
1444 }
1445 argv += oind;
1446 argc -= oind;
1447
1448 if (argc != 2)
1449 error (_("Usage: [ -o OFFSET ] ADDR LENGTH."));
1450
1451 addr = parse_and_eval_address (argv[0]) + offset;
1452 length = atol (argv[1]);
1453
1454 std::vector<memory_read_result> result
1455 = read_memory_robust (current_inferior ()->top_target (), addr, length);
1456
1457 if (result.size () == 0)
1458 error (_("Unable to read memory."));
1459
1460 ui_out_emit_list list_emitter (uiout, "memory");
1461 for (const memory_read_result &read_result : result)
1462 {
1463 ui_out_emit_tuple tuple_emitter (uiout, NULL);
1464
1465 uiout->field_core_addr ("begin", gdbarch, read_result.begin);
1466 uiout->field_core_addr ("offset", gdbarch, read_result.begin - addr);
1467 uiout->field_core_addr ("end", gdbarch, read_result.end);
1468
1469 std::string data = bin2hex (read_result.data.get (),
1470 (read_result.end - read_result.begin)
1471 * unit_size);
1472 uiout->field_string ("contents", data);
1473 }
1474 }
1475
1476 /* Implementation of the -data-write_memory command.
1477
1478 COLUMN_OFFSET: optional argument. Must be preceded by '-o'. The
1479 offset from the beginning of the memory grid row where the cell to
1480 be written is.
1481 ADDR: start address of the row in the memory grid where the memory
1482 cell is, if OFFSET_COLUMN is specified. Otherwise, the address of
1483 the location to write to.
1484 FORMAT: a char indicating format for the ``word''. See
1485 the ``x'' command.
1486 WORD_SIZE: size of each ``word''; 1,2,4, or 8 bytes
1487 VALUE: value to be written into the memory address.
1488
1489 Writes VALUE into ADDR + (COLUMN_OFFSET * WORD_SIZE).
1490
1491 Prints nothing. */
1492
1493 void
1494 mi_cmd_data_write_memory (const char *command, const char *const *argv,
1495 int argc)
1496 {
1497 struct gdbarch *gdbarch = get_current_arch ();
1498 enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1499 CORE_ADDR addr;
1500 long word_size;
1501 /* FIXME: ezannoni 2000-02-17 LONGEST could possibly not be big
1502 enough when using a compiler other than GCC. */
1503 LONGEST value;
1504 long offset = 0;
1505 int oind = 0;
1506 const char *oarg;
1507 enum opt
1508 {
1509 OFFSET_OPT
1510 };
1511 static const struct mi_opt opts[] =
1512 {
1513 {"o", OFFSET_OPT, 1},
1514 { 0, 0, 0 }
1515 };
1516
1517 while (1)
1518 {
1519 int opt = mi_getopt ("-data-write-memory", argc, argv, opts,
1520 &oind, &oarg);
1521
1522 if (opt < 0)
1523 break;
1524 switch ((enum opt) opt)
1525 {
1526 case OFFSET_OPT:
1527 offset = atol (oarg);
1528 break;
1529 }
1530 }
1531 argv += oind;
1532 argc -= oind;
1533
1534 if (argc != 4)
1535 error (_("-data-write-memory: Usage: "
1536 "[-o COLUMN_OFFSET] ADDR FORMAT WORD-SIZE VALUE."));
1537
1538 /* Extract all the arguments. */
1539 /* Start address of the memory dump. */
1540 addr = parse_and_eval_address (argv[0]);
1541 /* The size of the memory word. */
1542 word_size = atol (argv[2]);
1543
1544 /* Calculate the real address of the write destination. */
1545 addr += (offset * word_size);
1546
1547 /* Get the value as a number. */
1548 value = parse_and_eval_address (argv[3]);
1549 /* Get the value into an array. */
1550 gdb::byte_vector buffer (word_size);
1551 store_signed_integer (buffer.data (), word_size, byte_order, value);
1552 /* Write it down to memory. */
1553 write_memory_with_notification (addr, buffer.data (), word_size);
1554 }
1555
1556 /* Implementation of the -data-write-memory-bytes command.
1557
1558 ADDR: start address
1559 DATA: string of bytes to write at that address
1560 COUNT: number of bytes to be filled (decimal integer). */
1561
1562 void
1563 mi_cmd_data_write_memory_bytes (const char *command, const char *const *argv,
1564 int argc)
1565 {
1566 CORE_ADDR addr;
1567 const char *cdata;
1568 size_t len_hex, len_bytes, len_units, i, steps, remaining_units;
1569 long int count_units;
1570 int unit_size;
1571
1572 if (argc != 2 && argc != 3)
1573 error (_("Usage: ADDR DATA [COUNT]."));
1574
1575 addr = parse_and_eval_address (argv[0]);
1576 cdata = argv[1];
1577 len_hex = strlen (cdata);
1578 unit_size = gdbarch_addressable_memory_unit_size (get_current_arch ());
1579
1580 if (len_hex % (unit_size * 2) != 0)
1581 error (_("Hex-encoded '%s' must represent an integral number of "
1582 "addressable memory units."),
1583 cdata);
1584
1585 len_bytes = len_hex / 2;
1586 len_units = len_bytes / unit_size;
1587
1588 if (argc == 3)
1589 count_units = strtoul (argv[2], NULL, 10);
1590 else
1591 count_units = len_units;
1592
1593 gdb::byte_vector databuf (len_bytes);
1594
1595 for (i = 0; i < len_bytes; ++i)
1596 {
1597 int x;
1598 if (sscanf (cdata + i * 2, "%02x", &x) != 1)
1599 error (_("Invalid argument"));
1600 databuf[i] = (gdb_byte) x;
1601 }
1602
1603 gdb::byte_vector data;
1604 if (len_units < count_units)
1605 {
1606 /* Pattern is made of less units than count:
1607 repeat pattern to fill memory. */
1608 data = gdb::byte_vector (count_units * unit_size);
1609
1610 /* Number of times the pattern is entirely repeated. */
1611 steps = count_units / len_units;
1612 /* Number of remaining addressable memory units. */
1613 remaining_units = count_units % len_units;
1614 for (i = 0; i < steps; i++)
1615 memcpy (&data[i * len_bytes], &databuf[0], len_bytes);
1616
1617 if (remaining_units > 0)
1618 memcpy (&data[steps * len_bytes], &databuf[0],
1619 remaining_units * unit_size);
1620 }
1621 else
1622 {
1623 /* Pattern is longer than or equal to count:
1624 just copy count addressable memory units. */
1625 data = std::move (databuf);
1626 }
1627
1628 write_memory_with_notification (addr, data.data (), count_units);
1629 }
1630
1631 void
1632 mi_cmd_enable_timings (const char *command, const char *const *argv, int argc)
1633 {
1634 if (argc == 0)
1635 do_timings = 1;
1636 else if (argc == 1)
1637 {
1638 if (strcmp (argv[0], "yes") == 0)
1639 do_timings = 1;
1640 else if (strcmp (argv[0], "no") == 0)
1641 do_timings = 0;
1642 else
1643 goto usage_error;
1644 }
1645 else
1646 goto usage_error;
1647
1648 return;
1649
1650 usage_error:
1651 error (_("-enable-timings: Usage: %s {yes|no}"), command);
1652 }
1653
1654 void
1655 mi_cmd_list_features (const char *command, const char *const *argv, int argc)
1656 {
1657 if (argc == 0)
1658 {
1659 struct ui_out *uiout = current_uiout;
1660
1661 ui_out_emit_list list_emitter (uiout, "features");
1662 uiout->field_string (NULL, "frozen-varobjs");
1663 uiout->field_string (NULL, "pending-breakpoints");
1664 uiout->field_string (NULL, "thread-info");
1665 uiout->field_string (NULL, "data-read-memory-bytes");
1666 uiout->field_string (NULL, "breakpoint-notifications");
1667 uiout->field_string (NULL, "ada-task-info");
1668 uiout->field_string (NULL, "language-option");
1669 uiout->field_string (NULL, "info-gdb-mi-command");
1670 uiout->field_string (NULL, "undefined-command-error-code");
1671 uiout->field_string (NULL, "exec-run-start-option");
1672 uiout->field_string (NULL, "data-disassemble-a-option");
1673 uiout->field_string (NULL, "simple-values-ref-types");
1674
1675 if (ext_lang_initialized_p (get_ext_lang_defn (EXT_LANG_PYTHON)))
1676 uiout->field_string (NULL, "python");
1677
1678 return;
1679 }
1680
1681 error (_("-list-features should be passed no arguments"));
1682 }
1683
1684 void
1685 mi_cmd_list_target_features (const char *command, const char *const *argv,
1686 int argc)
1687 {
1688 if (argc == 0)
1689 {
1690 struct ui_out *uiout = current_uiout;
1691
1692 ui_out_emit_list list_emitter (uiout, "features");
1693 if (mi_async_p ())
1694 uiout->field_string (NULL, "async");
1695 if (target_can_execute_reverse ())
1696 uiout->field_string (NULL, "reverse");
1697 return;
1698 }
1699
1700 error (_("-list-target-features should be passed no arguments"));
1701 }
1702
1703 void
1704 mi_cmd_add_inferior (const char *command, const char *const *argv, int argc)
1705 {
1706 bool no_connection = false;
1707
1708 /* Parse the command options. */
1709 enum opt
1710 {
1711 NO_CONNECTION_OPT,
1712 };
1713 static const struct mi_opt opts[] =
1714 {
1715 {"-no-connection", NO_CONNECTION_OPT, 0},
1716 {NULL, 0, 0},
1717 };
1718
1719 int oind = 0;
1720 const char *oarg;
1721
1722 while (1)
1723 {
1724 int opt = mi_getopt ("-add-inferior", argc, argv, opts, &oind, &oarg);
1725
1726 if (opt < 0)
1727 break;
1728 switch ((enum opt) opt)
1729 {
1730 case NO_CONNECTION_OPT:
1731 no_connection = true;
1732 break;
1733 }
1734 }
1735
1736 scoped_restore_current_pspace_and_thread restore_pspace_thread;
1737
1738 inferior *inf = add_inferior_with_spaces ();
1739
1740 switch_to_inferior_and_push_target (inf, no_connection,
1741 current_inferior ());
1742
1743 current_uiout->field_fmt ("inferior", "i%d", inf->num);
1744
1745 process_stratum_target *proc_target = inf->process_target ();
1746
1747 if (proc_target != nullptr)
1748 {
1749 ui_out_emit_tuple tuple_emitter (current_uiout, "connection");
1750 current_uiout->field_unsigned ("number", proc_target->connection_number);
1751 current_uiout->field_string ("name", proc_target->shortname ());
1752 }
1753 }
1754
1755 void
1756 mi_cmd_remove_inferior (const char *command, const char *const *argv, int argc)
1757 {
1758 int id;
1759 struct inferior *inf_to_remove;
1760
1761 if (argc != 1)
1762 error (_("-remove-inferior should be passed a single argument"));
1763
1764 id = mi_parse_thread_group_id (argv[0]);
1765
1766 inf_to_remove = find_inferior_id (id);
1767 if (inf_to_remove == NULL)
1768 error (_("the specified thread group does not exist"));
1769
1770 if (inf_to_remove->pid != 0)
1771 error (_("cannot remove an active inferior"));
1772
1773 if (inf_to_remove == current_inferior ())
1774 {
1775 struct thread_info *tp = 0;
1776 struct inferior *new_inferior = NULL;
1777
1778 for (inferior *inf : all_inferiors ())
1779 {
1780 if (inf != inf_to_remove)
1781 new_inferior = inf;
1782 }
1783
1784 if (new_inferior == NULL)
1785 error (_("Cannot remove last inferior"));
1786
1787 set_current_inferior (new_inferior);
1788 if (new_inferior->pid != 0)
1789 tp = any_thread_of_inferior (new_inferior);
1790 if (tp != NULL)
1791 switch_to_thread (tp);
1792 else
1793 switch_to_no_thread ();
1794 set_current_program_space (new_inferior->pspace);
1795 }
1796
1797 delete_inferior (inf_to_remove);
1798 }
1799
1800 \f
1801
1802 /* Execute a command within a safe environment.
1803 Return <0 for error; >=0 for ok.
1804
1805 args->action will tell mi_execute_command what action
1806 to perform after the given command has executed (display/suppress
1807 prompt, display error). */
1808
1809 static void
1810 captured_mi_execute_command (struct mi_interp *mi, struct ui_out *uiout,
1811 struct mi_parse *context)
1812 {
1813 if (do_timings)
1814 current_command_ts = context->cmd_start;
1815
1816 scoped_restore save_token
1817 = make_scoped_restore (&mi->current_token, context->token.c_str ());
1818
1819 mi->running_result_record_printed = 0;
1820 mi->mi_proceeded = 0;
1821 switch (context->op)
1822 {
1823 case MI_COMMAND:
1824 /* A MI command was read from the input stream. */
1825 if (mi_debug_p)
1826 gdb_printf (gdb_stdlog,
1827 " token=`%s' command=`%s' args=`%s'\n",
1828 context->token.c_str (), context->command.get (),
1829 context->args ());
1830
1831 mi_cmd_execute (context);
1832
1833 /* Print the result if there were no errors.
1834
1835 Remember that on the way out of executing a command, you have
1836 to directly use the mi_interp's uiout, since the command
1837 could have reset the interpreter, in which case the current
1838 uiout will most likely crash in the mi_out_* routines. */
1839 if (!mi->running_result_record_printed)
1840 {
1841 gdb_puts (context->token.c_str (), mi->raw_stdout);
1842 /* There's no particularly good reason why target-connect results
1843 in not ^done. Should kill ^connected for MI3. */
1844 gdb_puts (strcmp (context->command.get (), "target-select") == 0
1845 ? "^connected" : "^done", mi->raw_stdout);
1846 mi_out_put (uiout, mi->raw_stdout);
1847 mi_out_rewind (uiout);
1848 mi_print_timing_maybe (mi->raw_stdout);
1849 gdb_puts ("\n", mi->raw_stdout);
1850 }
1851 else
1852 /* The command does not want anything to be printed. In that
1853 case, the command probably should not have written anything
1854 to uiout, but in case it has written something, discard it. */
1855 mi_out_rewind (uiout);
1856 break;
1857
1858 case CLI_COMMAND:
1859 {
1860 const char *argv[2];
1861
1862 /* A CLI command was read from the input stream. */
1863 /* This "feature" will be removed as soon as we have a
1864 complete set of mi commands. */
1865 /* Echo the command on the console. */
1866 gdb_printf (gdb_stdlog, "%s\n", context->command.get ());
1867 /* Call the "console" interpreter. */
1868 argv[0] = INTERP_CONSOLE;
1869 argv[1] = context->command.get ();
1870 mi_cmd_interpreter_exec ("-interpreter-exec", argv, 2);
1871
1872 /* If we changed interpreters, DON'T print out anything. */
1873 if (current_interp_named_p (INTERP_MI)
1874 || current_interp_named_p (INTERP_MI2)
1875 || current_interp_named_p (INTERP_MI3)
1876 || current_interp_named_p (INTERP_MI4))
1877 {
1878 if (!mi->running_result_record_printed)
1879 {
1880 gdb_puts (context->token.c_str (), mi->raw_stdout);
1881 gdb_puts ("^done", mi->raw_stdout);
1882 mi_out_put (uiout, mi->raw_stdout);
1883 mi_out_rewind (uiout);
1884 mi_print_timing_maybe (mi->raw_stdout);
1885 gdb_puts ("\n", mi->raw_stdout);
1886 }
1887 else
1888 mi_out_rewind (uiout);
1889 }
1890 break;
1891 }
1892 }
1893 }
1894
1895 /* Print a gdb exception to the MI output stream. */
1896
1897 static void
1898 mi_print_exception (struct mi_interp *mi, const char *token,
1899 const struct gdb_exception &exception)
1900 {
1901 gdb_puts (token, mi->raw_stdout);
1902 gdb_puts ("^error,msg=\"", mi->raw_stdout);
1903 if (exception.message == NULL)
1904 gdb_puts ("unknown error", mi->raw_stdout);
1905 else
1906 mi->raw_stdout->putstr (exception.what (), '"');
1907 gdb_puts ("\"", mi->raw_stdout);
1908
1909 switch (exception.error)
1910 {
1911 case UNDEFINED_COMMAND_ERROR:
1912 gdb_puts (",code=\"undefined-command\"", mi->raw_stdout);
1913 break;
1914 }
1915
1916 gdb_puts ("\n", mi->raw_stdout);
1917 }
1918
1919 void
1920 mi_execute_command (const char *cmd, int from_tty)
1921 {
1922 std::string token;
1923 std::unique_ptr<struct mi_parse> command;
1924
1925 /* This is to handle EOF (^D). We just quit gdb. */
1926 /* FIXME: we should call some API function here. */
1927 if (cmd == 0)
1928 quit_force (NULL, from_tty);
1929
1930 target_log_command (cmd);
1931
1932 struct mi_interp *mi
1933 = gdb::checked_static_cast<mi_interp *> (command_interp ());
1934 try
1935 {
1936 command = gdb::make_unique<mi_parse> (cmd, &token);
1937 }
1938 catch (const gdb_exception &exception)
1939 {
1940 mi_print_exception (mi, token.c_str (), exception);
1941 }
1942
1943 if (command != NULL)
1944 {
1945 command->token = std::move (token);
1946
1947 if (do_timings)
1948 {
1949 command->cmd_start = new mi_timestamp ();
1950 timestamp (command->cmd_start);
1951 }
1952
1953 try
1954 {
1955 captured_mi_execute_command (mi, current_uiout, command.get ());
1956 }
1957 catch (const gdb_exception &result)
1958 {
1959 /* Like in start_event_loop, enable input and force display
1960 of the prompt. Otherwise, any command that calls
1961 async_disable_stdin, and then throws, will leave input
1962 disabled. */
1963 async_enable_stdin ();
1964 current_ui->prompt_state = PROMPT_NEEDED;
1965
1966 /* The command execution failed and error() was called
1967 somewhere. */
1968 mi_print_exception (mi, command->token.c_str (), result);
1969 mi_out_rewind (current_uiout);
1970
1971 /* Throw to a higher level catch for SIGTERM sent to GDB. */
1972 if (result.reason == RETURN_FORCED_QUIT)
1973 throw;
1974 }
1975
1976 bpstat_do_actions ();
1977
1978 }
1979 }
1980
1981 /* See mi-cmds.h. */
1982
1983 void
1984 mi_execute_command (mi_parse *context)
1985 {
1986 if (context->op != MI_COMMAND)
1987 error (_("Command is not an MI command"));
1988
1989 mi_interp *mi = as_mi_interp (current_interpreter ());
1990
1991 /* The current interpreter may not be MI, for instance when using
1992 the Python gdb.execute_mi function. */
1993 if (mi != nullptr)
1994 scoped_restore save_token = make_scoped_restore (&mi->current_token,
1995 context->token.c_str ());
1996
1997 scoped_restore save_debug = make_scoped_restore (&mi_debug_p, 0);
1998
1999 mi_cmd_execute (context);
2000 }
2001
2002 /* Captures the current user selected context state, that is the current
2003 thread and frame. Later we can then check if the user selected context
2004 has changed at all. */
2005
2006 struct user_selected_context
2007 {
2008 /* Constructor. */
2009 user_selected_context ()
2010 : m_previous_ptid (inferior_ptid)
2011 {
2012 save_selected_frame (&m_previous_frame_id, &m_previous_frame_level);
2013 }
2014
2015 /* Return true if the user selected context has changed since this object
2016 was created. */
2017 bool has_changed () const
2018 {
2019 /* Did the selected thread change? */
2020 if (m_previous_ptid != null_ptid && inferior_ptid != null_ptid
2021 && m_previous_ptid != inferior_ptid)
2022 return true;
2023
2024 /* Grab details of the currently selected frame, for comparison. */
2025 frame_id current_frame_id;
2026 int current_frame_level;
2027 save_selected_frame (&current_frame_id, &current_frame_level);
2028
2029 /* Did the selected frame level change? */
2030 if (current_frame_level != m_previous_frame_level)
2031 return true;
2032
2033 /* Did the selected frame id change? If the innermost frame is
2034 selected then the level will be -1, and the frame-id will be
2035 null_frame_id. As comparing null_frame_id with itself always
2036 reports not-equal, we only do the equality test if we have something
2037 other than the innermost frame selected. */
2038 if (current_frame_level != -1
2039 && current_frame_id != m_previous_frame_id)
2040 return true;
2041
2042 /* Nothing changed! */
2043 return false;
2044 }
2045 private:
2046 /* The previously selected thread. This might be null_ptid if there was
2047 no previously selected thread. */
2048 ptid_t m_previous_ptid;
2049
2050 /* The previously selected frame. If the innermost frame is selected, or
2051 no frame is selected, then the frame_id will be null_frame_id, and the
2052 level will be -1. */
2053 frame_id m_previous_frame_id;
2054 int m_previous_frame_level;
2055 };
2056
2057 static void
2058 mi_cmd_execute (struct mi_parse *parse)
2059 {
2060 scoped_value_mark cleanup = prepare_execute_command ();
2061
2062 if (parse->all && parse->thread_group != -1)
2063 error (_("Cannot specify --thread-group together with --all"));
2064
2065 if (parse->all && parse->thread != -1)
2066 error (_("Cannot specify --thread together with --all"));
2067
2068 if (parse->thread_group != -1 && parse->thread != -1)
2069 error (_("Cannot specify --thread together with --thread-group"));
2070
2071 if (parse->frame != -1 && parse->thread == -1)
2072 error (_("Cannot specify --frame without --thread"));
2073
2074 if (parse->thread_group != -1)
2075 {
2076 struct inferior *inf = find_inferior_id (parse->thread_group);
2077 struct thread_info *tp = 0;
2078
2079 if (!inf)
2080 error (_("Invalid thread group for the --thread-group option"));
2081
2082 set_current_inferior (inf);
2083 /* This behaviour means that if --thread-group option identifies
2084 an inferior with multiple threads, then a random one will be
2085 picked. This is not a problem -- frontend should always
2086 provide --thread if it wishes to operate on a specific
2087 thread. */
2088 if (inf->pid != 0)
2089 tp = any_live_thread_of_inferior (inf);
2090 if (tp != NULL)
2091 switch_to_thread (tp);
2092 else
2093 switch_to_no_thread ();
2094 set_current_program_space (inf->pspace);
2095 }
2096
2097 user_selected_context current_user_selected_context;
2098
2099 gdb::optional<scoped_restore_current_thread> thread_saver;
2100 if (parse->thread != -1)
2101 {
2102 thread_info *tp = find_thread_global_id (parse->thread);
2103
2104 if (tp == NULL)
2105 error (_("Invalid thread id: %d"), parse->thread);
2106
2107 if (tp->state == THREAD_EXITED)
2108 error (_("Thread id: %d has terminated"), parse->thread);
2109
2110 if (parse->cmd->preserve_user_selected_context ())
2111 thread_saver.emplace ();
2112
2113 switch_to_thread (tp);
2114 }
2115
2116 gdb::optional<scoped_restore_selected_frame> frame_saver;
2117 if (parse->frame != -1)
2118 {
2119 frame_info_ptr fid;
2120 int frame = parse->frame;
2121
2122 fid = find_relative_frame (get_current_frame (), &frame);
2123 if (frame == 0)
2124 {
2125 if (parse->cmd->preserve_user_selected_context ())
2126 frame_saver.emplace ();
2127
2128 select_frame (fid);
2129 }
2130 else
2131 error (_("Invalid frame id: %d"), frame);
2132 }
2133
2134 gdb::optional<scoped_restore_current_language> lang_saver;
2135 if (parse->language != language_unknown)
2136 {
2137 lang_saver.emplace ();
2138 set_language (parse->language);
2139 }
2140
2141 current_context = parse;
2142
2143 gdb_assert (parse->cmd != nullptr);
2144
2145 gdb::optional<scoped_restore_tmpl<int>> restore_suppress_notification
2146 = parse->cmd->do_suppress_notification ();
2147
2148 parse->cmd->invoke (parse);
2149
2150 if (!parse->cmd->preserve_user_selected_context ()
2151 && current_user_selected_context.has_changed ())
2152 interps_notify_user_selected_context_changed
2153 (USER_SELECTED_THREAD | USER_SELECTED_FRAME);
2154 }
2155
2156 /* See mi-main.h. */
2157
2158 void
2159 mi_execute_cli_command (const char *cmd, bool args_p, const char *args)
2160 {
2161 if (cmd != nullptr)
2162 {
2163 std::string run (cmd);
2164
2165 if (args_p)
2166 run = run + " " + args;
2167 else
2168 gdb_assert (args == nullptr);
2169
2170 if (mi_debug_p)
2171 gdb_printf (gdb_stdlog, "cli=%s run=%s\n",
2172 cmd, run.c_str ());
2173
2174 execute_command (run.c_str (), 0 /* from_tty */ );
2175 }
2176 }
2177
2178 void
2179 mi_execute_async_cli_command (const char *cli_command, const char *const *argv,
2180 int argc)
2181 {
2182 std::string run = cli_command;
2183
2184 if (argc)
2185 run = run + " " + *argv;
2186 if (mi_async_p ())
2187 run += "&";
2188
2189 execute_command (run.c_str (), 0 /* from_tty */ );
2190 }
2191
2192 void
2193 mi_load_progress (const char *section_name,
2194 unsigned long sent_so_far,
2195 unsigned long total_section,
2196 unsigned long total_sent,
2197 unsigned long grand_total)
2198 {
2199 using namespace std::chrono;
2200 static steady_clock::time_point last_update;
2201 static char *previous_sect_name = NULL;
2202 int new_section;
2203 struct mi_interp *mi = as_mi_interp (current_interpreter ());
2204
2205 /* If the current interpreter is not an MI interpreter, then just
2206 don't bother printing anything. */
2207 if (mi == nullptr)
2208 return;
2209
2210 /* This function is called through deprecated_show_load_progress
2211 which means uiout may not be correct. Fix it for the duration
2212 of this function. */
2213
2214 auto uiout = mi_out_new (current_interpreter ()->name ());
2215 if (uiout == nullptr)
2216 return;
2217
2218 scoped_restore save_uiout
2219 = make_scoped_restore (&current_uiout, uiout.get ());
2220
2221 new_section = (previous_sect_name ?
2222 strcmp (previous_sect_name, section_name) : 1);
2223 if (new_section)
2224 {
2225 xfree (previous_sect_name);
2226 previous_sect_name = xstrdup (section_name);
2227
2228 if (mi->current_token)
2229 gdb_puts (mi->current_token, mi->raw_stdout);
2230 gdb_puts ("+download", mi->raw_stdout);
2231 {
2232 ui_out_emit_tuple tuple_emitter (uiout.get (), NULL);
2233 uiout->field_string ("section", section_name);
2234 uiout->field_signed ("section-size", total_section);
2235 uiout->field_signed ("total-size", grand_total);
2236 }
2237 mi_out_put (uiout.get (), mi->raw_stdout);
2238 gdb_puts ("\n", mi->raw_stdout);
2239 gdb_flush (mi->raw_stdout);
2240 }
2241
2242 steady_clock::time_point time_now = steady_clock::now ();
2243 if (time_now - last_update > milliseconds (500))
2244 {
2245 last_update = time_now;
2246 if (mi->current_token)
2247 gdb_puts (mi->current_token, mi->raw_stdout);
2248 gdb_puts ("+download", mi->raw_stdout);
2249 {
2250 ui_out_emit_tuple tuple_emitter (uiout.get (), NULL);
2251 uiout->field_string ("section", section_name);
2252 uiout->field_signed ("section-sent", sent_so_far);
2253 uiout->field_signed ("section-size", total_section);
2254 uiout->field_signed ("total-sent", total_sent);
2255 uiout->field_signed ("total-size", grand_total);
2256 }
2257 mi_out_put (uiout.get (), mi->raw_stdout);
2258 gdb_puts ("\n", mi->raw_stdout);
2259 gdb_flush (mi->raw_stdout);
2260 }
2261 }
2262
2263 static void
2264 timestamp (struct mi_timestamp *tv)
2265 {
2266 using namespace std::chrono;
2267
2268 tv->wallclock = steady_clock::now ();
2269 run_time_clock::now (tv->utime, tv->stime);
2270 }
2271
2272 static void
2273 print_diff_now (struct ui_file *file, struct mi_timestamp *start)
2274 {
2275 struct mi_timestamp now;
2276
2277 timestamp (&now);
2278 print_diff (file, start, &now);
2279 }
2280
2281 void
2282 mi_print_timing_maybe (struct ui_file *file)
2283 {
2284 /* If the command is -enable-timing then do_timings may be true
2285 whilst current_command_ts is not initialized. */
2286 if (do_timings && current_command_ts)
2287 print_diff_now (file, current_command_ts);
2288 }
2289
2290 static void
2291 print_diff (struct ui_file *file, struct mi_timestamp *start,
2292 struct mi_timestamp *end)
2293 {
2294 using namespace std::chrono;
2295
2296 duration<double> wallclock = end->wallclock - start->wallclock;
2297 duration<double> utime = end->utime - start->utime;
2298 duration<double> stime = end->stime - start->stime;
2299
2300 gdb_printf
2301 (file,
2302 ",time={wallclock=\"%0.5f\",user=\"%0.5f\",system=\"%0.5f\"}",
2303 wallclock.count (), utime.count (), stime.count ());
2304 }
2305
2306 void
2307 mi_cmd_trace_define_variable (const char *command, const char *const *argv,
2308 int argc)
2309 {
2310 LONGEST initval = 0;
2311 struct trace_state_variable *tsv;
2312 const char *name;
2313
2314 if (argc != 1 && argc != 2)
2315 error (_("Usage: -trace-define-variable VARIABLE [VALUE]"));
2316
2317 name = argv[0];
2318 if (*name++ != '$')
2319 error (_("Name of trace variable should start with '$'"));
2320
2321 validate_trace_state_variable_name (name);
2322
2323 tsv = find_trace_state_variable (name);
2324 if (!tsv)
2325 tsv = create_trace_state_variable (name);
2326
2327 if (argc == 2)
2328 initval = value_as_long (parse_and_eval (argv[1]));
2329
2330 tsv->initial_value = initval;
2331 }
2332
2333 void
2334 mi_cmd_trace_list_variables (const char *command, const char *const *argv,
2335 int argc)
2336 {
2337 if (argc != 0)
2338 error (_("-trace-list-variables: no arguments allowed"));
2339
2340 tvariables_info_1 ();
2341 }
2342
2343 void
2344 mi_cmd_trace_find (const char *command, const char *const *argv, int argc)
2345 {
2346 const char *mode;
2347
2348 if (argc == 0)
2349 error (_("trace selection mode is required"));
2350
2351 mode = argv[0];
2352
2353 if (strcmp (mode, "none") == 0)
2354 {
2355 tfind_1 (tfind_number, -1, 0, 0, 0);
2356 return;
2357 }
2358
2359 check_trace_running (current_trace_status ());
2360
2361 if (strcmp (mode, "frame-number") == 0)
2362 {
2363 if (argc != 2)
2364 error (_("frame number is required"));
2365 tfind_1 (tfind_number, atoi (argv[1]), 0, 0, 0);
2366 }
2367 else if (strcmp (mode, "tracepoint-number") == 0)
2368 {
2369 if (argc != 2)
2370 error (_("tracepoint number is required"));
2371 tfind_1 (tfind_tp, atoi (argv[1]), 0, 0, 0);
2372 }
2373 else if (strcmp (mode, "pc") == 0)
2374 {
2375 if (argc != 2)
2376 error (_("PC is required"));
2377 tfind_1 (tfind_pc, 0, parse_and_eval_address (argv[1]), 0, 0);
2378 }
2379 else if (strcmp (mode, "pc-inside-range") == 0)
2380 {
2381 if (argc != 3)
2382 error (_("Start and end PC are required"));
2383 tfind_1 (tfind_range, 0, parse_and_eval_address (argv[1]),
2384 parse_and_eval_address (argv[2]), 0);
2385 }
2386 else if (strcmp (mode, "pc-outside-range") == 0)
2387 {
2388 if (argc != 3)
2389 error (_("Start and end PC are required"));
2390 tfind_1 (tfind_outside, 0, parse_and_eval_address (argv[1]),
2391 parse_and_eval_address (argv[2]), 0);
2392 }
2393 else if (strcmp (mode, "line") == 0)
2394 {
2395 if (argc != 2)
2396 error (_("Line is required"));
2397
2398 std::vector<symtab_and_line> sals
2399 = decode_line_with_current_source (argv[1],
2400 DECODE_LINE_FUNFIRSTLINE);
2401 const symtab_and_line &sal = sals[0];
2402
2403 if (sal.symtab == 0)
2404 error (_("Could not find the specified line"));
2405
2406 CORE_ADDR start_pc, end_pc;
2407 if (sal.line > 0 && find_line_pc_range (sal, &start_pc, &end_pc))
2408 tfind_1 (tfind_range, 0, start_pc, end_pc - 1, 0);
2409 else
2410 error (_("Could not find the specified line"));
2411 }
2412 else
2413 error (_("Invalid mode '%s'"), mode);
2414
2415 if (has_stack_frames () || get_traceframe_number () >= 0)
2416 print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS, 1);
2417 }
2418
2419 void
2420 mi_cmd_trace_save (const char *command, const char *const *argv, int argc)
2421 {
2422 int target_saves = 0;
2423 int generate_ctf = 0;
2424 const char *filename;
2425 int oind = 0;
2426 const char *oarg;
2427
2428 enum opt
2429 {
2430 TARGET_SAVE_OPT, CTF_OPT
2431 };
2432 static const struct mi_opt opts[] =
2433 {
2434 {"r", TARGET_SAVE_OPT, 0},
2435 {"ctf", CTF_OPT, 0},
2436 { 0, 0, 0 }
2437 };
2438
2439 while (1)
2440 {
2441 int opt = mi_getopt ("-trace-save", argc, argv, opts,
2442 &oind, &oarg);
2443
2444 if (opt < 0)
2445 break;
2446 switch ((enum opt) opt)
2447 {
2448 case TARGET_SAVE_OPT:
2449 target_saves = 1;
2450 break;
2451 case CTF_OPT:
2452 generate_ctf = 1;
2453 break;
2454 }
2455 }
2456
2457 if (argc - oind != 1)
2458 error (_("Exactly one argument required "
2459 "(file in which to save trace data)"));
2460
2461 filename = argv[oind];
2462
2463 if (generate_ctf)
2464 trace_save_ctf (filename, target_saves);
2465 else
2466 trace_save_tfile (filename, target_saves);
2467 }
2468
2469 void
2470 mi_cmd_trace_start (const char *command, const char *const *argv, int argc)
2471 {
2472 start_tracing (NULL);
2473 }
2474
2475 void
2476 mi_cmd_trace_status (const char *command, const char *const *argv, int argc)
2477 {
2478 trace_status_mi (0);
2479 }
2480
2481 void
2482 mi_cmd_trace_stop (const char *command, const char *const *argv, int argc)
2483 {
2484 stop_tracing (NULL);
2485 trace_status_mi (1);
2486 }
2487
2488 /* Implement the "-ada-task-info" command. */
2489
2490 void
2491 mi_cmd_ada_task_info (const char *command, const char *const *argv, int argc)
2492 {
2493 if (argc != 0 && argc != 1)
2494 error (_("Invalid MI command"));
2495
2496 print_ada_task_info (current_uiout, argv[0], current_inferior ());
2497 }
2498
2499 /* Print EXPRESSION according to VALUES. */
2500
2501 static void
2502 print_variable_or_computed (const char *expression, enum print_values values)
2503 {
2504 struct value *val;
2505 struct ui_out *uiout = current_uiout;
2506
2507 string_file stb;
2508
2509 expression_up expr = parse_expression (expression);
2510
2511 if (values == PRINT_SIMPLE_VALUES)
2512 val = expr->evaluate_type ();
2513 else
2514 val = expr->evaluate ();
2515
2516 gdb::optional<ui_out_emit_tuple> tuple_emitter;
2517 if (values != PRINT_NO_VALUES)
2518 tuple_emitter.emplace (uiout, nullptr);
2519 uiout->field_string ("name", expression);
2520
2521 switch (values)
2522 {
2523 case PRINT_SIMPLE_VALUES:
2524 type_print (val->type (), "", &stb, -1);
2525 uiout->field_stream ("type", stb);
2526 if (mi_simple_type_p (val->type ()))
2527 {
2528 struct value_print_options opts;
2529
2530 get_no_prettyformat_print_options (&opts);
2531 opts.deref_ref = true;
2532 common_val_print (val, &stb, 0, &opts, current_language);
2533 uiout->field_stream ("value", stb);
2534 }
2535 break;
2536 case PRINT_ALL_VALUES:
2537 {
2538 struct value_print_options opts;
2539
2540 get_no_prettyformat_print_options (&opts);
2541 opts.deref_ref = true;
2542 common_val_print (val, &stb, 0, &opts, current_language);
2543 uiout->field_stream ("value", stb);
2544 }
2545 break;
2546 }
2547 }
2548
2549 /* Implement the "-trace-frame-collected" command. */
2550
2551 void
2552 mi_cmd_trace_frame_collected (const char *command, const char *const *argv,
2553 int argc)
2554 {
2555 struct bp_location *tloc;
2556 int stepping_frame;
2557 struct collection_list *clist;
2558 struct collection_list tracepoint_list, stepping_list;
2559 struct traceframe_info *tinfo;
2560 int oind = 0;
2561 enum print_values var_print_values = PRINT_ALL_VALUES;
2562 enum print_values comp_print_values = PRINT_ALL_VALUES;
2563 int registers_format = 'x';
2564 int memory_contents = 0;
2565 struct ui_out *uiout = current_uiout;
2566 enum opt
2567 {
2568 VAR_PRINT_VALUES,
2569 COMP_PRINT_VALUES,
2570 REGISTERS_FORMAT,
2571 MEMORY_CONTENTS,
2572 };
2573 static const struct mi_opt opts[] =
2574 {
2575 {"-var-print-values", VAR_PRINT_VALUES, 1},
2576 {"-comp-print-values", COMP_PRINT_VALUES, 1},
2577 {"-registers-format", REGISTERS_FORMAT, 1},
2578 {"-memory-contents", MEMORY_CONTENTS, 0},
2579 { 0, 0, 0 }
2580 };
2581
2582 while (1)
2583 {
2584 const char *oarg;
2585 int opt = mi_getopt ("-trace-frame-collected", argc, argv, opts,
2586 &oind, &oarg);
2587 if (opt < 0)
2588 break;
2589 switch ((enum opt) opt)
2590 {
2591 case VAR_PRINT_VALUES:
2592 var_print_values = mi_parse_print_values (oarg);
2593 break;
2594 case COMP_PRINT_VALUES:
2595 comp_print_values = mi_parse_print_values (oarg);
2596 break;
2597 case REGISTERS_FORMAT:
2598 registers_format = oarg[0];
2599 break;
2600 case MEMORY_CONTENTS:
2601 memory_contents = 1;
2602 break;
2603 }
2604 }
2605
2606 if (oind != argc)
2607 error (_("Usage: -trace-frame-collected "
2608 "[--var-print-values PRINT_VALUES] "
2609 "[--comp-print-values PRINT_VALUES] "
2610 "[--registers-format FORMAT]"
2611 "[--memory-contents]"));
2612
2613 /* This throws an error is not inspecting a trace frame. */
2614 tloc = get_traceframe_location (&stepping_frame);
2615
2616 /* This command only makes sense for the current frame, not the
2617 selected frame. */
2618 scoped_restore_current_thread restore_thread;
2619 select_frame (get_current_frame ());
2620
2621 encode_actions (tloc, &tracepoint_list, &stepping_list);
2622
2623 if (stepping_frame)
2624 clist = &stepping_list;
2625 else
2626 clist = &tracepoint_list;
2627
2628 tinfo = get_traceframe_info ();
2629
2630 /* Explicitly wholly collected variables. */
2631 {
2632 ui_out_emit_list list_emitter (uiout, "explicit-variables");
2633 const std::vector<std::string> &wholly_collected
2634 = clist->wholly_collected ();
2635 for (size_t i = 0; i < wholly_collected.size (); i++)
2636 {
2637 const std::string &str = wholly_collected[i];
2638 print_variable_or_computed (str.c_str (), var_print_values);
2639 }
2640 }
2641
2642 /* Computed expressions. */
2643 {
2644 ui_out_emit_list list_emitter (uiout, "computed-expressions");
2645
2646 const std::vector<std::string> &computed = clist->computed ();
2647 for (size_t i = 0; i < computed.size (); i++)
2648 {
2649 const std::string &str = computed[i];
2650 print_variable_or_computed (str.c_str (), comp_print_values);
2651 }
2652 }
2653
2654 /* Registers. Given pseudo-registers, and that some architectures
2655 (like MIPS) actually hide the raw registers, we don't go through
2656 the trace frame info, but instead consult the register cache for
2657 register availability. */
2658 {
2659 frame_info_ptr frame;
2660 struct gdbarch *gdbarch;
2661 int regnum;
2662 int numregs;
2663
2664 ui_out_emit_list list_emitter (uiout, "registers");
2665
2666 frame = get_selected_frame (NULL);
2667 gdbarch = get_frame_arch (frame);
2668 numregs = gdbarch_num_cooked_regs (gdbarch);
2669
2670 for (regnum = 0; regnum < numregs; regnum++)
2671 {
2672 if (*(gdbarch_register_name (gdbarch, regnum)) == '\0')
2673 continue;
2674
2675 output_register (frame, regnum, registers_format, 1);
2676 }
2677 }
2678
2679 /* Trace state variables. */
2680 {
2681 ui_out_emit_list list_emitter (uiout, "tvars");
2682
2683 for (int tvar : tinfo->tvars)
2684 {
2685 struct trace_state_variable *tsv;
2686
2687 tsv = find_trace_state_variable_by_number (tvar);
2688
2689 ui_out_emit_tuple tuple_emitter (uiout, NULL);
2690
2691 if (tsv != NULL)
2692 {
2693 uiout->field_fmt ("name", "$%s", tsv->name.c_str ());
2694
2695 tsv->value_known = target_get_trace_state_variable_value (tsv->number,
2696 &tsv->value);
2697 uiout->field_signed ("current", tsv->value);
2698 }
2699 else
2700 {
2701 uiout->field_skip ("name");
2702 uiout->field_skip ("current");
2703 }
2704 }
2705 }
2706
2707 /* Memory. */
2708 {
2709 std::vector<mem_range> available_memory;
2710
2711 traceframe_available_memory (&available_memory, 0, ULONGEST_MAX);
2712
2713 ui_out_emit_list list_emitter (uiout, "memory");
2714
2715 for (const mem_range &r : available_memory)
2716 {
2717 gdbarch *gdbarch = current_inferior ()->arch ();
2718
2719 ui_out_emit_tuple tuple_emitter (uiout, NULL);
2720
2721 uiout->field_core_addr ("address", gdbarch, r.start);
2722 uiout->field_signed ("length", r.length);
2723
2724 gdb::byte_vector data (r.length);
2725
2726 if (memory_contents)
2727 {
2728 if (target_read_memory (r.start, data.data (), r.length) == 0)
2729 {
2730 std::string data_str = bin2hex (data.data (), r.length);
2731 uiout->field_string ("contents", data_str);
2732 }
2733 else
2734 uiout->field_skip ("contents");
2735 }
2736 }
2737 }
2738 }
2739
2740 /* See mi/mi-main.h. */
2741
2742 void
2743 mi_cmd_fix_multi_location_breakpoint_output (const char *command,
2744 const char *const *argv,
2745 int argc)
2746 {
2747 fix_multi_location_breakpoint_output_globally = true;
2748 }
2749
2750 /* See mi/mi-main.h. */
2751
2752 void
2753 mi_cmd_fix_breakpoint_script_output (const char *command,
2754 const char *const *argv, int argc)
2755 {
2756 fix_breakpoint_script_output_globally = true;
2757 }
2758
2759 /* Implement the "-complete" command. */
2760
2761 void
2762 mi_cmd_complete (const char *command, const char *const *argv, int argc)
2763 {
2764 if (argc != 1)
2765 error (_("Usage: -complete COMMAND"));
2766
2767 if (max_completions == 0)
2768 error (_("max-completions is zero, completion is disabled."));
2769
2770 int quote_char = '\0';
2771 const char *word;
2772
2773 completion_result result = complete (argv[0], &word, &quote_char);
2774
2775 std::string arg_prefix (argv[0], word - argv[0]);
2776
2777 struct ui_out *uiout = current_uiout;
2778
2779 if (result.number_matches > 0)
2780 uiout->field_fmt ("completion", "%s%s",
2781 arg_prefix.c_str (),result.match_list[0]);
2782
2783 {
2784 ui_out_emit_list completions_emitter (uiout, "matches");
2785
2786 if (result.number_matches == 1)
2787 uiout->field_fmt (NULL, "%s%s",
2788 arg_prefix.c_str (), result.match_list[0]);
2789 else
2790 {
2791 result.sort_match_list ();
2792 for (size_t i = 0; i < result.number_matches; i++)
2793 {
2794 uiout->field_fmt (NULL, "%s%s",
2795 arg_prefix.c_str (), result.match_list[i + 1]);
2796 }
2797 }
2798 }
2799 uiout->field_string ("max_completions_reached",
2800 result.number_matches == max_completions ? "1" : "0");
2801 }
2802
2803 /* See mi-main.h. */
2804 int
2805 mi_parse_thread_group_id (const char *id)
2806 {
2807 if (*id != 'i')
2808 error (_("thread group id should start with an 'i'"));
2809
2810 char *end;
2811 long num = strtol (id + 1, &end, 10);
2812
2813 if (*end != '\0' || num > INT_MAX)
2814 error (_("invalid thread group id '%s'"), id);
2815
2816 return (int) num;
2817 }
2818
2819 void _initialize_mi_main ();
2820 void
2821 _initialize_mi_main ()
2822 {
2823 set_show_commands mi_async_cmds
2824 = add_setshow_boolean_cmd ("mi-async", class_run,
2825 &mi_async_1, _("\
2826 Set whether MI asynchronous mode is enabled."), _("\
2827 Show whether MI asynchronous mode is enabled."), _("\
2828 Tells GDB whether MI should be in asynchronous mode."),
2829 set_mi_async_command,
2830 show_mi_async_command,
2831 &setlist, &showlist);
2832
2833 /* Alias old "target-async" to "mi-async". */
2834 cmd_list_element *set_target_async_cmd
2835 = add_alias_cmd ("target-async", mi_async_cmds.set, class_run, 0, &setlist);
2836 deprecate_cmd (set_target_async_cmd, "set mi-async");
2837
2838 cmd_list_element *show_target_async_cmd
2839 = add_alias_cmd ("target-async", mi_async_cmds.show, class_run, 0,
2840 &showlist);
2841 deprecate_cmd (show_target_async_cmd, "show mi-async");
2842 }