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