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