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