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