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