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