Merge async and sync code paths some more
[external/binutils.git] / gdb / mi / mi-interp.c
1 /* MI Interpreter Definitions and Commands for GDB, the GNU debugger.
2
3    Copyright (C) 2002-2015 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19
20 #include "defs.h"
21 #include "interps.h"
22 #include "event-top.h"
23 #include "event-loop.h"
24 #include "inferior.h"
25 #include "infrun.h"
26 #include "ui-out.h"
27 #include "top.h"
28 #include "mi-main.h"
29 #include "mi-cmds.h"
30 #include "mi-out.h"
31 #include "mi-console.h"
32 #include "mi-common.h"
33 #include "observer.h"
34 #include "gdbthread.h"
35 #include "solist.h"
36 #include "gdb.h"
37 #include "objfiles.h"
38 #include "tracepoint.h"
39 #include "cli-out.h"
40
41 /* These are the interpreter setup, etc. functions for the MI
42    interpreter.  */
43
44 static void mi_execute_command_wrapper (const char *cmd);
45 static void mi_execute_command_input_handler (char *cmd);
46 static void mi_command_loop (void *data);
47
48 /* These are hooks that we put in place while doing interpreter_exec
49    so we can report interesting things that happened "behind the MI's
50    back" in this command.  */
51
52 static int mi_interp_query_hook (const char *ctlstr, va_list ap)
53   ATTRIBUTE_PRINTF (1, 0);
54
55 static void mi_insert_notify_hooks (void);
56 static void mi_remove_notify_hooks (void);
57
58 static void mi_on_signal_received (enum gdb_signal siggnal);
59 static void mi_on_end_stepping_range (void);
60 static void mi_on_signal_exited (enum gdb_signal siggnal);
61 static void mi_on_exited (int exitstatus);
62 static void mi_on_normal_stop (struct bpstats *bs, int print_frame);
63 static void mi_on_no_history (void);
64
65 static void mi_new_thread (struct thread_info *t);
66 static void mi_thread_exit (struct thread_info *t, int silent);
67 static void mi_record_changed (struct inferior*, int);
68 static void mi_inferior_added (struct inferior *inf);
69 static void mi_inferior_appeared (struct inferior *inf);
70 static void mi_inferior_exit (struct inferior *inf);
71 static void mi_inferior_removed (struct inferior *inf);
72 static void mi_on_resume (ptid_t ptid);
73 static void mi_solib_loaded (struct so_list *solib);
74 static void mi_solib_unloaded (struct so_list *solib);
75 static void mi_about_to_proceed (void);
76 static void mi_traceframe_changed (int tfnum, int tpnum);
77 static void mi_tsv_created (const struct trace_state_variable *tsv);
78 static void mi_tsv_deleted (const struct trace_state_variable *tsv);
79 static void mi_tsv_modified (const struct trace_state_variable *tsv);
80 static void mi_breakpoint_created (struct breakpoint *b);
81 static void mi_breakpoint_deleted (struct breakpoint *b);
82 static void mi_breakpoint_modified (struct breakpoint *b);
83 static void mi_command_param_changed (const char *param, const char *value);
84 static void mi_memory_changed (struct inferior *inf, CORE_ADDR memaddr,
85                                ssize_t len, const bfd_byte *myaddr);
86 static void mi_on_sync_execution_done (void);
87
88 static int report_initial_inferior (struct inferior *inf, void *closure);
89
90 static void *
91 mi_interpreter_init (struct interp *interp, int top_level)
92 {
93   struct mi_interp *mi = XNEW (struct mi_interp);
94   const char *name;
95   int mi_version;
96
97   /* Assign the output channel created at startup to its own global,
98      so that we can create a console channel that encapsulates and
99      prefixes all gdb_output-type bits coming from the rest of the
100      debugger.  */
101
102   raw_stdout = gdb_stdout;
103
104   /* Create MI console channels, each with a different prefix so they
105      can be distinguished.  */
106   mi->out = mi_console_file_new (raw_stdout, "~", '"');
107   mi->err = mi_console_file_new (raw_stdout, "&", '"');
108   mi->log = mi->err;
109   mi->targ = mi_console_file_new (raw_stdout, "@", '"');
110   mi->event_channel = mi_console_file_new (raw_stdout, "=", 0);
111
112   name = interp_name (interp);
113   /* INTERP_MI selects the most recent released version.  "mi2" was
114      released as part of GDB 6.0.  */
115   if (strcmp (name, INTERP_MI) == 0)
116     mi_version = 2;
117   else if (strcmp (name, INTERP_MI1) == 0)
118     mi_version = 1;
119   else if (strcmp (name, INTERP_MI2) == 0)
120     mi_version = 2;
121   else if (strcmp (name, INTERP_MI3) == 0)
122     mi_version = 3;
123   else
124     gdb_assert_not_reached ("unhandled MI version");
125
126   mi->mi_uiout = mi_out_new (mi_version);
127   mi->cli_uiout = cli_out_new (mi->out);
128
129   /* There are installed even if MI is not the top level interpreter.
130      The callbacks themselves decide whether to be skipped.  */
131   observer_attach_signal_received (mi_on_signal_received);
132   observer_attach_end_stepping_range (mi_on_end_stepping_range);
133   observer_attach_signal_exited (mi_on_signal_exited);
134   observer_attach_exited (mi_on_exited);
135   observer_attach_no_history (mi_on_no_history);
136
137   if (top_level)
138     {
139       observer_attach_new_thread (mi_new_thread);
140       observer_attach_thread_exit (mi_thread_exit);
141       observer_attach_inferior_added (mi_inferior_added);
142       observer_attach_inferior_appeared (mi_inferior_appeared);
143       observer_attach_inferior_exit (mi_inferior_exit);
144       observer_attach_inferior_removed (mi_inferior_removed);
145       observer_attach_record_changed (mi_record_changed);
146       observer_attach_normal_stop (mi_on_normal_stop);
147       observer_attach_target_resumed (mi_on_resume);
148       observer_attach_solib_loaded (mi_solib_loaded);
149       observer_attach_solib_unloaded (mi_solib_unloaded);
150       observer_attach_about_to_proceed (mi_about_to_proceed);
151       observer_attach_traceframe_changed (mi_traceframe_changed);
152       observer_attach_tsv_created (mi_tsv_created);
153       observer_attach_tsv_deleted (mi_tsv_deleted);
154       observer_attach_tsv_modified (mi_tsv_modified);
155       observer_attach_breakpoint_created (mi_breakpoint_created);
156       observer_attach_breakpoint_deleted (mi_breakpoint_deleted);
157       observer_attach_breakpoint_modified (mi_breakpoint_modified);
158       observer_attach_command_param_changed (mi_command_param_changed);
159       observer_attach_memory_changed (mi_memory_changed);
160       observer_attach_sync_execution_done (mi_on_sync_execution_done);
161
162       /* The initial inferior is created before this function is
163          called, so we need to report it explicitly.  Use iteration in
164          case future version of GDB creates more than one inferior
165          up-front.  */
166       iterate_over_inferiors (report_initial_inferior, mi);
167     }
168
169   return mi;
170 }
171
172 static int
173 mi_interpreter_resume (void *data)
174 {
175   struct mi_interp *mi = data;
176
177   /* As per hack note in mi_interpreter_init, swap in the output
178      channels... */
179   gdb_setup_readline ();
180
181   /* These overwrite some of the initialization done in
182      _intialize_event_loop.  */
183   call_readline = gdb_readline2;
184   input_handler = mi_execute_command_input_handler;
185   async_command_editing_p = 0;
186   /* FIXME: This is a total hack for now.  PB's use of the MI
187      implicitly relies on a bug in the async support which allows
188      asynchronous commands to leak through the commmand loop.  The bug
189      involves (but is not limited to) the fact that sync_execution was
190      erroneously initialized to 0.  Duplicate by initializing it thus
191      here...  */
192   sync_execution = 0;
193
194   gdb_stdout = mi->out;
195   /* Route error and log output through the MI.  */
196   gdb_stderr = mi->err;
197   gdb_stdlog = mi->log;
198   /* Route target output through the MI.  */
199   gdb_stdtarg = mi->targ;
200   /* Route target error through the MI as well.  */
201   gdb_stdtargerr = mi->targ;
202
203   /* Replace all the hooks that we know about.  There really needs to
204      be a better way of doing this... */
205   clear_interpreter_hooks ();
206
207   deprecated_show_load_progress = mi_load_progress;
208
209   return 1;
210 }
211
212 static int
213 mi_interpreter_suspend (void *data)
214 {
215   gdb_disable_readline ();
216   return 1;
217 }
218
219 static struct gdb_exception
220 mi_interpreter_exec (void *data, const char *command)
221 {
222   mi_execute_command_wrapper (command);
223   return exception_none;
224 }
225
226 void
227 mi_cmd_interpreter_exec (char *command, char **argv, int argc)
228 {
229   struct interp *interp_to_use;
230   int i;
231   char *mi_error_message = NULL;
232   struct cleanup *old_chain;
233
234   if (argc < 2)
235     error (_("-interpreter-exec: "
236              "Usage: -interpreter-exec interp command"));
237
238   interp_to_use = interp_lookup (argv[0]);
239   if (interp_to_use == NULL)
240     error (_("-interpreter-exec: could not find interpreter \"%s\""),
241            argv[0]);
242
243   /* Note that unlike the CLI version of this command, we don't
244      actually set INTERP_TO_USE as the current interpreter, as we
245      still want gdb_stdout, etc. to point at MI streams.  */
246
247   /* Insert the MI out hooks, making sure to also call the
248      interpreter's hooks if it has any.  */
249   /* KRS: We shouldn't need this... Events should be installed and
250      they should just ALWAYS fire something out down the MI
251      channel.  */
252   mi_insert_notify_hooks ();
253
254   /* Now run the code.  */
255
256   old_chain = make_cleanup (null_cleanup, 0);
257   for (i = 1; i < argc; i++)
258     {
259       struct gdb_exception e = interp_exec (interp_to_use, argv[i]);
260
261       if (e.reason < 0)
262         {
263           mi_error_message = xstrdup (e.message);
264           make_cleanup (xfree, mi_error_message);
265           break;
266         }
267     }
268
269   mi_remove_notify_hooks ();
270
271   if (mi_error_message != NULL)
272     error ("%s", mi_error_message);
273   do_cleanups (old_chain);
274 }
275
276 /* This inserts a number of hooks that are meant to produce
277    async-notify ("=") MI messages while running commands in another
278    interpreter using mi_interpreter_exec.  The canonical use for this
279    is to allow access to the gdb CLI interpreter from within the MI,
280    while still producing MI style output when actions in the CLI
281    command change GDB's state.  */
282
283 static void
284 mi_insert_notify_hooks (void)
285 {
286   deprecated_query_hook = mi_interp_query_hook;
287 }
288
289 static void
290 mi_remove_notify_hooks (void)
291 {
292   deprecated_query_hook = NULL;
293 }
294
295 static int
296 mi_interp_query_hook (const char *ctlstr, va_list ap)
297 {
298   return 1;
299 }
300
301 static void
302 mi_execute_command_wrapper (const char *cmd)
303 {
304   mi_execute_command (cmd, stdin == instream);
305 }
306
307 /* Observer for the synchronous_command_done notification.  */
308
309 static void
310 mi_on_sync_execution_done (void)
311 {
312   /* If MI is sync, then output the MI prompt now, indicating we're
313      ready for further input.  */
314   if (!mi_async_p ())
315     {
316       fputs_unfiltered ("(gdb) \n", raw_stdout);
317       gdb_flush (raw_stdout);
318     }
319 }
320
321 /* mi_execute_command_wrapper wrapper suitable for INPUT_HANDLER.  */
322
323 static void
324 mi_execute_command_input_handler (char *cmd)
325 {
326   mi_execute_command_wrapper (cmd);
327
328   /* Print a prompt, indicating we're ready for further input, unless
329      we just started a synchronous command.  In that case, we're about
330      to go back to the event loop and will output the prompt in the
331      'synchronous_command_done' observer when the target next
332      stops.  */
333   if (!sync_execution)
334     {
335       fputs_unfiltered ("(gdb) \n", raw_stdout);
336       gdb_flush (raw_stdout);
337     }
338 }
339
340 static void
341 mi_command_loop (void *data)
342 {
343   /* Turn off 8 bit strings in quoted output.  Any character with the
344      high bit set is printed using C's octal format.  */
345   sevenbit_strings = 1;
346
347   /* Tell the world that we're alive.  */
348   fputs_unfiltered ("(gdb) \n", raw_stdout);
349   gdb_flush (raw_stdout);
350
351   start_event_loop ();
352 }
353
354 static void
355 mi_new_thread (struct thread_info *t)
356 {
357   struct mi_interp *mi = top_level_interpreter_data ();
358   struct inferior *inf = find_inferior_ptid (t->ptid);
359
360   gdb_assert (inf);
361
362   fprintf_unfiltered (mi->event_channel, 
363                       "thread-created,id=\"%d\",group-id=\"i%d\"",
364                       t->num, inf->num);
365   gdb_flush (mi->event_channel);
366 }
367
368 static void
369 mi_thread_exit (struct thread_info *t, int silent)
370 {
371   struct mi_interp *mi;
372   struct inferior *inf;
373   struct cleanup *old_chain;
374
375   if (silent)
376     return;
377
378   inf = find_inferior_ptid (t->ptid);
379
380   mi = top_level_interpreter_data ();
381   old_chain = make_cleanup_restore_target_terminal ();
382   target_terminal_ours ();
383   fprintf_unfiltered (mi->event_channel, 
384                       "thread-exited,id=\"%d\",group-id=\"i%d\"",
385                       t->num, inf->num);
386   gdb_flush (mi->event_channel);
387
388   do_cleanups (old_chain);
389 }
390
391 /* Emit notification on changing the state of record.  */
392
393 static void
394 mi_record_changed (struct inferior *inferior, int started)
395 {
396   struct mi_interp *mi = top_level_interpreter_data ();
397
398   fprintf_unfiltered (mi->event_channel,  "record-%s,thread-group=\"i%d\"",
399                       started ? "started" : "stopped", inferior->num);
400
401   gdb_flush (mi->event_channel);
402 }
403
404 static void
405 mi_inferior_added (struct inferior *inf)
406 {
407   struct mi_interp *mi = top_level_interpreter_data ();
408
409   target_terminal_ours ();
410   fprintf_unfiltered (mi->event_channel,
411                       "thread-group-added,id=\"i%d\"",
412                       inf->num);
413   gdb_flush (mi->event_channel);
414 }
415
416 static void
417 mi_inferior_appeared (struct inferior *inf)
418 {
419   struct mi_interp *mi = top_level_interpreter_data ();
420
421   target_terminal_ours ();
422   fprintf_unfiltered (mi->event_channel,
423                       "thread-group-started,id=\"i%d\",pid=\"%d\"",
424                       inf->num, inf->pid);
425   gdb_flush (mi->event_channel);
426 }
427
428 static void
429 mi_inferior_exit (struct inferior *inf)
430 {
431   struct mi_interp *mi = top_level_interpreter_data ();
432
433   target_terminal_ours ();
434   if (inf->has_exit_code)
435     fprintf_unfiltered (mi->event_channel,
436                         "thread-group-exited,id=\"i%d\",exit-code=\"%s\"",
437                         inf->num, int_string (inf->exit_code, 8, 0, 0, 1));
438   else
439     fprintf_unfiltered (mi->event_channel,
440                         "thread-group-exited,id=\"i%d\"", inf->num);
441
442   gdb_flush (mi->event_channel);  
443 }
444
445 static void
446 mi_inferior_removed (struct inferior *inf)
447 {
448   struct mi_interp *mi = top_level_interpreter_data ();
449
450   target_terminal_ours ();
451   fprintf_unfiltered (mi->event_channel,
452                       "thread-group-removed,id=\"i%d\"",
453                       inf->num);
454   gdb_flush (mi->event_channel);
455 }
456
457 /* Cleanup that restores a previous current uiout.  */
458
459 static void
460 restore_current_uiout_cleanup (void *arg)
461 {
462   struct ui_out *saved_uiout = arg;
463
464   current_uiout = saved_uiout;
465 }
466
467 /* Return the MI interpreter, if it is active -- either because it's
468    the top-level interpreter or the interpreter executing the current
469    command.  Returns NULL if the MI interpreter is not being used.  */
470
471 static struct interp *
472 find_mi_interpreter (void)
473 {
474   struct interp *interp;
475
476   interp = top_level_interpreter ();
477   if (ui_out_is_mi_like_p (interp_ui_out (interp)))
478     return interp;
479
480   interp = command_interp ();
481   if (ui_out_is_mi_like_p (interp_ui_out (interp)))
482     return interp;
483
484   return NULL;
485 }
486
487 /* Return the MI_INTERP structure of the active MI interpreter.
488    Returns NULL if MI is not active.  */
489
490 static struct mi_interp *
491 mi_interp_data (void)
492 {
493   struct interp *interp = find_mi_interpreter ();
494
495   if (interp != NULL)
496     return interp_data (interp);
497   return NULL;
498 }
499
500 /* Observers for several run control events that print why the
501    inferior has stopped to both the the MI event channel and to the MI
502    console.  If the MI interpreter is not active, print nothing.  */
503
504 /* Observer for the signal_received notification.  */
505
506 static void
507 mi_on_signal_received (enum gdb_signal siggnal)
508 {
509   struct mi_interp *mi = mi_interp_data ();
510
511   if (mi == NULL)
512     return;
513
514   print_signal_received_reason (mi->mi_uiout, siggnal);
515   print_signal_received_reason (mi->cli_uiout, siggnal);
516 }
517
518 /* Observer for the end_stepping_range notification.  */
519
520 static void
521 mi_on_end_stepping_range (void)
522 {
523   struct mi_interp *mi = mi_interp_data ();
524
525   if (mi == NULL)
526     return;
527
528   print_end_stepping_range_reason (mi->mi_uiout);
529   print_end_stepping_range_reason (mi->cli_uiout);
530 }
531
532 /* Observer for the signal_exited notification.  */
533
534 static void
535 mi_on_signal_exited (enum gdb_signal siggnal)
536 {
537   struct mi_interp *mi = mi_interp_data ();
538
539   if (mi == NULL)
540     return;
541
542   print_signal_exited_reason (mi->mi_uiout, siggnal);
543   print_signal_exited_reason (mi->cli_uiout, siggnal);
544 }
545
546 /* Observer for the exited notification.  */
547
548 static void
549 mi_on_exited (int exitstatus)
550 {
551   struct mi_interp *mi = mi_interp_data ();
552
553   if (mi == NULL)
554     return;
555
556   print_exited_reason (mi->mi_uiout, exitstatus);
557   print_exited_reason (mi->cli_uiout, exitstatus);
558 }
559
560 /* Observer for the no_history notification.  */
561
562 static void
563 mi_on_no_history (void)
564 {
565   struct mi_interp *mi = mi_interp_data ();
566
567   if (mi == NULL)
568     return;
569
570   print_no_history_reason (mi->mi_uiout);
571   print_no_history_reason (mi->cli_uiout);
572 }
573
574 static void
575 mi_on_normal_stop (struct bpstats *bs, int print_frame)
576 {
577   /* Since this can be called when CLI command is executing,
578      using cli interpreter, be sure to use MI uiout for output,
579      not the current one.  */
580   struct ui_out *mi_uiout = interp_ui_out (top_level_interpreter ());
581
582   if (print_frame)
583     {
584       int core;
585
586       if (current_uiout != mi_uiout)
587         {
588           /* The normal_stop function has printed frame information
589              into CLI uiout, or some other non-MI uiout.  There's no
590              way we can extract proper fields from random uiout
591              object, so we print the frame again.  In practice, this
592              can only happen when running a CLI command in MI.  */
593           struct ui_out *saved_uiout = current_uiout;
594           struct target_waitstatus last;
595           ptid_t last_ptid;
596
597           current_uiout = mi_uiout;
598
599           get_last_target_status (&last_ptid, &last);
600           print_stop_event (&last);
601
602           current_uiout = saved_uiout;
603         }
604       /* Otherwise, frame information has already been printed by
605          normal_stop.  */
606       else
607         {
608           /* Breakpoint hits should always be mirrored to the console.
609              Deciding what to mirror to the console wrt to breakpoints
610              and random stops gets messy real fast.  E.g., say "s"
611              trips on a breakpoint.  We'd clearly want to mirror the
612              event to the console in this case.  But what about more
613              complicated cases like "s&; thread n; s&", and one of
614              those steps spawning a new thread, and that thread
615              hitting a breakpoint?  It's impossible in general to
616              track whether the thread had any relation to the commands
617              that had been executed.  So we just simplify and always
618              mirror breakpoints and random events to the console.
619
620              Also, CLI execution commands (-interpreter-exec console
621              "next", for example) in async mode have the opposite
622              issue as described in the "then" branch above --
623              normal_stop has already printed frame information to MI
624              uiout, but nothing has printed the same information to
625              the CLI channel.  We should print the source line to the
626              console when stepping or other similar commands, iff the
627              step was started by a console command (but not if it was
628              started with -exec-step or similar).  */
629           struct thread_info *tp = inferior_thread ();
630
631           if ((!tp->control.stop_step
632                   && !tp->control.proceed_to_finish)
633               || (tp->control.command_interp != NULL
634                   && tp->control.command_interp != top_level_interpreter ()))
635             {
636               struct mi_interp *mi = top_level_interpreter_data ();
637               struct target_waitstatus last;
638               ptid_t last_ptid;
639               struct cleanup *old_chain;
640
641               /* Set the current uiout to CLI uiout temporarily.  */
642               old_chain = make_cleanup (restore_current_uiout_cleanup,
643                                         current_uiout);
644               current_uiout = mi->cli_uiout;
645
646               get_last_target_status (&last_ptid, &last);
647               print_stop_event (&last);
648
649               do_cleanups (old_chain);
650             }
651         }
652
653       ui_out_field_int (mi_uiout, "thread-id",
654                         pid_to_thread_id (inferior_ptid));
655       if (non_stop)
656         {
657           struct cleanup *back_to = make_cleanup_ui_out_list_begin_end 
658             (mi_uiout, "stopped-threads");
659
660           ui_out_field_int (mi_uiout, NULL,
661                             pid_to_thread_id (inferior_ptid));
662           do_cleanups (back_to);
663         }
664       else
665         ui_out_field_string (mi_uiout, "stopped-threads", "all");
666
667       core = target_core_of_thread (inferior_ptid);
668       if (core != -1)
669         ui_out_field_int (mi_uiout, "core", core);
670     }
671   
672   fputs_unfiltered ("*stopped", raw_stdout);
673   mi_out_put (mi_uiout, raw_stdout);
674   mi_out_rewind (mi_uiout);
675   mi_print_timing_maybe ();
676   fputs_unfiltered ("\n", raw_stdout);
677   gdb_flush (raw_stdout);
678 }
679
680 static void
681 mi_about_to_proceed (void)
682 {
683   /* Suppress output while calling an inferior function.  */
684
685   if (!ptid_equal (inferior_ptid, null_ptid))
686     {
687       struct thread_info *tp = inferior_thread ();
688
689       if (tp->control.in_infcall)
690         return;
691     }
692
693   mi_proceeded = 1;
694 }
695
696 /* When the element is non-zero, no MI notifications will be emitted in
697    response to the corresponding observers.  */
698
699 struct mi_suppress_notification mi_suppress_notification =
700   {
701     0,
702     0,
703     0,
704   };
705
706 /* Emit notification on changing a traceframe.  */
707
708 static void
709 mi_traceframe_changed (int tfnum, int tpnum)
710 {
711   struct mi_interp *mi = top_level_interpreter_data ();
712
713   if (mi_suppress_notification.traceframe)
714     return;
715
716   target_terminal_ours ();
717
718   if (tfnum >= 0)
719     fprintf_unfiltered (mi->event_channel, "traceframe-changed,"
720                         "num=\"%d\",tracepoint=\"%d\"\n",
721                         tfnum, tpnum);
722   else
723     fprintf_unfiltered (mi->event_channel, "traceframe-changed,end");
724
725   gdb_flush (mi->event_channel);
726 }
727
728 /* Emit notification on creating a trace state variable.  */
729
730 static void
731 mi_tsv_created (const struct trace_state_variable *tsv)
732 {
733   struct mi_interp *mi = top_level_interpreter_data ();
734
735   target_terminal_ours ();
736
737   fprintf_unfiltered (mi->event_channel, "tsv-created,"
738                       "name=\"%s\",initial=\"%s\"\n",
739                       tsv->name, plongest (tsv->initial_value));
740
741   gdb_flush (mi->event_channel);
742 }
743
744 /* Emit notification on deleting a trace state variable.  */
745
746 static void
747 mi_tsv_deleted (const struct trace_state_variable *tsv)
748 {
749   struct mi_interp *mi = top_level_interpreter_data ();
750
751   target_terminal_ours ();
752
753   if (tsv != NULL)
754     fprintf_unfiltered (mi->event_channel, "tsv-deleted,"
755                         "name=\"%s\"\n", tsv->name);
756   else
757     fprintf_unfiltered (mi->event_channel, "tsv-deleted\n");
758
759   gdb_flush (mi->event_channel);
760 }
761
762 /* Emit notification on modifying a trace state variable.  */
763
764 static void
765 mi_tsv_modified (const struct trace_state_variable *tsv)
766 {
767   struct mi_interp *mi = top_level_interpreter_data ();
768   struct ui_out *mi_uiout = interp_ui_out (top_level_interpreter ());
769
770   target_terminal_ours ();
771
772   fprintf_unfiltered (mi->event_channel,
773                       "tsv-modified");
774
775   ui_out_redirect (mi_uiout, mi->event_channel);
776
777   ui_out_field_string (mi_uiout, "name", tsv->name);
778   ui_out_field_string (mi_uiout, "initial",
779                        plongest (tsv->initial_value));
780   if (tsv->value_known)
781     ui_out_field_string (mi_uiout, "current", plongest (tsv->value));
782
783   ui_out_redirect (mi_uiout, NULL);
784
785   gdb_flush (mi->event_channel);
786 }
787
788 /* Emit notification about a created breakpoint.  */
789
790 static void
791 mi_breakpoint_created (struct breakpoint *b)
792 {
793   struct mi_interp *mi = top_level_interpreter_data ();
794   struct ui_out *mi_uiout = interp_ui_out (top_level_interpreter ());
795
796   if (mi_suppress_notification.breakpoint)
797     return;
798
799   if (b->number <= 0)
800     return;
801
802   target_terminal_ours ();
803   fprintf_unfiltered (mi->event_channel,
804                       "breakpoint-created");
805   /* We want the output from gdb_breakpoint_query to go to
806      mi->event_channel.  One approach would be to just call
807      gdb_breakpoint_query, and then use mi_out_put to send the current
808      content of mi_outout into mi->event_channel.  However, that will
809      break if anything is output to mi_uiout prior to calling the
810      breakpoint_created notifications.  So, we use
811      ui_out_redirect.  */
812   ui_out_redirect (mi_uiout, mi->event_channel);
813   TRY
814     {
815       gdb_breakpoint_query (mi_uiout, b->number, NULL);
816     }
817   CATCH (e, RETURN_MASK_ERROR)
818     {
819     }
820   END_CATCH
821
822   ui_out_redirect (mi_uiout, NULL);
823
824   gdb_flush (mi->event_channel);
825 }
826
827 /* Emit notification about deleted breakpoint.  */
828
829 static void
830 mi_breakpoint_deleted (struct breakpoint *b)
831 {
832   struct mi_interp *mi = top_level_interpreter_data ();
833
834   if (mi_suppress_notification.breakpoint)
835     return;
836
837   if (b->number <= 0)
838     return;
839
840   target_terminal_ours ();
841
842   fprintf_unfiltered (mi->event_channel, "breakpoint-deleted,id=\"%d\"",
843                       b->number);
844
845   gdb_flush (mi->event_channel);
846 }
847
848 /* Emit notification about modified breakpoint.  */
849
850 static void
851 mi_breakpoint_modified (struct breakpoint *b)
852 {
853   struct mi_interp *mi = top_level_interpreter_data ();
854   struct ui_out *mi_uiout = interp_ui_out (top_level_interpreter ());
855
856   if (mi_suppress_notification.breakpoint)
857     return;
858
859   if (b->number <= 0)
860     return;
861
862   target_terminal_ours ();
863   fprintf_unfiltered (mi->event_channel,
864                       "breakpoint-modified");
865   /* We want the output from gdb_breakpoint_query to go to
866      mi->event_channel.  One approach would be to just call
867      gdb_breakpoint_query, and then use mi_out_put to send the current
868      content of mi_outout into mi->event_channel.  However, that will
869      break if anything is output to mi_uiout prior to calling the
870      breakpoint_created notifications.  So, we use
871      ui_out_redirect.  */
872   ui_out_redirect (mi_uiout, mi->event_channel);
873   TRY
874     {
875       gdb_breakpoint_query (mi_uiout, b->number, NULL);
876     }
877   CATCH (e, RETURN_MASK_ERROR)
878     {
879     }
880   END_CATCH
881
882   ui_out_redirect (mi_uiout, NULL);
883
884   gdb_flush (mi->event_channel);
885 }
886
887 static int
888 mi_output_running_pid (struct thread_info *info, void *arg)
889 {
890   ptid_t *ptid = arg;
891
892   if (ptid_get_pid (*ptid) == ptid_get_pid (info->ptid))
893     fprintf_unfiltered (raw_stdout,
894                         "*running,thread-id=\"%d\"\n",
895                         info->num);
896
897   return 0;
898 }
899
900 static int
901 mi_inferior_count (struct inferior *inf, void *arg)
902 {
903   if (inf->pid != 0)
904     {
905       int *count_p = arg;
906       (*count_p)++;
907     }
908
909   return 0;
910 }
911
912 static void
913 mi_on_resume (ptid_t ptid)
914 {
915   struct thread_info *tp = NULL;
916
917   if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
918     tp = inferior_thread ();
919   else
920     tp = find_thread_ptid (ptid);
921
922   /* Suppress output while calling an inferior function.  */
923   if (tp->control.in_infcall)
924     return;
925
926   /* To cater for older frontends, emit ^running, but do it only once
927      per each command.  We do it here, since at this point we know
928      that the target was successfully resumed, and in non-async mode,
929      we won't return back to MI interpreter code until the target
930      is done running, so delaying the output of "^running" until then
931      will make it impossible for frontend to know what's going on.
932
933      In future (MI3), we'll be outputting "^done" here.  */
934   if (!running_result_record_printed && mi_proceeded)
935     {
936       fprintf_unfiltered (raw_stdout, "%s^running\n",
937                           current_token ? current_token : "");
938     }
939
940   if (ptid_get_pid (ptid) == -1)
941     fprintf_unfiltered (raw_stdout, "*running,thread-id=\"all\"\n");
942   else if (ptid_is_pid (ptid))
943     {
944       int count = 0;
945
946       /* Backwards compatibility.  If there's only one inferior,
947          output "all", otherwise, output each resumed thread
948          individually.  */
949       iterate_over_inferiors (mi_inferior_count, &count);
950
951       if (count == 1)
952         fprintf_unfiltered (raw_stdout, "*running,thread-id=\"all\"\n");
953       else
954         iterate_over_threads (mi_output_running_pid, &ptid);
955     }
956   else
957     {
958       struct thread_info *ti = find_thread_ptid (ptid);
959
960       gdb_assert (ti);
961       fprintf_unfiltered (raw_stdout, "*running,thread-id=\"%d\"\n", ti->num);
962     }
963
964   if (!running_result_record_printed && mi_proceeded)
965     {
966       running_result_record_printed = 1;
967       /* This is what gdb used to do historically -- printing prompt even if
968          it cannot actually accept any input.  This will be surely removed
969          for MI3, and may be removed even earlier.  SYNC_EXECUTION is
970          checked here because we only need to emit a prompt if a
971          synchronous command was issued when the target is async.  */
972       if (!target_is_async_p () || sync_execution)
973         fputs_unfiltered ("(gdb) \n", raw_stdout);
974     }
975   gdb_flush (raw_stdout);
976 }
977
978 static void
979 mi_solib_loaded (struct so_list *solib)
980 {
981   struct mi_interp *mi = top_level_interpreter_data ();
982   struct ui_out *uiout = interp_ui_out (top_level_interpreter ());
983
984   target_terminal_ours ();
985
986   fprintf_unfiltered (mi->event_channel, "library-loaded");
987
988   ui_out_redirect (uiout, mi->event_channel);
989
990   ui_out_field_string (uiout, "id", solib->so_original_name);
991   ui_out_field_string (uiout, "target-name", solib->so_original_name);
992   ui_out_field_string (uiout, "host-name", solib->so_name);
993   ui_out_field_int (uiout, "symbols-loaded", solib->symbols_loaded);
994   if (!gdbarch_has_global_solist (target_gdbarch ()))
995     {
996       ui_out_field_fmt (uiout, "thread-group", "i%d", current_inferior ()->num);
997     }
998
999   ui_out_redirect (uiout, NULL);
1000
1001   gdb_flush (mi->event_channel);
1002 }
1003
1004 static void
1005 mi_solib_unloaded (struct so_list *solib)
1006 {
1007   struct mi_interp *mi = top_level_interpreter_data ();
1008   struct ui_out *uiout = interp_ui_out (top_level_interpreter ());
1009
1010   target_terminal_ours ();
1011
1012   fprintf_unfiltered (mi->event_channel, "library-unloaded");
1013
1014   ui_out_redirect (uiout, mi->event_channel);
1015
1016   ui_out_field_string (uiout, "id", solib->so_original_name);
1017   ui_out_field_string (uiout, "target-name", solib->so_original_name);
1018   ui_out_field_string (uiout, "host-name", solib->so_name);
1019   if (!gdbarch_has_global_solist (target_gdbarch ()))
1020     {
1021       ui_out_field_fmt (uiout, "thread-group", "i%d", current_inferior ()->num);
1022     }
1023
1024   ui_out_redirect (uiout, NULL);
1025
1026   gdb_flush (mi->event_channel);
1027 }
1028
1029 /* Emit notification about the command parameter change.  */
1030
1031 static void
1032 mi_command_param_changed (const char *param, const char *value)
1033 {
1034   struct mi_interp *mi = top_level_interpreter_data ();
1035   struct ui_out *mi_uiout = interp_ui_out (top_level_interpreter ());
1036
1037   if (mi_suppress_notification.cmd_param_changed)
1038     return;
1039
1040   target_terminal_ours ();
1041
1042   fprintf_unfiltered (mi->event_channel,
1043                       "cmd-param-changed");
1044
1045   ui_out_redirect (mi_uiout, mi->event_channel);
1046
1047   ui_out_field_string (mi_uiout, "param", param);
1048   ui_out_field_string (mi_uiout, "value", value);
1049
1050   ui_out_redirect (mi_uiout, NULL);
1051
1052   gdb_flush (mi->event_channel);
1053 }
1054
1055 /* Emit notification about the target memory change.  */
1056
1057 static void
1058 mi_memory_changed (struct inferior *inferior, CORE_ADDR memaddr,
1059                    ssize_t len, const bfd_byte *myaddr)
1060 {
1061   struct mi_interp *mi = top_level_interpreter_data ();
1062   struct ui_out *mi_uiout = interp_ui_out (top_level_interpreter ());
1063   struct obj_section *sec;
1064
1065   if (mi_suppress_notification.memory)
1066     return;
1067
1068   target_terminal_ours ();
1069
1070   fprintf_unfiltered (mi->event_channel,
1071                       "memory-changed");
1072
1073   ui_out_redirect (mi_uiout, mi->event_channel);
1074
1075   ui_out_field_fmt (mi_uiout, "thread-group", "i%d", inferior->num);
1076   ui_out_field_core_addr (mi_uiout, "addr", target_gdbarch (), memaddr);
1077   ui_out_field_fmt (mi_uiout, "len", "%s", hex_string (len));
1078
1079   /* Append 'type=code' into notification if MEMADDR falls in the range of
1080      sections contain code.  */
1081   sec = find_pc_section (memaddr);
1082   if (sec != NULL && sec->objfile != NULL)
1083     {
1084       flagword flags = bfd_get_section_flags (sec->objfile->obfd,
1085                                               sec->the_bfd_section);
1086
1087       if (flags & SEC_CODE)
1088         ui_out_field_string (mi_uiout, "type", "code");
1089     }
1090
1091   ui_out_redirect (mi_uiout, NULL);
1092
1093   gdb_flush (mi->event_channel);
1094 }
1095
1096 static int
1097 report_initial_inferior (struct inferior *inf, void *closure)
1098 {
1099   /* This function is called from mi_intepreter_init, and since
1100      mi_inferior_added assumes that inferior is fully initialized
1101      and top_level_interpreter_data is set, we cannot call
1102      it here.  */
1103   struct mi_interp *mi = closure;
1104
1105   target_terminal_ours ();
1106   fprintf_unfiltered (mi->event_channel,
1107                       "thread-group-added,id=\"i%d\"",
1108                       inf->num);
1109   gdb_flush (mi->event_channel);
1110   return 0;
1111 }
1112
1113 static struct ui_out *
1114 mi_ui_out (struct interp *interp)
1115 {
1116   struct mi_interp *mi = interp_data (interp);
1117
1118   return mi->mi_uiout;
1119 }
1120
1121 /* Save the original value of raw_stdout here when logging, so we can
1122    restore correctly when done.  */
1123
1124 static struct ui_file *saved_raw_stdout;
1125
1126 /* Do MI-specific logging actions; save raw_stdout, and change all
1127    the consoles to use the supplied ui-file(s).  */
1128
1129 static int
1130 mi_set_logging (struct interp *interp, int start_log,
1131                 struct ui_file *out, struct ui_file *logfile)
1132 {
1133   struct mi_interp *mi = interp_data (interp);
1134
1135   if (!mi)
1136     return 0;
1137
1138   if (start_log)
1139     {
1140       /* The tee created already is based on gdb_stdout, which for MI
1141          is a console and so we end up in an infinite loop of console
1142          writing to ui_file writing to console etc.  So discard the
1143          existing tee (it hasn't been used yet, and MI won't ever use
1144          it), and create one based on raw_stdout instead.  */
1145       if (logfile)
1146         {
1147           ui_file_delete (out);
1148           out = tee_file_new (raw_stdout, 0, logfile, 0);
1149         }
1150
1151       saved_raw_stdout = raw_stdout;
1152       raw_stdout = out;
1153     }
1154   else
1155     {
1156       raw_stdout = saved_raw_stdout;
1157       saved_raw_stdout = NULL;
1158     }
1159   
1160   mi_console_set_raw (mi->out, raw_stdout);
1161   mi_console_set_raw (mi->err, raw_stdout);
1162   mi_console_set_raw (mi->log, raw_stdout);
1163   mi_console_set_raw (mi->targ, raw_stdout);
1164   mi_console_set_raw (mi->event_channel, raw_stdout);
1165
1166   return 1;
1167 }
1168
1169 extern initialize_file_ftype _initialize_mi_interp; /* -Wmissing-prototypes */
1170
1171 void
1172 _initialize_mi_interp (void)
1173 {
1174   static const struct interp_procs procs =
1175     {
1176       mi_interpreter_init,      /* init_proc */
1177       mi_interpreter_resume,    /* resume_proc */
1178       mi_interpreter_suspend,   /* suspend_proc */
1179       mi_interpreter_exec,      /* exec_proc */
1180       mi_ui_out,                /* ui_out_proc */
1181       mi_set_logging,           /* set_logging_proc */
1182       mi_command_loop           /* command_loop_proc */
1183     };
1184
1185   /* The various interpreter levels.  */
1186   interp_add (interp_new (INTERP_MI1, &procs));
1187   interp_add (interp_new (INTERP_MI2, &procs));
1188   interp_add (interp_new (INTERP_MI3, &procs));
1189   interp_add (interp_new (INTERP_MI, &procs));
1190 }