Multiexec MI
[external/binutils.git] / gdb / mi / mi-main.c
1 /* MI Command Set.
2
3    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007, 2008, 2009, 2010
4    Free Software Foundation, Inc.
5
6    Contributed by Cygnus Solutions (a Red Hat company).
7
8    This file is part of GDB.
9
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 3 of the License, or
13    (at your option) any later version.
14
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19
20    You should have received a copy of the GNU General Public License
21    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
22
23 /* Work in progress.  */
24
25 #include "defs.h"
26 #include "arch-utils.h"
27 #include "target.h"
28 #include "inferior.h"
29 #include "gdb_string.h"
30 #include "exceptions.h"
31 #include "top.h"
32 #include "gdbthread.h"
33 #include "mi-cmds.h"
34 #include "mi-parse.h"
35 #include "mi-getopt.h"
36 #include "mi-console.h"
37 #include "ui-out.h"
38 #include "mi-out.h"
39 #include "interps.h"
40 #include "event-loop.h"
41 #include "event-top.h"
42 #include "gdbcore.h"            /* For write_memory().  */
43 #include "value.h"
44 #include "regcache.h"
45 #include "gdb.h"
46 #include "frame.h"
47 #include "mi-main.h"
48 #include "mi-common.h"
49 #include "language.h"
50 #include "valprint.h"
51 #include "inferior.h"
52 #include "osdata.h"
53 #include "splay-tree.h"
54
55 #include <ctype.h>
56 #include <sys/time.h>
57
58 #if defined HAVE_SYS_RESOURCE_H
59 #include <sys/resource.h>
60 #endif
61
62 #ifdef HAVE_GETRUSAGE
63 struct rusage rusage;
64 #endif
65
66 enum
67   {
68     FROM_TTY = 0
69   };
70
71 int mi_debug_p;
72 struct ui_file *raw_stdout;
73
74 /* This is used to pass the current command timestamp
75    down to continuation routines.  */
76 static struct mi_timestamp *current_command_ts;
77
78 static int do_timings = 0;
79
80 char *current_token;
81 /* Few commands would like to know if options like --thread-group
82    were explicitly specified.  This variable keeps the current
83    parsed command including all option, and make it possible.  */
84 static struct mi_parse *current_context;
85
86 int running_result_record_printed = 1;
87
88 /* Flag indicating that the target has proceeded since the last
89    command was issued.  */
90 int mi_proceeded;
91
92 extern void _initialize_mi_main (void);
93 static void mi_cmd_execute (struct mi_parse *parse);
94
95 static void mi_execute_cli_command (const char *cmd, int args_p,
96                                     const char *args);
97 static void mi_execute_async_cli_command (char *cli_command, 
98                                                         char **argv, int argc);
99 static int register_changed_p (int regnum, struct regcache *,
100                                struct regcache *);
101 static void get_register (struct frame_info *, int regnum, int format);
102
103 /* Command implementations.  FIXME: Is this libgdb?  No.  This is the MI
104    layer that calls libgdb.  Any operation used in the below should be
105    formalized.  */
106
107 static void timestamp (struct mi_timestamp *tv);
108
109 static void print_diff_now (struct mi_timestamp *start);
110 static void print_diff (struct mi_timestamp *start, struct mi_timestamp *end);
111
112 void
113 mi_cmd_gdb_exit (char *command, char **argv, int argc)
114 {
115   /* We have to print everything right here because we never return.  */
116   if (current_token)
117     fputs_unfiltered (current_token, raw_stdout);
118   fputs_unfiltered ("^exit\n", raw_stdout);
119   mi_out_put (uiout, raw_stdout);
120   gdb_flush (raw_stdout);
121   /* FIXME: The function called is not yet a formal libgdb function.  */
122   quit_force (NULL, FROM_TTY);
123 }
124
125 void
126 mi_cmd_exec_next (char *command, char **argv, int argc)
127 {
128   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
129   if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
130     mi_execute_async_cli_command ("reverse-next", argv + 1, argc - 1);
131   else
132     mi_execute_async_cli_command ("next", argv, argc);
133 }
134
135 void
136 mi_cmd_exec_next_instruction (char *command, char **argv, int argc)
137 {
138   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
139   if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
140     mi_execute_async_cli_command ("reverse-nexti", argv + 1, argc - 1);
141   else
142     mi_execute_async_cli_command ("nexti", argv, argc);
143 }
144
145 void
146 mi_cmd_exec_step (char *command, char **argv, int argc)
147 {
148   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
149   if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
150     mi_execute_async_cli_command ("reverse-step", argv + 1, argc - 1);
151   else
152     mi_execute_async_cli_command ("step", argv, argc);
153 }
154
155 void
156 mi_cmd_exec_step_instruction (char *command, char **argv, int argc)
157 {
158   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
159   if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
160     mi_execute_async_cli_command ("reverse-stepi", argv + 1, argc - 1);
161   else
162     mi_execute_async_cli_command ("stepi", argv, argc);
163 }
164
165 void
166 mi_cmd_exec_finish (char *command, char **argv, int argc)
167 {
168   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
169   if (argc > 0 && strcmp(argv[0], "--reverse") == 0)
170     mi_execute_async_cli_command ("reverse-finish", argv + 1, argc - 1);
171   else
172     mi_execute_async_cli_command ("finish", argv, argc);
173 }
174
175 void
176 mi_cmd_exec_return (char *command, char **argv, int argc)
177 {
178   /* This command doesn't really execute the target, it just pops the
179      specified number of frames. */
180   if (argc)
181     /* Call return_command with from_tty argument equal to 0 so as to
182        avoid being queried.  */
183     return_command (*argv, 0);
184   else
185     /* Call return_command with from_tty argument equal to 0 so as to
186        avoid being queried.  */
187     return_command (NULL, 0);
188
189   /* Because we have called return_command with from_tty = 0, we need
190      to print the frame here.  */
191   print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS);
192 }
193
194 void
195 mi_cmd_exec_jump (char *args, char **argv, int argc)
196 {
197   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
198   mi_execute_async_cli_command ("jump", argv, argc);
199 }
200  
201 static void
202 proceed_thread (struct thread_info *thread, int pid)
203 {
204   if (!is_stopped (thread->ptid))
205     return;
206
207   if (pid != 0 && PIDGET (thread->ptid) != pid)
208     return;
209
210   switch_to_thread (thread->ptid);
211   clear_proceed_status ();
212   proceed ((CORE_ADDR) -1, TARGET_SIGNAL_DEFAULT, 0);
213 }
214
215
216 static int
217 proceed_thread_callback (struct thread_info *thread, void *arg)
218 {
219   int pid = *(int *)arg;
220   proceed_thread (thread, pid);
221   return 0;
222 }
223
224 static void
225 exec_continue (char **argv, int argc)
226 {
227   if (non_stop)
228     {
229       /* In non-stop mode, 'resume' always resumes a single thread.  Therefore,
230          to resume all threads of the current inferior, or all threads in all
231          inferiors, we need to iterate over threads.
232
233          See comment on infcmd.c:proceed_thread_callback for rationale.  */
234       if (current_context->all || current_context->thread_group != -1)
235         {
236           int pid = 0;
237           struct cleanup *back_to = make_cleanup_restore_current_thread ();
238
239           if (!current_context->all)
240             {
241               struct inferior *inf = find_inferior_id (current_context->thread_group);
242               pid = inf->pid;
243             }
244           iterate_over_threads (proceed_thread_callback, &pid);
245           do_cleanups (back_to);
246         }
247       else
248         {
249           continue_1 (0);
250         }
251     }
252   else
253     {
254       struct cleanup *back_to = make_cleanup_restore_integer (&sched_multi);
255       if (current_context->all)
256         {
257           sched_multi = 1;
258           continue_1 (0);
259         }
260       else
261         {
262           /* In all-stop mode, -exec-continue traditionally resumed either
263              all threads, or one thread, depending on the 'scheduler-locking'
264              variable.  Let's continue to do the same.  */
265           continue_1 (1);
266         }
267       do_cleanups (back_to);
268     }
269 }
270
271 static void
272 exec_direction_forward (void *notused)
273 {
274   execution_direction = EXEC_FORWARD;
275 }
276
277 static void
278 exec_reverse_continue (char **argv, int argc)
279 {
280   enum exec_direction_kind dir = execution_direction;
281   struct cleanup *old_chain;
282
283   if (dir == EXEC_ERROR)
284     error (_("Target %s does not support this command."), target_shortname);
285
286   if (dir == EXEC_REVERSE)
287     error (_("Already in reverse mode."));
288
289   if (!target_can_execute_reverse)
290     error (_("Target %s does not support this command."), target_shortname);
291
292   old_chain = make_cleanup (exec_direction_forward, NULL);
293   execution_direction = EXEC_REVERSE;
294   exec_continue (argv, argc);
295   do_cleanups (old_chain);
296 }
297
298 void
299 mi_cmd_exec_continue (char *command, char **argv, int argc)
300 {
301   if (argc > 0 && strcmp (argv[0], "--reverse") == 0)
302     exec_reverse_continue (argv + 1, argc - 1);
303   else
304     exec_continue (argv, argc);
305 }
306
307 static int
308 interrupt_thread_callback (struct thread_info *thread, void *arg)
309 {
310   int pid = *(int *)arg;
311
312   if (!is_running (thread->ptid))
313     return 0;
314
315   if (PIDGET (thread->ptid) != pid)
316     return 0;
317
318   target_stop (thread->ptid);
319   return 0;
320 }
321
322 /* Interrupt the execution of the target.  Note how we must play around
323    with the token variables, in order to display the current token in
324    the result of the interrupt command, and the previous execution
325    token when the target finally stops.  See comments in
326    mi_cmd_execute.  */
327 void
328 mi_cmd_exec_interrupt (char *command, char **argv, int argc)
329 {
330   /* In all-stop mode, everything stops, so we don't need to try
331      anything specific.  */
332   if (!non_stop)
333     {
334       interrupt_target_1 (0);
335       return;
336     }
337
338   if (current_context->all)
339     {
340       /* This will interrupt all threads in all inferiors.  */
341       interrupt_target_1 (1);
342     }
343   else if (current_context->thread_group != -1)
344     {
345       struct inferior *inf = find_inferior_id (current_context->thread_group);
346       iterate_over_threads (interrupt_thread_callback, &inf->pid);
347     }
348   else
349     {
350       /* Interrupt just the current thread -- either explicitly
351          specified via --thread or whatever was current before
352          MI command was sent.  */
353       interrupt_target_1 (0);
354     }
355 }
356
357 static int
358 run_one_inferior (struct inferior *inf, void *arg)
359 {
360   struct thread_info *tp = 0;
361
362   if (inf->pid != 0)
363     {
364       if (inf->pid != ptid_get_pid (inferior_ptid))
365         {
366           struct thread_info *tp;
367
368           tp = any_thread_of_process (inf->pid);
369           if (!tp)
370             error (_("Inferior has no threads."));
371
372           switch_to_thread (tp->ptid);
373         }
374     }
375   else
376     {
377       set_current_inferior (inf);
378       switch_to_thread (null_ptid);
379       set_current_program_space (inf->pspace);
380     }
381   mi_execute_cli_command ("run", target_can_async_p (),
382                           target_can_async_p () ? "&" : NULL);
383   return 0;
384 }
385
386 void
387 mi_cmd_exec_run (char *command, char **argv, int argc)
388 {
389   if (current_context->all)
390     {
391       struct cleanup *back_to = save_current_space_and_thread ();
392       iterate_over_inferiors (run_one_inferior, NULL);
393       do_cleanups (back_to);
394     }
395   else
396     {
397       mi_execute_cli_command ("run", target_can_async_p (),
398                               target_can_async_p () ? "&" : NULL);
399     }
400 }
401
402
403 static int
404 find_thread_of_process (struct thread_info *ti, void *p)
405 {
406   int pid = *(int *)p;
407   if (PIDGET (ti->ptid) == pid && !is_exited (ti->ptid))
408     return 1;
409
410   return 0;
411 }
412
413 void
414 mi_cmd_target_detach (char *command, char **argv, int argc)
415 {
416   if (argc != 0 && argc != 1)
417     error ("Usage: -target-detach [thread-group]");
418
419   if (argc == 1)
420     {
421       struct thread_info *tp;
422       char *end = argv[0];
423       int pid = strtol (argv[0], &end, 10);
424       if (*end != '\0')
425         error (_("Cannot parse thread group id '%s'"), argv[0]);
426
427       /* Pick any thread in the desired process.  Current
428          target_detach deteches from the parent of inferior_ptid.  */
429       tp = iterate_over_threads (find_thread_of_process, &pid);
430       if (!tp)
431         error (_("Thread group is empty"));
432
433       switch_to_thread (tp->ptid);
434     }
435
436   detach_command (NULL, 0);
437 }
438
439 void
440 mi_cmd_thread_select (char *command, char **argv, int argc)
441 {
442   enum gdb_rc rc;
443   char *mi_error_message;
444
445   if (argc != 1)
446     error ("mi_cmd_thread_select: USAGE: threadnum.");
447
448   rc = gdb_thread_select (uiout, argv[0], &mi_error_message);
449
450   if (rc == GDB_RC_FAIL)
451     {
452       make_cleanup (xfree, mi_error_message);
453       error ("%s", mi_error_message);
454     }
455 }
456
457 void
458 mi_cmd_thread_list_ids (char *command, char **argv, int argc)
459 {
460   enum gdb_rc rc;
461   char *mi_error_message;
462
463   if (argc != 0)
464     error ("mi_cmd_thread_list_ids: No arguments required.");
465
466   rc = gdb_list_thread_ids (uiout, &mi_error_message);
467
468   if (rc == GDB_RC_FAIL)
469     {
470       make_cleanup (xfree, mi_error_message);
471       error ("%s", mi_error_message);
472     }
473 }
474
475 void
476 mi_cmd_thread_info (char *command, char **argv, int argc)
477 {
478   int thread = -1;
479   
480   if (argc != 0 && argc != 1)
481     error ("Invalid MI command");
482
483   if (argc == 1)
484     thread = atoi (argv[0]);
485
486   print_thread_info (uiout, thread, -1);
487 }
488
489 struct collect_cores_data
490 {
491   int pid;
492
493   VEC (int) *cores;
494 };
495
496 static int
497 collect_cores (struct thread_info *ti, void *xdata)
498 {
499   struct collect_cores_data *data = xdata;
500
501   if (ptid_get_pid (ti->ptid) == data->pid)
502     {
503       int core = target_core_of_thread (ti->ptid);
504       if (core != -1)
505         VEC_safe_push (int, data->cores, core);
506     }
507
508   return 0;
509 }
510
511 static int *
512 unique (int *b, int *e)
513 {
514   int *d = b;
515   while (++b != e)
516     if (*d != *b)
517       *++d = *b;
518   return ++d;
519 }
520
521 struct print_one_inferior_data
522 {
523   int recurse;
524   VEC (int) *inferiors;
525 };
526
527 static int
528 print_one_inferior (struct inferior *inferior, void *xdata)
529 {
530   struct print_one_inferior_data *top_data = xdata;
531
532   if (VEC_empty (int, top_data->inferiors)
533       || bsearch (&(inferior->pid), VEC_address (int, top_data->inferiors),
534                   VEC_length (int, top_data->inferiors), sizeof (int),
535                   compare_positive_ints))
536     {
537       struct collect_cores_data data;
538       struct cleanup *back_to
539         = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
540
541       ui_out_field_fmt (uiout, "id", "i%d", inferior->num);
542       ui_out_field_string (uiout, "type", "process");
543       if (inferior->pid != 0)
544         ui_out_field_int (uiout, "pid", inferior->pid);
545
546       if (inferior->pspace->ebfd)
547         {
548           ui_out_field_string (uiout, "executable",
549                                bfd_get_filename (inferior->pspace->ebfd));
550         }
551
552       data.cores = 0;
553       if (inferior->pid != 0)
554         {
555           data.pid = inferior->pid;
556           iterate_over_threads (collect_cores, &data);
557         }
558
559       if (!VEC_empty (int, data.cores))
560         {
561           int elt;
562           int i;
563           int *b, *e;
564           struct cleanup *back_to_2 =
565             make_cleanup_ui_out_list_begin_end (uiout, "cores");
566
567           qsort (VEC_address (int, data.cores),
568                  VEC_length (int, data.cores), sizeof (int),
569                  compare_positive_ints);
570
571           b = VEC_address (int, data.cores);
572           e = b + VEC_length (int, data.cores);
573           e = unique (b, e);
574
575           for (; b != e; ++b)
576             ui_out_field_int (uiout, NULL, *b);
577
578           do_cleanups (back_to_2);
579         }
580
581       if (top_data->recurse)
582         print_thread_info (uiout, -1, inferior->pid);
583
584       do_cleanups (back_to);
585     }
586
587   return 0;
588 }
589
590 /* Output a field named 'cores' with a list as the value.  The elements of
591    the list are obtained by splitting 'cores' on comma.  */
592
593 static void
594 output_cores (struct ui_out *uiout, const char *field_name, const char *xcores)
595 {
596   struct cleanup *back_to = make_cleanup_ui_out_list_begin_end (uiout,
597                                                                 field_name);
598   char *cores = xstrdup (xcores);
599   char *p = cores;
600
601   make_cleanup (xfree, cores);
602
603   for (p = strtok (p, ","); p;  p = strtok (NULL, ","))
604     ui_out_field_string (uiout, NULL, p);
605
606   do_cleanups (back_to);
607 }
608
609 static void
610 free_vector_of_ints (void *xvector)
611 {
612   VEC (int) **vector = xvector;
613   VEC_free (int, *vector);
614 }
615
616 static void
617 do_nothing (splay_tree_key k)
618 {
619 }
620
621 static void
622 free_vector_of_osdata_items (splay_tree_value xvalue)
623 {
624   VEC (osdata_item_s) *value = (VEC (osdata_item_s) *) xvalue;
625   /* We don't free the items itself, it will be done separately.  */
626   VEC_free (osdata_item_s, value);
627 }
628
629 static int
630 splay_tree_int_comparator (splay_tree_key xa, splay_tree_key xb)
631 {
632   int a = xa;
633   int b = xb;
634   return a - b;
635 }
636
637 static void
638 free_splay_tree (void *xt)
639 {
640   splay_tree t = xt;
641   splay_tree_delete (t);
642 }
643
644 static void
645 list_available_thread_groups (VEC (int) *ids, int recurse)
646 {
647   struct osdata *data;
648   struct osdata_item *item;
649   int ix_items;
650   /* This keeps a map from integer (pid) to VEC (struct osdata_item *)*
651      The vector contains information about all threads for the given pid.
652      This is assigned an initial value to avoid "may be used uninitialized"
653      warning from gcc.  */
654   splay_tree tree = NULL;
655
656   /* get_osdata will throw if it cannot return data.  */
657   data = get_osdata ("processes");
658   make_cleanup_osdata_free (data);
659
660   if (recurse)
661     {
662       struct osdata *threads = get_osdata ("threads");
663       make_cleanup_osdata_free (threads);
664
665       tree = splay_tree_new (splay_tree_int_comparator,
666                              do_nothing,
667                              free_vector_of_osdata_items);
668       make_cleanup (free_splay_tree, tree);
669
670       for (ix_items = 0;
671            VEC_iterate (osdata_item_s, threads->items,
672                         ix_items, item);
673            ix_items++)
674         {
675           const char *pid = get_osdata_column (item, "pid");
676           int pid_i = strtoul (pid, NULL, 0);
677           VEC (osdata_item_s) *vec = 0;
678
679           splay_tree_node n = splay_tree_lookup (tree, pid_i);
680           if (!n)
681             {
682               VEC_safe_push (osdata_item_s, vec, item);
683               splay_tree_insert (tree, pid_i, (splay_tree_value)vec);
684             }
685           else
686             {
687               vec = (VEC (osdata_item_s) *) n->value;
688               VEC_safe_push (osdata_item_s, vec, item);
689               n->value = (splay_tree_value) vec;
690             }
691         }
692     }
693
694   make_cleanup_ui_out_list_begin_end (uiout, "groups");
695
696   for (ix_items = 0;
697        VEC_iterate (osdata_item_s, data->items,
698                     ix_items, item);
699        ix_items++)
700     {
701       struct cleanup *back_to;
702
703       const char *pid = get_osdata_column (item, "pid");
704       const char *cmd = get_osdata_column (item, "command");
705       const char *user = get_osdata_column (item, "user");
706       const char *cores = get_osdata_column (item, "cores");
707
708       int pid_i = strtoul (pid, NULL, 0);
709
710       /* At present, the target will return all available processes
711          and if information about specific ones was required, we filter
712          undesired processes here.  */
713       if (ids && bsearch (&pid_i, VEC_address (int, ids),
714                           VEC_length (int, ids),
715                           sizeof (int), compare_positive_ints) == NULL)
716         continue;
717
718
719       back_to = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
720
721       ui_out_field_fmt (uiout, "id", "%s", pid);
722       ui_out_field_string (uiout, "type", "process");
723       if (cmd)
724         ui_out_field_string (uiout, "description", cmd);
725       if (user)
726         ui_out_field_string (uiout, "user", user);
727       if (cores)
728         output_cores (uiout, "cores", cores);
729
730       if (recurse)
731         {
732           splay_tree_node n = splay_tree_lookup (tree, pid_i);
733           if (n)
734             {
735               VEC (osdata_item_s) *children = (VEC (osdata_item_s) *) n->value;
736               struct osdata_item *child;
737               int ix_child;
738
739               make_cleanup_ui_out_list_begin_end (uiout, "threads");
740
741               for (ix_child = 0;
742                    VEC_iterate (osdata_item_s, children, ix_child, child);
743                    ++ix_child)
744                 {
745                   struct cleanup *back_to_2 =
746                     make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
747
748                   const char *tid = get_osdata_column (child, "tid");
749                   const char *tcore = get_osdata_column (child, "core");
750                   ui_out_field_string (uiout, "id", tid);
751                   if (tcore)
752                     ui_out_field_string (uiout, "core", tcore);
753
754                   do_cleanups (back_to_2);
755                 }
756             }
757         }
758
759       do_cleanups (back_to);
760     }
761 }
762
763 void
764 mi_cmd_list_thread_groups (char *command, char **argv, int argc)
765 {
766   struct cleanup *back_to;
767   int available = 0;
768   int recurse = 0;
769   VEC (int) *ids = 0;
770
771   enum opt
772     {
773       AVAILABLE_OPT, RECURSE_OPT
774     };
775   static struct mi_opt opts[] =
776   {
777     {"-available", AVAILABLE_OPT, 0},
778     {"-recurse", RECURSE_OPT, 1},
779     { 0, 0, 0 }
780   };
781
782   int optind = 0;
783   char *optarg;
784
785   while (1)
786     {
787       int opt = mi_getopt ("-list-thread-groups", argc, argv, opts,
788                            &optind, &optarg);
789       if (opt < 0)
790         break;
791       switch ((enum opt) opt)
792         {
793         case AVAILABLE_OPT:
794           available = 1;
795           break;
796         case RECURSE_OPT:
797           if (strcmp (optarg, "0") == 0)
798             ;
799           else if (strcmp (optarg, "1") == 0)
800             recurse = 1;
801           else
802             error ("only '0' and '1' are valid values for the '--recurse' option");
803           break;
804         }
805     }
806
807   for (; optind < argc; ++optind)
808     {
809       char *end;
810       int inf = strtoul (argv[optind], &end, 0);
811       if (*end != '\0')
812         error ("invalid group id '%s'", argv[optind]);
813       VEC_safe_push (int, ids, inf);
814     }
815   if (VEC_length (int, ids) > 1)
816     qsort (VEC_address (int, ids),
817            VEC_length (int, ids),
818            sizeof (int), compare_positive_ints);
819
820   back_to = make_cleanup (free_vector_of_ints, &ids);
821
822   if (available)
823     {
824       list_available_thread_groups (ids, recurse);
825     }
826   else if (VEC_length (int, ids) == 1)
827     {
828       /* Local thread groups, single id. */
829       int pid = *VEC_address (int, ids);
830       if (!in_inferior_list (pid))
831         error ("Invalid thread group id '%d'", pid);
832       print_thread_info (uiout, -1, pid);
833     }
834   else
835     {
836       struct print_one_inferior_data data;
837       data.recurse = recurse;
838       data.inferiors = ids;
839
840       /* Local thread groups.  Either no explicit ids -- and we
841          print everything, or several explicit ids.  In both cases,
842          we print more than one group, and have to use 'groups'
843          as the top-level element.  */
844       make_cleanup_ui_out_list_begin_end (uiout, "groups");
845       update_thread_list ();
846       iterate_over_inferiors (print_one_inferior, &data);
847     }
848
849   do_cleanups (back_to);
850 }
851
852 void
853 mi_cmd_data_list_register_names (char *command, char **argv, int argc)
854 {
855   struct frame_info *frame;
856   struct gdbarch *gdbarch;
857   int regnum, numregs;
858   int i;
859   struct cleanup *cleanup;
860
861   /* Note that the test for a valid register must include checking the
862      gdbarch_register_name because gdbarch_num_regs may be allocated for
863      the union of the register sets within a family of related processors.
864      In this case, some entries of gdbarch_register_name will change depending
865      upon the particular processor being debugged.  */
866
867   frame = get_selected_frame (NULL);
868   gdbarch = get_frame_arch (frame);
869   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
870
871   cleanup = make_cleanup_ui_out_list_begin_end (uiout, "register-names");
872
873   if (argc == 0)                /* No args, just do all the regs.  */
874     {
875       for (regnum = 0;
876            regnum < numregs;
877            regnum++)
878         {
879           if (gdbarch_register_name (gdbarch, regnum) == NULL
880               || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
881             ui_out_field_string (uiout, NULL, "");
882           else
883             ui_out_field_string (uiout, NULL,
884                                  gdbarch_register_name (gdbarch, regnum));
885         }
886     }
887
888   /* Else, list of register #s, just do listed regs.  */
889   for (i = 0; i < argc; i++)
890     {
891       regnum = atoi (argv[i]);
892       if (regnum < 0 || regnum >= numregs)
893         error ("bad register number");
894
895       if (gdbarch_register_name (gdbarch, regnum) == NULL
896           || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
897         ui_out_field_string (uiout, NULL, "");
898       else
899         ui_out_field_string (uiout, NULL,
900                              gdbarch_register_name (gdbarch, regnum));
901     }
902   do_cleanups (cleanup);
903 }
904
905 void
906 mi_cmd_data_list_changed_registers (char *command, char **argv, int argc)
907 {
908   static struct regcache *this_regs = NULL;
909   struct regcache *prev_regs;
910   struct gdbarch *gdbarch;
911   int regnum, numregs, changed;
912   int i;
913   struct cleanup *cleanup;
914
915   /* The last time we visited this function, the current frame's register
916      contents were saved in THIS_REGS.  Move THIS_REGS over to PREV_REGS,
917      and refresh THIS_REGS with the now-current register contents.  */
918
919   prev_regs = this_regs;
920   this_regs = frame_save_as_regcache (get_selected_frame (NULL));
921   cleanup = make_cleanup_regcache_xfree (prev_regs);
922
923   /* Note that the test for a valid register must include checking the
924      gdbarch_register_name because gdbarch_num_regs may be allocated for
925      the union of the register sets within a family of related processors.
926      In this  case, some entries of gdbarch_register_name will change depending
927      upon the particular processor being debugged.  */
928
929   gdbarch = get_regcache_arch (this_regs);
930   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
931
932   make_cleanup_ui_out_list_begin_end (uiout, "changed-registers");
933
934   if (argc == 0)                /* No args, just do all the regs.  */
935     {
936       for (regnum = 0;
937            regnum < numregs;
938            regnum++)
939         {
940           if (gdbarch_register_name (gdbarch, regnum) == NULL
941               || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
942             continue;
943           changed = register_changed_p (regnum, prev_regs, this_regs);
944           if (changed < 0)
945             error ("mi_cmd_data_list_changed_registers: Unable to read register contents.");
946           else if (changed)
947             ui_out_field_int (uiout, NULL, regnum);
948         }
949     }
950
951   /* Else, list of register #s, just do listed regs.  */
952   for (i = 0; i < argc; i++)
953     {
954       regnum = atoi (argv[i]);
955
956       if (regnum >= 0
957           && regnum < numregs
958           && gdbarch_register_name (gdbarch, regnum) != NULL
959           && *gdbarch_register_name (gdbarch, regnum) != '\000')
960         {
961           changed = register_changed_p (regnum, prev_regs, this_regs);
962           if (changed < 0)
963             error ("mi_cmd_data_list_register_change: Unable to read register contents.");
964           else if (changed)
965             ui_out_field_int (uiout, NULL, regnum);
966         }
967       else
968         error ("bad register number");
969     }
970   do_cleanups (cleanup);
971 }
972
973 static int
974 register_changed_p (int regnum, struct regcache *prev_regs,
975                     struct regcache *this_regs)
976 {
977   struct gdbarch *gdbarch = get_regcache_arch (this_regs);
978   gdb_byte prev_buffer[MAX_REGISTER_SIZE];
979   gdb_byte this_buffer[MAX_REGISTER_SIZE];
980
981   /* Registers not valid in this frame return count as unchanged.  */
982   if (!regcache_valid_p (this_regs, regnum))
983     return 0;
984
985   /* First time through or after gdbarch change consider all registers as
986      changed.  Same for registers not valid in the previous frame.  */
987   if (!prev_regs || get_regcache_arch (prev_regs) != gdbarch
988       || !regcache_valid_p (prev_regs, regnum))
989     return 1;
990
991   /* Get register contents and compare.  */
992   regcache_cooked_read (prev_regs, regnum, prev_buffer);
993   regcache_cooked_read (this_regs, regnum, this_buffer);
994
995   return memcmp (prev_buffer, this_buffer,
996                  register_size (gdbarch, regnum)) != 0;
997 }
998
999 /* Return a list of register number and value pairs.  The valid
1000    arguments expected are: a letter indicating the format in which to
1001    display the registers contents.  This can be one of: x (hexadecimal), d
1002    (decimal), N (natural), t (binary), o (octal), r (raw).  After the
1003    format argumetn there can be a sequence of numbers, indicating which
1004    registers to fetch the content of.  If the format is the only argument,
1005    a list of all the registers with their values is returned.  */
1006 void
1007 mi_cmd_data_list_register_values (char *command, char **argv, int argc)
1008 {
1009   struct frame_info *frame;
1010   struct gdbarch *gdbarch;
1011   int regnum, numregs, format;
1012   int i;
1013   struct cleanup *list_cleanup, *tuple_cleanup;
1014
1015   /* Note that the test for a valid register must include checking the
1016      gdbarch_register_name because gdbarch_num_regs may be allocated for
1017      the union of the register sets within a family of related processors.
1018      In this case, some entries of gdbarch_register_name will change depending
1019      upon the particular processor being debugged.  */
1020
1021   if (argc == 0)
1022     error ("mi_cmd_data_list_register_values: Usage: -data-list-register-values <format> [<regnum1>...<regnumN>]");
1023
1024   format = (int) argv[0][0];
1025
1026   frame = get_selected_frame (NULL);
1027   gdbarch = get_frame_arch (frame);
1028   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
1029
1030   list_cleanup = make_cleanup_ui_out_list_begin_end (uiout, "register-values");
1031
1032   if (argc == 1)            /* No args, beside the format: do all the regs.  */
1033     {
1034       for (regnum = 0;
1035            regnum < numregs;
1036            regnum++)
1037         {
1038           if (gdbarch_register_name (gdbarch, regnum) == NULL
1039               || *(gdbarch_register_name (gdbarch, regnum)) == '\0')
1040             continue;
1041           tuple_cleanup = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
1042           ui_out_field_int (uiout, "number", regnum);
1043           get_register (frame, regnum, format);
1044           do_cleanups (tuple_cleanup);
1045         }
1046     }
1047
1048   /* Else, list of register #s, just do listed regs.  */
1049   for (i = 1; i < argc; i++)
1050     {
1051       regnum = atoi (argv[i]);
1052
1053       if (regnum >= 0
1054           && regnum < numregs
1055           && gdbarch_register_name (gdbarch, regnum) != NULL
1056           && *gdbarch_register_name (gdbarch, regnum) != '\000')
1057         {
1058           tuple_cleanup = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
1059           ui_out_field_int (uiout, "number", regnum);
1060           get_register (frame, regnum, format);
1061           do_cleanups (tuple_cleanup);
1062         }
1063       else
1064         error ("bad register number");
1065     }
1066   do_cleanups (list_cleanup);
1067 }
1068
1069 /* Output one register's contents in the desired format.  */
1070 static void
1071 get_register (struct frame_info *frame, int regnum, int format)
1072 {
1073   struct gdbarch *gdbarch = get_frame_arch (frame);
1074   gdb_byte buffer[MAX_REGISTER_SIZE];
1075   int optim;
1076   int realnum;
1077   CORE_ADDR addr;
1078   enum lval_type lval;
1079   static struct ui_stream *stb = NULL;
1080
1081   stb = ui_out_stream_new (uiout);
1082
1083   if (format == 'N')
1084     format = 0;
1085
1086   frame_register (frame, regnum, &optim, &lval, &addr, &realnum, buffer);
1087
1088   if (optim)
1089     error ("Optimized out");
1090
1091   if (format == 'r')
1092     {
1093       int j;
1094       char *ptr, buf[1024];
1095
1096       strcpy (buf, "0x");
1097       ptr = buf + 2;
1098       for (j = 0; j < register_size (gdbarch, regnum); j++)
1099         {
1100           int idx = gdbarch_byte_order (gdbarch) == BFD_ENDIAN_BIG ?
1101                     j : register_size (gdbarch, regnum) - 1 - j;
1102           sprintf (ptr, "%02x", (unsigned char) buffer[idx]);
1103           ptr += 2;
1104         }
1105       ui_out_field_string (uiout, "value", buf);
1106       /*fputs_filtered (buf, gdb_stdout); */
1107     }
1108   else
1109     {
1110       struct value_print_options opts;
1111       get_formatted_print_options (&opts, format);
1112       opts.deref_ref = 1;
1113       val_print (register_type (gdbarch, regnum), buffer, 0, 0,
1114                  stb->stream, 0, &opts, current_language);
1115       ui_out_field_stream (uiout, "value", stb);
1116       ui_out_stream_delete (stb);
1117     }
1118 }
1119
1120 /* Write given values into registers. The registers and values are
1121    given as pairs.  The corresponding MI command is 
1122    -data-write-register-values <format> [<regnum1> <value1>...<regnumN> <valueN>]*/
1123 void
1124 mi_cmd_data_write_register_values (char *command, char **argv, int argc)
1125 {
1126   struct regcache *regcache;
1127   struct gdbarch *gdbarch;
1128   int numregs, i;
1129   char format;
1130
1131   /* Note that the test for a valid register must include checking the
1132      gdbarch_register_name because gdbarch_num_regs may be allocated for
1133      the union of the register sets within a family of related processors.
1134      In this case, some entries of gdbarch_register_name will change depending
1135      upon the particular processor being debugged.  */
1136
1137   regcache = get_current_regcache ();
1138   gdbarch = get_regcache_arch (regcache);
1139   numregs = gdbarch_num_regs (gdbarch) + gdbarch_num_pseudo_regs (gdbarch);
1140
1141   if (argc == 0)
1142     error ("mi_cmd_data_write_register_values: Usage: -data-write-register-values <format> [<regnum1> <value1>...<regnumN> <valueN>]");
1143
1144   format = (int) argv[0][0];
1145
1146   if (!target_has_registers)
1147     error ("mi_cmd_data_write_register_values: No registers.");
1148
1149   if (!(argc - 1))
1150     error ("mi_cmd_data_write_register_values: No regs and values specified.");
1151
1152   if ((argc - 1) % 2)
1153     error ("mi_cmd_data_write_register_values: Regs and vals are not in pairs.");
1154
1155   for (i = 1; i < argc; i = i + 2)
1156     {
1157       int regnum = atoi (argv[i]);
1158
1159       if (regnum >= 0 && regnum < numregs
1160           && gdbarch_register_name (gdbarch, regnum)
1161           && *gdbarch_register_name (gdbarch, regnum))
1162         {
1163           LONGEST value;
1164
1165           /* Get the value as a number.  */
1166           value = parse_and_eval_address (argv[i + 1]);
1167
1168           /* Write it down.  */
1169           regcache_cooked_write_signed (regcache, regnum, value);
1170         }
1171       else
1172         error ("bad register number");
1173     }
1174 }
1175
1176 /* Evaluate the value of the argument.  The argument is an
1177    expression. If the expression contains spaces it needs to be
1178    included in double quotes.  */
1179 void
1180 mi_cmd_data_evaluate_expression (char *command, char **argv, int argc)
1181 {
1182   struct expression *expr;
1183   struct cleanup *old_chain = NULL;
1184   struct value *val;
1185   struct ui_stream *stb = NULL;
1186   struct value_print_options opts;
1187
1188   stb = ui_out_stream_new (uiout);
1189
1190   if (argc != 1)
1191     {
1192       ui_out_stream_delete (stb);
1193       error ("mi_cmd_data_evaluate_expression: Usage: -data-evaluate-expression expression");
1194     }
1195
1196   expr = parse_expression (argv[0]);
1197
1198   old_chain = make_cleanup (free_current_contents, &expr);
1199
1200   val = evaluate_expression (expr);
1201
1202   /* Print the result of the expression evaluation.  */
1203   get_user_print_options (&opts);
1204   opts.deref_ref = 0;
1205   val_print (value_type (val), value_contents (val),
1206              value_embedded_offset (val), value_address (val),
1207              stb->stream, 0, &opts, current_language);
1208
1209   ui_out_field_stream (uiout, "value", stb);
1210   ui_out_stream_delete (stb);
1211
1212   do_cleanups (old_chain);
1213 }
1214
1215 /* DATA-MEMORY-READ:
1216
1217    ADDR: start address of data to be dumped.
1218    WORD-FORMAT: a char indicating format for the ``word''.  See 
1219    the ``x'' command.
1220    WORD-SIZE: size of each ``word''; 1,2,4, or 8 bytes.
1221    NR_ROW: Number of rows.
1222    NR_COL: The number of colums (words per row).
1223    ASCHAR: (OPTIONAL) Append an ascii character dump to each row.  Use
1224    ASCHAR for unprintable characters.
1225
1226    Reads SIZE*NR_ROW*NR_COL bytes starting at ADDR from memory and
1227    displayes them.  Returns:
1228
1229    {addr="...",rowN={wordN="..." ,... [,ascii="..."]}, ...}
1230
1231    Returns: 
1232    The number of bytes read is SIZE*ROW*COL. */
1233
1234 void
1235 mi_cmd_data_read_memory (char *command, char **argv, int argc)
1236 {
1237   struct gdbarch *gdbarch = get_current_arch ();
1238   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
1239   CORE_ADDR addr;
1240   long total_bytes;
1241   long nr_cols;
1242   long nr_rows;
1243   char word_format;
1244   struct type *word_type;
1245   long word_size;
1246   char word_asize;
1247   char aschar;
1248   gdb_byte *mbuf;
1249   int nr_bytes;
1250   long offset = 0;
1251   int optind = 0;
1252   char *optarg;
1253   enum opt
1254     {
1255       OFFSET_OPT
1256     };
1257   static struct mi_opt opts[] =
1258   {
1259     {"o", OFFSET_OPT, 1},
1260     { 0, 0, 0 }
1261   };
1262
1263   while (1)
1264     {
1265       int opt = mi_getopt ("mi_cmd_data_read_memory", argc, argv, opts,
1266                            &optind, &optarg);
1267       if (opt < 0)
1268         break;
1269       switch ((enum opt) opt)
1270         {
1271         case OFFSET_OPT:
1272           offset = atol (optarg);
1273           break;
1274         }
1275     }
1276   argv += optind;
1277   argc -= optind;
1278
1279   if (argc < 5 || argc > 6)
1280     error ("mi_cmd_data_read_memory: Usage: ADDR WORD-FORMAT WORD-SIZE NR-ROWS NR-COLS [ASCHAR].");
1281
1282   /* Extract all the arguments. */
1283
1284   /* Start address of the memory dump.  */
1285   addr = parse_and_eval_address (argv[0]) + offset;
1286   /* The format character to use when displaying a memory word.  See
1287      the ``x'' command. */
1288   word_format = argv[1][0];
1289   /* The size of the memory word.  */
1290   word_size = atol (argv[2]);
1291   switch (word_size)
1292     {
1293     case 1:
1294       word_type = builtin_type (gdbarch)->builtin_int8;
1295       word_asize = 'b';
1296       break;
1297     case 2:
1298       word_type = builtin_type (gdbarch)->builtin_int16;
1299       word_asize = 'h';
1300       break;
1301     case 4:
1302       word_type = builtin_type (gdbarch)->builtin_int32;
1303       word_asize = 'w';
1304       break;
1305     case 8:
1306       word_type = builtin_type (gdbarch)->builtin_int64;
1307       word_asize = 'g';
1308       break;
1309     default:
1310       word_type = builtin_type (gdbarch)->builtin_int8;
1311       word_asize = 'b';
1312     }
1313   /* The number of rows.  */
1314   nr_rows = atol (argv[3]);
1315   if (nr_rows <= 0)
1316     error ("mi_cmd_data_read_memory: invalid number of rows.");
1317
1318   /* Number of bytes per row.  */
1319   nr_cols = atol (argv[4]);
1320   if (nr_cols <= 0)
1321     error ("mi_cmd_data_read_memory: invalid number of columns.");
1322
1323   /* The un-printable character when printing ascii.  */
1324   if (argc == 6)
1325     aschar = *argv[5];
1326   else
1327     aschar = 0;
1328
1329   /* Create a buffer and read it in.  */
1330   total_bytes = word_size * nr_rows * nr_cols;
1331   mbuf = xcalloc (total_bytes, 1);
1332   make_cleanup (xfree, mbuf);
1333
1334   /* Dispatch memory reads to the topmost target, not the flattened
1335      current_target.  */
1336   nr_bytes = target_read_until_error (current_target.beneath,
1337                                       TARGET_OBJECT_MEMORY, NULL, mbuf,
1338                                       addr, total_bytes);
1339   if (nr_bytes <= 0)
1340     error ("Unable to read memory.");
1341
1342   /* Output the header information.  */
1343   ui_out_field_core_addr (uiout, "addr", gdbarch, addr);
1344   ui_out_field_int (uiout, "nr-bytes", nr_bytes);
1345   ui_out_field_int (uiout, "total-bytes", total_bytes);
1346   ui_out_field_core_addr (uiout, "next-row",
1347                           gdbarch, addr + word_size * nr_cols);
1348   ui_out_field_core_addr (uiout, "prev-row",
1349                           gdbarch, addr - word_size * nr_cols);
1350   ui_out_field_core_addr (uiout, "next-page", gdbarch, addr + total_bytes);
1351   ui_out_field_core_addr (uiout, "prev-page", gdbarch, addr - total_bytes);
1352
1353   /* Build the result as a two dimentional table.  */
1354   {
1355     struct ui_stream *stream = ui_out_stream_new (uiout);
1356     struct cleanup *cleanup_list_memory;
1357     int row;
1358     int row_byte;
1359     cleanup_list_memory = make_cleanup_ui_out_list_begin_end (uiout, "memory");
1360     for (row = 0, row_byte = 0;
1361          row < nr_rows;
1362          row++, row_byte += nr_cols * word_size)
1363       {
1364         int col;
1365         int col_byte;
1366         struct cleanup *cleanup_tuple;
1367         struct cleanup *cleanup_list_data;
1368         struct value_print_options opts;
1369
1370         cleanup_tuple = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
1371         ui_out_field_core_addr (uiout, "addr", gdbarch, addr + row_byte);
1372         /* ui_out_field_core_addr_symbolic (uiout, "saddr", addr + row_byte); */
1373         cleanup_list_data = make_cleanup_ui_out_list_begin_end (uiout, "data");
1374         get_formatted_print_options (&opts, word_format);
1375         for (col = 0, col_byte = row_byte;
1376              col < nr_cols;
1377              col++, col_byte += word_size)
1378           {
1379             if (col_byte + word_size > nr_bytes)
1380               {
1381                 ui_out_field_string (uiout, NULL, "N/A");
1382               }
1383             else
1384               {
1385                 ui_file_rewind (stream->stream);
1386                 print_scalar_formatted (mbuf + col_byte, word_type, &opts,
1387                                         word_asize, stream->stream);
1388                 ui_out_field_stream (uiout, NULL, stream);
1389               }
1390           }
1391         do_cleanups (cleanup_list_data);
1392         if (aschar)
1393           {
1394             int byte;
1395             ui_file_rewind (stream->stream);
1396             for (byte = row_byte; byte < row_byte + word_size * nr_cols; byte++)
1397               {
1398                 if (byte >= nr_bytes)
1399                   {
1400                     fputc_unfiltered ('X', stream->stream);
1401                   }
1402                 else if (mbuf[byte] < 32 || mbuf[byte] > 126)
1403                   {
1404                     fputc_unfiltered (aschar, stream->stream);
1405                   }
1406                 else
1407                   fputc_unfiltered (mbuf[byte], stream->stream);
1408               }
1409             ui_out_field_stream (uiout, "ascii", stream);
1410           }
1411         do_cleanups (cleanup_tuple);
1412       }
1413     ui_out_stream_delete (stream);
1414     do_cleanups (cleanup_list_memory);
1415   }
1416   do_cleanups (cleanups);
1417 }
1418
1419 /* DATA-MEMORY-WRITE:
1420
1421    COLUMN_OFFSET: optional argument. Must be preceeded by '-o'. The
1422    offset from the beginning of the memory grid row where the cell to
1423    be written is.
1424    ADDR: start address of the row in the memory grid where the memory
1425    cell is, if OFFSET_COLUMN is specified.  Otherwise, the address of
1426    the location to write to.
1427    FORMAT: a char indicating format for the ``word''.  See 
1428    the ``x'' command.
1429    WORD_SIZE: size of each ``word''; 1,2,4, or 8 bytes
1430    VALUE: value to be written into the memory address.
1431
1432    Writes VALUE into ADDR + (COLUMN_OFFSET * WORD_SIZE).
1433
1434    Prints nothing.  */
1435 void
1436 mi_cmd_data_write_memory (char *command, char **argv, int argc)
1437 {
1438   struct gdbarch *gdbarch = get_current_arch ();
1439   enum bfd_endian byte_order = gdbarch_byte_order (gdbarch);
1440   CORE_ADDR addr;
1441   char word_format;
1442   long word_size;
1443   /* FIXME: ezannoni 2000-02-17 LONGEST could possibly not be big
1444      enough when using a compiler other than GCC.  */
1445   LONGEST value;
1446   void *buffer;
1447   struct cleanup *old_chain;
1448   long offset = 0;
1449   int optind = 0;
1450   char *optarg;
1451   enum opt
1452     {
1453       OFFSET_OPT
1454     };
1455   static struct mi_opt opts[] =
1456   {
1457     {"o", OFFSET_OPT, 1},
1458     { 0, 0, 0 }
1459   };
1460
1461   while (1)
1462     {
1463       int opt = mi_getopt ("mi_cmd_data_write_memory", argc, argv, opts,
1464                            &optind, &optarg);
1465       if (opt < 0)
1466         break;
1467       switch ((enum opt) opt)
1468         {
1469         case OFFSET_OPT:
1470           offset = atol (optarg);
1471           break;
1472         }
1473     }
1474   argv += optind;
1475   argc -= optind;
1476
1477   if (argc != 4)
1478     error ("mi_cmd_data_write_memory: Usage: [-o COLUMN_OFFSET] ADDR FORMAT WORD-SIZE VALUE.");
1479
1480   /* Extract all the arguments.  */
1481   /* Start address of the memory dump.  */
1482   addr = parse_and_eval_address (argv[0]);
1483   /* The format character to use when displaying a memory word.  See
1484      the ``x'' command.  */
1485   word_format = argv[1][0];
1486   /* The size of the memory word. */
1487   word_size = atol (argv[2]);
1488
1489   /* Calculate the real address of the write destination.  */
1490   addr += (offset * word_size);
1491
1492   /* Get the value as a number.  */
1493   value = parse_and_eval_address (argv[3]);
1494   /* Get the value into an array.  */
1495   buffer = xmalloc (word_size);
1496   old_chain = make_cleanup (xfree, buffer);
1497   store_signed_integer (buffer, word_size, byte_order, value);
1498   /* Write it down to memory.  */
1499   write_memory (addr, buffer, word_size);
1500   /* Free the buffer.  */
1501   do_cleanups (old_chain);
1502 }
1503
1504 void
1505 mi_cmd_enable_timings (char *command, char **argv, int argc)
1506 {
1507   if (argc == 0)
1508     do_timings = 1;
1509   else if (argc == 1)
1510     {
1511       if (strcmp (argv[0], "yes") == 0)
1512         do_timings = 1;
1513       else if (strcmp (argv[0], "no") == 0)
1514         do_timings = 0;
1515       else
1516         goto usage_error;
1517     }
1518   else
1519     goto usage_error;
1520     
1521   return;
1522
1523  usage_error:
1524   error ("mi_cmd_enable_timings: Usage: %s {yes|no}", command);
1525 }
1526
1527 void
1528 mi_cmd_list_features (char *command, char **argv, int argc)
1529 {
1530   if (argc == 0)
1531     {
1532       struct cleanup *cleanup = NULL;
1533       cleanup = make_cleanup_ui_out_list_begin_end (uiout, "features");      
1534
1535       ui_out_field_string (uiout, NULL, "frozen-varobjs");
1536       ui_out_field_string (uiout, NULL, "pending-breakpoints");
1537       ui_out_field_string (uiout, NULL, "thread-info");
1538       
1539 #if HAVE_PYTHON
1540       ui_out_field_string (uiout, NULL, "python");
1541 #endif
1542       
1543       do_cleanups (cleanup);
1544       return;
1545     }
1546
1547   error ("-list-features should be passed no arguments");
1548 }
1549
1550 void
1551 mi_cmd_list_target_features (char *command, char **argv, int argc)
1552 {
1553   if (argc == 0)
1554     {
1555       struct cleanup *cleanup = NULL;
1556       cleanup = make_cleanup_ui_out_list_begin_end (uiout, "features");      
1557
1558       if (target_can_async_p ())
1559         ui_out_field_string (uiout, NULL, "async");
1560       
1561       do_cleanups (cleanup);
1562       return;
1563     }
1564
1565   error ("-list-target-features should be passed no arguments");
1566 }
1567
1568 void
1569 mi_cmd_add_inferior (char *command, char **argv, int argc)
1570 {
1571   struct inferior *inf;
1572
1573   if (argc != 0)
1574     error (_("-add-inferior should be passed no arguments"));
1575
1576   inf = add_inferior_with_spaces ();
1577
1578   ui_out_field_fmt (uiout, "inferior", "i%d", inf->num);
1579 }
1580
1581 void
1582 mi_cmd_remove_inferior (char *command, char **argv, int argc)
1583 {
1584   int id;
1585   struct inferior *inf;
1586
1587   if (argc != 1)
1588     error ("-remove-inferior should be passed a single argument");
1589
1590   if (sscanf (argv[1], "i%d", &id) != 1)
1591     error ("the thread group id is syntactically invalid");
1592
1593   inf = find_inferior_id (id);
1594   if (!inf)
1595     error ("the specified thread group does not exist");
1596
1597   delete_inferior_1 (inf, 1 /* silent */);
1598 }
1599
1600 \f
1601
1602 /* Execute a command within a safe environment.
1603    Return <0 for error; >=0 for ok.
1604
1605    args->action will tell mi_execute_command what action
1606    to perfrom after the given command has executed (display/suppress
1607    prompt, display error). */
1608
1609 static void
1610 captured_mi_execute_command (struct ui_out *uiout, void *data)
1611 {
1612   struct cleanup *cleanup;
1613   struct mi_parse *context = (struct mi_parse *) data;
1614
1615   if (do_timings)
1616     current_command_ts = context->cmd_start;
1617
1618   current_token = xstrdup (context->token);
1619   cleanup = make_cleanup (free_current_contents, &current_token);
1620
1621   running_result_record_printed = 0;
1622   mi_proceeded = 0;
1623   switch (context->op)
1624     {
1625     case MI_COMMAND:
1626       /* A MI command was read from the input stream.  */
1627       if (mi_debug_p)
1628         /* FIXME: gdb_???? */
1629         fprintf_unfiltered (raw_stdout, " token=`%s' command=`%s' args=`%s'\n",
1630                             context->token, context->command, context->args);
1631
1632
1633       mi_cmd_execute (context);
1634
1635       /* Print the result if there were no errors.
1636
1637          Remember that on the way out of executing a command, you have
1638          to directly use the mi_interp's uiout, since the command could 
1639          have reset the interpreter, in which case the current uiout 
1640          will most likely crash in the mi_out_* routines.  */
1641       if (!running_result_record_printed)
1642         {
1643           fputs_unfiltered (context->token, raw_stdout);
1644           /* There's no particularly good reason why target-connect results
1645              in not ^done.  Should kill ^connected for MI3.  */
1646           fputs_unfiltered (strcmp (context->command, "target-select") == 0
1647                             ? "^connected" : "^done", raw_stdout);
1648           mi_out_put (uiout, raw_stdout);
1649           mi_out_rewind (uiout);
1650           mi_print_timing_maybe ();
1651           fputs_unfiltered ("\n", raw_stdout);
1652         }
1653       else
1654             /* The command does not want anything to be printed.  In that
1655                case, the command probably should not have written anything
1656                to uiout, but in case it has written something, discard it.  */
1657         mi_out_rewind (uiout);
1658       break;
1659
1660     case CLI_COMMAND:
1661       {
1662         char *argv[2];
1663         /* A CLI command was read from the input stream.  */
1664         /* This "feature" will be removed as soon as we have a
1665            complete set of mi commands.  */
1666         /* Echo the command on the console.  */
1667         fprintf_unfiltered (gdb_stdlog, "%s\n", context->command);
1668         /* Call the "console" interpreter.  */
1669         argv[0] = "console";
1670         argv[1] = context->command;
1671         mi_cmd_interpreter_exec ("-interpreter-exec", argv, 2);
1672
1673         /* If we changed interpreters, DON'T print out anything.  */
1674         if (current_interp_named_p (INTERP_MI)
1675             || current_interp_named_p (INTERP_MI1)
1676             || current_interp_named_p (INTERP_MI2)
1677             || current_interp_named_p (INTERP_MI3))
1678           {
1679             if (!running_result_record_printed)
1680               {
1681                 fputs_unfiltered (context->token, raw_stdout);
1682                 fputs_unfiltered ("^done", raw_stdout);
1683                 mi_out_put (uiout, raw_stdout);
1684                 mi_out_rewind (uiout);
1685                 mi_print_timing_maybe ();
1686                 fputs_unfiltered ("\n", raw_stdout);            
1687               }
1688             else
1689               mi_out_rewind (uiout);
1690           }
1691         break;
1692       }
1693
1694     }
1695
1696   do_cleanups (cleanup);
1697
1698   return;
1699 }
1700
1701
1702 void
1703 mi_execute_command (char *cmd, int from_tty)
1704 {
1705   struct mi_parse *command;
1706   struct ui_out *saved_uiout = uiout;
1707
1708   /* This is to handle EOF (^D). We just quit gdb.  */
1709   /* FIXME: we should call some API function here.  */
1710   if (cmd == 0)
1711     quit_force (NULL, from_tty);
1712
1713   target_log_command (cmd);
1714
1715   command = mi_parse (cmd);
1716
1717   if (command != NULL)
1718     {
1719       struct gdb_exception result;
1720       ptid_t previous_ptid = inferior_ptid;
1721
1722       if (do_timings)
1723         {
1724           command->cmd_start = (struct mi_timestamp *)
1725             xmalloc (sizeof (struct mi_timestamp));
1726           timestamp (command->cmd_start);
1727         }
1728
1729       result = catch_exception (uiout, captured_mi_execute_command, command,
1730                                 RETURN_MASK_ALL);
1731       if (result.reason < 0)
1732         {
1733           /* The command execution failed and error() was called
1734              somewhere.  */
1735           fputs_unfiltered (command->token, raw_stdout);
1736           fputs_unfiltered ("^error,msg=\"", raw_stdout);
1737           if (result.message == NULL)
1738             fputs_unfiltered ("unknown error", raw_stdout);
1739           else
1740             fputstr_unfiltered (result.message, '"', raw_stdout);
1741           fputs_unfiltered ("\"\n", raw_stdout);
1742           mi_out_rewind (uiout);
1743         }
1744
1745       bpstat_do_actions ();
1746
1747       if (/* The notifications are only output when the top-level
1748              interpreter (specified on the command line) is MI.  */      
1749           ui_out_is_mi_like_p (interp_ui_out (top_level_interpreter ()))
1750           /* Don't try report anything if there are no threads -- 
1751              the program is dead.  */
1752           && thread_count () != 0
1753           /* -thread-select explicitly changes thread. If frontend uses that
1754              internally, we don't want to emit =thread-selected, since
1755              =thread-selected is supposed to indicate user's intentions.  */
1756           && strcmp (command->command, "thread-select") != 0)
1757         {
1758           struct mi_interp *mi = top_level_interpreter_data ();
1759           int report_change = 0;
1760
1761           if (command->thread == -1)
1762             {
1763               report_change = (!ptid_equal (previous_ptid, null_ptid)
1764                                && !ptid_equal (inferior_ptid, previous_ptid)
1765                                && !ptid_equal (inferior_ptid, null_ptid));
1766             }
1767           else if (!ptid_equal (inferior_ptid, null_ptid))
1768             {
1769               struct thread_info *ti = inferior_thread ();
1770               report_change = (ti->num != command->thread);
1771             }
1772
1773           if (report_change)
1774             {     
1775               struct thread_info *ti = inferior_thread ();
1776               target_terminal_ours ();
1777               fprintf_unfiltered (mi->event_channel, 
1778                                   "thread-selected,id=\"%d\"",
1779                                   ti->num);
1780               gdb_flush (mi->event_channel);
1781             }
1782         }
1783
1784       mi_parse_free (command);
1785     }
1786
1787   fputs_unfiltered ("(gdb) \n", raw_stdout);
1788   gdb_flush (raw_stdout);
1789   /* Print any buffered hook code.  */
1790   /* ..... */
1791 }
1792
1793 static void
1794 mi_cmd_execute (struct mi_parse *parse)
1795 {
1796   struct cleanup *cleanup;
1797   int i;
1798
1799   prepare_execute_command ();
1800
1801   cleanup = make_cleanup (null_cleanup, NULL);
1802
1803   if (parse->all && parse->thread_group != -1)
1804     error (_("Cannot specify --thread-group together with --all"));
1805
1806   if (parse->all && parse->thread != -1)
1807     error (_("Cannot specify --thread together with --all"));
1808
1809   if (parse->thread_group != -1 && parse->thread != -1)
1810     error (_("Cannot specify --thread together with --thread-group"));
1811
1812   if (parse->frame != -1 && parse->thread == -1)
1813     error (_("Cannot specify --frame without --thread"));
1814
1815   if (parse->thread_group != -1)
1816     {
1817       struct inferior *inf = find_inferior_id (parse->thread_group);
1818       struct thread_info *tp = 0;
1819
1820       if (!inf)
1821         error (_("Invalid thread group for the --tread-group option"));
1822
1823       set_current_inferior (inf);
1824       /* This behaviour means that if --thread-group option identifies
1825          an inferior with multiple threads, then a random one will be picked.
1826          This is not a problem -- frontend should always provide --thread if
1827          it wishes to operate on a specific thread.  */
1828       if (inf->pid != 0)
1829         tp = any_thread_of_process (inf->pid);
1830       switch_to_thread (tp ? tp->ptid : null_ptid);
1831       set_current_program_space (inf->pspace);
1832     }
1833
1834   if (parse->thread != -1)
1835     {
1836       struct thread_info *tp = find_thread_id (parse->thread);
1837       if (!tp)
1838         error (_("Invalid thread id: %d"), parse->thread);
1839
1840       if (is_exited (tp->ptid))
1841         error (_("Thread id: %d has terminated"), parse->thread);
1842
1843       switch_to_thread (tp->ptid);
1844     }
1845
1846   if (parse->frame != -1)
1847     {
1848       struct frame_info *fid;
1849       int frame = parse->frame;
1850       fid = find_relative_frame (get_current_frame (), &frame);
1851       if (frame == 0)
1852         /* find_relative_frame was successful */
1853         select_frame (fid);
1854       else
1855         error (_("Invalid frame id: %d"), frame);
1856     }
1857
1858   current_context = parse;
1859
1860   if (parse->cmd->argv_func != NULL)
1861     parse->cmd->argv_func (parse->command, parse->argv, parse->argc);
1862   else if (parse->cmd->cli.cmd != 0)
1863     {
1864       /* FIXME: DELETE THIS. */
1865       /* The operation is still implemented by a cli command.  */
1866       /* Must be a synchronous one.  */
1867       mi_execute_cli_command (parse->cmd->cli.cmd, parse->cmd->cli.args_p,
1868                               parse->args);
1869     }
1870   else
1871     {
1872       /* FIXME: DELETE THIS.  */
1873       struct ui_file *stb;
1874
1875       stb = mem_fileopen ();
1876
1877       fputs_unfiltered ("Undefined mi command: ", stb);
1878       fputstr_unfiltered (parse->command, '"', stb);
1879       fputs_unfiltered (" (missing implementation)", stb);
1880
1881       make_cleanup_ui_file_delete (stb);
1882       error_stream (stb);
1883     }
1884   do_cleanups (cleanup);
1885 }
1886
1887 /* FIXME: This is just a hack so we can get some extra commands going.
1888    We don't want to channel things through the CLI, but call libgdb directly.
1889    Use only for synchronous commands.  */
1890
1891 void
1892 mi_execute_cli_command (const char *cmd, int args_p, const char *args)
1893 {
1894   if (cmd != 0)
1895     {
1896       struct cleanup *old_cleanups;
1897       char *run;
1898       if (args_p)
1899         run = xstrprintf ("%s %s", cmd, args);
1900       else
1901         run = xstrdup (cmd);
1902       if (mi_debug_p)
1903         /* FIXME: gdb_???? */
1904         fprintf_unfiltered (gdb_stdout, "cli=%s run=%s\n",
1905                             cmd, run);
1906       old_cleanups = make_cleanup (xfree, run);
1907       execute_command ( /*ui */ run, 0 /*from_tty */ );
1908       do_cleanups (old_cleanups);
1909       return;
1910     }
1911 }
1912
1913 void
1914 mi_execute_async_cli_command (char *cli_command, char **argv, int argc)
1915 {
1916   struct cleanup *old_cleanups;
1917   char *run;
1918
1919   if (target_can_async_p ())
1920     run = xstrprintf ("%s %s&", cli_command, argc ? *argv : "");
1921   else
1922     run = xstrprintf ("%s %s", cli_command, argc ? *argv : "");
1923   old_cleanups = make_cleanup (xfree, run);  
1924
1925   execute_command ( /*ui */ run, 0 /*from_tty */ );
1926
1927   if (target_can_async_p ())
1928     {
1929       /* If we're not executing, an exception should have been throw.  */
1930       gdb_assert (is_running (inferior_ptid));
1931       do_cleanups (old_cleanups);
1932     }
1933   else
1934     {
1935       /* Do this before doing any printing.  It would appear that some
1936          print code leaves garbage around in the buffer.  */
1937       do_cleanups (old_cleanups);
1938     }
1939 }
1940
1941 void
1942 mi_load_progress (const char *section_name,
1943                   unsigned long sent_so_far,
1944                   unsigned long total_section,
1945                   unsigned long total_sent,
1946                   unsigned long grand_total)
1947 {
1948   struct timeval time_now, delta, update_threshold;
1949   static struct timeval last_update;
1950   static char *previous_sect_name = NULL;
1951   int new_section;
1952   struct ui_out *saved_uiout;
1953
1954   /* This function is called through deprecated_show_load_progress
1955      which means uiout may not be correct.  Fix it for the duration
1956      of this function.  */
1957   saved_uiout = uiout;
1958
1959   if (current_interp_named_p (INTERP_MI)
1960       || current_interp_named_p (INTERP_MI2))
1961     uiout = mi_out_new (2);
1962   else if (current_interp_named_p (INTERP_MI1))
1963     uiout = mi_out_new (1);
1964   else if (current_interp_named_p (INTERP_MI3))
1965     uiout = mi_out_new (3);
1966   else
1967     return;
1968
1969   update_threshold.tv_sec = 0;
1970   update_threshold.tv_usec = 500000;
1971   gettimeofday (&time_now, NULL);
1972
1973   delta.tv_usec = time_now.tv_usec - last_update.tv_usec;
1974   delta.tv_sec = time_now.tv_sec - last_update.tv_sec;
1975
1976   if (delta.tv_usec < 0)
1977     {
1978       delta.tv_sec -= 1;
1979       delta.tv_usec += 1000000L;
1980     }
1981
1982   new_section = (previous_sect_name ?
1983                  strcmp (previous_sect_name, section_name) : 1);
1984   if (new_section)
1985     {
1986       struct cleanup *cleanup_tuple;
1987       xfree (previous_sect_name);
1988       previous_sect_name = xstrdup (section_name);
1989
1990       if (current_token)
1991         fputs_unfiltered (current_token, raw_stdout);
1992       fputs_unfiltered ("+download", raw_stdout);
1993       cleanup_tuple = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
1994       ui_out_field_string (uiout, "section", section_name);
1995       ui_out_field_int (uiout, "section-size", total_section);
1996       ui_out_field_int (uiout, "total-size", grand_total);
1997       do_cleanups (cleanup_tuple);
1998       mi_out_put (uiout, raw_stdout);
1999       fputs_unfiltered ("\n", raw_stdout);
2000       gdb_flush (raw_stdout);
2001     }
2002
2003   if (delta.tv_sec >= update_threshold.tv_sec &&
2004       delta.tv_usec >= update_threshold.tv_usec)
2005     {
2006       struct cleanup *cleanup_tuple;
2007       last_update.tv_sec = time_now.tv_sec;
2008       last_update.tv_usec = time_now.tv_usec;
2009       if (current_token)
2010         fputs_unfiltered (current_token, raw_stdout);
2011       fputs_unfiltered ("+download", raw_stdout);
2012       cleanup_tuple = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
2013       ui_out_field_string (uiout, "section", section_name);
2014       ui_out_field_int (uiout, "section-sent", sent_so_far);
2015       ui_out_field_int (uiout, "section-size", total_section);
2016       ui_out_field_int (uiout, "total-sent", total_sent);
2017       ui_out_field_int (uiout, "total-size", grand_total);
2018       do_cleanups (cleanup_tuple);
2019       mi_out_put (uiout, raw_stdout);
2020       fputs_unfiltered ("\n", raw_stdout);
2021       gdb_flush (raw_stdout);
2022     }
2023
2024   xfree (uiout);
2025   uiout = saved_uiout;
2026 }
2027
2028 static void 
2029 timestamp (struct mi_timestamp *tv)
2030   {
2031     long usec;
2032     gettimeofday (&tv->wallclock, NULL);
2033 #ifdef HAVE_GETRUSAGE
2034     getrusage (RUSAGE_SELF, &rusage);
2035     tv->utime.tv_sec = rusage.ru_utime.tv_sec;
2036     tv->utime.tv_usec = rusage.ru_utime.tv_usec;
2037     tv->stime.tv_sec = rusage.ru_stime.tv_sec;
2038     tv->stime.tv_usec = rusage.ru_stime.tv_usec;
2039 #else
2040     usec = get_run_time ();
2041     tv->utime.tv_sec = usec/1000000L;
2042     tv->utime.tv_usec = usec - 1000000L*tv->utime.tv_sec;
2043     tv->stime.tv_sec = 0;
2044     tv->stime.tv_usec = 0;
2045 #endif
2046   }
2047
2048 static void 
2049 print_diff_now (struct mi_timestamp *start)
2050   {
2051     struct mi_timestamp now;
2052     timestamp (&now);
2053     print_diff (start, &now);
2054   }
2055
2056 void
2057 mi_print_timing_maybe (void)
2058 {
2059   /* If the command is -enable-timing then do_timings may be
2060      true whilst current_command_ts is not initialized.  */
2061   if (do_timings && current_command_ts)
2062     print_diff_now (current_command_ts);
2063 }
2064
2065 static long 
2066 timeval_diff (struct timeval start, struct timeval end)
2067   {
2068     return ((end.tv_sec - start.tv_sec) * 1000000L)
2069       + (end.tv_usec - start.tv_usec);
2070   }
2071
2072 static void 
2073 print_diff (struct mi_timestamp *start, struct mi_timestamp *end)
2074   {
2075     fprintf_unfiltered
2076       (raw_stdout,
2077        ",time={wallclock=\"%0.5f\",user=\"%0.5f\",system=\"%0.5f\"}", 
2078        timeval_diff (start->wallclock, end->wallclock) / 1000000.0, 
2079        timeval_diff (start->utime, end->utime) / 1000000.0, 
2080        timeval_diff (start->stime, end->stime) / 1000000.0);
2081   }