2007-08-10 Michael Snyder <msnyder@access-company.com>
[external/binutils.git] / gdb / mi / mi-main.c
1 /* MI Command Set.
2
3    Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2007
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 2 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, write to the Free Software
22    Foundation, Inc., 51 Franklin Street, Fifth Floor,
23    Boston, MA 02110-1301, USA.  */
24
25 /* Work in progress.  */
26
27 #include "defs.h"
28 #include "target.h"
29 #include "inferior.h"
30 #include "gdb_string.h"
31 #include "exceptions.h"
32 #include "top.h"
33 #include "gdbthread.h"
34 #include "mi-cmds.h"
35 #include "mi-parse.h"
36 #include "mi-getopt.h"
37 #include "mi-console.h"
38 #include "ui-out.h"
39 #include "mi-out.h"
40 #include "interps.h"
41 #include "event-loop.h"
42 #include "event-top.h"
43 #include "gdbcore.h"            /* For write_memory().  */
44 #include "value.h"
45 #include "regcache.h"
46 #include "gdb.h"
47 #include "frame.h"
48 #include "mi-main.h"
49
50 #include <ctype.h>
51 #include <sys/time.h>
52
53 #if defined HAVE_SYS_RESOURCE_H
54 #include <sys/resource.h>
55 #endif
56
57 #ifdef HAVE_GETRUSAGE
58 struct rusage rusage;
59 #endif
60
61 enum
62   {
63     FROM_TTY = 0
64   };
65
66 /* Enumerations of the actions that may result from calling
67    captured_mi_execute_command.  */
68
69 enum captured_mi_execute_command_actions
70   {
71     EXECUTE_COMMAND_DISPLAY_PROMPT,
72     EXECUTE_COMMAND_SUPRESS_PROMPT
73   };
74
75 /* This structure is used to pass information from captured_mi_execute_command
76    to mi_execute_command.  */
77 struct captured_mi_execute_command_args
78 {
79   /* This return result of the MI command (output).  */
80   enum mi_cmd_result rc;
81
82   /* What action to perform when the call is finished (output).  */
83   enum captured_mi_execute_command_actions action;
84
85   /* The command context to be executed (input).  */
86   struct mi_parse *command;
87 };
88
89 int mi_debug_p;
90 struct ui_file *raw_stdout;
91
92 /* This is used to pass the current command timestamp
93    down to continuation routines.  */
94 static struct mi_timestamp *current_command_ts;
95
96 static int do_timings = 0;
97
98 /* The token of the last asynchronous command.  */
99 static char *last_async_command;
100 static char *previous_async_command;
101 char *mi_error_message;
102
103 extern void _initialize_mi_main (void);
104 static enum mi_cmd_result mi_cmd_execute (struct mi_parse *parse);
105
106 static void mi_execute_cli_command (const char *cmd, int args_p,
107                                     const char *args);
108 static enum mi_cmd_result mi_execute_async_cli_command (char *mi, char *args, int from_tty);
109
110 static void mi_exec_async_cli_cmd_continuation (struct continuation_arg *arg);
111
112 static int register_changed_p (int regnum, struct regcache *,
113                                struct regcache *);
114 static int get_register (int regnum, int format);
115
116 /* Command implementations.  FIXME: Is this libgdb?  No.  This is the MI
117    layer that calls libgdb.  Any operation used in the below should be
118    formalized.  */
119
120 static void timestamp (struct mi_timestamp *tv);
121
122 static void print_diff_now (struct mi_timestamp *start);
123 static void print_diff (struct mi_timestamp *start, struct mi_timestamp *end);
124
125 enum mi_cmd_result
126 mi_cmd_gdb_exit (char *command, char **argv, int argc)
127 {
128   /* We have to print everything right here because we never return.  */
129   if (last_async_command)
130     fputs_unfiltered (last_async_command, raw_stdout);
131   fputs_unfiltered ("^exit\n", raw_stdout);
132   mi_out_put (uiout, raw_stdout);
133   /* FIXME: The function called is not yet a formal libgdb function.  */
134   quit_force (NULL, FROM_TTY);
135   return MI_CMD_DONE;
136 }
137
138 enum mi_cmd_result
139 mi_cmd_exec_run (char *args, int from_tty)
140 {
141   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
142   return mi_execute_async_cli_command ("run", args, from_tty);
143 }
144
145 enum mi_cmd_result
146 mi_cmd_exec_next (char *args, int from_tty)
147 {
148   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
149   return mi_execute_async_cli_command ("next", args, from_tty);
150 }
151
152 enum mi_cmd_result
153 mi_cmd_exec_next_instruction (char *args, int from_tty)
154 {
155   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
156   return mi_execute_async_cli_command ("nexti", args, from_tty);
157 }
158
159 enum mi_cmd_result
160 mi_cmd_exec_step (char *args, int from_tty)
161 {
162   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
163   return mi_execute_async_cli_command ("step", args, from_tty);
164 }
165
166 enum mi_cmd_result
167 mi_cmd_exec_step_instruction (char *args, int from_tty)
168 {
169   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
170   return mi_execute_async_cli_command ("stepi", args, from_tty);
171 }
172
173 enum mi_cmd_result
174 mi_cmd_exec_finish (char *args, int from_tty)
175 {
176   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
177   return mi_execute_async_cli_command ("finish", args, from_tty);
178 }
179
180 enum mi_cmd_result
181 mi_cmd_exec_until (char *args, int from_tty)
182 {
183   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
184   return mi_execute_async_cli_command ("until", args, from_tty);
185 }
186
187 enum mi_cmd_result
188 mi_cmd_exec_return (char *args, int from_tty)
189 {
190   /* This command doesn't really execute the target, it just pops the
191      specified number of frames. */
192   if (*args)
193     /* Call return_command with from_tty argument equal to 0 so as to
194        avoid being queried.  */
195     return_command (args, 0);
196   else
197     /* Call return_command with from_tty argument equal to 0 so as to
198        avoid being queried.  */
199     return_command (NULL, 0);
200
201   /* Because we have called return_command with from_tty = 0, we need
202      to print the frame here.  */
203   print_stack_frame (get_selected_frame (NULL), 1, LOC_AND_ADDRESS);
204
205   return MI_CMD_DONE;
206 }
207
208 enum mi_cmd_result
209 mi_cmd_exec_continue (char *args, int from_tty)
210 {
211   /* FIXME: Should call a libgdb function, not a cli wrapper.  */
212   return mi_execute_async_cli_command ("continue", args, from_tty);
213 }
214
215 /* Interrupt the execution of the target.  Note how we must play around
216    with the token variables, in order to display the current token in
217    the result of the interrupt command, and the previous execution
218    token when the target finally stops.  See comments in
219    mi_cmd_execute.  */
220 enum mi_cmd_result
221 mi_cmd_exec_interrupt (char *args, int from_tty)
222 {
223   if (!target_executing)
224     {
225       mi_error_message = xstrprintf ("mi_cmd_exec_interrupt: Inferior not executing.");
226       return MI_CMD_ERROR;
227     }
228   interrupt_target_command (args, from_tty);
229   if (last_async_command)
230     fputs_unfiltered (last_async_command, raw_stdout);
231   fputs_unfiltered ("^done", raw_stdout);
232   xfree (last_async_command);
233   if (previous_async_command)
234     last_async_command = xstrdup (previous_async_command);
235   xfree (previous_async_command);
236   previous_async_command = NULL;
237   mi_out_put (uiout, raw_stdout);
238   mi_out_rewind (uiout);
239   fputs_unfiltered ("\n", raw_stdout);
240   return MI_CMD_QUIET;
241 }
242
243 enum mi_cmd_result
244 mi_cmd_thread_select (char *command, char **argv, int argc)
245 {
246   enum gdb_rc rc;
247
248   if (argc != 1)
249     {
250       mi_error_message = xstrprintf ("mi_cmd_thread_select: USAGE: threadnum.");
251       return MI_CMD_ERROR;
252     }
253   else
254     rc = gdb_thread_select (uiout, argv[0], &mi_error_message);
255
256   if (rc == GDB_RC_FAIL)
257     return MI_CMD_ERROR;
258   else
259     return MI_CMD_DONE;
260 }
261
262 enum mi_cmd_result
263 mi_cmd_thread_list_ids (char *command, char **argv, int argc)
264 {
265   enum gdb_rc rc;
266
267   if (argc != 0)
268     {
269       mi_error_message = xstrprintf ("mi_cmd_thread_list_ids: No arguments required.");
270       return MI_CMD_ERROR;
271     }
272   else
273     rc = gdb_list_thread_ids (uiout, &mi_error_message);
274
275   if (rc == GDB_RC_FAIL)
276     return MI_CMD_ERROR;
277   else
278     return MI_CMD_DONE;
279 }
280
281 enum mi_cmd_result
282 mi_cmd_data_list_register_names (char *command, char **argv, int argc)
283 {
284   int regnum, numregs;
285   int i;
286   struct cleanup *cleanup;
287
288   /* Note that the test for a valid register must include checking the
289      gdbarch_register_name because gdbarch_num_regs may be allocated for
290      the union of the register sets within a family of related processors.
291      In this case, some entries of gdbarch_register_name will change depending
292      upon the particular processor being debugged.  */
293
294   numregs = gdbarch_num_regs (current_gdbarch)
295             + gdbarch_num_pseudo_regs (current_gdbarch);
296
297   cleanup = make_cleanup_ui_out_list_begin_end (uiout, "register-names");
298
299   if (argc == 0)                /* No args, just do all the regs.  */
300     {
301       for (regnum = 0;
302            regnum < numregs;
303            regnum++)
304         {
305           if (gdbarch_register_name (current_gdbarch, regnum) == NULL
306               || *(gdbarch_register_name (current_gdbarch, regnum)) == '\0')
307             ui_out_field_string (uiout, NULL, "");
308           else
309             ui_out_field_string (uiout, NULL,
310                                  gdbarch_register_name
311                                    (current_gdbarch, regnum));
312         }
313     }
314
315   /* Else, list of register #s, just do listed regs.  */
316   for (i = 0; i < argc; i++)
317     {
318       regnum = atoi (argv[i]);
319       if (regnum < 0 || regnum >= numregs)
320         {
321           do_cleanups (cleanup);
322           mi_error_message = xstrprintf ("bad register number");
323           return MI_CMD_ERROR;
324         }
325       if (gdbarch_register_name (current_gdbarch, regnum) == NULL
326           || *(gdbarch_register_name (current_gdbarch, regnum)) == '\0')
327         ui_out_field_string (uiout, NULL, "");
328       else
329         ui_out_field_string (uiout, NULL,
330                              gdbarch_register_name (current_gdbarch, regnum));
331     }
332   do_cleanups (cleanup);
333   return MI_CMD_DONE;
334 }
335
336 enum mi_cmd_result
337 mi_cmd_data_list_changed_registers (char *command, char **argv, int argc)
338 {
339   static struct regcache *this_regs = NULL;
340   struct regcache *prev_regs;
341   int regnum, numregs, changed;
342   int i;
343   struct cleanup *cleanup;
344
345   /* The last time we visited this function, the current frame's register
346      contents were saved in THIS_REGS.  Move THIS_REGS over to PREV_REGS,
347      and refresh THIS_REGS with the now-current register contents.  */
348
349   prev_regs = this_regs;
350   this_regs = frame_save_as_regcache (get_selected_frame (NULL));
351   cleanup = make_cleanup_regcache_xfree (prev_regs);
352
353   /* Note that the test for a valid register must include checking the
354      gdbarch_register_name because gdbarch_num_regs may be allocated for
355      the union of the register sets within a family of related processors.
356      In this  case, some entries of gdbarch_register_name will change depending
357      upon the particular processor being debugged.  */
358
359   numregs = gdbarch_num_regs (current_gdbarch)
360             + gdbarch_num_pseudo_regs (current_gdbarch);
361
362   make_cleanup_ui_out_list_begin_end (uiout, "changed-registers");
363
364   if (argc == 0)                /* No args, just do all the regs.  */
365     {
366       for (regnum = 0;
367            regnum < numregs;
368            regnum++)
369         {
370           if (gdbarch_register_name (current_gdbarch, regnum) == NULL
371               || *(gdbarch_register_name (current_gdbarch, regnum)) == '\0')
372             continue;
373           changed = register_changed_p (regnum, prev_regs, this_regs);
374           if (changed < 0)
375             {
376               do_cleanups (cleanup);
377               mi_error_message = xstrprintf ("mi_cmd_data_list_changed_registers: Unable to read register contents.");
378               return MI_CMD_ERROR;
379             }
380           else if (changed)
381             ui_out_field_int (uiout, NULL, regnum);
382         }
383     }
384
385   /* Else, list of register #s, just do listed regs.  */
386   for (i = 0; i < argc; i++)
387     {
388       regnum = atoi (argv[i]);
389
390       if (regnum >= 0
391           && regnum < numregs
392           && gdbarch_register_name (current_gdbarch, regnum) != NULL
393           && *gdbarch_register_name (current_gdbarch, regnum) != '\000')
394         {
395           changed = register_changed_p (regnum, prev_regs, this_regs);
396           if (changed < 0)
397             {
398               do_cleanups (cleanup);
399               mi_error_message = xstrprintf ("mi_cmd_data_list_register_change: Unable to read register contents.");
400               return MI_CMD_ERROR;
401             }
402           else if (changed)
403             ui_out_field_int (uiout, NULL, regnum);
404         }
405       else
406         {
407           do_cleanups (cleanup);
408           mi_error_message = xstrprintf ("bad register number");
409           return MI_CMD_ERROR;
410         }
411     }
412   do_cleanups (cleanup);
413   return MI_CMD_DONE;
414 }
415
416 static int
417 register_changed_p (int regnum, struct regcache *prev_regs,
418                     struct regcache *this_regs)
419 {
420   struct gdbarch *gdbarch = get_regcache_arch (this_regs);
421   gdb_byte prev_buffer[MAX_REGISTER_SIZE];
422   gdb_byte this_buffer[MAX_REGISTER_SIZE];
423
424   /* Registers not valid in this frame return count as unchanged.  */
425   if (!regcache_valid_p (this_regs, regnum))
426     return 0;
427
428   /* First time through or after gdbarch change consider all registers as
429      changed.  Same for registers not valid in the previous frame.  */
430   if (!prev_regs || get_regcache_arch (prev_regs) != gdbarch
431       || !regcache_valid_p (prev_regs, regnum))
432     return 1;
433
434   /* Get register contents and compare.  */
435   regcache_cooked_read (prev_regs, regnum, prev_buffer);
436   regcache_cooked_read (this_regs, regnum, this_buffer);
437
438   return memcmp (prev_buffer, this_buffer,
439                  register_size (gdbarch, regnum)) != 0;
440 }
441
442 /* Return a list of register number and value pairs.  The valid
443    arguments expected are: a letter indicating the format in which to
444    display the registers contents.  This can be one of: x (hexadecimal), d
445    (decimal), N (natural), t (binary), o (octal), r (raw).  After the
446    format argumetn there can be a sequence of numbers, indicating which
447    registers to fetch the content of.  If the format is the only argument,
448    a list of all the registers with their values is returned.  */
449 enum mi_cmd_result
450 mi_cmd_data_list_register_values (char *command, char **argv, int argc)
451 {
452   int regnum, numregs, format, result;
453   int i;
454   struct cleanup *list_cleanup, *tuple_cleanup;
455
456   /* Note that the test for a valid register must include checking the
457      gdbarch_register_name because gdbarch_num_regs may be allocated for
458      the union of the register sets within a family of related processors.
459      In this case, some entries of gdbarch_register_name will change depending
460      upon the particular processor being debugged.  */
461
462   numregs = gdbarch_num_regs (current_gdbarch)
463             + gdbarch_num_pseudo_regs (current_gdbarch);
464
465   if (argc == 0)
466     {
467       mi_error_message = xstrprintf ("mi_cmd_data_list_register_values: Usage: -data-list-register-values <format> [<regnum1>...<regnumN>]");
468       return MI_CMD_ERROR;
469     }
470
471   format = (int) argv[0][0];
472
473   list_cleanup = make_cleanup_ui_out_list_begin_end (uiout, "register-values");
474
475   if (argc == 1)            /* No args, beside the format: do all the regs.  */
476     {
477       for (regnum = 0;
478            regnum < numregs;
479            regnum++)
480         {
481           if (gdbarch_register_name (current_gdbarch, regnum) == NULL
482               || *(gdbarch_register_name (current_gdbarch, regnum)) == '\0')
483             continue;
484           tuple_cleanup = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
485           ui_out_field_int (uiout, "number", regnum);
486           result = get_register (regnum, format);
487           if (result == -1)
488             {
489               do_cleanups (list_cleanup);
490               return MI_CMD_ERROR;
491             }
492           do_cleanups (tuple_cleanup);
493         }
494     }
495
496   /* Else, list of register #s, just do listed regs.  */
497   for (i = 1; i < argc; i++)
498     {
499       regnum = atoi (argv[i]);
500
501       if (regnum >= 0
502           && regnum < numregs
503           && gdbarch_register_name (current_gdbarch, regnum) != NULL
504           && *gdbarch_register_name (current_gdbarch, regnum) != '\000')
505         {
506           tuple_cleanup = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
507           ui_out_field_int (uiout, "number", regnum);
508           result = get_register (regnum, format);
509           if (result == -1)
510             {
511               do_cleanups (list_cleanup);
512               return MI_CMD_ERROR;
513             }
514           do_cleanups (tuple_cleanup);
515         }
516       else
517         {
518           do_cleanups (list_cleanup);
519           mi_error_message = xstrprintf ("bad register number");
520           return MI_CMD_ERROR;
521         }
522     }
523   do_cleanups (list_cleanup);
524   return MI_CMD_DONE;
525 }
526
527 /* Output one register's contents in the desired format.  */
528 static int
529 get_register (int regnum, int format)
530 {
531   gdb_byte buffer[MAX_REGISTER_SIZE];
532   int optim;
533   int realnum;
534   CORE_ADDR addr;
535   enum lval_type lval;
536   static struct ui_stream *stb = NULL;
537
538   stb = ui_out_stream_new (uiout);
539
540   if (format == 'N')
541     format = 0;
542
543   frame_register (get_selected_frame (NULL), regnum, &optim, &lval, &addr,
544                   &realnum, buffer);
545
546   if (optim)
547     {
548       mi_error_message = xstrprintf ("Optimized out");
549       return -1;
550     }
551
552   if (format == 'r')
553     {
554       int j;
555       char *ptr, buf[1024];
556
557       strcpy (buf, "0x");
558       ptr = buf + 2;
559       for (j = 0; j < register_size (current_gdbarch, regnum); j++)
560         {
561           int idx = gdbarch_byte_order (current_gdbarch) == BFD_ENDIAN_BIG ? j
562           : register_size (current_gdbarch, regnum) - 1 - j;
563           sprintf (ptr, "%02x", (unsigned char) buffer[idx]);
564           ptr += 2;
565         }
566       ui_out_field_string (uiout, "value", buf);
567       /*fputs_filtered (buf, gdb_stdout); */
568     }
569   else
570     {
571       val_print (register_type (current_gdbarch, regnum), buffer, 0, 0,
572                  stb->stream, format, 1, 0, Val_pretty_default);
573       ui_out_field_stream (uiout, "value", stb);
574       ui_out_stream_delete (stb);
575     }
576   return 1;
577 }
578
579 /* Write given values into registers. The registers and values are
580    given as pairs.  The corresponding MI command is 
581    -data-write-register-values <format> [<regnum1> <value1>...<regnumN> <valueN>]*/
582 enum mi_cmd_result
583 mi_cmd_data_write_register_values (char *command, char **argv, int argc)
584 {
585   int numregs, i;
586   char format;
587
588   /* Note that the test for a valid register must include checking the
589      gdbarch_register_name because gdbarch_num_regs may be allocated for
590      the union of the register sets within a family of related processors.
591      In this case, some entries of gdbarch_register_name will change depending
592      upon the particular processor being debugged.  */
593
594   numregs = gdbarch_num_regs (current_gdbarch)
595             + gdbarch_num_pseudo_regs (current_gdbarch);
596
597   if (argc == 0)
598     {
599       mi_error_message = xstrprintf ("mi_cmd_data_write_register_values: Usage: -data-write-register-values <format> [<regnum1> <value1>...<regnumN> <valueN>]");
600       return MI_CMD_ERROR;
601     }
602
603   format = (int) argv[0][0];
604
605   if (!target_has_registers)
606     {
607       mi_error_message = xstrprintf ("mi_cmd_data_write_register_values: No registers.");
608       return MI_CMD_ERROR;
609     }
610
611   if (!(argc - 1))
612     {
613       mi_error_message = xstrprintf ("mi_cmd_data_write_register_values: No regs and values specified.");
614       return MI_CMD_ERROR;
615     }
616
617   if ((argc - 1) % 2)
618     {
619       mi_error_message = xstrprintf ("mi_cmd_data_write_register_values: Regs and vals are not in pairs.");
620       return MI_CMD_ERROR;
621     }
622
623   for (i = 1; i < argc; i = i + 2)
624     {
625       int regnum = atoi (argv[i]);
626
627       if (regnum >= 0 && regnum < numregs
628           && gdbarch_register_name (current_gdbarch, regnum)
629           && *gdbarch_register_name (current_gdbarch, regnum))
630         {
631           LONGEST value;
632
633           /* Get the value as a number.  */
634           value = parse_and_eval_address (argv[i + 1]);
635
636           /* Write it down.  */
637           regcache_cooked_write_signed (get_current_regcache (), regnum, value);
638         }
639       else
640         {
641           mi_error_message = xstrprintf ("bad register number");
642           return MI_CMD_ERROR;
643         }
644     }
645   return MI_CMD_DONE;
646 }
647
648 #if 0
649 /* This is commented out because we decided it was not useful.  I leave
650    it, just in case.  ezannoni:1999-12-08 */
651
652 /* Assign a value to a variable.  The expression argument must be in
653    the form A=2 or "A = 2" i.e. if there are spaces it needs to be
654    quoted.  */
655 enum mi_cmd_result
656 mi_cmd_data_assign (char *command, char **argv, int argc)
657 {
658   struct expression *expr;
659   struct cleanup *old_chain;
660
661   if (argc != 1)
662     {
663       mi_error_message = xstrprintf ("mi_cmd_data_assign: Usage: -data-assign expression");
664       return MI_CMD_ERROR;
665     }
666
667   /* NOTE what follows is a clone of set_command().  FIXME: ezannoni
668      01-12-1999: Need to decide what to do with this for libgdb purposes.  */
669
670   expr = parse_expression (argv[0]);
671   old_chain = make_cleanup (free_current_contents, &expr);
672   evaluate_expression (expr);
673   do_cleanups (old_chain);
674   return MI_CMD_DONE;
675 }
676 #endif
677
678 /* Evaluate the value of the argument.  The argument is an
679    expression. If the expression contains spaces it needs to be
680    included in double quotes.  */
681 enum mi_cmd_result
682 mi_cmd_data_evaluate_expression (char *command, char **argv, int argc)
683 {
684   struct expression *expr;
685   struct cleanup *old_chain = NULL;
686   struct value *val;
687   struct ui_stream *stb = NULL;
688
689   stb = ui_out_stream_new (uiout);
690
691   if (argc != 1)
692     {
693       mi_error_message = xstrprintf ("mi_cmd_data_evaluate_expression: Usage: -data-evaluate-expression expression");
694       ui_out_stream_delete (stb);
695       return MI_CMD_ERROR;
696     }
697
698   expr = parse_expression (argv[0]);
699
700   old_chain = make_cleanup (free_current_contents, &expr);
701
702   val = evaluate_expression (expr);
703
704   /* Print the result of the expression evaluation.  */
705   val_print (value_type (val), value_contents (val),
706              value_embedded_offset (val), VALUE_ADDRESS (val),
707              stb->stream, 0, 0, 0, 0);
708
709   ui_out_field_stream (uiout, "value", stb);
710   ui_out_stream_delete (stb);
711
712   do_cleanups (old_chain);
713
714   return MI_CMD_DONE;
715 }
716
717 enum mi_cmd_result
718 mi_cmd_target_download (char *args, int from_tty)
719 {
720   char *run;
721   struct cleanup *old_cleanups = NULL;
722
723   run = xstrprintf ("load %s", args);
724   old_cleanups = make_cleanup (xfree, run);
725   execute_command (run, from_tty);
726
727   do_cleanups (old_cleanups);
728   return MI_CMD_DONE;
729 }
730
731 /* Connect to the remote target.  */
732 enum mi_cmd_result
733 mi_cmd_target_select (char *args, int from_tty)
734 {
735   char *run;
736   struct cleanup *old_cleanups = NULL;
737
738   run = xstrprintf ("target %s", args);
739   old_cleanups = make_cleanup (xfree, run);
740
741   /* target-select is always synchronous.  Once the call has returned
742      we know that we are connected.  */
743   /* NOTE: At present all targets that are connected are also
744      (implicitly) talking to a halted target.  In the future this may
745      change.  */
746   execute_command (run, from_tty);
747
748   do_cleanups (old_cleanups);
749
750   /* Issue the completion message here.  */
751   if (last_async_command)
752     fputs_unfiltered (last_async_command, raw_stdout);
753   fputs_unfiltered ("^connected", raw_stdout);
754   mi_out_put (uiout, raw_stdout);
755   mi_out_rewind (uiout);
756   fputs_unfiltered ("\n", raw_stdout);
757   do_exec_cleanups (ALL_CLEANUPS);
758   return MI_CMD_QUIET;
759 }
760
761 /* DATA-MEMORY-READ:
762
763    ADDR: start address of data to be dumped.
764    WORD-FORMAT: a char indicating format for the ``word''.  See 
765    the ``x'' command.
766    WORD-SIZE: size of each ``word''; 1,2,4, or 8 bytes.
767    NR_ROW: Number of rows.
768    NR_COL: The number of colums (words per row).
769    ASCHAR: (OPTIONAL) Append an ascii character dump to each row.  Use
770    ASCHAR for unprintable characters.
771
772    Reads SIZE*NR_ROW*NR_COL bytes starting at ADDR from memory and
773    displayes them.  Returns:
774
775    {addr="...",rowN={wordN="..." ,... [,ascii="..."]}, ...}
776
777    Returns: 
778    The number of bytes read is SIZE*ROW*COL. */
779
780 enum mi_cmd_result
781 mi_cmd_data_read_memory (char *command, char **argv, int argc)
782 {
783   struct cleanup *cleanups = make_cleanup (null_cleanup, NULL);
784   CORE_ADDR addr;
785   long total_bytes;
786   long nr_cols;
787   long nr_rows;
788   char word_format;
789   struct type *word_type;
790   long word_size;
791   char word_asize;
792   char aschar;
793   gdb_byte *mbuf;
794   int nr_bytes;
795   long offset = 0;
796   int optind = 0;
797   char *optarg;
798   enum opt
799     {
800       OFFSET_OPT
801     };
802   static struct mi_opt opts[] =
803   {
804     {"o", OFFSET_OPT, 1},
805     { 0, 0, 0 }
806   };
807
808   while (1)
809     {
810       int opt = mi_getopt ("mi_cmd_data_read_memory", argc, argv, opts,
811                            &optind, &optarg);
812       if (opt < 0)
813         break;
814       switch ((enum opt) opt)
815         {
816         case OFFSET_OPT:
817           offset = atol (optarg);
818           break;
819         }
820     }
821   argv += optind;
822   argc -= optind;
823
824   if (argc < 5 || argc > 6)
825     {
826       mi_error_message = xstrprintf ("mi_cmd_data_read_memory: Usage: ADDR WORD-FORMAT WORD-SIZE NR-ROWS NR-COLS [ASCHAR].");
827       return MI_CMD_ERROR;
828     }
829
830   /* Extract all the arguments. */
831
832   /* Start address of the memory dump.  */
833   addr = parse_and_eval_address (argv[0]) + offset;
834   /* The format character to use when displaying a memory word.  See
835      the ``x'' command. */
836   word_format = argv[1][0];
837   /* The size of the memory word.  */
838   word_size = atol (argv[2]);
839   switch (word_size)
840     {
841     case 1:
842       word_type = builtin_type_int8;
843       word_asize = 'b';
844       break;
845     case 2:
846       word_type = builtin_type_int16;
847       word_asize = 'h';
848       break;
849     case 4:
850       word_type = builtin_type_int32;
851       word_asize = 'w';
852       break;
853     case 8:
854       word_type = builtin_type_int64;
855       word_asize = 'g';
856       break;
857     default:
858       word_type = builtin_type_int8;
859       word_asize = 'b';
860     }
861   /* The number of rows.  */
862   nr_rows = atol (argv[3]);
863   if (nr_rows <= 0)
864     {
865       mi_error_message = xstrprintf ("mi_cmd_data_read_memory: invalid number of rows.");
866       return MI_CMD_ERROR;
867     }
868   /* Number of bytes per row.  */
869   nr_cols = atol (argv[4]);
870   if (nr_cols <= 0)
871     {
872       mi_error_message = xstrprintf ("mi_cmd_data_read_memory: invalid number of columns.");
873       return MI_CMD_ERROR;
874     }
875   /* The un-printable character when printing ascii.  */
876   if (argc == 6)
877     aschar = *argv[5];
878   else
879     aschar = 0;
880
881   /* Create a buffer and read it in.  */
882   total_bytes = word_size * nr_rows * nr_cols;
883   mbuf = xcalloc (total_bytes, 1);
884   make_cleanup (xfree, mbuf);
885
886   nr_bytes = target_read (&current_target, TARGET_OBJECT_MEMORY, NULL,
887                           mbuf, addr, total_bytes);
888   if (nr_bytes <= 0)
889     {
890       do_cleanups (cleanups);
891       mi_error_message = xstrdup ("Unable to read memory.");
892       return MI_CMD_ERROR;
893     }
894
895   /* Output the header information.  */
896   ui_out_field_core_addr (uiout, "addr", addr);
897   ui_out_field_int (uiout, "nr-bytes", nr_bytes);
898   ui_out_field_int (uiout, "total-bytes", total_bytes);
899   ui_out_field_core_addr (uiout, "next-row", addr + word_size * nr_cols);
900   ui_out_field_core_addr (uiout, "prev-row", addr - word_size * nr_cols);
901   ui_out_field_core_addr (uiout, "next-page", addr + total_bytes);
902   ui_out_field_core_addr (uiout, "prev-page", addr - total_bytes);
903
904   /* Build the result as a two dimentional table.  */
905   {
906     struct ui_stream *stream = ui_out_stream_new (uiout);
907     struct cleanup *cleanup_list_memory;
908     int row;
909     int row_byte;
910     cleanup_list_memory = make_cleanup_ui_out_list_begin_end (uiout, "memory");
911     for (row = 0, row_byte = 0;
912          row < nr_rows;
913          row++, row_byte += nr_cols * word_size)
914       {
915         int col;
916         int col_byte;
917         struct cleanup *cleanup_tuple;
918         struct cleanup *cleanup_list_data;
919         cleanup_tuple = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
920         ui_out_field_core_addr (uiout, "addr", addr + row_byte);
921         /* ui_out_field_core_addr_symbolic (uiout, "saddr", addr + row_byte); */
922         cleanup_list_data = make_cleanup_ui_out_list_begin_end (uiout, "data");
923         for (col = 0, col_byte = row_byte;
924              col < nr_cols;
925              col++, col_byte += word_size)
926           {
927             if (col_byte + word_size > nr_bytes)
928               {
929                 ui_out_field_string (uiout, NULL, "N/A");
930               }
931             else
932               {
933                 ui_file_rewind (stream->stream);
934                 print_scalar_formatted (mbuf + col_byte, word_type, word_format,
935                                         word_asize, stream->stream);
936                 ui_out_field_stream (uiout, NULL, stream);
937               }
938           }
939         do_cleanups (cleanup_list_data);
940         if (aschar)
941           {
942             int byte;
943             ui_file_rewind (stream->stream);
944             for (byte = row_byte; byte < row_byte + word_size * nr_cols; byte++)
945               {
946                 if (byte >= nr_bytes)
947                   {
948                     fputc_unfiltered ('X', stream->stream);
949                   }
950                 else if (mbuf[byte] < 32 || mbuf[byte] > 126)
951                   {
952                     fputc_unfiltered (aschar, stream->stream);
953                   }
954                 else
955                   fputc_unfiltered (mbuf[byte], stream->stream);
956               }
957             ui_out_field_stream (uiout, "ascii", stream);
958           }
959         do_cleanups (cleanup_tuple);
960       }
961     ui_out_stream_delete (stream);
962     do_cleanups (cleanup_list_memory);
963   }
964   do_cleanups (cleanups);
965   return MI_CMD_DONE;
966 }
967
968 /* DATA-MEMORY-WRITE:
969
970    COLUMN_OFFSET: optional argument. Must be preceeded by '-o'. The
971    offset from the beginning of the memory grid row where the cell to
972    be written is.
973    ADDR: start address of the row in the memory grid where the memory
974    cell is, if OFFSET_COLUMN is specified.  Otherwise, the address of
975    the location to write to.
976    FORMAT: a char indicating format for the ``word''.  See 
977    the ``x'' command.
978    WORD_SIZE: size of each ``word''; 1,2,4, or 8 bytes
979    VALUE: value to be written into the memory address.
980
981    Writes VALUE into ADDR + (COLUMN_OFFSET * WORD_SIZE).
982
983    Prints nothing.  */
984 enum mi_cmd_result
985 mi_cmd_data_write_memory (char *command, char **argv, int argc)
986 {
987   CORE_ADDR addr;
988   char word_format;
989   long word_size;
990   /* FIXME: ezannoni 2000-02-17 LONGEST could possibly not be big
991      enough when using a compiler other than GCC.  */
992   LONGEST value;
993   void *buffer;
994   struct cleanup *old_chain;
995   long offset = 0;
996   int optind = 0;
997   char *optarg;
998   enum opt
999     {
1000       OFFSET_OPT
1001     };
1002   static struct mi_opt opts[] =
1003   {
1004     {"o", OFFSET_OPT, 1},
1005     { 0, 0, 0 }
1006   };
1007
1008   while (1)
1009     {
1010       int opt = mi_getopt ("mi_cmd_data_write_memory", argc, argv, opts,
1011                            &optind, &optarg);
1012       if (opt < 0)
1013         break;
1014       switch ((enum opt) opt)
1015         {
1016         case OFFSET_OPT:
1017           offset = atol (optarg);
1018           break;
1019         }
1020     }
1021   argv += optind;
1022   argc -= optind;
1023
1024   if (argc != 4)
1025     {
1026       mi_error_message = xstrprintf ("mi_cmd_data_write_memory: Usage: [-o COLUMN_OFFSET] ADDR FORMAT WORD-SIZE VALUE.");
1027       return MI_CMD_ERROR;
1028     }
1029
1030   /* Extract all the arguments.  */
1031   /* Start address of the memory dump.  */
1032   addr = parse_and_eval_address (argv[0]);
1033   /* The format character to use when displaying a memory word.  See
1034      the ``x'' command.  */
1035   word_format = argv[1][0];
1036   /* The size of the memory word. */
1037   word_size = atol (argv[2]);
1038
1039   /* Calculate the real address of the write destination.  */
1040   addr += (offset * word_size);
1041
1042   /* Get the value as a number.  */
1043   value = parse_and_eval_address (argv[3]);
1044   /* Get the value into an array.  */
1045   buffer = xmalloc (word_size);
1046   old_chain = make_cleanup (xfree, buffer);
1047   store_signed_integer (buffer, word_size, value);
1048   /* Write it down to memory.  */
1049   write_memory (addr, buffer, word_size);
1050   /* Free the buffer.  */
1051   do_cleanups (old_chain);
1052
1053   return MI_CMD_DONE;
1054 }
1055
1056 enum mi_cmd_result
1057 mi_cmd_enable_timings (char *command, char **argv, int argc)
1058 {
1059   if (argc == 0)
1060     do_timings = 1;
1061   else if (argc == 1)
1062     {
1063       if (strcmp (argv[0], "yes") == 0)
1064         do_timings = 1;
1065       else if (strcmp (argv[0], "no") == 0)
1066         do_timings = 0;
1067       else
1068         goto usage_error;
1069     }
1070   else
1071     goto usage_error;
1072     
1073   return MI_CMD_DONE;
1074
1075  usage_error:
1076   error ("mi_cmd_enable_timings: Usage: %s {yes|no}", command);
1077   return MI_CMD_ERROR;
1078 }
1079
1080 /* Execute a command within a safe environment.
1081    Return <0 for error; >=0 for ok.
1082
1083    args->action will tell mi_execute_command what action
1084    to perfrom after the given command has executed (display/supress
1085    prompt, display error). */
1086
1087 static void
1088 captured_mi_execute_command (struct ui_out *uiout, void *data)
1089 {
1090   struct captured_mi_execute_command_args *args =
1091     (struct captured_mi_execute_command_args *) data;
1092   struct mi_parse *context = args->command;
1093
1094   struct mi_timestamp cmd_finished;
1095
1096   switch (context->op)
1097     {
1098
1099     case MI_COMMAND:
1100       /* A MI command was read from the input stream.  */
1101       if (mi_debug_p)
1102         /* FIXME: gdb_???? */
1103         fprintf_unfiltered (raw_stdout, " token=`%s' command=`%s' args=`%s'\n",
1104                             context->token, context->command, context->args);
1105       /* FIXME: cagney/1999-09-25: Rather than this convoluted
1106          condition expression, each function should return an
1107          indication of what action is required and then switch on
1108          that.  */
1109       args->action = EXECUTE_COMMAND_DISPLAY_PROMPT;
1110
1111       if (do_timings)
1112         current_command_ts = context->cmd_start;
1113
1114       args->rc = mi_cmd_execute (context);
1115
1116       if (do_timings)
1117           timestamp (&cmd_finished);
1118
1119       if (!target_can_async_p () || !target_executing)
1120         {
1121           /* Print the result if there were no errors.
1122
1123              Remember that on the way out of executing a command, you have
1124              to directly use the mi_interp's uiout, since the command could 
1125              have reset the interpreter, in which case the current uiout 
1126              will most likely crash in the mi_out_* routines.  */
1127           if (args->rc == MI_CMD_DONE)
1128             {
1129               fputs_unfiltered (context->token, raw_stdout);
1130               fputs_unfiltered ("^done", raw_stdout);
1131               mi_out_put (uiout, raw_stdout);
1132               mi_out_rewind (uiout);
1133               /* Have to check cmd_start, since the command could be
1134                  -enable-timings.  */
1135               if (do_timings && context->cmd_start)
1136                   print_diff (context->cmd_start, &cmd_finished);
1137               fputs_unfiltered ("\n", raw_stdout);
1138             }
1139           else if (args->rc == MI_CMD_ERROR)
1140             {
1141               if (mi_error_message)
1142                 {
1143                   fputs_unfiltered (context->token, raw_stdout);
1144                   fputs_unfiltered ("^error,msg=\"", raw_stdout);
1145                   fputstr_unfiltered (mi_error_message, '"', raw_stdout);
1146                   xfree (mi_error_message);
1147                   fputs_unfiltered ("\"\n", raw_stdout);
1148                 }
1149               mi_out_rewind (uiout);
1150             }
1151           else
1152             mi_out_rewind (uiout);
1153         }
1154       else if (sync_execution)
1155         {
1156           /* Don't print the prompt. We are executing the target in
1157              synchronous mode.  */
1158           args->action = EXECUTE_COMMAND_SUPRESS_PROMPT;
1159           return;
1160         }
1161       break;
1162
1163     case CLI_COMMAND:
1164       {
1165         char *argv[2];
1166         /* A CLI command was read from the input stream.  */
1167         /* This "feature" will be removed as soon as we have a
1168            complete set of mi commands.  */
1169         /* Echo the command on the console.  */
1170         fprintf_unfiltered (gdb_stdlog, "%s\n", context->command);
1171         /* Call the "console" interpreter.  */
1172         argv[0] = "console";
1173         argv[1] = context->command;
1174         args->rc = mi_cmd_interpreter_exec ("-interpreter-exec", argv, 2);
1175
1176         /* If we changed interpreters, DON'T print out anything.  */
1177         if (current_interp_named_p (INTERP_MI)
1178             || current_interp_named_p (INTERP_MI1)
1179             || current_interp_named_p (INTERP_MI2)
1180             || current_interp_named_p (INTERP_MI3))
1181           {
1182             if (args->rc == MI_CMD_DONE)
1183               {
1184                 fputs_unfiltered (context->token, raw_stdout);
1185                 fputs_unfiltered ("^done", raw_stdout);
1186                 mi_out_put (uiout, raw_stdout);
1187                 mi_out_rewind (uiout);
1188                 fputs_unfiltered ("\n", raw_stdout);
1189                 args->action = EXECUTE_COMMAND_DISPLAY_PROMPT;
1190               }
1191             else if (args->rc == MI_CMD_ERROR)
1192               {
1193                 if (mi_error_message)
1194                   {
1195                     fputs_unfiltered (context->token, raw_stdout);
1196                     fputs_unfiltered ("^error,msg=\"", raw_stdout);
1197                     fputstr_unfiltered (mi_error_message, '"', raw_stdout);
1198                     xfree (mi_error_message);
1199                     fputs_unfiltered ("\"\n", raw_stdout);
1200                   }
1201                 mi_out_rewind (uiout);
1202               }
1203             else
1204               mi_out_rewind (uiout);
1205           }
1206         break;
1207       }
1208
1209     }
1210
1211   return;
1212 }
1213
1214
1215 void
1216 mi_execute_command (char *cmd, int from_tty)
1217 {
1218   struct mi_parse *command;
1219   struct captured_mi_execute_command_args args;
1220   struct ui_out *saved_uiout = uiout;
1221
1222   /* This is to handle EOF (^D). We just quit gdb.  */
1223   /* FIXME: we should call some API function here.  */
1224   if (cmd == 0)
1225     quit_force (NULL, from_tty);
1226
1227   command = mi_parse (cmd);
1228
1229   if (command != NULL)
1230     {
1231       struct gdb_exception result;
1232
1233       if (do_timings)
1234         {
1235           command->cmd_start = (struct mi_timestamp *)
1236             xmalloc (sizeof (struct mi_timestamp));
1237           timestamp (command->cmd_start);
1238         }
1239
1240       /* FIXME: cagney/1999-11-04: Can this use of catch_exceptions either
1241          be pushed even further down or even eliminated?  */
1242       args.command = command;
1243       result = catch_exception (uiout, captured_mi_execute_command, &args,
1244                                 RETURN_MASK_ALL);
1245       exception_print (gdb_stderr, result);
1246
1247       if (args.action == EXECUTE_COMMAND_SUPRESS_PROMPT)
1248         {
1249           /* The command is executing synchronously.  Bail out early
1250              suppressing the finished prompt.  */
1251           mi_parse_free (command);
1252           return;
1253         }
1254       if (result.reason < 0)
1255         {
1256           /* The command execution failed and error() was called
1257              somewhere.  */
1258           fputs_unfiltered (command->token, raw_stdout);
1259           fputs_unfiltered ("^error,msg=\"", raw_stdout);
1260           if (result.message == NULL)
1261             fputs_unfiltered ("unknown error", raw_stdout);
1262           else
1263               fputstr_unfiltered (result.message, '"', raw_stdout);
1264           fputs_unfiltered ("\"\n", raw_stdout);
1265           mi_out_rewind (uiout);
1266         }
1267       mi_parse_free (command);
1268     }
1269
1270   fputs_unfiltered ("(gdb) \n", raw_stdout);
1271   gdb_flush (raw_stdout);
1272   /* Print any buffered hook code.  */
1273   /* ..... */
1274 }
1275
1276 static enum mi_cmd_result
1277 mi_cmd_execute (struct mi_parse *parse)
1278 {
1279   free_all_values ();
1280
1281   if (parse->cmd->argv_func != NULL
1282       || parse->cmd->args_func != NULL)
1283     {
1284       /* FIXME: We need to save the token because the command executed
1285          may be asynchronous and need to print the token again.
1286          In the future we can pass the token down to the func
1287          and get rid of the last_async_command.  */
1288       /* The problem here is to keep the token around when we launch
1289          the target, and we want to interrupt it later on.  The
1290          interrupt command will have its own token, but when the
1291          target stops, we must display the token corresponding to the
1292          last execution command given.  So we have another string where
1293          we copy the token (previous_async_command), if this was
1294          indeed the token of an execution command, and when we stop we
1295          print that one.  This is possible because the interrupt
1296          command, when over, will copy that token back into the
1297          default token string (last_async_command).  */
1298
1299       if (target_executing)
1300         {
1301           if (!previous_async_command)
1302             previous_async_command = xstrdup (last_async_command);
1303           if (strcmp (parse->command, "exec-interrupt"))
1304             {
1305               fputs_unfiltered (parse->token, raw_stdout);
1306               fputs_unfiltered ("^error,msg=\"", raw_stdout);
1307               fputs_unfiltered ("Cannot execute command ", raw_stdout);
1308               fputstr_unfiltered (parse->command, '"', raw_stdout);
1309               fputs_unfiltered (" while target running", raw_stdout);
1310               fputs_unfiltered ("\"\n", raw_stdout);
1311               return MI_CMD_ERROR;
1312             }
1313         }
1314       last_async_command = xstrdup (parse->token);
1315       make_exec_cleanup (free_current_contents, &last_async_command);
1316       /* FIXME: DELETE THIS! */
1317       if (parse->cmd->args_func != NULL)
1318         return parse->cmd->args_func (parse->args, 0 /*from_tty */ );
1319       return parse->cmd->argv_func (parse->command, parse->argv, parse->argc);
1320     }
1321   else if (parse->cmd->cli.cmd != 0)
1322     {
1323       /* FIXME: DELETE THIS. */
1324       /* The operation is still implemented by a cli command.  */
1325       /* Must be a synchronous one.  */
1326       mi_execute_cli_command (parse->cmd->cli.cmd, parse->cmd->cli.args_p,
1327                               parse->args);
1328       return MI_CMD_DONE;
1329     }
1330   else
1331     {
1332       /* FIXME: DELETE THIS.  */
1333       fputs_unfiltered (parse->token, raw_stdout);
1334       fputs_unfiltered ("^error,msg=\"", raw_stdout);
1335       fputs_unfiltered ("Undefined mi command: ", raw_stdout);
1336       fputstr_unfiltered (parse->command, '"', raw_stdout);
1337       fputs_unfiltered (" (missing implementation)", raw_stdout);
1338       fputs_unfiltered ("\"\n", raw_stdout);
1339       return MI_CMD_ERROR;
1340     }
1341 }
1342
1343 /* FIXME: This is just a hack so we can get some extra commands going.
1344    We don't want to channel things through the CLI, but call libgdb directly.
1345    Use only for synchronous commands.  */
1346
1347 void
1348 mi_execute_cli_command (const char *cmd, int args_p, const char *args)
1349 {
1350   if (cmd != 0)
1351     {
1352       struct cleanup *old_cleanups;
1353       char *run;
1354       if (args_p)
1355         run = xstrprintf ("%s %s", cmd, args);
1356       else
1357         run = xstrdup (cmd);
1358       if (mi_debug_p)
1359         /* FIXME: gdb_???? */
1360         fprintf_unfiltered (gdb_stdout, "cli=%s run=%s\n",
1361                             cmd, run);
1362       old_cleanups = make_cleanup (xfree, run);
1363       execute_command ( /*ui */ run, 0 /*from_tty */ );
1364       do_cleanups (old_cleanups);
1365       return;
1366     }
1367 }
1368
1369 enum mi_cmd_result
1370 mi_execute_async_cli_command (char *mi, char *args, int from_tty)
1371 {
1372   struct cleanup *old_cleanups;
1373   char *run;
1374   char *async_args;
1375
1376   if (target_can_async_p ())
1377     {
1378       async_args = (char *) xmalloc (strlen (args) + 2);
1379       make_exec_cleanup (free, async_args);
1380       strcpy (async_args, args);
1381       strcat (async_args, "&");
1382       run = xstrprintf ("%s %s", mi, async_args);
1383       make_exec_cleanup (free, run);
1384       add_continuation (mi_exec_async_cli_cmd_continuation, NULL);
1385       old_cleanups = NULL;
1386     }
1387   else
1388     {
1389       run = xstrprintf ("%s %s", mi, args);
1390       old_cleanups = make_cleanup (xfree, run);
1391     }
1392
1393   if (!target_can_async_p ())
1394     {
1395       /* NOTE: For synchronous targets asynchronous behavour is faked by
1396          printing out the GDB prompt before we even try to execute the
1397          command.  */
1398       if (last_async_command)
1399         fputs_unfiltered (last_async_command, raw_stdout);
1400       fputs_unfiltered ("^running\n", raw_stdout);
1401       fputs_unfiltered ("(gdb) \n", raw_stdout);
1402       gdb_flush (raw_stdout);
1403     }
1404   else
1405     {
1406       /* FIXME: cagney/1999-11-29: Printing this message before
1407          calling execute_command is wrong.  It should only be printed
1408          once gdb has confirmed that it really has managed to send a
1409          run command to the target.  */
1410       if (last_async_command)
1411         fputs_unfiltered (last_async_command, raw_stdout);
1412       fputs_unfiltered ("^running\n", raw_stdout);
1413     }
1414
1415   execute_command ( /*ui */ run, 0 /*from_tty */ );
1416
1417   if (!target_can_async_p ())
1418     {
1419       /* Do this before doing any printing.  It would appear that some
1420          print code leaves garbage around in the buffer.  */
1421       do_cleanups (old_cleanups);
1422       /* If the target was doing the operation synchronously we fake
1423          the stopped message.  */
1424       if (last_async_command)
1425         fputs_unfiltered (last_async_command, raw_stdout);
1426       fputs_unfiltered ("*stopped", raw_stdout);
1427       mi_out_put (uiout, raw_stdout);
1428       mi_out_rewind (uiout);
1429       if (do_timings)
1430         print_diff_now (current_command_ts);
1431       fputs_unfiltered ("\n", raw_stdout);
1432       return MI_CMD_QUIET;
1433     }
1434   return MI_CMD_DONE;
1435 }
1436
1437 void
1438 mi_exec_async_cli_cmd_continuation (struct continuation_arg *arg)
1439 {
1440   if (last_async_command)
1441     fputs_unfiltered (last_async_command, raw_stdout);
1442   fputs_unfiltered ("*stopped", raw_stdout);
1443   mi_out_put (uiout, raw_stdout);
1444   fputs_unfiltered ("\n", raw_stdout);
1445   fputs_unfiltered ("(gdb) \n", raw_stdout);
1446   gdb_flush (raw_stdout);
1447   do_exec_cleanups (ALL_CLEANUPS);
1448 }
1449
1450 void
1451 mi_load_progress (const char *section_name,
1452                   unsigned long sent_so_far,
1453                   unsigned long total_section,
1454                   unsigned long total_sent,
1455                   unsigned long grand_total)
1456 {
1457   struct timeval time_now, delta, update_threshold;
1458   static struct timeval last_update;
1459   static char *previous_sect_name = NULL;
1460   int new_section;
1461   struct ui_out *saved_uiout;
1462
1463   /* This function is called through deprecated_show_load_progress
1464      which means uiout may not be correct.  Fix it for the duration
1465      of this function.  */
1466   saved_uiout = uiout;
1467
1468   if (current_interp_named_p (INTERP_MI))
1469     uiout = mi_out_new (2);
1470   else if (current_interp_named_p (INTERP_MI1))
1471     uiout = mi_out_new (1);
1472   else
1473     return;
1474
1475   update_threshold.tv_sec = 0;
1476   update_threshold.tv_usec = 500000;
1477   gettimeofday (&time_now, NULL);
1478
1479   delta.tv_usec = time_now.tv_usec - last_update.tv_usec;
1480   delta.tv_sec = time_now.tv_sec - last_update.tv_sec;
1481
1482   if (delta.tv_usec < 0)
1483     {
1484       delta.tv_sec -= 1;
1485       delta.tv_usec += 1000000L;
1486     }
1487
1488   new_section = (previous_sect_name ?
1489                  strcmp (previous_sect_name, section_name) : 1);
1490   if (new_section)
1491     {
1492       struct cleanup *cleanup_tuple;
1493       xfree (previous_sect_name);
1494       previous_sect_name = xstrdup (section_name);
1495
1496       if (last_async_command)
1497         fputs_unfiltered (last_async_command, raw_stdout);
1498       fputs_unfiltered ("+download", raw_stdout);
1499       cleanup_tuple = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
1500       ui_out_field_string (uiout, "section", section_name);
1501       ui_out_field_int (uiout, "section-size", total_section);
1502       ui_out_field_int (uiout, "total-size", grand_total);
1503       do_cleanups (cleanup_tuple);
1504       mi_out_put (uiout, raw_stdout);
1505       fputs_unfiltered ("\n", raw_stdout);
1506       gdb_flush (raw_stdout);
1507     }
1508
1509   if (delta.tv_sec >= update_threshold.tv_sec &&
1510       delta.tv_usec >= update_threshold.tv_usec)
1511     {
1512       struct cleanup *cleanup_tuple;
1513       last_update.tv_sec = time_now.tv_sec;
1514       last_update.tv_usec = time_now.tv_usec;
1515       if (last_async_command)
1516         fputs_unfiltered (last_async_command, raw_stdout);
1517       fputs_unfiltered ("+download", raw_stdout);
1518       cleanup_tuple = make_cleanup_ui_out_tuple_begin_end (uiout, NULL);
1519       ui_out_field_string (uiout, "section", section_name);
1520       ui_out_field_int (uiout, "section-sent", sent_so_far);
1521       ui_out_field_int (uiout, "section-size", total_section);
1522       ui_out_field_int (uiout, "total-sent", total_sent);
1523       ui_out_field_int (uiout, "total-size", grand_total);
1524       do_cleanups (cleanup_tuple);
1525       mi_out_put (uiout, raw_stdout);
1526       fputs_unfiltered ("\n", raw_stdout);
1527       gdb_flush (raw_stdout);
1528     }
1529
1530   xfree (uiout);
1531   uiout = saved_uiout;
1532 }
1533
1534 static void 
1535 timestamp (struct mi_timestamp *tv)
1536   {
1537     long usec;
1538     gettimeofday (&tv->wallclock, NULL);
1539 #ifdef HAVE_GETRUSAGE
1540     getrusage (RUSAGE_SELF, &rusage);
1541     tv->utime.tv_sec = rusage.ru_utime.tv_sec;
1542     tv->utime.tv_usec = rusage.ru_utime.tv_usec;
1543     tv->stime.tv_sec = rusage.ru_stime.tv_sec;
1544     tv->stime.tv_usec = rusage.ru_stime.tv_usec;
1545 #else
1546     usec = get_run_time ();
1547     tv->utime.tv_sec = usec/1000000L;
1548     tv->utime.tv_usec = usec - 1000000L*tv->utime.tv_sec;
1549     tv->stime.tv_sec = 0;
1550     tv->stime.tv_usec = 0;
1551 #endif
1552   }
1553
1554 static void 
1555 print_diff_now (struct mi_timestamp *start)
1556   {
1557     struct mi_timestamp now;
1558     timestamp (&now);
1559     print_diff (start, &now);
1560   }
1561
1562 static long 
1563 timeval_diff (struct timeval start, struct timeval end)
1564   {
1565     return ((end.tv_sec - start.tv_sec) * 1000000L)
1566       + (end.tv_usec - start.tv_usec);
1567   }
1568
1569 static void 
1570 print_diff (struct mi_timestamp *start, struct mi_timestamp *end)
1571   {
1572     fprintf_unfiltered
1573       (raw_stdout,
1574        ",time={wallclock=\"%0.5f\",user=\"%0.5f\",system=\"%0.5f\"}", 
1575        timeval_diff (start->wallclock, end->wallclock) / 1000000.0, 
1576        timeval_diff (start->utime, end->utime) / 1000000.0, 
1577        timeval_diff (start->stime, end->stime) / 1000000.0);
1578   }