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