OSDN Git Service

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