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