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