Fix regresssion(internal-error) printing subprogram argument (PR gdb/22670)
[external/binutils.git] / gdb / infrun.c
1 /* Target-struct-independent code to start (run) and stop an inferior
2    process.
3
4    Copyright (C) 1986-2018 Free Software Foundation, Inc.
5
6    This file is part of GDB.
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "defs.h"
22 #include "infrun.h"
23 #include <ctype.h>
24 #include "symtab.h"
25 #include "frame.h"
26 #include "inferior.h"
27 #include "breakpoint.h"
28 #include "gdb_wait.h"
29 #include "gdbcore.h"
30 #include "gdbcmd.h"
31 #include "cli/cli-script.h"
32 #include "target.h"
33 #include "gdbthread.h"
34 #include "annotate.h"
35 #include "symfile.h"
36 #include "top.h"
37 #include <signal.h>
38 #include "inf-loop.h"
39 #include "regcache.h"
40 #include "value.h"
41 #include "observer.h"
42 #include "language.h"
43 #include "solib.h"
44 #include "main.h"
45 #include "dictionary.h"
46 #include "block.h"
47 #include "mi/mi-common.h"
48 #include "event-top.h"
49 #include "record.h"
50 #include "record-full.h"
51 #include "inline-frame.h"
52 #include "jit.h"
53 #include "tracepoint.h"
54 #include "continuations.h"
55 #include "interps.h"
56 #include "skip.h"
57 #include "probe.h"
58 #include "objfiles.h"
59 #include "completer.h"
60 #include "target-descriptions.h"
61 #include "target-dcache.h"
62 #include "terminal.h"
63 #include "solist.h"
64 #include "event-loop.h"
65 #include "thread-fsm.h"
66 #include "common/enum-flags.h"
67 #include "progspace-and-thread.h"
68 #include "common/gdb_optional.h"
69 #include "arch-utils.h"
70
71 /* Prototypes for local functions */
72
73 static void sig_print_info (enum gdb_signal);
74
75 static void sig_print_header (void);
76
77 static int follow_fork (void);
78
79 static int follow_fork_inferior (int follow_child, int detach_fork);
80
81 static void follow_inferior_reset_breakpoints (void);
82
83 static int currently_stepping (struct thread_info *tp);
84
85 void nullify_last_target_wait_ptid (void);
86
87 static void insert_hp_step_resume_breakpoint_at_frame (struct frame_info *);
88
89 static void insert_step_resume_breakpoint_at_caller (struct frame_info *);
90
91 static void insert_longjmp_resume_breakpoint (struct gdbarch *, CORE_ADDR);
92
93 static int maybe_software_singlestep (struct gdbarch *gdbarch, CORE_ADDR pc);
94
95 /* Asynchronous signal handler registered as event loop source for
96    when we have pending events ready to be passed to the core.  */
97 static struct async_event_handler *infrun_async_inferior_event_token;
98
99 /* Stores whether infrun_async was previously enabled or disabled.
100    Starts off as -1, indicating "never enabled/disabled".  */
101 static int infrun_is_async = -1;
102
103 /* See infrun.h.  */
104
105 void
106 infrun_async (int enable)
107 {
108   if (infrun_is_async != enable)
109     {
110       infrun_is_async = enable;
111
112       if (debug_infrun)
113         fprintf_unfiltered (gdb_stdlog,
114                             "infrun: infrun_async(%d)\n",
115                             enable);
116
117       if (enable)
118         mark_async_event_handler (infrun_async_inferior_event_token);
119       else
120         clear_async_event_handler (infrun_async_inferior_event_token);
121     }
122 }
123
124 /* See infrun.h.  */
125
126 void
127 mark_infrun_async_event_handler (void)
128 {
129   mark_async_event_handler (infrun_async_inferior_event_token);
130 }
131
132 /* When set, stop the 'step' command if we enter a function which has
133    no line number information.  The normal behavior is that we step
134    over such function.  */
135 int step_stop_if_no_debug = 0;
136 static void
137 show_step_stop_if_no_debug (struct ui_file *file, int from_tty,
138                             struct cmd_list_element *c, const char *value)
139 {
140   fprintf_filtered (file, _("Mode of the step operation is %s.\n"), value);
141 }
142
143 /* proceed and normal_stop use this to notify the user when the
144    inferior stopped in a different thread than it had been running
145    in.  */
146
147 static ptid_t previous_inferior_ptid;
148
149 /* If set (default for legacy reasons), when following a fork, GDB
150    will detach from one of the fork branches, child or parent.
151    Exactly which branch is detached depends on 'set follow-fork-mode'
152    setting.  */
153
154 static int detach_fork = 1;
155
156 int debug_displaced = 0;
157 static void
158 show_debug_displaced (struct ui_file *file, int from_tty,
159                       struct cmd_list_element *c, const char *value)
160 {
161   fprintf_filtered (file, _("Displace stepping debugging is %s.\n"), value);
162 }
163
164 unsigned int debug_infrun = 0;
165 static void
166 show_debug_infrun (struct ui_file *file, int from_tty,
167                    struct cmd_list_element *c, const char *value)
168 {
169   fprintf_filtered (file, _("Inferior debugging is %s.\n"), value);
170 }
171
172
173 /* Support for disabling address space randomization.  */
174
175 int disable_randomization = 1;
176
177 static void
178 show_disable_randomization (struct ui_file *file, int from_tty,
179                             struct cmd_list_element *c, const char *value)
180 {
181   if (target_supports_disable_randomization ())
182     fprintf_filtered (file,
183                       _("Disabling randomization of debuggee's "
184                         "virtual address space is %s.\n"),
185                       value);
186   else
187     fputs_filtered (_("Disabling randomization of debuggee's "
188                       "virtual address space is unsupported on\n"
189                       "this platform.\n"), file);
190 }
191
192 static void
193 set_disable_randomization (const char *args, int from_tty,
194                            struct cmd_list_element *c)
195 {
196   if (!target_supports_disable_randomization ())
197     error (_("Disabling randomization of debuggee's "
198              "virtual address space is unsupported on\n"
199              "this platform."));
200 }
201
202 /* User interface for non-stop mode.  */
203
204 int non_stop = 0;
205 static int non_stop_1 = 0;
206
207 static void
208 set_non_stop (const char *args, int from_tty,
209               struct cmd_list_element *c)
210 {
211   if (target_has_execution)
212     {
213       non_stop_1 = non_stop;
214       error (_("Cannot change this setting while the inferior is running."));
215     }
216
217   non_stop = non_stop_1;
218 }
219
220 static void
221 show_non_stop (struct ui_file *file, int from_tty,
222                struct cmd_list_element *c, const char *value)
223 {
224   fprintf_filtered (file,
225                     _("Controlling the inferior in non-stop mode is %s.\n"),
226                     value);
227 }
228
229 /* "Observer mode" is somewhat like a more extreme version of
230    non-stop, in which all GDB operations that might affect the
231    target's execution have been disabled.  */
232
233 int observer_mode = 0;
234 static int observer_mode_1 = 0;
235
236 static void
237 set_observer_mode (const char *args, int from_tty,
238                    struct cmd_list_element *c)
239 {
240   if (target_has_execution)
241     {
242       observer_mode_1 = observer_mode;
243       error (_("Cannot change this setting while the inferior is running."));
244     }
245
246   observer_mode = observer_mode_1;
247
248   may_write_registers = !observer_mode;
249   may_write_memory = !observer_mode;
250   may_insert_breakpoints = !observer_mode;
251   may_insert_tracepoints = !observer_mode;
252   /* We can insert fast tracepoints in or out of observer mode,
253      but enable them if we're going into this mode.  */
254   if (observer_mode)
255     may_insert_fast_tracepoints = 1;
256   may_stop = !observer_mode;
257   update_target_permissions ();
258
259   /* Going *into* observer mode we must force non-stop, then
260      going out we leave it that way.  */
261   if (observer_mode)
262     {
263       pagination_enabled = 0;
264       non_stop = non_stop_1 = 1;
265     }
266
267   if (from_tty)
268     printf_filtered (_("Observer mode is now %s.\n"),
269                      (observer_mode ? "on" : "off"));
270 }
271
272 static void
273 show_observer_mode (struct ui_file *file, int from_tty,
274                     struct cmd_list_element *c, const char *value)
275 {
276   fprintf_filtered (file, _("Observer mode is %s.\n"), value);
277 }
278
279 /* This updates the value of observer mode based on changes in
280    permissions.  Note that we are deliberately ignoring the values of
281    may-write-registers and may-write-memory, since the user may have
282    reason to enable these during a session, for instance to turn on a
283    debugging-related global.  */
284
285 void
286 update_observer_mode (void)
287 {
288   int newval;
289
290   newval = (!may_insert_breakpoints
291             && !may_insert_tracepoints
292             && may_insert_fast_tracepoints
293             && !may_stop
294             && non_stop);
295
296   /* Let the user know if things change.  */
297   if (newval != observer_mode)
298     printf_filtered (_("Observer mode is now %s.\n"),
299                      (newval ? "on" : "off"));
300
301   observer_mode = observer_mode_1 = newval;
302 }
303
304 /* Tables of how to react to signals; the user sets them.  */
305
306 static unsigned char *signal_stop;
307 static unsigned char *signal_print;
308 static unsigned char *signal_program;
309
310 /* Table of signals that are registered with "catch signal".  A
311    non-zero entry indicates that the signal is caught by some "catch
312    signal" command.  This has size GDB_SIGNAL_LAST, to accommodate all
313    signals.  */
314 static unsigned char *signal_catch;
315
316 /* Table of signals that the target may silently handle.
317    This is automatically determined from the flags above,
318    and simply cached here.  */
319 static unsigned char *signal_pass;
320
321 #define SET_SIGS(nsigs,sigs,flags) \
322   do { \
323     int signum = (nsigs); \
324     while (signum-- > 0) \
325       if ((sigs)[signum]) \
326         (flags)[signum] = 1; \
327   } while (0)
328
329 #define UNSET_SIGS(nsigs,sigs,flags) \
330   do { \
331     int signum = (nsigs); \
332     while (signum-- > 0) \
333       if ((sigs)[signum]) \
334         (flags)[signum] = 0; \
335   } while (0)
336
337 /* Update the target's copy of SIGNAL_PROGRAM.  The sole purpose of
338    this function is to avoid exporting `signal_program'.  */
339
340 void
341 update_signals_program_target (void)
342 {
343   target_program_signals ((int) GDB_SIGNAL_LAST, signal_program);
344 }
345
346 /* Value to pass to target_resume() to cause all threads to resume.  */
347
348 #define RESUME_ALL minus_one_ptid
349
350 /* Command list pointer for the "stop" placeholder.  */
351
352 static struct cmd_list_element *stop_command;
353
354 /* Nonzero if we want to give control to the user when we're notified
355    of shared library events by the dynamic linker.  */
356 int stop_on_solib_events;
357
358 /* Enable or disable optional shared library event breakpoints
359    as appropriate when the above flag is changed.  */
360
361 static void
362 set_stop_on_solib_events (const char *args,
363                           int from_tty, struct cmd_list_element *c)
364 {
365   update_solib_breakpoints ();
366 }
367
368 static void
369 show_stop_on_solib_events (struct ui_file *file, int from_tty,
370                            struct cmd_list_element *c, const char *value)
371 {
372   fprintf_filtered (file, _("Stopping for shared library events is %s.\n"),
373                     value);
374 }
375
376 /* Nonzero after stop if current stack frame should be printed.  */
377
378 static int stop_print_frame;
379
380 /* This is a cached copy of the pid/waitstatus of the last event
381    returned by target_wait()/deprecated_target_wait_hook().  This
382    information is returned by get_last_target_status().  */
383 static ptid_t target_last_wait_ptid;
384 static struct target_waitstatus target_last_waitstatus;
385
386 static void context_switch (ptid_t ptid);
387
388 void init_thread_stepping_state (struct thread_info *tss);
389
390 static const char follow_fork_mode_child[] = "child";
391 static const char follow_fork_mode_parent[] = "parent";
392
393 static const char *const follow_fork_mode_kind_names[] = {
394   follow_fork_mode_child,
395   follow_fork_mode_parent,
396   NULL
397 };
398
399 static const char *follow_fork_mode_string = follow_fork_mode_parent;
400 static void
401 show_follow_fork_mode_string (struct ui_file *file, int from_tty,
402                               struct cmd_list_element *c, const char *value)
403 {
404   fprintf_filtered (file,
405                     _("Debugger response to a program "
406                       "call of fork or vfork is \"%s\".\n"),
407                     value);
408 }
409 \f
410
411 /* Handle changes to the inferior list based on the type of fork,
412    which process is being followed, and whether the other process
413    should be detached.  On entry inferior_ptid must be the ptid of
414    the fork parent.  At return inferior_ptid is the ptid of the
415    followed inferior.  */
416
417 static int
418 follow_fork_inferior (int follow_child, int detach_fork)
419 {
420   int has_vforked;
421   ptid_t parent_ptid, child_ptid;
422
423   has_vforked = (inferior_thread ()->pending_follow.kind
424                  == TARGET_WAITKIND_VFORKED);
425   parent_ptid = inferior_ptid;
426   child_ptid = inferior_thread ()->pending_follow.value.related_pid;
427
428   if (has_vforked
429       && !non_stop /* Non-stop always resumes both branches.  */
430       && current_ui->prompt_state == PROMPT_BLOCKED
431       && !(follow_child || detach_fork || sched_multi))
432     {
433       /* The parent stays blocked inside the vfork syscall until the
434          child execs or exits.  If we don't let the child run, then
435          the parent stays blocked.  If we're telling the parent to run
436          in the foreground, the user will not be able to ctrl-c to get
437          back the terminal, effectively hanging the debug session.  */
438       fprintf_filtered (gdb_stderr, _("\
439 Can not resume the parent process over vfork in the foreground while\n\
440 holding the child stopped.  Try \"set detach-on-fork\" or \
441 \"set schedule-multiple\".\n"));
442       /* FIXME output string > 80 columns.  */
443       return 1;
444     }
445
446   if (!follow_child)
447     {
448       /* Detach new forked process?  */
449       if (detach_fork)
450         {
451           /* Before detaching from the child, remove all breakpoints
452              from it.  If we forked, then this has already been taken
453              care of by infrun.c.  If we vforked however, any
454              breakpoint inserted in the parent is visible in the
455              child, even those added while stopped in a vfork
456              catchpoint.  This will remove the breakpoints from the
457              parent also, but they'll be reinserted below.  */
458           if (has_vforked)
459             {
460               /* Keep breakpoints list in sync.  */
461               remove_breakpoints_pid (ptid_get_pid (inferior_ptid));
462             }
463
464           if (info_verbose || debug_infrun)
465             {
466               /* Ensure that we have a process ptid.  */
467               ptid_t process_ptid = pid_to_ptid (ptid_get_pid (child_ptid));
468
469               target_terminal::ours_for_output ();
470               fprintf_filtered (gdb_stdlog,
471                                 _("Detaching after %s from child %s.\n"),
472                                 has_vforked ? "vfork" : "fork",
473                                 target_pid_to_str (process_ptid));
474             }
475         }
476       else
477         {
478           struct inferior *parent_inf, *child_inf;
479
480           /* Add process to GDB's tables.  */
481           child_inf = add_inferior (ptid_get_pid (child_ptid));
482
483           parent_inf = current_inferior ();
484           child_inf->attach_flag = parent_inf->attach_flag;
485           copy_terminal_info (child_inf, parent_inf);
486           child_inf->gdbarch = parent_inf->gdbarch;
487           copy_inferior_target_desc_info (child_inf, parent_inf);
488
489           scoped_restore_current_pspace_and_thread restore_pspace_thread;
490
491           inferior_ptid = child_ptid;
492           add_thread (inferior_ptid);
493           set_current_inferior (child_inf);
494           child_inf->symfile_flags = SYMFILE_NO_READ;
495
496           /* If this is a vfork child, then the address-space is
497              shared with the parent.  */
498           if (has_vforked)
499             {
500               child_inf->pspace = parent_inf->pspace;
501               child_inf->aspace = parent_inf->aspace;
502
503               /* The parent will be frozen until the child is done
504                  with the shared region.  Keep track of the
505                  parent.  */
506               child_inf->vfork_parent = parent_inf;
507               child_inf->pending_detach = 0;
508               parent_inf->vfork_child = child_inf;
509               parent_inf->pending_detach = 0;
510             }
511           else
512             {
513               child_inf->aspace = new_address_space ();
514               child_inf->pspace = add_program_space (child_inf->aspace);
515               child_inf->removable = 1;
516               set_current_program_space (child_inf->pspace);
517               clone_program_space (child_inf->pspace, parent_inf->pspace);
518
519               /* Let the shared library layer (e.g., solib-svr4) learn
520                  about this new process, relocate the cloned exec, pull
521                  in shared libraries, and install the solib event
522                  breakpoint.  If a "cloned-VM" event was propagated
523                  better throughout the core, this wouldn't be
524                  required.  */
525               solib_create_inferior_hook (0);
526             }
527         }
528
529       if (has_vforked)
530         {
531           struct inferior *parent_inf;
532
533           parent_inf = current_inferior ();
534
535           /* If we detached from the child, then we have to be careful
536              to not insert breakpoints in the parent until the child
537              is done with the shared memory region.  However, if we're
538              staying attached to the child, then we can and should
539              insert breakpoints, so that we can debug it.  A
540              subsequent child exec or exit is enough to know when does
541              the child stops using the parent's address space.  */
542           parent_inf->waiting_for_vfork_done = detach_fork;
543           parent_inf->pspace->breakpoints_not_allowed = detach_fork;
544         }
545     }
546   else
547     {
548       /* Follow the child.  */
549       struct inferior *parent_inf, *child_inf;
550       struct program_space *parent_pspace;
551
552       if (info_verbose || debug_infrun)
553         {
554           target_terminal::ours_for_output ();
555           fprintf_filtered (gdb_stdlog,
556                             _("Attaching after %s %s to child %s.\n"),
557                             target_pid_to_str (parent_ptid),
558                             has_vforked ? "vfork" : "fork",
559                             target_pid_to_str (child_ptid));
560         }
561
562       /* Add the new inferior first, so that the target_detach below
563          doesn't unpush the target.  */
564
565       child_inf = add_inferior (ptid_get_pid (child_ptid));
566
567       parent_inf = current_inferior ();
568       child_inf->attach_flag = parent_inf->attach_flag;
569       copy_terminal_info (child_inf, parent_inf);
570       child_inf->gdbarch = parent_inf->gdbarch;
571       copy_inferior_target_desc_info (child_inf, parent_inf);
572
573       parent_pspace = parent_inf->pspace;
574
575       /* If we're vforking, we want to hold on to the parent until the
576          child exits or execs.  At child exec or exit time we can
577          remove the old breakpoints from the parent and detach or
578          resume debugging it.  Otherwise, detach the parent now; we'll
579          want to reuse it's program/address spaces, but we can't set
580          them to the child before removing breakpoints from the
581          parent, otherwise, the breakpoints module could decide to
582          remove breakpoints from the wrong process (since they'd be
583          assigned to the same address space).  */
584
585       if (has_vforked)
586         {
587           gdb_assert (child_inf->vfork_parent == NULL);
588           gdb_assert (parent_inf->vfork_child == NULL);
589           child_inf->vfork_parent = parent_inf;
590           child_inf->pending_detach = 0;
591           parent_inf->vfork_child = child_inf;
592           parent_inf->pending_detach = detach_fork;
593           parent_inf->waiting_for_vfork_done = 0;
594         }
595       else if (detach_fork)
596         {
597           if (info_verbose || debug_infrun)
598             {
599               /* Ensure that we have a process ptid.  */
600               ptid_t process_ptid = pid_to_ptid (ptid_get_pid (child_ptid));
601
602               target_terminal::ours_for_output ();
603               fprintf_filtered (gdb_stdlog,
604                                 _("Detaching after fork from "
605                                   "child %s.\n"),
606                                 target_pid_to_str (process_ptid));
607             }
608
609           target_detach (NULL, 0);
610         }
611
612       /* Note that the detach above makes PARENT_INF dangling.  */
613
614       /* Add the child thread to the appropriate lists, and switch to
615          this new thread, before cloning the program space, and
616          informing the solib layer about this new process.  */
617
618       inferior_ptid = child_ptid;
619       add_thread (inferior_ptid);
620       set_current_inferior (child_inf);
621
622       /* If this is a vfork child, then the address-space is shared
623          with the parent.  If we detached from the parent, then we can
624          reuse the parent's program/address spaces.  */
625       if (has_vforked || detach_fork)
626         {
627           child_inf->pspace = parent_pspace;
628           child_inf->aspace = child_inf->pspace->aspace;
629         }
630       else
631         {
632           child_inf->aspace = new_address_space ();
633           child_inf->pspace = add_program_space (child_inf->aspace);
634           child_inf->removable = 1;
635           child_inf->symfile_flags = SYMFILE_NO_READ;
636           set_current_program_space (child_inf->pspace);
637           clone_program_space (child_inf->pspace, parent_pspace);
638
639           /* Let the shared library layer (e.g., solib-svr4) learn
640              about this new process, relocate the cloned exec, pull in
641              shared libraries, and install the solib event breakpoint.
642              If a "cloned-VM" event was propagated better throughout
643              the core, this wouldn't be required.  */
644           solib_create_inferior_hook (0);
645         }
646     }
647
648   return target_follow_fork (follow_child, detach_fork);
649 }
650
651 /* Tell the target to follow the fork we're stopped at.  Returns true
652    if the inferior should be resumed; false, if the target for some
653    reason decided it's best not to resume.  */
654
655 static int
656 follow_fork (void)
657 {
658   int follow_child = (follow_fork_mode_string == follow_fork_mode_child);
659   int should_resume = 1;
660   struct thread_info *tp;
661
662   /* Copy user stepping state to the new inferior thread.  FIXME: the
663      followed fork child thread should have a copy of most of the
664      parent thread structure's run control related fields, not just these.
665      Initialized to avoid "may be used uninitialized" warnings from gcc.  */
666   struct breakpoint *step_resume_breakpoint = NULL;
667   struct breakpoint *exception_resume_breakpoint = NULL;
668   CORE_ADDR step_range_start = 0;
669   CORE_ADDR step_range_end = 0;
670   struct frame_id step_frame_id = { 0 };
671   struct thread_fsm *thread_fsm = NULL;
672
673   if (!non_stop)
674     {
675       ptid_t wait_ptid;
676       struct target_waitstatus wait_status;
677
678       /* Get the last target status returned by target_wait().  */
679       get_last_target_status (&wait_ptid, &wait_status);
680
681       /* If not stopped at a fork event, then there's nothing else to
682          do.  */
683       if (wait_status.kind != TARGET_WAITKIND_FORKED
684           && wait_status.kind != TARGET_WAITKIND_VFORKED)
685         return 1;
686
687       /* Check if we switched over from WAIT_PTID, since the event was
688          reported.  */
689       if (!ptid_equal (wait_ptid, minus_one_ptid)
690           && !ptid_equal (inferior_ptid, wait_ptid))
691         {
692           /* We did.  Switch back to WAIT_PTID thread, to tell the
693              target to follow it (in either direction).  We'll
694              afterwards refuse to resume, and inform the user what
695              happened.  */
696           switch_to_thread (wait_ptid);
697           should_resume = 0;
698         }
699     }
700
701   tp = inferior_thread ();
702
703   /* If there were any forks/vforks that were caught and are now to be
704      followed, then do so now.  */
705   switch (tp->pending_follow.kind)
706     {
707     case TARGET_WAITKIND_FORKED:
708     case TARGET_WAITKIND_VFORKED:
709       {
710         ptid_t parent, child;
711
712         /* If the user did a next/step, etc, over a fork call,
713            preserve the stepping state in the fork child.  */
714         if (follow_child && should_resume)
715           {
716             step_resume_breakpoint = clone_momentary_breakpoint
717                                          (tp->control.step_resume_breakpoint);
718             step_range_start = tp->control.step_range_start;
719             step_range_end = tp->control.step_range_end;
720             step_frame_id = tp->control.step_frame_id;
721             exception_resume_breakpoint
722               = clone_momentary_breakpoint (tp->control.exception_resume_breakpoint);
723             thread_fsm = tp->thread_fsm;
724
725             /* For now, delete the parent's sr breakpoint, otherwise,
726                parent/child sr breakpoints are considered duplicates,
727                and the child version will not be installed.  Remove
728                this when the breakpoints module becomes aware of
729                inferiors and address spaces.  */
730             delete_step_resume_breakpoint (tp);
731             tp->control.step_range_start = 0;
732             tp->control.step_range_end = 0;
733             tp->control.step_frame_id = null_frame_id;
734             delete_exception_resume_breakpoint (tp);
735             tp->thread_fsm = NULL;
736           }
737
738         parent = inferior_ptid;
739         child = tp->pending_follow.value.related_pid;
740
741         /* Set up inferior(s) as specified by the caller, and tell the
742            target to do whatever is necessary to follow either parent
743            or child.  */
744         if (follow_fork_inferior (follow_child, detach_fork))
745           {
746             /* Target refused to follow, or there's some other reason
747                we shouldn't resume.  */
748             should_resume = 0;
749           }
750         else
751           {
752             /* This pending follow fork event is now handled, one way
753                or another.  The previous selected thread may be gone
754                from the lists by now, but if it is still around, need
755                to clear the pending follow request.  */
756             tp = find_thread_ptid (parent);
757             if (tp)
758               tp->pending_follow.kind = TARGET_WAITKIND_SPURIOUS;
759
760             /* This makes sure we don't try to apply the "Switched
761                over from WAIT_PID" logic above.  */
762             nullify_last_target_wait_ptid ();
763
764             /* If we followed the child, switch to it...  */
765             if (follow_child)
766               {
767                 switch_to_thread (child);
768
769                 /* ... and preserve the stepping state, in case the
770                    user was stepping over the fork call.  */
771                 if (should_resume)
772                   {
773                     tp = inferior_thread ();
774                     tp->control.step_resume_breakpoint
775                       = step_resume_breakpoint;
776                     tp->control.step_range_start = step_range_start;
777                     tp->control.step_range_end = step_range_end;
778                     tp->control.step_frame_id = step_frame_id;
779                     tp->control.exception_resume_breakpoint
780                       = exception_resume_breakpoint;
781                     tp->thread_fsm = thread_fsm;
782                   }
783                 else
784                   {
785                     /* If we get here, it was because we're trying to
786                        resume from a fork catchpoint, but, the user
787                        has switched threads away from the thread that
788                        forked.  In that case, the resume command
789                        issued is most likely not applicable to the
790                        child, so just warn, and refuse to resume.  */
791                     warning (_("Not resuming: switched threads "
792                                "before following fork child."));
793                   }
794
795                 /* Reset breakpoints in the child as appropriate.  */
796                 follow_inferior_reset_breakpoints ();
797               }
798             else
799               switch_to_thread (parent);
800           }
801       }
802       break;
803     case TARGET_WAITKIND_SPURIOUS:
804       /* Nothing to follow.  */
805       break;
806     default:
807       internal_error (__FILE__, __LINE__,
808                       "Unexpected pending_follow.kind %d\n",
809                       tp->pending_follow.kind);
810       break;
811     }
812
813   return should_resume;
814 }
815
816 static void
817 follow_inferior_reset_breakpoints (void)
818 {
819   struct thread_info *tp = inferior_thread ();
820
821   /* Was there a step_resume breakpoint?  (There was if the user
822      did a "next" at the fork() call.)  If so, explicitly reset its
823      thread number.  Cloned step_resume breakpoints are disabled on
824      creation, so enable it here now that it is associated with the
825      correct thread.
826
827      step_resumes are a form of bp that are made to be per-thread.
828      Since we created the step_resume bp when the parent process
829      was being debugged, and now are switching to the child process,
830      from the breakpoint package's viewpoint, that's a switch of
831      "threads".  We must update the bp's notion of which thread
832      it is for, or it'll be ignored when it triggers.  */
833
834   if (tp->control.step_resume_breakpoint)
835     {
836       breakpoint_re_set_thread (tp->control.step_resume_breakpoint);
837       tp->control.step_resume_breakpoint->loc->enabled = 1;
838     }
839
840   /* Treat exception_resume breakpoints like step_resume breakpoints.  */
841   if (tp->control.exception_resume_breakpoint)
842     {
843       breakpoint_re_set_thread (tp->control.exception_resume_breakpoint);
844       tp->control.exception_resume_breakpoint->loc->enabled = 1;
845     }
846
847   /* Reinsert all breakpoints in the child.  The user may have set
848      breakpoints after catching the fork, in which case those
849      were never set in the child, but only in the parent.  This makes
850      sure the inserted breakpoints match the breakpoint list.  */
851
852   breakpoint_re_set ();
853   insert_breakpoints ();
854 }
855
856 /* The child has exited or execed: resume threads of the parent the
857    user wanted to be executing.  */
858
859 static int
860 proceed_after_vfork_done (struct thread_info *thread,
861                           void *arg)
862 {
863   int pid = * (int *) arg;
864
865   if (ptid_get_pid (thread->ptid) == pid
866       && is_running (thread->ptid)
867       && !is_executing (thread->ptid)
868       && !thread->stop_requested
869       && thread->suspend.stop_signal == GDB_SIGNAL_0)
870     {
871       if (debug_infrun)
872         fprintf_unfiltered (gdb_stdlog,
873                             "infrun: resuming vfork parent thread %s\n",
874                             target_pid_to_str (thread->ptid));
875
876       switch_to_thread (thread->ptid);
877       clear_proceed_status (0);
878       proceed ((CORE_ADDR) -1, GDB_SIGNAL_DEFAULT);
879     }
880
881   return 0;
882 }
883
884 /* Save/restore inferior_ptid, current program space and current
885    inferior.  Only use this if the current context points at an exited
886    inferior (and therefore there's no current thread to save).  */
887 class scoped_restore_exited_inferior
888 {
889 public:
890   scoped_restore_exited_inferior ()
891     : m_saved_ptid (&inferior_ptid)
892   {}
893
894 private:
895   scoped_restore_tmpl<ptid_t> m_saved_ptid;
896   scoped_restore_current_program_space m_pspace;
897   scoped_restore_current_inferior m_inferior;
898 };
899
900 /* Called whenever we notice an exec or exit event, to handle
901    detaching or resuming a vfork parent.  */
902
903 static void
904 handle_vfork_child_exec_or_exit (int exec)
905 {
906   struct inferior *inf = current_inferior ();
907
908   if (inf->vfork_parent)
909     {
910       int resume_parent = -1;
911
912       /* This exec or exit marks the end of the shared memory region
913          between the parent and the child.  If the user wanted to
914          detach from the parent, now is the time.  */
915
916       if (inf->vfork_parent->pending_detach)
917         {
918           struct thread_info *tp;
919           struct program_space *pspace;
920           struct address_space *aspace;
921
922           /* follow-fork child, detach-on-fork on.  */
923
924           inf->vfork_parent->pending_detach = 0;
925
926           gdb::optional<scoped_restore_exited_inferior>
927             maybe_restore_inferior;
928           gdb::optional<scoped_restore_current_pspace_and_thread>
929             maybe_restore_thread;
930
931           /* If we're handling a child exit, then inferior_ptid points
932              at the inferior's pid, not to a thread.  */
933           if (!exec)
934             maybe_restore_inferior.emplace ();
935           else
936             maybe_restore_thread.emplace ();
937
938           /* We're letting loose of the parent.  */
939           tp = any_live_thread_of_process (inf->vfork_parent->pid);
940           switch_to_thread (tp->ptid);
941
942           /* We're about to detach from the parent, which implicitly
943              removes breakpoints from its address space.  There's a
944              catch here: we want to reuse the spaces for the child,
945              but, parent/child are still sharing the pspace at this
946              point, although the exec in reality makes the kernel give
947              the child a fresh set of new pages.  The problem here is
948              that the breakpoints module being unaware of this, would
949              likely chose the child process to write to the parent
950              address space.  Swapping the child temporarily away from
951              the spaces has the desired effect.  Yes, this is "sort
952              of" a hack.  */
953
954           pspace = inf->pspace;
955           aspace = inf->aspace;
956           inf->aspace = NULL;
957           inf->pspace = NULL;
958
959           if (debug_infrun || info_verbose)
960             {
961               target_terminal::ours_for_output ();
962
963               if (exec)
964                 {
965                   fprintf_filtered (gdb_stdlog,
966                                     _("Detaching vfork parent process "
967                                       "%d after child exec.\n"),
968                                     inf->vfork_parent->pid);
969                 }
970               else
971                 {
972                   fprintf_filtered (gdb_stdlog,
973                                     _("Detaching vfork parent process "
974                                       "%d after child exit.\n"),
975                                     inf->vfork_parent->pid);
976                 }
977             }
978
979           target_detach (NULL, 0);
980
981           /* Put it back.  */
982           inf->pspace = pspace;
983           inf->aspace = aspace;
984         }
985       else if (exec)
986         {
987           /* We're staying attached to the parent, so, really give the
988              child a new address space.  */
989           inf->pspace = add_program_space (maybe_new_address_space ());
990           inf->aspace = inf->pspace->aspace;
991           inf->removable = 1;
992           set_current_program_space (inf->pspace);
993
994           resume_parent = inf->vfork_parent->pid;
995
996           /* Break the bonds.  */
997           inf->vfork_parent->vfork_child = NULL;
998         }
999       else
1000         {
1001           struct program_space *pspace;
1002
1003           /* If this is a vfork child exiting, then the pspace and
1004              aspaces were shared with the parent.  Since we're
1005              reporting the process exit, we'll be mourning all that is
1006              found in the address space, and switching to null_ptid,
1007              preparing to start a new inferior.  But, since we don't
1008              want to clobber the parent's address/program spaces, we
1009              go ahead and create a new one for this exiting
1010              inferior.  */
1011
1012           /* Switch to null_ptid while running clone_program_space, so
1013              that clone_program_space doesn't want to read the
1014              selected frame of a dead process.  */
1015           scoped_restore restore_ptid
1016             = make_scoped_restore (&inferior_ptid, null_ptid);
1017
1018           /* This inferior is dead, so avoid giving the breakpoints
1019              module the option to write through to it (cloning a
1020              program space resets breakpoints).  */
1021           inf->aspace = NULL;
1022           inf->pspace = NULL;
1023           pspace = add_program_space (maybe_new_address_space ());
1024           set_current_program_space (pspace);
1025           inf->removable = 1;
1026           inf->symfile_flags = SYMFILE_NO_READ;
1027           clone_program_space (pspace, inf->vfork_parent->pspace);
1028           inf->pspace = pspace;
1029           inf->aspace = pspace->aspace;
1030
1031           resume_parent = inf->vfork_parent->pid;
1032           /* Break the bonds.  */
1033           inf->vfork_parent->vfork_child = NULL;
1034         }
1035
1036       inf->vfork_parent = NULL;
1037
1038       gdb_assert (current_program_space == inf->pspace);
1039
1040       if (non_stop && resume_parent != -1)
1041         {
1042           /* If the user wanted the parent to be running, let it go
1043              free now.  */
1044           scoped_restore_current_thread restore_thread;
1045
1046           if (debug_infrun)
1047             fprintf_unfiltered (gdb_stdlog,
1048                                 "infrun: resuming vfork parent process %d\n",
1049                                 resume_parent);
1050
1051           iterate_over_threads (proceed_after_vfork_done, &resume_parent);
1052         }
1053     }
1054 }
1055
1056 /* Enum strings for "set|show follow-exec-mode".  */
1057
1058 static const char follow_exec_mode_new[] = "new";
1059 static const char follow_exec_mode_same[] = "same";
1060 static const char *const follow_exec_mode_names[] =
1061 {
1062   follow_exec_mode_new,
1063   follow_exec_mode_same,
1064   NULL,
1065 };
1066
1067 static const char *follow_exec_mode_string = follow_exec_mode_same;
1068 static void
1069 show_follow_exec_mode_string (struct ui_file *file, int from_tty,
1070                               struct cmd_list_element *c, const char *value)
1071 {
1072   fprintf_filtered (file, _("Follow exec mode is \"%s\".\n"),  value);
1073 }
1074
1075 /* EXEC_FILE_TARGET is assumed to be non-NULL.  */
1076
1077 static void
1078 follow_exec (ptid_t ptid, char *exec_file_target)
1079 {
1080   struct thread_info *th, *tmp;
1081   struct inferior *inf = current_inferior ();
1082   int pid = ptid_get_pid (ptid);
1083   ptid_t process_ptid;
1084   char *exec_file_host;
1085   struct cleanup *old_chain;
1086
1087   /* This is an exec event that we actually wish to pay attention to.
1088      Refresh our symbol table to the newly exec'd program, remove any
1089      momentary bp's, etc.
1090
1091      If there are breakpoints, they aren't really inserted now,
1092      since the exec() transformed our inferior into a fresh set
1093      of instructions.
1094
1095      We want to preserve symbolic breakpoints on the list, since
1096      we have hopes that they can be reset after the new a.out's
1097      symbol table is read.
1098
1099      However, any "raw" breakpoints must be removed from the list
1100      (e.g., the solib bp's), since their address is probably invalid
1101      now.
1102
1103      And, we DON'T want to call delete_breakpoints() here, since
1104      that may write the bp's "shadow contents" (the instruction
1105      value that was overwritten witha TRAP instruction).  Since
1106      we now have a new a.out, those shadow contents aren't valid.  */
1107
1108   mark_breakpoints_out ();
1109
1110   /* The target reports the exec event to the main thread, even if
1111      some other thread does the exec, and even if the main thread was
1112      stopped or already gone.  We may still have non-leader threads of
1113      the process on our list.  E.g., on targets that don't have thread
1114      exit events (like remote); or on native Linux in non-stop mode if
1115      there were only two threads in the inferior and the non-leader
1116      one is the one that execs (and nothing forces an update of the
1117      thread list up to here).  When debugging remotely, it's best to
1118      avoid extra traffic, when possible, so avoid syncing the thread
1119      list with the target, and instead go ahead and delete all threads
1120      of the process but one that reported the event.  Note this must
1121      be done before calling update_breakpoints_after_exec, as
1122      otherwise clearing the threads' resources would reference stale
1123      thread breakpoints -- it may have been one of these threads that
1124      stepped across the exec.  We could just clear their stepping
1125      states, but as long as we're iterating, might as well delete
1126      them.  Deleting them now rather than at the next user-visible
1127      stop provides a nicer sequence of events for user and MI
1128      notifications.  */
1129   ALL_THREADS_SAFE (th, tmp)
1130     if (ptid_get_pid (th->ptid) == pid && !ptid_equal (th->ptid, ptid))
1131       delete_thread (th->ptid);
1132
1133   /* We also need to clear any left over stale state for the
1134      leader/event thread.  E.g., if there was any step-resume
1135      breakpoint or similar, it's gone now.  We cannot truly
1136      step-to-next statement through an exec().  */
1137   th = inferior_thread ();
1138   th->control.step_resume_breakpoint = NULL;
1139   th->control.exception_resume_breakpoint = NULL;
1140   th->control.single_step_breakpoints = NULL;
1141   th->control.step_range_start = 0;
1142   th->control.step_range_end = 0;
1143
1144   /* The user may have had the main thread held stopped in the
1145      previous image (e.g., schedlock on, or non-stop).  Release
1146      it now.  */
1147   th->stop_requested = 0;
1148
1149   update_breakpoints_after_exec ();
1150
1151   /* What is this a.out's name?  */
1152   process_ptid = pid_to_ptid (pid);
1153   printf_unfiltered (_("%s is executing new program: %s\n"),
1154                      target_pid_to_str (process_ptid),
1155                      exec_file_target);
1156
1157   /* We've followed the inferior through an exec.  Therefore, the
1158      inferior has essentially been killed & reborn.  */
1159
1160   gdb_flush (gdb_stdout);
1161
1162   breakpoint_init_inferior (inf_execd);
1163
1164   exec_file_host = exec_file_find (exec_file_target, NULL);
1165   old_chain = make_cleanup (xfree, exec_file_host);
1166
1167   /* If we were unable to map the executable target pathname onto a host
1168      pathname, tell the user that.  Otherwise GDB's subsequent behavior
1169      is confusing.  Maybe it would even be better to stop at this point
1170      so that the user can specify a file manually before continuing.  */
1171   if (exec_file_host == NULL)
1172     warning (_("Could not load symbols for executable %s.\n"
1173                "Do you need \"set sysroot\"?"),
1174              exec_file_target);
1175
1176   /* Reset the shared library package.  This ensures that we get a
1177      shlib event when the child reaches "_start", at which point the
1178      dld will have had a chance to initialize the child.  */
1179   /* Also, loading a symbol file below may trigger symbol lookups, and
1180      we don't want those to be satisfied by the libraries of the
1181      previous incarnation of this process.  */
1182   no_shared_libraries (NULL, 0);
1183
1184   if (follow_exec_mode_string == follow_exec_mode_new)
1185     {
1186       /* The user wants to keep the old inferior and program spaces
1187          around.  Create a new fresh one, and switch to it.  */
1188
1189       /* Do exit processing for the original inferior before adding
1190          the new inferior so we don't have two active inferiors with
1191          the same ptid, which can confuse find_inferior_ptid.  */
1192       exit_inferior_num_silent (current_inferior ()->num);
1193
1194       inf = add_inferior_with_spaces ();
1195       inf->pid = pid;
1196       target_follow_exec (inf, exec_file_target);
1197
1198       set_current_inferior (inf);
1199       set_current_program_space (inf->pspace);
1200     }
1201   else
1202     {
1203       /* The old description may no longer be fit for the new image.
1204          E.g, a 64-bit process exec'ed a 32-bit process.  Clear the
1205          old description; we'll read a new one below.  No need to do
1206          this on "follow-exec-mode new", as the old inferior stays
1207          around (its description is later cleared/refetched on
1208          restart).  */
1209       target_clear_description ();
1210     }
1211
1212   gdb_assert (current_program_space == inf->pspace);
1213
1214   /* Attempt to open the exec file.  SYMFILE_DEFER_BP_RESET is used
1215      because the proper displacement for a PIE (Position Independent
1216      Executable) main symbol file will only be computed by
1217      solib_create_inferior_hook below.  breakpoint_re_set would fail
1218      to insert the breakpoints with the zero displacement.  */
1219   try_open_exec_file (exec_file_host, inf, SYMFILE_DEFER_BP_RESET);
1220
1221   do_cleanups (old_chain);
1222
1223   /* If the target can specify a description, read it.  Must do this
1224      after flipping to the new executable (because the target supplied
1225      description must be compatible with the executable's
1226      architecture, and the old executable may e.g., be 32-bit, while
1227      the new one 64-bit), and before anything involving memory or
1228      registers.  */
1229   target_find_description ();
1230
1231   /* The add_thread call ends up reading registers, so do it after updating the
1232      target description.  */
1233   if (follow_exec_mode_string == follow_exec_mode_new)
1234     add_thread (ptid);
1235
1236   solib_create_inferior_hook (0);
1237
1238   jit_inferior_created_hook ();
1239
1240   breakpoint_re_set ();
1241
1242   /* Reinsert all breakpoints.  (Those which were symbolic have
1243      been reset to the proper address in the new a.out, thanks
1244      to symbol_file_command...).  */
1245   insert_breakpoints ();
1246
1247   /* The next resume of this inferior should bring it to the shlib
1248      startup breakpoints.  (If the user had also set bp's on
1249      "main" from the old (parent) process, then they'll auto-
1250      matically get reset there in the new process.).  */
1251 }
1252
1253 /* The queue of threads that need to do a step-over operation to get
1254    past e.g., a breakpoint.  What technique is used to step over the
1255    breakpoint/watchpoint does not matter -- all threads end up in the
1256    same queue, to maintain rough temporal order of execution, in order
1257    to avoid starvation, otherwise, we could e.g., find ourselves
1258    constantly stepping the same couple threads past their breakpoints
1259    over and over, if the single-step finish fast enough.  */
1260 struct thread_info *step_over_queue_head;
1261
1262 /* Bit flags indicating what the thread needs to step over.  */
1263
1264 enum step_over_what_flag
1265   {
1266     /* Step over a breakpoint.  */
1267     STEP_OVER_BREAKPOINT = 1,
1268
1269     /* Step past a non-continuable watchpoint, in order to let the
1270        instruction execute so we can evaluate the watchpoint
1271        expression.  */
1272     STEP_OVER_WATCHPOINT = 2
1273   };
1274 DEF_ENUM_FLAGS_TYPE (enum step_over_what_flag, step_over_what);
1275
1276 /* Info about an instruction that is being stepped over.  */
1277
1278 struct step_over_info
1279 {
1280   /* If we're stepping past a breakpoint, this is the address space
1281      and address of the instruction the breakpoint is set at.  We'll
1282      skip inserting all breakpoints here.  Valid iff ASPACE is
1283      non-NULL.  */
1284   const address_space *aspace;
1285   CORE_ADDR address;
1286
1287   /* The instruction being stepped over triggers a nonsteppable
1288      watchpoint.  If true, we'll skip inserting watchpoints.  */
1289   int nonsteppable_watchpoint_p;
1290
1291   /* The thread's global number.  */
1292   int thread;
1293 };
1294
1295 /* The step-over info of the location that is being stepped over.
1296
1297    Note that with async/breakpoint always-inserted mode, a user might
1298    set a new breakpoint/watchpoint/etc. exactly while a breakpoint is
1299    being stepped over.  As setting a new breakpoint inserts all
1300    breakpoints, we need to make sure the breakpoint being stepped over
1301    isn't inserted then.  We do that by only clearing the step-over
1302    info when the step-over is actually finished (or aborted).
1303
1304    Presently GDB can only step over one breakpoint at any given time.
1305    Given threads that can't run code in the same address space as the
1306    breakpoint's can't really miss the breakpoint, GDB could be taught
1307    to step-over at most one breakpoint per address space (so this info
1308    could move to the address space object if/when GDB is extended).
1309    The set of breakpoints being stepped over will normally be much
1310    smaller than the set of all breakpoints, so a flag in the
1311    breakpoint location structure would be wasteful.  A separate list
1312    also saves complexity and run-time, as otherwise we'd have to go
1313    through all breakpoint locations clearing their flag whenever we
1314    start a new sequence.  Similar considerations weigh against storing
1315    this info in the thread object.  Plus, not all step overs actually
1316    have breakpoint locations -- e.g., stepping past a single-step
1317    breakpoint, or stepping to complete a non-continuable
1318    watchpoint.  */
1319 static struct step_over_info step_over_info;
1320
1321 /* Record the address of the breakpoint/instruction we're currently
1322    stepping over.
1323    N.B. We record the aspace and address now, instead of say just the thread,
1324    because when we need the info later the thread may be running.  */
1325
1326 static void
1327 set_step_over_info (const address_space *aspace, CORE_ADDR address,
1328                     int nonsteppable_watchpoint_p,
1329                     int thread)
1330 {
1331   step_over_info.aspace = aspace;
1332   step_over_info.address = address;
1333   step_over_info.nonsteppable_watchpoint_p = nonsteppable_watchpoint_p;
1334   step_over_info.thread = thread;
1335 }
1336
1337 /* Called when we're not longer stepping over a breakpoint / an
1338    instruction, so all breakpoints are free to be (re)inserted.  */
1339
1340 static void
1341 clear_step_over_info (void)
1342 {
1343   if (debug_infrun)
1344     fprintf_unfiltered (gdb_stdlog,
1345                         "infrun: clear_step_over_info\n");
1346   step_over_info.aspace = NULL;
1347   step_over_info.address = 0;
1348   step_over_info.nonsteppable_watchpoint_p = 0;
1349   step_over_info.thread = -1;
1350 }
1351
1352 /* See infrun.h.  */
1353
1354 int
1355 stepping_past_instruction_at (struct address_space *aspace,
1356                               CORE_ADDR address)
1357 {
1358   return (step_over_info.aspace != NULL
1359           && breakpoint_address_match (aspace, address,
1360                                        step_over_info.aspace,
1361                                        step_over_info.address));
1362 }
1363
1364 /* See infrun.h.  */
1365
1366 int
1367 thread_is_stepping_over_breakpoint (int thread)
1368 {
1369   return (step_over_info.thread != -1
1370           && thread == step_over_info.thread);
1371 }
1372
1373 /* See infrun.h.  */
1374
1375 int
1376 stepping_past_nonsteppable_watchpoint (void)
1377 {
1378   return step_over_info.nonsteppable_watchpoint_p;
1379 }
1380
1381 /* Returns true if step-over info is valid.  */
1382
1383 static int
1384 step_over_info_valid_p (void)
1385 {
1386   return (step_over_info.aspace != NULL
1387           || stepping_past_nonsteppable_watchpoint ());
1388 }
1389
1390 \f
1391 /* Displaced stepping.  */
1392
1393 /* In non-stop debugging mode, we must take special care to manage
1394    breakpoints properly; in particular, the traditional strategy for
1395    stepping a thread past a breakpoint it has hit is unsuitable.
1396    'Displaced stepping' is a tactic for stepping one thread past a
1397    breakpoint it has hit while ensuring that other threads running
1398    concurrently will hit the breakpoint as they should.
1399
1400    The traditional way to step a thread T off a breakpoint in a
1401    multi-threaded program in all-stop mode is as follows:
1402
1403    a0) Initially, all threads are stopped, and breakpoints are not
1404        inserted.
1405    a1) We single-step T, leaving breakpoints uninserted.
1406    a2) We insert breakpoints, and resume all threads.
1407
1408    In non-stop debugging, however, this strategy is unsuitable: we
1409    don't want to have to stop all threads in the system in order to
1410    continue or step T past a breakpoint.  Instead, we use displaced
1411    stepping:
1412
1413    n0) Initially, T is stopped, other threads are running, and
1414        breakpoints are inserted.
1415    n1) We copy the instruction "under" the breakpoint to a separate
1416        location, outside the main code stream, making any adjustments
1417        to the instruction, register, and memory state as directed by
1418        T's architecture.
1419    n2) We single-step T over the instruction at its new location.
1420    n3) We adjust the resulting register and memory state as directed
1421        by T's architecture.  This includes resetting T's PC to point
1422        back into the main instruction stream.
1423    n4) We resume T.
1424
1425    This approach depends on the following gdbarch methods:
1426
1427    - gdbarch_max_insn_length and gdbarch_displaced_step_location
1428      indicate where to copy the instruction, and how much space must
1429      be reserved there.  We use these in step n1.
1430
1431    - gdbarch_displaced_step_copy_insn copies a instruction to a new
1432      address, and makes any necessary adjustments to the instruction,
1433      register contents, and memory.  We use this in step n1.
1434
1435    - gdbarch_displaced_step_fixup adjusts registers and memory after
1436      we have successfuly single-stepped the instruction, to yield the
1437      same effect the instruction would have had if we had executed it
1438      at its original address.  We use this in step n3.
1439
1440    The gdbarch_displaced_step_copy_insn and
1441    gdbarch_displaced_step_fixup functions must be written so that
1442    copying an instruction with gdbarch_displaced_step_copy_insn,
1443    single-stepping across the copied instruction, and then applying
1444    gdbarch_displaced_insn_fixup should have the same effects on the
1445    thread's memory and registers as stepping the instruction in place
1446    would have.  Exactly which responsibilities fall to the copy and
1447    which fall to the fixup is up to the author of those functions.
1448
1449    See the comments in gdbarch.sh for details.
1450
1451    Note that displaced stepping and software single-step cannot
1452    currently be used in combination, although with some care I think
1453    they could be made to.  Software single-step works by placing
1454    breakpoints on all possible subsequent instructions; if the
1455    displaced instruction is a PC-relative jump, those breakpoints
1456    could fall in very strange places --- on pages that aren't
1457    executable, or at addresses that are not proper instruction
1458    boundaries.  (We do generally let other threads run while we wait
1459    to hit the software single-step breakpoint, and they might
1460    encounter such a corrupted instruction.)  One way to work around
1461    this would be to have gdbarch_displaced_step_copy_insn fully
1462    simulate the effect of PC-relative instructions (and return NULL)
1463    on architectures that use software single-stepping.
1464
1465    In non-stop mode, we can have independent and simultaneous step
1466    requests, so more than one thread may need to simultaneously step
1467    over a breakpoint.  The current implementation assumes there is
1468    only one scratch space per process.  In this case, we have to
1469    serialize access to the scratch space.  If thread A wants to step
1470    over a breakpoint, but we are currently waiting for some other
1471    thread to complete a displaced step, we leave thread A stopped and
1472    place it in the displaced_step_request_queue.  Whenever a displaced
1473    step finishes, we pick the next thread in the queue and start a new
1474    displaced step operation on it.  See displaced_step_prepare and
1475    displaced_step_fixup for details.  */
1476
1477 /* Default destructor for displaced_step_closure.  */
1478
1479 displaced_step_closure::~displaced_step_closure () = default;
1480
1481 /* Per-inferior displaced stepping state.  */
1482 struct displaced_step_inferior_state
1483 {
1484   /* Pointer to next in linked list.  */
1485   struct displaced_step_inferior_state *next;
1486
1487   /* The process this displaced step state refers to.  */
1488   int pid;
1489
1490   /* True if preparing a displaced step ever failed.  If so, we won't
1491      try displaced stepping for this inferior again.  */
1492   int failed_before;
1493
1494   /* If this is not null_ptid, this is the thread carrying out a
1495      displaced single-step in process PID.  This thread's state will
1496      require fixing up once it has completed its step.  */
1497   ptid_t step_ptid;
1498
1499   /* The architecture the thread had when we stepped it.  */
1500   struct gdbarch *step_gdbarch;
1501
1502   /* The closure provided gdbarch_displaced_step_copy_insn, to be used
1503      for post-step cleanup.  */
1504   struct displaced_step_closure *step_closure;
1505
1506   /* The address of the original instruction, and the copy we
1507      made.  */
1508   CORE_ADDR step_original, step_copy;
1509
1510   /* Saved contents of copy area.  */
1511   gdb_byte *step_saved_copy;
1512 };
1513
1514 /* The list of states of processes involved in displaced stepping
1515    presently.  */
1516 static struct displaced_step_inferior_state *displaced_step_inferior_states;
1517
1518 /* Get the displaced stepping state of process PID.  */
1519
1520 static struct displaced_step_inferior_state *
1521 get_displaced_stepping_state (int pid)
1522 {
1523   struct displaced_step_inferior_state *state;
1524
1525   for (state = displaced_step_inferior_states;
1526        state != NULL;
1527        state = state->next)
1528     if (state->pid == pid)
1529       return state;
1530
1531   return NULL;
1532 }
1533
1534 /* Returns true if any inferior has a thread doing a displaced
1535    step.  */
1536
1537 static int
1538 displaced_step_in_progress_any_inferior (void)
1539 {
1540   struct displaced_step_inferior_state *state;
1541
1542   for (state = displaced_step_inferior_states;
1543        state != NULL;
1544        state = state->next)
1545     if (!ptid_equal (state->step_ptid, null_ptid))
1546       return 1;
1547
1548   return 0;
1549 }
1550
1551 /* Return true if thread represented by PTID is doing a displaced
1552    step.  */
1553
1554 static int
1555 displaced_step_in_progress_thread (ptid_t ptid)
1556 {
1557   struct displaced_step_inferior_state *displaced;
1558
1559   gdb_assert (!ptid_equal (ptid, null_ptid));
1560
1561   displaced = get_displaced_stepping_state (ptid_get_pid (ptid));
1562
1563   return (displaced != NULL && ptid_equal (displaced->step_ptid, ptid));
1564 }
1565
1566 /* Return true if process PID has a thread doing a displaced step.  */
1567
1568 static int
1569 displaced_step_in_progress (int pid)
1570 {
1571   struct displaced_step_inferior_state *displaced;
1572
1573   displaced = get_displaced_stepping_state (pid);
1574   if (displaced != NULL && !ptid_equal (displaced->step_ptid, null_ptid))
1575     return 1;
1576
1577   return 0;
1578 }
1579
1580 /* Add a new displaced stepping state for process PID to the displaced
1581    stepping state list, or return a pointer to an already existing
1582    entry, if it already exists.  Never returns NULL.  */
1583
1584 static struct displaced_step_inferior_state *
1585 add_displaced_stepping_state (int pid)
1586 {
1587   struct displaced_step_inferior_state *state;
1588
1589   for (state = displaced_step_inferior_states;
1590        state != NULL;
1591        state = state->next)
1592     if (state->pid == pid)
1593       return state;
1594
1595   state = XCNEW (struct displaced_step_inferior_state);
1596   state->pid = pid;
1597   state->next = displaced_step_inferior_states;
1598   displaced_step_inferior_states = state;
1599
1600   return state;
1601 }
1602
1603 /* If inferior is in displaced stepping, and ADDR equals to starting address
1604    of copy area, return corresponding displaced_step_closure.  Otherwise,
1605    return NULL.  */
1606
1607 struct displaced_step_closure*
1608 get_displaced_step_closure_by_addr (CORE_ADDR addr)
1609 {
1610   struct displaced_step_inferior_state *displaced
1611     = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
1612
1613   /* If checking the mode of displaced instruction in copy area.  */
1614   if (displaced && !ptid_equal (displaced->step_ptid, null_ptid)
1615      && (displaced->step_copy == addr))
1616     return displaced->step_closure;
1617
1618   return NULL;
1619 }
1620
1621 /* Remove the displaced stepping state of process PID.  */
1622
1623 static void
1624 remove_displaced_stepping_state (int pid)
1625 {
1626   struct displaced_step_inferior_state *it, **prev_next_p;
1627
1628   gdb_assert (pid != 0);
1629
1630   it = displaced_step_inferior_states;
1631   prev_next_p = &displaced_step_inferior_states;
1632   while (it)
1633     {
1634       if (it->pid == pid)
1635         {
1636           *prev_next_p = it->next;
1637           xfree (it);
1638           return;
1639         }
1640
1641       prev_next_p = &it->next;
1642       it = *prev_next_p;
1643     }
1644 }
1645
1646 static void
1647 infrun_inferior_exit (struct inferior *inf)
1648 {
1649   remove_displaced_stepping_state (inf->pid);
1650 }
1651
1652 /* If ON, and the architecture supports it, GDB will use displaced
1653    stepping to step over breakpoints.  If OFF, or if the architecture
1654    doesn't support it, GDB will instead use the traditional
1655    hold-and-step approach.  If AUTO (which is the default), GDB will
1656    decide which technique to use to step over breakpoints depending on
1657    which of all-stop or non-stop mode is active --- displaced stepping
1658    in non-stop mode; hold-and-step in all-stop mode.  */
1659
1660 static enum auto_boolean can_use_displaced_stepping = AUTO_BOOLEAN_AUTO;
1661
1662 static void
1663 show_can_use_displaced_stepping (struct ui_file *file, int from_tty,
1664                                  struct cmd_list_element *c,
1665                                  const char *value)
1666 {
1667   if (can_use_displaced_stepping == AUTO_BOOLEAN_AUTO)
1668     fprintf_filtered (file,
1669                       _("Debugger's willingness to use displaced stepping "
1670                         "to step over breakpoints is %s (currently %s).\n"),
1671                       value, target_is_non_stop_p () ? "on" : "off");
1672   else
1673     fprintf_filtered (file,
1674                       _("Debugger's willingness to use displaced stepping "
1675                         "to step over breakpoints is %s.\n"), value);
1676 }
1677
1678 /* Return non-zero if displaced stepping can/should be used to step
1679    over breakpoints of thread TP.  */
1680
1681 static int
1682 use_displaced_stepping (struct thread_info *tp)
1683 {
1684   struct regcache *regcache = get_thread_regcache (tp->ptid);
1685   struct gdbarch *gdbarch = regcache->arch ();
1686   struct displaced_step_inferior_state *displaced_state;
1687
1688   displaced_state = get_displaced_stepping_state (ptid_get_pid (tp->ptid));
1689
1690   return (((can_use_displaced_stepping == AUTO_BOOLEAN_AUTO
1691             && target_is_non_stop_p ())
1692            || can_use_displaced_stepping == AUTO_BOOLEAN_TRUE)
1693           && gdbarch_displaced_step_copy_insn_p (gdbarch)
1694           && find_record_target () == NULL
1695           && (displaced_state == NULL
1696               || !displaced_state->failed_before));
1697 }
1698
1699 /* Clean out any stray displaced stepping state.  */
1700 static void
1701 displaced_step_clear (struct displaced_step_inferior_state *displaced)
1702 {
1703   /* Indicate that there is no cleanup pending.  */
1704   displaced->step_ptid = null_ptid;
1705
1706   delete displaced->step_closure;
1707   displaced->step_closure = NULL;
1708 }
1709
1710 static void
1711 displaced_step_clear_cleanup (void *arg)
1712 {
1713   struct displaced_step_inferior_state *state
1714     = (struct displaced_step_inferior_state *) arg;
1715
1716   displaced_step_clear (state);
1717 }
1718
1719 /* Dump LEN bytes at BUF in hex to FILE, followed by a newline.  */
1720 void
1721 displaced_step_dump_bytes (struct ui_file *file,
1722                            const gdb_byte *buf,
1723                            size_t len)
1724 {
1725   int i;
1726
1727   for (i = 0; i < len; i++)
1728     fprintf_unfiltered (file, "%02x ", buf[i]);
1729   fputs_unfiltered ("\n", file);
1730 }
1731
1732 /* Prepare to single-step, using displaced stepping.
1733
1734    Note that we cannot use displaced stepping when we have a signal to
1735    deliver.  If we have a signal to deliver and an instruction to step
1736    over, then after the step, there will be no indication from the
1737    target whether the thread entered a signal handler or ignored the
1738    signal and stepped over the instruction successfully --- both cases
1739    result in a simple SIGTRAP.  In the first case we mustn't do a
1740    fixup, and in the second case we must --- but we can't tell which.
1741    Comments in the code for 'random signals' in handle_inferior_event
1742    explain how we handle this case instead.
1743
1744    Returns 1 if preparing was successful -- this thread is going to be
1745    stepped now; 0 if displaced stepping this thread got queued; or -1
1746    if this instruction can't be displaced stepped.  */
1747
1748 static int
1749 displaced_step_prepare_throw (ptid_t ptid)
1750 {
1751   struct cleanup *ignore_cleanups;
1752   struct thread_info *tp = find_thread_ptid (ptid);
1753   struct regcache *regcache = get_thread_regcache (ptid);
1754   struct gdbarch *gdbarch = regcache->arch ();
1755   const address_space *aspace = regcache->aspace ();
1756   CORE_ADDR original, copy;
1757   ULONGEST len;
1758   struct displaced_step_closure *closure;
1759   struct displaced_step_inferior_state *displaced;
1760   int status;
1761
1762   /* We should never reach this function if the architecture does not
1763      support displaced stepping.  */
1764   gdb_assert (gdbarch_displaced_step_copy_insn_p (gdbarch));
1765
1766   /* Nor if the thread isn't meant to step over a breakpoint.  */
1767   gdb_assert (tp->control.trap_expected);
1768
1769   /* Disable range stepping while executing in the scratch pad.  We
1770      want a single-step even if executing the displaced instruction in
1771      the scratch buffer lands within the stepping range (e.g., a
1772      jump/branch).  */
1773   tp->control.may_range_step = 0;
1774
1775   /* We have to displaced step one thread at a time, as we only have
1776      access to a single scratch space per inferior.  */
1777
1778   displaced = add_displaced_stepping_state (ptid_get_pid (ptid));
1779
1780   if (!ptid_equal (displaced->step_ptid, null_ptid))
1781     {
1782       /* Already waiting for a displaced step to finish.  Defer this
1783          request and place in queue.  */
1784
1785       if (debug_displaced)
1786         fprintf_unfiltered (gdb_stdlog,
1787                             "displaced: deferring step of %s\n",
1788                             target_pid_to_str (ptid));
1789
1790       thread_step_over_chain_enqueue (tp);
1791       return 0;
1792     }
1793   else
1794     {
1795       if (debug_displaced)
1796         fprintf_unfiltered (gdb_stdlog,
1797                             "displaced: stepping %s now\n",
1798                             target_pid_to_str (ptid));
1799     }
1800
1801   displaced_step_clear (displaced);
1802
1803   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
1804   inferior_ptid = ptid;
1805
1806   original = regcache_read_pc (regcache);
1807
1808   copy = gdbarch_displaced_step_location (gdbarch);
1809   len = gdbarch_max_insn_length (gdbarch);
1810
1811   if (breakpoint_in_range_p (aspace, copy, len))
1812     {
1813       /* There's a breakpoint set in the scratch pad location range
1814          (which is usually around the entry point).  We'd either
1815          install it before resuming, which would overwrite/corrupt the
1816          scratch pad, or if it was already inserted, this displaced
1817          step would overwrite it.  The latter is OK in the sense that
1818          we already assume that no thread is going to execute the code
1819          in the scratch pad range (after initial startup) anyway, but
1820          the former is unacceptable.  Simply punt and fallback to
1821          stepping over this breakpoint in-line.  */
1822       if (debug_displaced)
1823         {
1824           fprintf_unfiltered (gdb_stdlog,
1825                               "displaced: breakpoint set in scratch pad.  "
1826                               "Stepping over breakpoint in-line instead.\n");
1827         }
1828
1829       return -1;
1830     }
1831
1832   /* Save the original contents of the copy area.  */
1833   displaced->step_saved_copy = (gdb_byte *) xmalloc (len);
1834   ignore_cleanups = make_cleanup (free_current_contents,
1835                                   &displaced->step_saved_copy);
1836   status = target_read_memory (copy, displaced->step_saved_copy, len);
1837   if (status != 0)
1838     throw_error (MEMORY_ERROR,
1839                  _("Error accessing memory address %s (%s) for "
1840                    "displaced-stepping scratch space."),
1841                  paddress (gdbarch, copy), safe_strerror (status));
1842   if (debug_displaced)
1843     {
1844       fprintf_unfiltered (gdb_stdlog, "displaced: saved %s: ",
1845                           paddress (gdbarch, copy));
1846       displaced_step_dump_bytes (gdb_stdlog,
1847                                  displaced->step_saved_copy,
1848                                  len);
1849     };
1850
1851   closure = gdbarch_displaced_step_copy_insn (gdbarch,
1852                                               original, copy, regcache);
1853   if (closure == NULL)
1854     {
1855       /* The architecture doesn't know how or want to displaced step
1856          this instruction or instruction sequence.  Fallback to
1857          stepping over the breakpoint in-line.  */
1858       do_cleanups (ignore_cleanups);
1859       return -1;
1860     }
1861
1862   /* Save the information we need to fix things up if the step
1863      succeeds.  */
1864   displaced->step_ptid = ptid;
1865   displaced->step_gdbarch = gdbarch;
1866   displaced->step_closure = closure;
1867   displaced->step_original = original;
1868   displaced->step_copy = copy;
1869
1870   make_cleanup (displaced_step_clear_cleanup, displaced);
1871
1872   /* Resume execution at the copy.  */
1873   regcache_write_pc (regcache, copy);
1874
1875   discard_cleanups (ignore_cleanups);
1876
1877   if (debug_displaced)
1878     fprintf_unfiltered (gdb_stdlog, "displaced: displaced pc to %s\n",
1879                         paddress (gdbarch, copy));
1880
1881   return 1;
1882 }
1883
1884 /* Wrapper for displaced_step_prepare_throw that disabled further
1885    attempts at displaced stepping if we get a memory error.  */
1886
1887 static int
1888 displaced_step_prepare (ptid_t ptid)
1889 {
1890   int prepared = -1;
1891
1892   TRY
1893     {
1894       prepared = displaced_step_prepare_throw (ptid);
1895     }
1896   CATCH (ex, RETURN_MASK_ERROR)
1897     {
1898       struct displaced_step_inferior_state *displaced_state;
1899
1900       if (ex.error != MEMORY_ERROR
1901           && ex.error != NOT_SUPPORTED_ERROR)
1902         throw_exception (ex);
1903
1904       if (debug_infrun)
1905         {
1906           fprintf_unfiltered (gdb_stdlog,
1907                               "infrun: disabling displaced stepping: %s\n",
1908                               ex.message);
1909         }
1910
1911       /* Be verbose if "set displaced-stepping" is "on", silent if
1912          "auto".  */
1913       if (can_use_displaced_stepping == AUTO_BOOLEAN_TRUE)
1914         {
1915           warning (_("disabling displaced stepping: %s"),
1916                    ex.message);
1917         }
1918
1919       /* Disable further displaced stepping attempts.  */
1920       displaced_state
1921         = get_displaced_stepping_state (ptid_get_pid (ptid));
1922       displaced_state->failed_before = 1;
1923     }
1924   END_CATCH
1925
1926   return prepared;
1927 }
1928
1929 static void
1930 write_memory_ptid (ptid_t ptid, CORE_ADDR memaddr,
1931                    const gdb_byte *myaddr, int len)
1932 {
1933   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
1934
1935   inferior_ptid = ptid;
1936   write_memory (memaddr, myaddr, len);
1937 }
1938
1939 /* Restore the contents of the copy area for thread PTID.  */
1940
1941 static void
1942 displaced_step_restore (struct displaced_step_inferior_state *displaced,
1943                         ptid_t ptid)
1944 {
1945   ULONGEST len = gdbarch_max_insn_length (displaced->step_gdbarch);
1946
1947   write_memory_ptid (ptid, displaced->step_copy,
1948                      displaced->step_saved_copy, len);
1949   if (debug_displaced)
1950     fprintf_unfiltered (gdb_stdlog, "displaced: restored %s %s\n",
1951                         target_pid_to_str (ptid),
1952                         paddress (displaced->step_gdbarch,
1953                                   displaced->step_copy));
1954 }
1955
1956 /* If we displaced stepped an instruction successfully, adjust
1957    registers and memory to yield the same effect the instruction would
1958    have had if we had executed it at its original address, and return
1959    1.  If the instruction didn't complete, relocate the PC and return
1960    -1.  If the thread wasn't displaced stepping, return 0.  */
1961
1962 static int
1963 displaced_step_fixup (ptid_t event_ptid, enum gdb_signal signal)
1964 {
1965   struct cleanup *old_cleanups;
1966   struct displaced_step_inferior_state *displaced
1967     = get_displaced_stepping_state (ptid_get_pid (event_ptid));
1968   int ret;
1969
1970   /* Was any thread of this process doing a displaced step?  */
1971   if (displaced == NULL)
1972     return 0;
1973
1974   /* Was this event for the pid we displaced?  */
1975   if (ptid_equal (displaced->step_ptid, null_ptid)
1976       || ! ptid_equal (displaced->step_ptid, event_ptid))
1977     return 0;
1978
1979   old_cleanups = make_cleanup (displaced_step_clear_cleanup, displaced);
1980
1981   displaced_step_restore (displaced, displaced->step_ptid);
1982
1983   /* Fixup may need to read memory/registers.  Switch to the thread
1984      that we're fixing up.  Also, target_stopped_by_watchpoint checks
1985      the current thread.  */
1986   switch_to_thread (event_ptid);
1987
1988   /* Did the instruction complete successfully?  */
1989   if (signal == GDB_SIGNAL_TRAP
1990       && !(target_stopped_by_watchpoint ()
1991            && (gdbarch_have_nonsteppable_watchpoint (displaced->step_gdbarch)
1992                || target_have_steppable_watchpoint)))
1993     {
1994       /* Fix up the resulting state.  */
1995       gdbarch_displaced_step_fixup (displaced->step_gdbarch,
1996                                     displaced->step_closure,
1997                                     displaced->step_original,
1998                                     displaced->step_copy,
1999                                     get_thread_regcache (displaced->step_ptid));
2000       ret = 1;
2001     }
2002   else
2003     {
2004       /* Since the instruction didn't complete, all we can do is
2005          relocate the PC.  */
2006       struct regcache *regcache = get_thread_regcache (event_ptid);
2007       CORE_ADDR pc = regcache_read_pc (regcache);
2008
2009       pc = displaced->step_original + (pc - displaced->step_copy);
2010       regcache_write_pc (regcache, pc);
2011       ret = -1;
2012     }
2013
2014   do_cleanups (old_cleanups);
2015
2016   displaced->step_ptid = null_ptid;
2017
2018   return ret;
2019 }
2020
2021 /* Data to be passed around while handling an event.  This data is
2022    discarded between events.  */
2023 struct execution_control_state
2024 {
2025   ptid_t ptid;
2026   /* The thread that got the event, if this was a thread event; NULL
2027      otherwise.  */
2028   struct thread_info *event_thread;
2029
2030   struct target_waitstatus ws;
2031   int stop_func_filled_in;
2032   CORE_ADDR stop_func_start;
2033   CORE_ADDR stop_func_end;
2034   const char *stop_func_name;
2035   int wait_some_more;
2036
2037   /* True if the event thread hit the single-step breakpoint of
2038      another thread.  Thus the event doesn't cause a stop, the thread
2039      needs to be single-stepped past the single-step breakpoint before
2040      we can switch back to the original stepping thread.  */
2041   int hit_singlestep_breakpoint;
2042 };
2043
2044 /* Clear ECS and set it to point at TP.  */
2045
2046 static void
2047 reset_ecs (struct execution_control_state *ecs, struct thread_info *tp)
2048 {
2049   memset (ecs, 0, sizeof (*ecs));
2050   ecs->event_thread = tp;
2051   ecs->ptid = tp->ptid;
2052 }
2053
2054 static void keep_going_pass_signal (struct execution_control_state *ecs);
2055 static void prepare_to_wait (struct execution_control_state *ecs);
2056 static int keep_going_stepped_thread (struct thread_info *tp);
2057 static step_over_what thread_still_needs_step_over (struct thread_info *tp);
2058
2059 /* Are there any pending step-over requests?  If so, run all we can
2060    now and return true.  Otherwise, return false.  */
2061
2062 static int
2063 start_step_over (void)
2064 {
2065   struct thread_info *tp, *next;
2066
2067   /* Don't start a new step-over if we already have an in-line
2068      step-over operation ongoing.  */
2069   if (step_over_info_valid_p ())
2070     return 0;
2071
2072   for (tp = step_over_queue_head; tp != NULL; tp = next)
2073     {
2074       struct execution_control_state ecss;
2075       struct execution_control_state *ecs = &ecss;
2076       step_over_what step_what;
2077       int must_be_in_line;
2078
2079       gdb_assert (!tp->stop_requested);
2080
2081       next = thread_step_over_chain_next (tp);
2082
2083       /* If this inferior already has a displaced step in process,
2084          don't start a new one.  */
2085       if (displaced_step_in_progress (ptid_get_pid (tp->ptid)))
2086         continue;
2087
2088       step_what = thread_still_needs_step_over (tp);
2089       must_be_in_line = ((step_what & STEP_OVER_WATCHPOINT)
2090                          || ((step_what & STEP_OVER_BREAKPOINT)
2091                              && !use_displaced_stepping (tp)));
2092
2093       /* We currently stop all threads of all processes to step-over
2094          in-line.  If we need to start a new in-line step-over, let
2095          any pending displaced steps finish first.  */
2096       if (must_be_in_line && displaced_step_in_progress_any_inferior ())
2097         return 0;
2098
2099       thread_step_over_chain_remove (tp);
2100
2101       if (step_over_queue_head == NULL)
2102         {
2103           if (debug_infrun)
2104             fprintf_unfiltered (gdb_stdlog,
2105                                 "infrun: step-over queue now empty\n");
2106         }
2107
2108       if (tp->control.trap_expected
2109           || tp->resumed
2110           || tp->executing)
2111         {
2112           internal_error (__FILE__, __LINE__,
2113                           "[%s] has inconsistent state: "
2114                           "trap_expected=%d, resumed=%d, executing=%d\n",
2115                           target_pid_to_str (tp->ptid),
2116                           tp->control.trap_expected,
2117                           tp->resumed,
2118                           tp->executing);
2119         }
2120
2121       if (debug_infrun)
2122         fprintf_unfiltered (gdb_stdlog,
2123                             "infrun: resuming [%s] for step-over\n",
2124                             target_pid_to_str (tp->ptid));
2125
2126       /* keep_going_pass_signal skips the step-over if the breakpoint
2127          is no longer inserted.  In all-stop, we want to keep looking
2128          for a thread that needs a step-over instead of resuming TP,
2129          because we wouldn't be able to resume anything else until the
2130          target stops again.  In non-stop, the resume always resumes
2131          only TP, so it's OK to let the thread resume freely.  */
2132       if (!target_is_non_stop_p () && !step_what)
2133         continue;
2134
2135       switch_to_thread (tp->ptid);
2136       reset_ecs (ecs, tp);
2137       keep_going_pass_signal (ecs);
2138
2139       if (!ecs->wait_some_more)
2140         error (_("Command aborted."));
2141
2142       gdb_assert (tp->resumed);
2143
2144       /* If we started a new in-line step-over, we're done.  */
2145       if (step_over_info_valid_p ())
2146         {
2147           gdb_assert (tp->control.trap_expected);
2148           return 1;
2149         }
2150
2151       if (!target_is_non_stop_p ())
2152         {
2153           /* On all-stop, shouldn't have resumed unless we needed a
2154              step over.  */
2155           gdb_assert (tp->control.trap_expected
2156                       || tp->step_after_step_resume_breakpoint);
2157
2158           /* With remote targets (at least), in all-stop, we can't
2159              issue any further remote commands until the program stops
2160              again.  */
2161           return 1;
2162         }
2163
2164       /* Either the thread no longer needed a step-over, or a new
2165          displaced stepping sequence started.  Even in the latter
2166          case, continue looking.  Maybe we can also start another
2167          displaced step on a thread of other process. */
2168     }
2169
2170   return 0;
2171 }
2172
2173 /* Update global variables holding ptids to hold NEW_PTID if they were
2174    holding OLD_PTID.  */
2175 static void
2176 infrun_thread_ptid_changed (ptid_t old_ptid, ptid_t new_ptid)
2177 {
2178   struct displaced_step_inferior_state *displaced;
2179
2180   if (ptid_equal (inferior_ptid, old_ptid))
2181     inferior_ptid = new_ptid;
2182
2183   for (displaced = displaced_step_inferior_states;
2184        displaced;
2185        displaced = displaced->next)
2186     {
2187       if (ptid_equal (displaced->step_ptid, old_ptid))
2188         displaced->step_ptid = new_ptid;
2189     }
2190 }
2191
2192 \f
2193
2194 static const char schedlock_off[] = "off";
2195 static const char schedlock_on[] = "on";
2196 static const char schedlock_step[] = "step";
2197 static const char schedlock_replay[] = "replay";
2198 static const char *const scheduler_enums[] = {
2199   schedlock_off,
2200   schedlock_on,
2201   schedlock_step,
2202   schedlock_replay,
2203   NULL
2204 };
2205 static const char *scheduler_mode = schedlock_replay;
2206 static void
2207 show_scheduler_mode (struct ui_file *file, int from_tty,
2208                      struct cmd_list_element *c, const char *value)
2209 {
2210   fprintf_filtered (file,
2211                     _("Mode for locking scheduler "
2212                       "during execution is \"%s\".\n"),
2213                     value);
2214 }
2215
2216 static void
2217 set_schedlock_func (const char *args, int from_tty, struct cmd_list_element *c)
2218 {
2219   if (!target_can_lock_scheduler)
2220     {
2221       scheduler_mode = schedlock_off;
2222       error (_("Target '%s' cannot support this command."), target_shortname);
2223     }
2224 }
2225
2226 /* True if execution commands resume all threads of all processes by
2227    default; otherwise, resume only threads of the current inferior
2228    process.  */
2229 int sched_multi = 0;
2230
2231 /* Try to setup for software single stepping over the specified location.
2232    Return 1 if target_resume() should use hardware single step.
2233
2234    GDBARCH the current gdbarch.
2235    PC the location to step over.  */
2236
2237 static int
2238 maybe_software_singlestep (struct gdbarch *gdbarch, CORE_ADDR pc)
2239 {
2240   int hw_step = 1;
2241
2242   if (execution_direction == EXEC_FORWARD
2243       && gdbarch_software_single_step_p (gdbarch))
2244     hw_step = !insert_single_step_breakpoints (gdbarch);
2245
2246   return hw_step;
2247 }
2248
2249 /* See infrun.h.  */
2250
2251 ptid_t
2252 user_visible_resume_ptid (int step)
2253 {
2254   ptid_t resume_ptid;
2255
2256   if (non_stop)
2257     {
2258       /* With non-stop mode on, threads are always handled
2259          individually.  */
2260       resume_ptid = inferior_ptid;
2261     }
2262   else if ((scheduler_mode == schedlock_on)
2263            || (scheduler_mode == schedlock_step && step))
2264     {
2265       /* User-settable 'scheduler' mode requires solo thread
2266          resume.  */
2267       resume_ptid = inferior_ptid;
2268     }
2269   else if ((scheduler_mode == schedlock_replay)
2270            && target_record_will_replay (minus_one_ptid, execution_direction))
2271     {
2272       /* User-settable 'scheduler' mode requires solo thread resume in replay
2273          mode.  */
2274       resume_ptid = inferior_ptid;
2275     }
2276   else if (!sched_multi && target_supports_multi_process ())
2277     {
2278       /* Resume all threads of the current process (and none of other
2279          processes).  */
2280       resume_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
2281     }
2282   else
2283     {
2284       /* Resume all threads of all processes.  */
2285       resume_ptid = RESUME_ALL;
2286     }
2287
2288   return resume_ptid;
2289 }
2290
2291 /* Return a ptid representing the set of threads that we will resume,
2292    in the perspective of the target, assuming run control handling
2293    does not require leaving some threads stopped (e.g., stepping past
2294    breakpoint).  USER_STEP indicates whether we're about to start the
2295    target for a stepping command.  */
2296
2297 static ptid_t
2298 internal_resume_ptid (int user_step)
2299 {
2300   /* In non-stop, we always control threads individually.  Note that
2301      the target may always work in non-stop mode even with "set
2302      non-stop off", in which case user_visible_resume_ptid could
2303      return a wildcard ptid.  */
2304   if (target_is_non_stop_p ())
2305     return inferior_ptid;
2306   else
2307     return user_visible_resume_ptid (user_step);
2308 }
2309
2310 /* Wrapper for target_resume, that handles infrun-specific
2311    bookkeeping.  */
2312
2313 static void
2314 do_target_resume (ptid_t resume_ptid, int step, enum gdb_signal sig)
2315 {
2316   struct thread_info *tp = inferior_thread ();
2317
2318   gdb_assert (!tp->stop_requested);
2319
2320   /* Install inferior's terminal modes.  */
2321   target_terminal::inferior ();
2322
2323   /* Avoid confusing the next resume, if the next stop/resume
2324      happens to apply to another thread.  */
2325   tp->suspend.stop_signal = GDB_SIGNAL_0;
2326
2327   /* Advise target which signals may be handled silently.
2328
2329      If we have removed breakpoints because we are stepping over one
2330      in-line (in any thread), we need to receive all signals to avoid
2331      accidentally skipping a breakpoint during execution of a signal
2332      handler.
2333
2334      Likewise if we're displaced stepping, otherwise a trap for a
2335      breakpoint in a signal handler might be confused with the
2336      displaced step finishing.  We don't make the displaced_step_fixup
2337      step distinguish the cases instead, because:
2338
2339      - a backtrace while stopped in the signal handler would show the
2340        scratch pad as frame older than the signal handler, instead of
2341        the real mainline code.
2342
2343      - when the thread is later resumed, the signal handler would
2344        return to the scratch pad area, which would no longer be
2345        valid.  */
2346   if (step_over_info_valid_p ()
2347       || displaced_step_in_progress (ptid_get_pid (tp->ptid)))
2348     target_pass_signals (0, NULL);
2349   else
2350     target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
2351
2352   target_resume (resume_ptid, step, sig);
2353
2354   target_commit_resume ();
2355 }
2356
2357 /* Resume the inferior.  SIG is the signal to give the inferior
2358    (GDB_SIGNAL_0 for none).  */
2359
2360 void
2361 resume (enum gdb_signal sig)
2362 {
2363   struct regcache *regcache = get_current_regcache ();
2364   struct gdbarch *gdbarch = regcache->arch ();
2365   struct thread_info *tp = inferior_thread ();
2366   CORE_ADDR pc = regcache_read_pc (regcache);
2367   const address_space *aspace = regcache->aspace ();
2368   ptid_t resume_ptid;
2369   /* This represents the user's step vs continue request.  When
2370      deciding whether "set scheduler-locking step" applies, it's the
2371      user's intention that counts.  */
2372   const int user_step = tp->control.stepping_command;
2373   /* This represents what we'll actually request the target to do.
2374      This can decay from a step to a continue, if e.g., we need to
2375      implement single-stepping with breakpoints (software
2376      single-step).  */
2377   int step;
2378
2379   gdb_assert (!tp->stop_requested);
2380   gdb_assert (!thread_is_in_step_over_chain (tp));
2381
2382   if (tp->suspend.waitstatus_pending_p)
2383     {
2384       if (debug_infrun)
2385         {
2386           std::string statstr
2387             = target_waitstatus_to_string (&tp->suspend.waitstatus);
2388
2389           fprintf_unfiltered (gdb_stdlog,
2390                               "infrun: resume: thread %s has pending wait "
2391                               "status %s (currently_stepping=%d).\n",
2392                               target_pid_to_str (tp->ptid), statstr.c_str (),
2393                               currently_stepping (tp));
2394         }
2395
2396       tp->resumed = 1;
2397
2398       /* FIXME: What should we do if we are supposed to resume this
2399          thread with a signal?  Maybe we should maintain a queue of
2400          pending signals to deliver.  */
2401       if (sig != GDB_SIGNAL_0)
2402         {
2403           warning (_("Couldn't deliver signal %s to %s."),
2404                    gdb_signal_to_name (sig), target_pid_to_str (tp->ptid));
2405         }
2406
2407       tp->suspend.stop_signal = GDB_SIGNAL_0;
2408
2409       if (target_can_async_p ())
2410         target_async (1);
2411       return;
2412     }
2413
2414   tp->stepped_breakpoint = 0;
2415
2416   /* Depends on stepped_breakpoint.  */
2417   step = currently_stepping (tp);
2418
2419   if (current_inferior ()->waiting_for_vfork_done)
2420     {
2421       /* Don't try to single-step a vfork parent that is waiting for
2422          the child to get out of the shared memory region (by exec'ing
2423          or exiting).  This is particularly important on software
2424          single-step archs, as the child process would trip on the
2425          software single step breakpoint inserted for the parent
2426          process.  Since the parent will not actually execute any
2427          instruction until the child is out of the shared region (such
2428          are vfork's semantics), it is safe to simply continue it.
2429          Eventually, we'll see a TARGET_WAITKIND_VFORK_DONE event for
2430          the parent, and tell it to `keep_going', which automatically
2431          re-sets it stepping.  */
2432       if (debug_infrun)
2433         fprintf_unfiltered (gdb_stdlog,
2434                             "infrun: resume : clear step\n");
2435       step = 0;
2436     }
2437
2438   if (debug_infrun)
2439     fprintf_unfiltered (gdb_stdlog,
2440                         "infrun: resume (step=%d, signal=%s), "
2441                         "trap_expected=%d, current thread [%s] at %s\n",
2442                         step, gdb_signal_to_symbol_string (sig),
2443                         tp->control.trap_expected,
2444                         target_pid_to_str (inferior_ptid),
2445                         paddress (gdbarch, pc));
2446
2447   /* Normally, by the time we reach `resume', the breakpoints are either
2448      removed or inserted, as appropriate.  The exception is if we're sitting
2449      at a permanent breakpoint; we need to step over it, but permanent
2450      breakpoints can't be removed.  So we have to test for it here.  */
2451   if (breakpoint_here_p (aspace, pc) == permanent_breakpoint_here)
2452     {
2453       if (sig != GDB_SIGNAL_0)
2454         {
2455           /* We have a signal to pass to the inferior.  The resume
2456              may, or may not take us to the signal handler.  If this
2457              is a step, we'll need to stop in the signal handler, if
2458              there's one, (if the target supports stepping into
2459              handlers), or in the next mainline instruction, if
2460              there's no handler.  If this is a continue, we need to be
2461              sure to run the handler with all breakpoints inserted.
2462              In all cases, set a breakpoint at the current address
2463              (where the handler returns to), and once that breakpoint
2464              is hit, resume skipping the permanent breakpoint.  If
2465              that breakpoint isn't hit, then we've stepped into the
2466              signal handler (or hit some other event).  We'll delete
2467              the step-resume breakpoint then.  */
2468
2469           if (debug_infrun)
2470             fprintf_unfiltered (gdb_stdlog,
2471                                 "infrun: resume: skipping permanent breakpoint, "
2472                                 "deliver signal first\n");
2473
2474           clear_step_over_info ();
2475           tp->control.trap_expected = 0;
2476
2477           if (tp->control.step_resume_breakpoint == NULL)
2478             {
2479               /* Set a "high-priority" step-resume, as we don't want
2480                  user breakpoints at PC to trigger (again) when this
2481                  hits.  */
2482               insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
2483               gdb_assert (tp->control.step_resume_breakpoint->loc->permanent);
2484
2485               tp->step_after_step_resume_breakpoint = step;
2486             }
2487
2488           insert_breakpoints ();
2489         }
2490       else
2491         {
2492           /* There's no signal to pass, we can go ahead and skip the
2493              permanent breakpoint manually.  */
2494           if (debug_infrun)
2495             fprintf_unfiltered (gdb_stdlog,
2496                                 "infrun: resume: skipping permanent breakpoint\n");
2497           gdbarch_skip_permanent_breakpoint (gdbarch, regcache);
2498           /* Update pc to reflect the new address from which we will
2499              execute instructions.  */
2500           pc = regcache_read_pc (regcache);
2501
2502           if (step)
2503             {
2504               /* We've already advanced the PC, so the stepping part
2505                  is done.  Now we need to arrange for a trap to be
2506                  reported to handle_inferior_event.  Set a breakpoint
2507                  at the current PC, and run to it.  Don't update
2508                  prev_pc, because if we end in
2509                  switch_back_to_stepped_thread, we want the "expected
2510                  thread advanced also" branch to be taken.  IOW, we
2511                  don't want this thread to step further from PC
2512                  (overstep).  */
2513               gdb_assert (!step_over_info_valid_p ());
2514               insert_single_step_breakpoint (gdbarch, aspace, pc);
2515               insert_breakpoints ();
2516
2517               resume_ptid = internal_resume_ptid (user_step);
2518               do_target_resume (resume_ptid, 0, GDB_SIGNAL_0);
2519               tp->resumed = 1;
2520               return;
2521             }
2522         }
2523     }
2524
2525   /* If we have a breakpoint to step over, make sure to do a single
2526      step only.  Same if we have software watchpoints.  */
2527   if (tp->control.trap_expected || bpstat_should_step ())
2528     tp->control.may_range_step = 0;
2529
2530   /* If enabled, step over breakpoints by executing a copy of the
2531      instruction at a different address.
2532
2533      We can't use displaced stepping when we have a signal to deliver;
2534      the comments for displaced_step_prepare explain why.  The
2535      comments in the handle_inferior event for dealing with 'random
2536      signals' explain what we do instead.
2537
2538      We can't use displaced stepping when we are waiting for vfork_done
2539      event, displaced stepping breaks the vfork child similarly as single
2540      step software breakpoint.  */
2541   if (tp->control.trap_expected
2542       && use_displaced_stepping (tp)
2543       && !step_over_info_valid_p ()
2544       && sig == GDB_SIGNAL_0
2545       && !current_inferior ()->waiting_for_vfork_done)
2546     {
2547       int prepared = displaced_step_prepare (inferior_ptid);
2548
2549       if (prepared == 0)
2550         {
2551           if (debug_infrun)
2552             fprintf_unfiltered (gdb_stdlog,
2553                                 "Got placed in step-over queue\n");
2554
2555           tp->control.trap_expected = 0;
2556           return;
2557         }
2558       else if (prepared < 0)
2559         {
2560           /* Fallback to stepping over the breakpoint in-line.  */
2561
2562           if (target_is_non_stop_p ())
2563             stop_all_threads ();
2564
2565           set_step_over_info (regcache->aspace (),
2566                               regcache_read_pc (regcache), 0, tp->global_num);
2567
2568           step = maybe_software_singlestep (gdbarch, pc);
2569
2570           insert_breakpoints ();
2571         }
2572       else if (prepared > 0)
2573         {
2574           struct displaced_step_inferior_state *displaced;
2575
2576           /* Update pc to reflect the new address from which we will
2577              execute instructions due to displaced stepping.  */
2578           pc = regcache_read_pc (get_thread_regcache (inferior_ptid));
2579
2580           displaced = get_displaced_stepping_state (ptid_get_pid (inferior_ptid));
2581           step = gdbarch_displaced_step_hw_singlestep (gdbarch,
2582                                                        displaced->step_closure);
2583         }
2584     }
2585
2586   /* Do we need to do it the hard way, w/temp breakpoints?  */
2587   else if (step)
2588     step = maybe_software_singlestep (gdbarch, pc);
2589
2590   /* Currently, our software single-step implementation leads to different
2591      results than hardware single-stepping in one situation: when stepping
2592      into delivering a signal which has an associated signal handler,
2593      hardware single-step will stop at the first instruction of the handler,
2594      while software single-step will simply skip execution of the handler.
2595
2596      For now, this difference in behavior is accepted since there is no
2597      easy way to actually implement single-stepping into a signal handler
2598      without kernel support.
2599
2600      However, there is one scenario where this difference leads to follow-on
2601      problems: if we're stepping off a breakpoint by removing all breakpoints
2602      and then single-stepping.  In this case, the software single-step
2603      behavior means that even if there is a *breakpoint* in the signal
2604      handler, GDB still would not stop.
2605
2606      Fortunately, we can at least fix this particular issue.  We detect
2607      here the case where we are about to deliver a signal while software
2608      single-stepping with breakpoints removed.  In this situation, we
2609      revert the decisions to remove all breakpoints and insert single-
2610      step breakpoints, and instead we install a step-resume breakpoint
2611      at the current address, deliver the signal without stepping, and
2612      once we arrive back at the step-resume breakpoint, actually step
2613      over the breakpoint we originally wanted to step over.  */
2614   if (thread_has_single_step_breakpoints_set (tp)
2615       && sig != GDB_SIGNAL_0
2616       && step_over_info_valid_p ())
2617     {
2618       /* If we have nested signals or a pending signal is delivered
2619          immediately after a handler returns, might might already have
2620          a step-resume breakpoint set on the earlier handler.  We cannot
2621          set another step-resume breakpoint; just continue on until the
2622          original breakpoint is hit.  */
2623       if (tp->control.step_resume_breakpoint == NULL)
2624         {
2625           insert_hp_step_resume_breakpoint_at_frame (get_current_frame ());
2626           tp->step_after_step_resume_breakpoint = 1;
2627         }
2628
2629       delete_single_step_breakpoints (tp);
2630
2631       clear_step_over_info ();
2632       tp->control.trap_expected = 0;
2633
2634       insert_breakpoints ();
2635     }
2636
2637   /* If STEP is set, it's a request to use hardware stepping
2638      facilities.  But in that case, we should never
2639      use singlestep breakpoint.  */
2640   gdb_assert (!(thread_has_single_step_breakpoints_set (tp) && step));
2641
2642   /* Decide the set of threads to ask the target to resume.  */
2643   if (tp->control.trap_expected)
2644     {
2645       /* We're allowing a thread to run past a breakpoint it has
2646          hit, either by single-stepping the thread with the breakpoint
2647          removed, or by displaced stepping, with the breakpoint inserted.
2648          In the former case, we need to single-step only this thread,
2649          and keep others stopped, as they can miss this breakpoint if
2650          allowed to run.  That's not really a problem for displaced
2651          stepping, but, we still keep other threads stopped, in case
2652          another thread is also stopped for a breakpoint waiting for
2653          its turn in the displaced stepping queue.  */
2654       resume_ptid = inferior_ptid;
2655     }
2656   else
2657     resume_ptid = internal_resume_ptid (user_step);
2658
2659   if (execution_direction != EXEC_REVERSE
2660       && step && breakpoint_inserted_here_p (aspace, pc))
2661     {
2662       /* There are two cases where we currently need to step a
2663          breakpoint instruction when we have a signal to deliver:
2664
2665          - See handle_signal_stop where we handle random signals that
2666          could take out us out of the stepping range.  Normally, in
2667          that case we end up continuing (instead of stepping) over the
2668          signal handler with a breakpoint at PC, but there are cases
2669          where we should _always_ single-step, even if we have a
2670          step-resume breakpoint, like when a software watchpoint is
2671          set.  Assuming single-stepping and delivering a signal at the
2672          same time would takes us to the signal handler, then we could
2673          have removed the breakpoint at PC to step over it.  However,
2674          some hardware step targets (like e.g., Mac OS) can't step
2675          into signal handlers, and for those, we need to leave the
2676          breakpoint at PC inserted, as otherwise if the handler
2677          recurses and executes PC again, it'll miss the breakpoint.
2678          So we leave the breakpoint inserted anyway, but we need to
2679          record that we tried to step a breakpoint instruction, so
2680          that adjust_pc_after_break doesn't end up confused.
2681
2682          - In non-stop if we insert a breakpoint (e.g., a step-resume)
2683          in one thread after another thread that was stepping had been
2684          momentarily paused for a step-over.  When we re-resume the
2685          stepping thread, it may be resumed from that address with a
2686          breakpoint that hasn't trapped yet.  Seen with
2687          gdb.threads/non-stop-fair-events.exp, on targets that don't
2688          do displaced stepping.  */
2689
2690       if (debug_infrun)
2691         fprintf_unfiltered (gdb_stdlog,
2692                             "infrun: resume: [%s] stepped breakpoint\n",
2693                             target_pid_to_str (tp->ptid));
2694
2695       tp->stepped_breakpoint = 1;
2696
2697       /* Most targets can step a breakpoint instruction, thus
2698          executing it normally.  But if this one cannot, just
2699          continue and we will hit it anyway.  */
2700       if (gdbarch_cannot_step_breakpoint (gdbarch))
2701         step = 0;
2702     }
2703
2704   if (debug_displaced
2705       && tp->control.trap_expected
2706       && use_displaced_stepping (tp)
2707       && !step_over_info_valid_p ())
2708     {
2709       struct regcache *resume_regcache = get_thread_regcache (tp->ptid);
2710       struct gdbarch *resume_gdbarch = resume_regcache->arch ();
2711       CORE_ADDR actual_pc = regcache_read_pc (resume_regcache);
2712       gdb_byte buf[4];
2713
2714       fprintf_unfiltered (gdb_stdlog, "displaced: run %s: ",
2715                           paddress (resume_gdbarch, actual_pc));
2716       read_memory (actual_pc, buf, sizeof (buf));
2717       displaced_step_dump_bytes (gdb_stdlog, buf, sizeof (buf));
2718     }
2719
2720   if (tp->control.may_range_step)
2721     {
2722       /* If we're resuming a thread with the PC out of the step
2723          range, then we're doing some nested/finer run control
2724          operation, like stepping the thread out of the dynamic
2725          linker or the displaced stepping scratch pad.  We
2726          shouldn't have allowed a range step then.  */
2727       gdb_assert (pc_in_thread_step_range (pc, tp));
2728     }
2729
2730   do_target_resume (resume_ptid, step, sig);
2731   tp->resumed = 1;
2732 }
2733 \f
2734 /* Proceeding.  */
2735
2736 /* See infrun.h.  */
2737
2738 /* Counter that tracks number of user visible stops.  This can be used
2739    to tell whether a command has proceeded the inferior past the
2740    current location.  This allows e.g., inferior function calls in
2741    breakpoint commands to not interrupt the command list.  When the
2742    call finishes successfully, the inferior is standing at the same
2743    breakpoint as if nothing happened (and so we don't call
2744    normal_stop).  */
2745 static ULONGEST current_stop_id;
2746
2747 /* See infrun.h.  */
2748
2749 ULONGEST
2750 get_stop_id (void)
2751 {
2752   return current_stop_id;
2753 }
2754
2755 /* Called when we report a user visible stop.  */
2756
2757 static void
2758 new_stop_id (void)
2759 {
2760   current_stop_id++;
2761 }
2762
2763 /* Clear out all variables saying what to do when inferior is continued.
2764    First do this, then set the ones you want, then call `proceed'.  */
2765
2766 static void
2767 clear_proceed_status_thread (struct thread_info *tp)
2768 {
2769   if (debug_infrun)
2770     fprintf_unfiltered (gdb_stdlog,
2771                         "infrun: clear_proceed_status_thread (%s)\n",
2772                         target_pid_to_str (tp->ptid));
2773
2774   /* If we're starting a new sequence, then the previous finished
2775      single-step is no longer relevant.  */
2776   if (tp->suspend.waitstatus_pending_p)
2777     {
2778       if (tp->suspend.stop_reason == TARGET_STOPPED_BY_SINGLE_STEP)
2779         {
2780           if (debug_infrun)
2781             fprintf_unfiltered (gdb_stdlog,
2782                                 "infrun: clear_proceed_status: pending "
2783                                 "event of %s was a finished step. "
2784                                 "Discarding.\n",
2785                                 target_pid_to_str (tp->ptid));
2786
2787           tp->suspend.waitstatus_pending_p = 0;
2788           tp->suspend.stop_reason = TARGET_STOPPED_BY_NO_REASON;
2789         }
2790       else if (debug_infrun)
2791         {
2792           std::string statstr
2793             = target_waitstatus_to_string (&tp->suspend.waitstatus);
2794
2795           fprintf_unfiltered (gdb_stdlog,
2796                               "infrun: clear_proceed_status_thread: thread %s "
2797                               "has pending wait status %s "
2798                               "(currently_stepping=%d).\n",
2799                               target_pid_to_str (tp->ptid), statstr.c_str (),
2800                               currently_stepping (tp));
2801         }
2802     }
2803
2804   /* If this signal should not be seen by program, give it zero.
2805      Used for debugging signals.  */
2806   if (!signal_pass_state (tp->suspend.stop_signal))
2807     tp->suspend.stop_signal = GDB_SIGNAL_0;
2808
2809   thread_fsm_delete (tp->thread_fsm);
2810   tp->thread_fsm = NULL;
2811
2812   tp->control.trap_expected = 0;
2813   tp->control.step_range_start = 0;
2814   tp->control.step_range_end = 0;
2815   tp->control.may_range_step = 0;
2816   tp->control.step_frame_id = null_frame_id;
2817   tp->control.step_stack_frame_id = null_frame_id;
2818   tp->control.step_over_calls = STEP_OVER_UNDEBUGGABLE;
2819   tp->control.step_start_function = NULL;
2820   tp->stop_requested = 0;
2821
2822   tp->control.stop_step = 0;
2823
2824   tp->control.proceed_to_finish = 0;
2825
2826   tp->control.stepping_command = 0;
2827
2828   /* Discard any remaining commands or status from previous stop.  */
2829   bpstat_clear (&tp->control.stop_bpstat);
2830 }
2831
2832 void
2833 clear_proceed_status (int step)
2834 {
2835   /* With scheduler-locking replay, stop replaying other threads if we're
2836      not replaying the user-visible resume ptid.
2837
2838      This is a convenience feature to not require the user to explicitly
2839      stop replaying the other threads.  We're assuming that the user's
2840      intent is to resume tracing the recorded process.  */
2841   if (!non_stop && scheduler_mode == schedlock_replay
2842       && target_record_is_replaying (minus_one_ptid)
2843       && !target_record_will_replay (user_visible_resume_ptid (step),
2844                                      execution_direction))
2845     target_record_stop_replaying ();
2846
2847   if (!non_stop)
2848     {
2849       struct thread_info *tp;
2850       ptid_t resume_ptid;
2851
2852       resume_ptid = user_visible_resume_ptid (step);
2853
2854       /* In all-stop mode, delete the per-thread status of all threads
2855          we're about to resume, implicitly and explicitly.  */
2856       ALL_NON_EXITED_THREADS (tp)
2857         {
2858           if (!ptid_match (tp->ptid, resume_ptid))
2859             continue;
2860           clear_proceed_status_thread (tp);
2861         }
2862     }
2863
2864   if (!ptid_equal (inferior_ptid, null_ptid))
2865     {
2866       struct inferior *inferior;
2867
2868       if (non_stop)
2869         {
2870           /* If in non-stop mode, only delete the per-thread status of
2871              the current thread.  */
2872           clear_proceed_status_thread (inferior_thread ());
2873         }
2874
2875       inferior = current_inferior ();
2876       inferior->control.stop_soon = NO_STOP_QUIETLY;
2877     }
2878
2879   observer_notify_about_to_proceed ();
2880 }
2881
2882 /* Returns true if TP is still stopped at a breakpoint that needs
2883    stepping-over in order to make progress.  If the breakpoint is gone
2884    meanwhile, we can skip the whole step-over dance.  */
2885
2886 static int
2887 thread_still_needs_step_over_bp (struct thread_info *tp)
2888 {
2889   if (tp->stepping_over_breakpoint)
2890     {
2891       struct regcache *regcache = get_thread_regcache (tp->ptid);
2892
2893       if (breakpoint_here_p (regcache->aspace (),
2894                              regcache_read_pc (regcache))
2895           == ordinary_breakpoint_here)
2896         return 1;
2897
2898       tp->stepping_over_breakpoint = 0;
2899     }
2900
2901   return 0;
2902 }
2903
2904 /* Check whether thread TP still needs to start a step-over in order
2905    to make progress when resumed.  Returns an bitwise or of enum
2906    step_over_what bits, indicating what needs to be stepped over.  */
2907
2908 static step_over_what
2909 thread_still_needs_step_over (struct thread_info *tp)
2910 {
2911   step_over_what what = 0;
2912
2913   if (thread_still_needs_step_over_bp (tp))
2914     what |= STEP_OVER_BREAKPOINT;
2915
2916   if (tp->stepping_over_watchpoint
2917       && !target_have_steppable_watchpoint)
2918     what |= STEP_OVER_WATCHPOINT;
2919
2920   return what;
2921 }
2922
2923 /* Returns true if scheduler locking applies.  STEP indicates whether
2924    we're about to do a step/next-like command to a thread.  */
2925
2926 static int
2927 schedlock_applies (struct thread_info *tp)
2928 {
2929   return (scheduler_mode == schedlock_on
2930           || (scheduler_mode == schedlock_step
2931               && tp->control.stepping_command)
2932           || (scheduler_mode == schedlock_replay
2933               && target_record_will_replay (minus_one_ptid,
2934                                             execution_direction)));
2935 }
2936
2937 /* Basic routine for continuing the program in various fashions.
2938
2939    ADDR is the address to resume at, or -1 for resume where stopped.
2940    SIGGNAL is the signal to give it, or 0 for none,
2941    or -1 for act according to how it stopped.
2942    STEP is nonzero if should trap after one instruction.
2943    -1 means return after that and print nothing.
2944    You should probably set various step_... variables
2945    before calling here, if you are stepping.
2946
2947    You should call clear_proceed_status before calling proceed.  */
2948
2949 void
2950 proceed (CORE_ADDR addr, enum gdb_signal siggnal)
2951 {
2952   struct regcache *regcache;
2953   struct gdbarch *gdbarch;
2954   struct thread_info *tp;
2955   CORE_ADDR pc;
2956   ptid_t resume_ptid;
2957   struct execution_control_state ecss;
2958   struct execution_control_state *ecs = &ecss;
2959   struct cleanup *old_chain;
2960   int started;
2961
2962   /* If we're stopped at a fork/vfork, follow the branch set by the
2963      "set follow-fork-mode" command; otherwise, we'll just proceed
2964      resuming the current thread.  */
2965   if (!follow_fork ())
2966     {
2967       /* The target for some reason decided not to resume.  */
2968       normal_stop ();
2969       if (target_can_async_p ())
2970         inferior_event_handler (INF_EXEC_COMPLETE, NULL);
2971       return;
2972     }
2973
2974   /* We'll update this if & when we switch to a new thread.  */
2975   previous_inferior_ptid = inferior_ptid;
2976
2977   regcache = get_current_regcache ();
2978   gdbarch = regcache->arch ();
2979   const address_space *aspace = regcache->aspace ();
2980
2981   pc = regcache_read_pc (regcache);
2982   tp = inferior_thread ();
2983
2984   /* Fill in with reasonable starting values.  */
2985   init_thread_stepping_state (tp);
2986
2987   gdb_assert (!thread_is_in_step_over_chain (tp));
2988
2989   if (addr == (CORE_ADDR) -1)
2990     {
2991       if (pc == stop_pc
2992           && breakpoint_here_p (aspace, pc) == ordinary_breakpoint_here
2993           && execution_direction != EXEC_REVERSE)
2994         /* There is a breakpoint at the address we will resume at,
2995            step one instruction before inserting breakpoints so that
2996            we do not stop right away (and report a second hit at this
2997            breakpoint).
2998
2999            Note, we don't do this in reverse, because we won't
3000            actually be executing the breakpoint insn anyway.
3001            We'll be (un-)executing the previous instruction.  */
3002         tp->stepping_over_breakpoint = 1;
3003       else if (gdbarch_single_step_through_delay_p (gdbarch)
3004                && gdbarch_single_step_through_delay (gdbarch,
3005                                                      get_current_frame ()))
3006         /* We stepped onto an instruction that needs to be stepped
3007            again before re-inserting the breakpoint, do so.  */
3008         tp->stepping_over_breakpoint = 1;
3009     }
3010   else
3011     {
3012       regcache_write_pc (regcache, addr);
3013     }
3014
3015   if (siggnal != GDB_SIGNAL_DEFAULT)
3016     tp->suspend.stop_signal = siggnal;
3017
3018   resume_ptid = user_visible_resume_ptid (tp->control.stepping_command);
3019
3020   /* If an exception is thrown from this point on, make sure to
3021      propagate GDB's knowledge of the executing state to the
3022      frontend/user running state.  */
3023   old_chain = make_cleanup (finish_thread_state_cleanup, &resume_ptid);
3024
3025   /* Even if RESUME_PTID is a wildcard, and we end up resuming fewer
3026      threads (e.g., we might need to set threads stepping over
3027      breakpoints first), from the user/frontend's point of view, all
3028      threads in RESUME_PTID are now running.  Unless we're calling an
3029      inferior function, as in that case we pretend the inferior
3030      doesn't run at all.  */
3031   if (!tp->control.in_infcall)
3032    set_running (resume_ptid, 1);
3033
3034   if (debug_infrun)
3035     fprintf_unfiltered (gdb_stdlog,
3036                         "infrun: proceed (addr=%s, signal=%s)\n",
3037                         paddress (gdbarch, addr),
3038                         gdb_signal_to_symbol_string (siggnal));
3039
3040   annotate_starting ();
3041
3042   /* Make sure that output from GDB appears before output from the
3043      inferior.  */
3044   gdb_flush (gdb_stdout);
3045
3046   /* Since we've marked the inferior running, give it the terminal.  A
3047      QUIT/Ctrl-C from here on is forwarded to the target (which can
3048      still detect attempts to unblock a stuck connection with repeated
3049      Ctrl-C from within target_pass_ctrlc).  */
3050   target_terminal::inferior ();
3051
3052   /* In a multi-threaded task we may select another thread and
3053      then continue or step.
3054
3055      But if a thread that we're resuming had stopped at a breakpoint,
3056      it will immediately cause another breakpoint stop without any
3057      execution (i.e. it will report a breakpoint hit incorrectly).  So
3058      we must step over it first.
3059
3060      Look for threads other than the current (TP) that reported a
3061      breakpoint hit and haven't been resumed yet since.  */
3062
3063   /* If scheduler locking applies, we can avoid iterating over all
3064      threads.  */
3065   if (!non_stop && !schedlock_applies (tp))
3066     {
3067       struct thread_info *current = tp;
3068
3069       ALL_NON_EXITED_THREADS (tp)
3070         {
3071           /* Ignore the current thread here.  It's handled
3072              afterwards.  */
3073           if (tp == current)
3074             continue;
3075
3076           /* Ignore threads of processes we're not resuming.  */
3077           if (!ptid_match (tp->ptid, resume_ptid))
3078             continue;
3079
3080           if (!thread_still_needs_step_over (tp))
3081             continue;
3082
3083           gdb_assert (!thread_is_in_step_over_chain (tp));
3084
3085           if (debug_infrun)
3086             fprintf_unfiltered (gdb_stdlog,
3087                                 "infrun: need to step-over [%s] first\n",
3088                                 target_pid_to_str (tp->ptid));
3089
3090           thread_step_over_chain_enqueue (tp);
3091         }
3092
3093       tp = current;
3094     }
3095
3096   /* Enqueue the current thread last, so that we move all other
3097      threads over their breakpoints first.  */
3098   if (tp->stepping_over_breakpoint)
3099     thread_step_over_chain_enqueue (tp);
3100
3101   /* If the thread isn't started, we'll still need to set its prev_pc,
3102      so that switch_back_to_stepped_thread knows the thread hasn't
3103      advanced.  Must do this before resuming any thread, as in
3104      all-stop/remote, once we resume we can't send any other packet
3105      until the target stops again.  */
3106   tp->prev_pc = regcache_read_pc (regcache);
3107
3108   {
3109     scoped_restore save_defer_tc = make_scoped_defer_target_commit_resume ();
3110
3111     started = start_step_over ();
3112
3113     if (step_over_info_valid_p ())
3114       {
3115         /* Either this thread started a new in-line step over, or some
3116            other thread was already doing one.  In either case, don't
3117            resume anything else until the step-over is finished.  */
3118       }
3119     else if (started && !target_is_non_stop_p ())
3120       {
3121         /* A new displaced stepping sequence was started.  In all-stop,
3122            we can't talk to the target anymore until it next stops.  */
3123       }
3124     else if (!non_stop && target_is_non_stop_p ())
3125       {
3126         /* In all-stop, but the target is always in non-stop mode.
3127            Start all other threads that are implicitly resumed too.  */
3128         ALL_NON_EXITED_THREADS (tp)
3129         {
3130           /* Ignore threads of processes we're not resuming.  */
3131           if (!ptid_match (tp->ptid, resume_ptid))
3132             continue;
3133
3134           if (tp->resumed)
3135             {
3136               if (debug_infrun)
3137                 fprintf_unfiltered (gdb_stdlog,
3138                                     "infrun: proceed: [%s] resumed\n",
3139                                     target_pid_to_str (tp->ptid));
3140               gdb_assert (tp->executing || tp->suspend.waitstatus_pending_p);
3141               continue;
3142             }
3143
3144           if (thread_is_in_step_over_chain (tp))
3145             {
3146               if (debug_infrun)
3147                 fprintf_unfiltered (gdb_stdlog,
3148                                     "infrun: proceed: [%s] needs step-over\n",
3149                                     target_pid_to_str (tp->ptid));
3150               continue;
3151             }
3152
3153           if (debug_infrun)
3154             fprintf_unfiltered (gdb_stdlog,
3155                                 "infrun: proceed: resuming %s\n",
3156                                 target_pid_to_str (tp->ptid));
3157
3158           reset_ecs (ecs, tp);
3159           switch_to_thread (tp->ptid);
3160           keep_going_pass_signal (ecs);
3161           if (!ecs->wait_some_more)
3162             error (_("Command aborted."));
3163         }
3164       }
3165     else if (!tp->resumed && !thread_is_in_step_over_chain (tp))
3166       {
3167         /* The thread wasn't started, and isn't queued, run it now.  */
3168         reset_ecs (ecs, tp);
3169         switch_to_thread (tp->ptid);
3170         keep_going_pass_signal (ecs);
3171         if (!ecs->wait_some_more)
3172           error (_("Command aborted."));
3173       }
3174   }
3175
3176   target_commit_resume ();
3177
3178   discard_cleanups (old_chain);
3179
3180   /* Tell the event loop to wait for it to stop.  If the target
3181      supports asynchronous execution, it'll do this from within
3182      target_resume.  */
3183   if (!target_can_async_p ())
3184     mark_async_event_handler (infrun_async_inferior_event_token);
3185 }
3186 \f
3187
3188 /* Start remote-debugging of a machine over a serial link.  */
3189
3190 void
3191 start_remote (int from_tty)
3192 {
3193   struct inferior *inferior;
3194
3195   inferior = current_inferior ();
3196   inferior->control.stop_soon = STOP_QUIETLY_REMOTE;
3197
3198   /* Always go on waiting for the target, regardless of the mode.  */
3199   /* FIXME: cagney/1999-09-23: At present it isn't possible to
3200      indicate to wait_for_inferior that a target should timeout if
3201      nothing is returned (instead of just blocking).  Because of this,
3202      targets expecting an immediate response need to, internally, set
3203      things up so that the target_wait() is forced to eventually
3204      timeout.  */
3205   /* FIXME: cagney/1999-09-24: It isn't possible for target_open() to
3206      differentiate to its caller what the state of the target is after
3207      the initial open has been performed.  Here we're assuming that
3208      the target has stopped.  It should be possible to eventually have
3209      target_open() return to the caller an indication that the target
3210      is currently running and GDB state should be set to the same as
3211      for an async run.  */
3212   wait_for_inferior ();
3213
3214   /* Now that the inferior has stopped, do any bookkeeping like
3215      loading shared libraries.  We want to do this before normal_stop,
3216      so that the displayed frame is up to date.  */
3217   post_create_inferior (&current_target, from_tty);
3218
3219   normal_stop ();
3220 }
3221
3222 /* Initialize static vars when a new inferior begins.  */
3223
3224 void
3225 init_wait_for_inferior (void)
3226 {
3227   /* These are meaningless until the first time through wait_for_inferior.  */
3228
3229   breakpoint_init_inferior (inf_starting);
3230
3231   clear_proceed_status (0);
3232
3233   target_last_wait_ptid = minus_one_ptid;
3234
3235   previous_inferior_ptid = inferior_ptid;
3236
3237   /* Discard any skipped inlined frames.  */
3238   clear_inline_frame_state (minus_one_ptid);
3239 }
3240
3241 \f
3242
3243 static void handle_inferior_event (struct execution_control_state *ecs);
3244
3245 static void handle_step_into_function (struct gdbarch *gdbarch,
3246                                        struct execution_control_state *ecs);
3247 static void handle_step_into_function_backward (struct gdbarch *gdbarch,
3248                                                 struct execution_control_state *ecs);
3249 static void handle_signal_stop (struct execution_control_state *ecs);
3250 static void check_exception_resume (struct execution_control_state *,
3251                                     struct frame_info *);
3252
3253 static void end_stepping_range (struct execution_control_state *ecs);
3254 static void stop_waiting (struct execution_control_state *ecs);
3255 static void keep_going (struct execution_control_state *ecs);
3256 static void process_event_stop_test (struct execution_control_state *ecs);
3257 static int switch_back_to_stepped_thread (struct execution_control_state *ecs);
3258
3259 /* This function is attached as a "thread_stop_requested" observer.
3260    Cleanup local state that assumed the PTID was to be resumed, and
3261    report the stop to the frontend.  */
3262
3263 static void
3264 infrun_thread_stop_requested (ptid_t ptid)
3265 {
3266   struct thread_info *tp;
3267
3268   /* PTID was requested to stop.  If the thread was already stopped,
3269      but the user/frontend doesn't know about that yet (e.g., the
3270      thread had been temporarily paused for some step-over), set up
3271      for reporting the stop now.  */
3272   ALL_NON_EXITED_THREADS (tp)
3273     if (ptid_match (tp->ptid, ptid))
3274       {
3275         if (tp->state != THREAD_RUNNING)
3276           continue;
3277         if (tp->executing)
3278           continue;
3279
3280         /* Remove matching threads from the step-over queue, so
3281            start_step_over doesn't try to resume them
3282            automatically.  */
3283         if (thread_is_in_step_over_chain (tp))
3284           thread_step_over_chain_remove (tp);
3285
3286         /* If the thread is stopped, but the user/frontend doesn't
3287            know about that yet, queue a pending event, as if the
3288            thread had just stopped now.  Unless the thread already had
3289            a pending event.  */
3290         if (!tp->suspend.waitstatus_pending_p)
3291           {
3292             tp->suspend.waitstatus_pending_p = 1;
3293             tp->suspend.waitstatus.kind = TARGET_WAITKIND_STOPPED;
3294             tp->suspend.waitstatus.value.sig = GDB_SIGNAL_0;
3295           }
3296
3297         /* Clear the inline-frame state, since we're re-processing the
3298            stop.  */
3299         clear_inline_frame_state (tp->ptid);
3300
3301         /* If this thread was paused because some other thread was
3302            doing an inline-step over, let that finish first.  Once
3303            that happens, we'll restart all threads and consume pending
3304            stop events then.  */
3305         if (step_over_info_valid_p ())
3306           continue;
3307
3308         /* Otherwise we can process the (new) pending event now.  Set
3309            it so this pending event is considered by
3310            do_target_wait.  */
3311         tp->resumed = 1;
3312       }
3313 }
3314
3315 static void
3316 infrun_thread_thread_exit (struct thread_info *tp, int silent)
3317 {
3318   if (ptid_equal (target_last_wait_ptid, tp->ptid))
3319     nullify_last_target_wait_ptid ();
3320 }
3321
3322 /* Delete the step resume, single-step and longjmp/exception resume
3323    breakpoints of TP.  */
3324
3325 static void
3326 delete_thread_infrun_breakpoints (struct thread_info *tp)
3327 {
3328   delete_step_resume_breakpoint (tp);
3329   delete_exception_resume_breakpoint (tp);
3330   delete_single_step_breakpoints (tp);
3331 }
3332
3333 /* If the target still has execution, call FUNC for each thread that
3334    just stopped.  In all-stop, that's all the non-exited threads; in
3335    non-stop, that's the current thread, only.  */
3336
3337 typedef void (*for_each_just_stopped_thread_callback_func)
3338   (struct thread_info *tp);
3339
3340 static void
3341 for_each_just_stopped_thread (for_each_just_stopped_thread_callback_func func)
3342 {
3343   if (!target_has_execution || ptid_equal (inferior_ptid, null_ptid))
3344     return;
3345
3346   if (target_is_non_stop_p ())
3347     {
3348       /* If in non-stop mode, only the current thread stopped.  */
3349       func (inferior_thread ());
3350     }
3351   else
3352     {
3353       struct thread_info *tp;
3354
3355       /* In all-stop mode, all threads have stopped.  */
3356       ALL_NON_EXITED_THREADS (tp)
3357         {
3358           func (tp);
3359         }
3360     }
3361 }
3362
3363 /* Delete the step resume and longjmp/exception resume breakpoints of
3364    the threads that just stopped.  */
3365
3366 static void
3367 delete_just_stopped_threads_infrun_breakpoints (void)
3368 {
3369   for_each_just_stopped_thread (delete_thread_infrun_breakpoints);
3370 }
3371
3372 /* Delete the single-step breakpoints of the threads that just
3373    stopped.  */
3374
3375 static void
3376 delete_just_stopped_threads_single_step_breakpoints (void)
3377 {
3378   for_each_just_stopped_thread (delete_single_step_breakpoints);
3379 }
3380
3381 /* A cleanup wrapper.  */
3382
3383 static void
3384 delete_just_stopped_threads_infrun_breakpoints_cleanup (void *arg)
3385 {
3386   delete_just_stopped_threads_infrun_breakpoints ();
3387 }
3388
3389 /* See infrun.h.  */
3390
3391 void
3392 print_target_wait_results (ptid_t waiton_ptid, ptid_t result_ptid,
3393                            const struct target_waitstatus *ws)
3394 {
3395   std::string status_string = target_waitstatus_to_string (ws);
3396   string_file stb;
3397
3398   /* The text is split over several lines because it was getting too long.
3399      Call fprintf_unfiltered (gdb_stdlog) once so that the text is still
3400      output as a unit; we want only one timestamp printed if debug_timestamp
3401      is set.  */
3402
3403   stb.printf ("infrun: target_wait (%d.%ld.%ld",
3404               ptid_get_pid (waiton_ptid),
3405               ptid_get_lwp (waiton_ptid),
3406               ptid_get_tid (waiton_ptid));
3407   if (ptid_get_pid (waiton_ptid) != -1)
3408     stb.printf (" [%s]", target_pid_to_str (waiton_ptid));
3409   stb.printf (", status) =\n");
3410   stb.printf ("infrun:   %d.%ld.%ld [%s],\n",
3411               ptid_get_pid (result_ptid),
3412               ptid_get_lwp (result_ptid),
3413               ptid_get_tid (result_ptid),
3414               target_pid_to_str (result_ptid));
3415   stb.printf ("infrun:   %s\n", status_string.c_str ());
3416
3417   /* This uses %s in part to handle %'s in the text, but also to avoid
3418      a gcc error: the format attribute requires a string literal.  */
3419   fprintf_unfiltered (gdb_stdlog, "%s", stb.c_str ());
3420 }
3421
3422 /* Select a thread at random, out of those which are resumed and have
3423    had events.  */
3424
3425 static struct thread_info *
3426 random_pending_event_thread (ptid_t waiton_ptid)
3427 {
3428   struct thread_info *event_tp;
3429   int num_events = 0;
3430   int random_selector;
3431
3432   /* First see how many events we have.  Count only resumed threads
3433      that have an event pending.  */
3434   ALL_NON_EXITED_THREADS (event_tp)
3435     if (ptid_match (event_tp->ptid, waiton_ptid)
3436         && event_tp->resumed
3437         && event_tp->suspend.waitstatus_pending_p)
3438       num_events++;
3439
3440   if (num_events == 0)
3441     return NULL;
3442
3443   /* Now randomly pick a thread out of those that have had events.  */
3444   random_selector = (int)
3445     ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
3446
3447   if (debug_infrun && num_events > 1)
3448     fprintf_unfiltered (gdb_stdlog,
3449                         "infrun: Found %d events, selecting #%d\n",
3450                         num_events, random_selector);
3451
3452   /* Select the Nth thread that has had an event.  */
3453   ALL_NON_EXITED_THREADS (event_tp)
3454     if (ptid_match (event_tp->ptid, waiton_ptid)
3455         && event_tp->resumed
3456         && event_tp->suspend.waitstatus_pending_p)
3457       if (random_selector-- == 0)
3458         break;
3459
3460   return event_tp;
3461 }
3462
3463 /* Wrapper for target_wait that first checks whether threads have
3464    pending statuses to report before actually asking the target for
3465    more events.  */
3466
3467 static ptid_t
3468 do_target_wait (ptid_t ptid, struct target_waitstatus *status, int options)
3469 {
3470   ptid_t event_ptid;
3471   struct thread_info *tp;
3472
3473   /* First check if there is a resumed thread with a wait status
3474      pending.  */
3475   if (ptid_equal (ptid, minus_one_ptid) || ptid_is_pid (ptid))
3476     {
3477       tp = random_pending_event_thread (ptid);
3478     }
3479   else
3480     {
3481       if (debug_infrun)
3482         fprintf_unfiltered (gdb_stdlog,
3483                             "infrun: Waiting for specific thread %s.\n",
3484                             target_pid_to_str (ptid));
3485
3486       /* We have a specific thread to check.  */
3487       tp = find_thread_ptid (ptid);
3488       gdb_assert (tp != NULL);
3489       if (!tp->suspend.waitstatus_pending_p)
3490         tp = NULL;
3491     }
3492
3493   if (tp != NULL
3494       && (tp->suspend.stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3495           || tp->suspend.stop_reason == TARGET_STOPPED_BY_HW_BREAKPOINT))
3496     {
3497       struct regcache *regcache = get_thread_regcache (tp->ptid);
3498       struct gdbarch *gdbarch = regcache->arch ();
3499       CORE_ADDR pc;
3500       int discard = 0;
3501
3502       pc = regcache_read_pc (regcache);
3503
3504       if (pc != tp->suspend.stop_pc)
3505         {
3506           if (debug_infrun)
3507             fprintf_unfiltered (gdb_stdlog,
3508                                 "infrun: PC of %s changed.  was=%s, now=%s\n",
3509                                 target_pid_to_str (tp->ptid),
3510                                 paddress (gdbarch, tp->prev_pc),
3511                                 paddress (gdbarch, pc));
3512           discard = 1;
3513         }
3514       else if (!breakpoint_inserted_here_p (regcache->aspace (), pc))
3515         {
3516           if (debug_infrun)
3517             fprintf_unfiltered (gdb_stdlog,
3518                                 "infrun: previous breakpoint of %s, at %s gone\n",
3519                                 target_pid_to_str (tp->ptid),
3520                                 paddress (gdbarch, pc));
3521
3522           discard = 1;
3523         }
3524
3525       if (discard)
3526         {
3527           if (debug_infrun)
3528             fprintf_unfiltered (gdb_stdlog,
3529                                 "infrun: pending event of %s cancelled.\n",
3530                                 target_pid_to_str (tp->ptid));
3531
3532           tp->suspend.waitstatus.kind = TARGET_WAITKIND_SPURIOUS;
3533           tp->suspend.stop_reason = TARGET_STOPPED_BY_NO_REASON;
3534         }
3535     }
3536
3537   if (tp != NULL)
3538     {
3539       if (debug_infrun)
3540         {
3541           std::string statstr
3542             = target_waitstatus_to_string (&tp->suspend.waitstatus);
3543
3544           fprintf_unfiltered (gdb_stdlog,
3545                               "infrun: Using pending wait status %s for %s.\n",
3546                               statstr.c_str (),
3547                               target_pid_to_str (tp->ptid));
3548         }
3549
3550       /* Now that we've selected our final event LWP, un-adjust its PC
3551          if it was a software breakpoint (and the target doesn't
3552          always adjust the PC itself).  */
3553       if (tp->suspend.stop_reason == TARGET_STOPPED_BY_SW_BREAKPOINT
3554           && !target_supports_stopped_by_sw_breakpoint ())
3555         {
3556           struct regcache *regcache;
3557           struct gdbarch *gdbarch;
3558           int decr_pc;
3559
3560           regcache = get_thread_regcache (tp->ptid);
3561           gdbarch = regcache->arch ();
3562
3563           decr_pc = gdbarch_decr_pc_after_break (gdbarch);
3564           if (decr_pc != 0)
3565             {
3566               CORE_ADDR pc;
3567
3568               pc = regcache_read_pc (regcache);
3569               regcache_write_pc (regcache, pc + decr_pc);
3570             }
3571         }
3572
3573       tp->suspend.stop_reason = TARGET_STOPPED_BY_NO_REASON;
3574       *status = tp->suspend.waitstatus;
3575       tp->suspend.waitstatus_pending_p = 0;
3576
3577       /* Wake up the event loop again, until all pending events are
3578          processed.  */
3579       if (target_is_async_p ())
3580         mark_async_event_handler (infrun_async_inferior_event_token);
3581       return tp->ptid;
3582     }
3583
3584   /* But if we don't find one, we'll have to wait.  */
3585
3586   if (deprecated_target_wait_hook)
3587     event_ptid = deprecated_target_wait_hook (ptid, status, options);
3588   else
3589     event_ptid = target_wait (ptid, status, options);
3590
3591   return event_ptid;
3592 }
3593
3594 /* Prepare and stabilize the inferior for detaching it.  E.g.,
3595    detaching while a thread is displaced stepping is a recipe for
3596    crashing it, as nothing would readjust the PC out of the scratch
3597    pad.  */
3598
3599 void
3600 prepare_for_detach (void)
3601 {
3602   struct inferior *inf = current_inferior ();
3603   ptid_t pid_ptid = pid_to_ptid (inf->pid);
3604   struct displaced_step_inferior_state *displaced;
3605
3606   displaced = get_displaced_stepping_state (inf->pid);
3607
3608   /* Is any thread of this process displaced stepping?  If not,
3609      there's nothing else to do.  */
3610   if (displaced == NULL || ptid_equal (displaced->step_ptid, null_ptid))
3611     return;
3612
3613   if (debug_infrun)
3614     fprintf_unfiltered (gdb_stdlog,
3615                         "displaced-stepping in-process while detaching");
3616
3617   scoped_restore restore_detaching = make_scoped_restore (&inf->detaching, true);
3618
3619   while (!ptid_equal (displaced->step_ptid, null_ptid))
3620     {
3621       struct cleanup *old_chain_2;
3622       struct execution_control_state ecss;
3623       struct execution_control_state *ecs;
3624
3625       ecs = &ecss;
3626       memset (ecs, 0, sizeof (*ecs));
3627
3628       overlay_cache_invalid = 1;
3629       /* Flush target cache before starting to handle each event.
3630          Target was running and cache could be stale.  This is just a
3631          heuristic.  Running threads may modify target memory, but we
3632          don't get any event.  */
3633       target_dcache_invalidate ();
3634
3635       ecs->ptid = do_target_wait (pid_ptid, &ecs->ws, 0);
3636
3637       if (debug_infrun)
3638         print_target_wait_results (pid_ptid, ecs->ptid, &ecs->ws);
3639
3640       /* If an error happens while handling the event, propagate GDB's
3641          knowledge of the executing state to the frontend/user running
3642          state.  */
3643       old_chain_2 = make_cleanup (finish_thread_state_cleanup,
3644                                   &minus_one_ptid);
3645
3646       /* Now figure out what to do with the result of the result.  */
3647       handle_inferior_event (ecs);
3648
3649       /* No error, don't finish the state yet.  */
3650       discard_cleanups (old_chain_2);
3651
3652       /* Breakpoints and watchpoints are not installed on the target
3653          at this point, and signals are passed directly to the
3654          inferior, so this must mean the process is gone.  */
3655       if (!ecs->wait_some_more)
3656         {
3657           restore_detaching.release ();
3658           error (_("Program exited while detaching"));
3659         }
3660     }
3661
3662   restore_detaching.release ();
3663 }
3664
3665 /* Wait for control to return from inferior to debugger.
3666
3667    If inferior gets a signal, we may decide to start it up again
3668    instead of returning.  That is why there is a loop in this function.
3669    When this function actually returns it means the inferior
3670    should be left stopped and GDB should read more commands.  */
3671
3672 void
3673 wait_for_inferior (void)
3674 {
3675   struct cleanup *old_cleanups;
3676   struct cleanup *thread_state_chain;
3677
3678   if (debug_infrun)
3679     fprintf_unfiltered
3680       (gdb_stdlog, "infrun: wait_for_inferior ()\n");
3681
3682   old_cleanups
3683     = make_cleanup (delete_just_stopped_threads_infrun_breakpoints_cleanup,
3684                     NULL);
3685
3686   /* If an error happens while handling the event, propagate GDB's
3687      knowledge of the executing state to the frontend/user running
3688      state.  */
3689   thread_state_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
3690
3691   while (1)
3692     {
3693       struct execution_control_state ecss;
3694       struct execution_control_state *ecs = &ecss;
3695       ptid_t waiton_ptid = minus_one_ptid;
3696
3697       memset (ecs, 0, sizeof (*ecs));
3698
3699       overlay_cache_invalid = 1;
3700
3701       /* Flush target cache before starting to handle each event.
3702          Target was running and cache could be stale.  This is just a
3703          heuristic.  Running threads may modify target memory, but we
3704          don't get any event.  */
3705       target_dcache_invalidate ();
3706
3707       ecs->ptid = do_target_wait (waiton_ptid, &ecs->ws, 0);
3708
3709       if (debug_infrun)
3710         print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
3711
3712       /* Now figure out what to do with the result of the result.  */
3713       handle_inferior_event (ecs);
3714
3715       if (!ecs->wait_some_more)
3716         break;
3717     }
3718
3719   /* No error, don't finish the state yet.  */
3720   discard_cleanups (thread_state_chain);
3721
3722   do_cleanups (old_cleanups);
3723 }
3724
3725 /* Cleanup that reinstalls the readline callback handler, if the
3726    target is running in the background.  If while handling the target
3727    event something triggered a secondary prompt, like e.g., a
3728    pagination prompt, we'll have removed the callback handler (see
3729    gdb_readline_wrapper_line).  Need to do this as we go back to the
3730    event loop, ready to process further input.  Note this has no
3731    effect if the handler hasn't actually been removed, because calling
3732    rl_callback_handler_install resets the line buffer, thus losing
3733    input.  */
3734
3735 static void
3736 reinstall_readline_callback_handler_cleanup (void *arg)
3737 {
3738   struct ui *ui = current_ui;
3739
3740   if (!ui->async)
3741     {
3742       /* We're not going back to the top level event loop yet.  Don't
3743          install the readline callback, as it'd prep the terminal,
3744          readline-style (raw, noecho) (e.g., --batch).  We'll install
3745          it the next time the prompt is displayed, when we're ready
3746          for input.  */
3747       return;
3748     }
3749
3750   if (ui->command_editing && ui->prompt_state != PROMPT_BLOCKED)
3751     gdb_rl_callback_handler_reinstall ();
3752 }
3753
3754 /* Clean up the FSMs of threads that are now stopped.  In non-stop,
3755    that's just the event thread.  In all-stop, that's all threads.  */
3756
3757 static void
3758 clean_up_just_stopped_threads_fsms (struct execution_control_state *ecs)
3759 {
3760   struct thread_info *thr = ecs->event_thread;
3761
3762   if (thr != NULL && thr->thread_fsm != NULL)
3763     thread_fsm_clean_up (thr->thread_fsm, thr);
3764
3765   if (!non_stop)
3766     {
3767       ALL_NON_EXITED_THREADS (thr)
3768         {
3769           if (thr->thread_fsm == NULL)
3770             continue;
3771           if (thr == ecs->event_thread)
3772             continue;
3773
3774           switch_to_thread (thr->ptid);
3775           thread_fsm_clean_up (thr->thread_fsm, thr);
3776         }
3777
3778       if (ecs->event_thread != NULL)
3779         switch_to_thread (ecs->event_thread->ptid);
3780     }
3781 }
3782
3783 /* Helper for all_uis_check_sync_execution_done that works on the
3784    current UI.  */
3785
3786 static void
3787 check_curr_ui_sync_execution_done (void)
3788 {
3789   struct ui *ui = current_ui;
3790
3791   if (ui->prompt_state == PROMPT_NEEDED
3792       && ui->async
3793       && !gdb_in_secondary_prompt_p (ui))
3794     {
3795       target_terminal::ours ();
3796       observer_notify_sync_execution_done ();
3797       ui_register_input_event_handler (ui);
3798     }
3799 }
3800
3801 /* See infrun.h.  */
3802
3803 void
3804 all_uis_check_sync_execution_done (void)
3805 {
3806   SWITCH_THRU_ALL_UIS ()
3807     {
3808       check_curr_ui_sync_execution_done ();
3809     }
3810 }
3811
3812 /* See infrun.h.  */
3813
3814 void
3815 all_uis_on_sync_execution_starting (void)
3816 {
3817   SWITCH_THRU_ALL_UIS ()
3818     {
3819       if (current_ui->prompt_state == PROMPT_NEEDED)
3820         async_disable_stdin ();
3821     }
3822 }
3823
3824 /* Asynchronous version of wait_for_inferior.  It is called by the
3825    event loop whenever a change of state is detected on the file
3826    descriptor corresponding to the target.  It can be called more than
3827    once to complete a single execution command.  In such cases we need
3828    to keep the state in a global variable ECSS.  If it is the last time
3829    that this function is called for a single execution command, then
3830    report to the user that the inferior has stopped, and do the
3831    necessary cleanups.  */
3832
3833 void
3834 fetch_inferior_event (void *client_data)
3835 {
3836   struct execution_control_state ecss;
3837   struct execution_control_state *ecs = &ecss;
3838   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
3839   struct cleanup *ts_old_chain;
3840   int cmd_done = 0;
3841   ptid_t waiton_ptid = minus_one_ptid;
3842
3843   memset (ecs, 0, sizeof (*ecs));
3844
3845   /* Events are always processed with the main UI as current UI.  This
3846      way, warnings, debug output, etc. are always consistently sent to
3847      the main console.  */
3848   scoped_restore save_ui = make_scoped_restore (&current_ui, main_ui);
3849
3850   /* End up with readline processing input, if necessary.  */
3851   make_cleanup (reinstall_readline_callback_handler_cleanup, NULL);
3852
3853   /* We're handling a live event, so make sure we're doing live
3854      debugging.  If we're looking at traceframes while the target is
3855      running, we're going to need to get back to that mode after
3856      handling the event.  */
3857   if (non_stop)
3858     {
3859       make_cleanup_restore_current_traceframe ();
3860       set_current_traceframe (-1);
3861     }
3862
3863   gdb::optional<scoped_restore_current_thread> maybe_restore_thread;
3864
3865   if (non_stop)
3866     /* In non-stop mode, the user/frontend should not notice a thread
3867        switch due to internal events.  Make sure we reverse to the
3868        user selected thread and frame after handling the event and
3869        running any breakpoint commands.  */
3870     maybe_restore_thread.emplace ();
3871
3872   overlay_cache_invalid = 1;
3873   /* Flush target cache before starting to handle each event.  Target
3874      was running and cache could be stale.  This is just a heuristic.
3875      Running threads may modify target memory, but we don't get any
3876      event.  */
3877   target_dcache_invalidate ();
3878
3879   scoped_restore save_exec_dir
3880     = make_scoped_restore (&execution_direction, target_execution_direction ());
3881
3882   ecs->ptid = do_target_wait (waiton_ptid, &ecs->ws,
3883                               target_can_async_p () ? TARGET_WNOHANG : 0);
3884
3885   if (debug_infrun)
3886     print_target_wait_results (waiton_ptid, ecs->ptid, &ecs->ws);
3887
3888   /* If an error happens while handling the event, propagate GDB's
3889      knowledge of the executing state to the frontend/user running
3890      state.  */
3891   if (!target_is_non_stop_p ())
3892     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
3893   else
3894     ts_old_chain = make_cleanup (finish_thread_state_cleanup, &ecs->ptid);
3895
3896   /* Get executed before make_cleanup_restore_current_thread above to apply
3897      still for the thread which has thrown the exception.  */
3898   make_bpstat_clear_actions_cleanup ();
3899
3900   make_cleanup (delete_just_stopped_threads_infrun_breakpoints_cleanup, NULL);
3901
3902   /* Now figure out what to do with the result of the result.  */
3903   handle_inferior_event (ecs);
3904
3905   if (!ecs->wait_some_more)
3906     {
3907       struct inferior *inf = find_inferior_ptid (ecs->ptid);
3908       int should_stop = 1;
3909       struct thread_info *thr = ecs->event_thread;
3910       int should_notify_stop = 1;
3911
3912       delete_just_stopped_threads_infrun_breakpoints ();
3913
3914       if (thr != NULL)
3915         {
3916           struct thread_fsm *thread_fsm = thr->thread_fsm;
3917
3918           if (thread_fsm != NULL)
3919             should_stop = thread_fsm_should_stop (thread_fsm, thr);
3920         }
3921
3922       if (!should_stop)
3923         {
3924           keep_going (ecs);
3925         }
3926       else
3927         {
3928           clean_up_just_stopped_threads_fsms (ecs);
3929
3930           if (thr != NULL && thr->thread_fsm != NULL)
3931             {
3932               should_notify_stop
3933                 = thread_fsm_should_notify_stop (thr->thread_fsm);
3934             }
3935
3936           if (should_notify_stop)
3937             {
3938               int proceeded = 0;
3939
3940               /* We may not find an inferior if this was a process exit.  */
3941               if (inf == NULL || inf->control.stop_soon == NO_STOP_QUIETLY)
3942                 proceeded = normal_stop ();
3943
3944               if (!proceeded)
3945                 {
3946                   inferior_event_handler (INF_EXEC_COMPLETE, NULL);
3947                   cmd_done = 1;
3948                 }
3949             }
3950         }
3951     }
3952
3953   /* No error, don't finish the thread states yet.  */
3954   discard_cleanups (ts_old_chain);
3955
3956   /* Revert thread and frame.  */
3957   do_cleanups (old_chain);
3958
3959   /* If a UI was in sync execution mode, and now isn't, restore its
3960      prompt (a synchronous execution command has finished, and we're
3961      ready for input).  */
3962   all_uis_check_sync_execution_done ();
3963
3964   if (cmd_done
3965       && exec_done_display_p
3966       && (ptid_equal (inferior_ptid, null_ptid)
3967           || !is_running (inferior_ptid)))
3968     printf_unfiltered (_("completed.\n"));
3969 }
3970
3971 /* Record the frame and location we're currently stepping through.  */
3972 void
3973 set_step_info (struct frame_info *frame, struct symtab_and_line sal)
3974 {
3975   struct thread_info *tp = inferior_thread ();
3976
3977   tp->control.step_frame_id = get_frame_id (frame);
3978   tp->control.step_stack_frame_id = get_stack_frame_id (frame);
3979
3980   tp->current_symtab = sal.symtab;
3981   tp->current_line = sal.line;
3982 }
3983
3984 /* Clear context switchable stepping state.  */
3985
3986 void
3987 init_thread_stepping_state (struct thread_info *tss)
3988 {
3989   tss->stepped_breakpoint = 0;
3990   tss->stepping_over_breakpoint = 0;
3991   tss->stepping_over_watchpoint = 0;
3992   tss->step_after_step_resume_breakpoint = 0;
3993 }
3994
3995 /* Set the cached copy of the last ptid/waitstatus.  */
3996
3997 void
3998 set_last_target_status (ptid_t ptid, struct target_waitstatus status)
3999 {
4000   target_last_wait_ptid = ptid;
4001   target_last_waitstatus = status;
4002 }
4003
4004 /* Return the cached copy of the last pid/waitstatus returned by
4005    target_wait()/deprecated_target_wait_hook().  The data is actually
4006    cached by handle_inferior_event(), which gets called immediately
4007    after target_wait()/deprecated_target_wait_hook().  */
4008
4009 void
4010 get_last_target_status (ptid_t *ptidp, struct target_waitstatus *status)
4011 {
4012   *ptidp = target_last_wait_ptid;
4013   *status = target_last_waitstatus;
4014 }
4015
4016 void
4017 nullify_last_target_wait_ptid (void)
4018 {
4019   target_last_wait_ptid = minus_one_ptid;
4020 }
4021
4022 /* Switch thread contexts.  */
4023
4024 static void
4025 context_switch (ptid_t ptid)
4026 {
4027   if (debug_infrun && !ptid_equal (ptid, inferior_ptid))
4028     {
4029       fprintf_unfiltered (gdb_stdlog, "infrun: Switching context from %s ",
4030                           target_pid_to_str (inferior_ptid));
4031       fprintf_unfiltered (gdb_stdlog, "to %s\n",
4032                           target_pid_to_str (ptid));
4033     }
4034
4035   switch_to_thread (ptid);
4036 }
4037
4038 /* If the target can't tell whether we've hit breakpoints
4039    (target_supports_stopped_by_sw_breakpoint), and we got a SIGTRAP,
4040    check whether that could have been caused by a breakpoint.  If so,
4041    adjust the PC, per gdbarch_decr_pc_after_break.  */
4042
4043 static void
4044 adjust_pc_after_break (struct thread_info *thread,
4045                        struct target_waitstatus *ws)
4046 {
4047   struct regcache *regcache;
4048   struct gdbarch *gdbarch;
4049   CORE_ADDR breakpoint_pc, decr_pc;
4050
4051   /* If we've hit a breakpoint, we'll normally be stopped with SIGTRAP.  If
4052      we aren't, just return.
4053
4054      We assume that waitkinds other than TARGET_WAITKIND_STOPPED are not
4055      affected by gdbarch_decr_pc_after_break.  Other waitkinds which are
4056      implemented by software breakpoints should be handled through the normal
4057      breakpoint layer.
4058
4059      NOTE drow/2004-01-31: On some targets, breakpoints may generate
4060      different signals (SIGILL or SIGEMT for instance), but it is less
4061      clear where the PC is pointing afterwards.  It may not match
4062      gdbarch_decr_pc_after_break.  I don't know any specific target that
4063      generates these signals at breakpoints (the code has been in GDB since at
4064      least 1992) so I can not guess how to handle them here.
4065
4066      In earlier versions of GDB, a target with 
4067      gdbarch_have_nonsteppable_watchpoint would have the PC after hitting a
4068      watchpoint affected by gdbarch_decr_pc_after_break.  I haven't found any
4069      target with both of these set in GDB history, and it seems unlikely to be
4070      correct, so gdbarch_have_nonsteppable_watchpoint is not checked here.  */
4071
4072   if (ws->kind != TARGET_WAITKIND_STOPPED)
4073     return;
4074
4075   if (ws->value.sig != GDB_SIGNAL_TRAP)
4076     return;
4077
4078   /* In reverse execution, when a breakpoint is hit, the instruction
4079      under it has already been de-executed.  The reported PC always
4080      points at the breakpoint address, so adjusting it further would
4081      be wrong.  E.g., consider this case on a decr_pc_after_break == 1
4082      architecture:
4083
4084        B1         0x08000000 :   INSN1
4085        B2         0x08000001 :   INSN2
4086                   0x08000002 :   INSN3
4087             PC -> 0x08000003 :   INSN4
4088
4089      Say you're stopped at 0x08000003 as above.  Reverse continuing
4090      from that point should hit B2 as below.  Reading the PC when the
4091      SIGTRAP is reported should read 0x08000001 and INSN2 should have
4092      been de-executed already.
4093
4094        B1         0x08000000 :   INSN1
4095        B2   PC -> 0x08000001 :   INSN2
4096                   0x08000002 :   INSN3
4097                   0x08000003 :   INSN4
4098
4099      We can't apply the same logic as for forward execution, because
4100      we would wrongly adjust the PC to 0x08000000, since there's a
4101      breakpoint at PC - 1.  We'd then report a hit on B1, although
4102      INSN1 hadn't been de-executed yet.  Doing nothing is the correct
4103      behaviour.  */
4104   if (execution_direction == EXEC_REVERSE)
4105     return;
4106
4107   /* If the target can tell whether the thread hit a SW breakpoint,
4108      trust it.  Targets that can tell also adjust the PC
4109      themselves.  */
4110   if (target_supports_stopped_by_sw_breakpoint ())
4111     return;
4112
4113   /* Note that relying on whether a breakpoint is planted in memory to
4114      determine this can fail.  E.g,. the breakpoint could have been
4115      removed since.  Or the thread could have been told to step an
4116      instruction the size of a breakpoint instruction, and only
4117      _after_ was a breakpoint inserted at its address.  */
4118
4119   /* If this target does not decrement the PC after breakpoints, then
4120      we have nothing to do.  */
4121   regcache = get_thread_regcache (thread->ptid);
4122   gdbarch = regcache->arch ();
4123
4124   decr_pc = gdbarch_decr_pc_after_break (gdbarch);
4125   if (decr_pc == 0)
4126     return;
4127
4128   const address_space *aspace = regcache->aspace ();
4129
4130   /* Find the location where (if we've hit a breakpoint) the
4131      breakpoint would be.  */
4132   breakpoint_pc = regcache_read_pc (regcache) - decr_pc;
4133
4134   /* If the target can't tell whether a software breakpoint triggered,
4135      fallback to figuring it out based on breakpoints we think were
4136      inserted in the target, and on whether the thread was stepped or
4137      continued.  */
4138
4139   /* Check whether there actually is a software breakpoint inserted at
4140      that location.
4141
4142      If in non-stop mode, a race condition is possible where we've
4143      removed a breakpoint, but stop events for that breakpoint were
4144      already queued and arrive later.  To suppress those spurious
4145      SIGTRAPs, we keep a list of such breakpoint locations for a bit,
4146      and retire them after a number of stop events are reported.  Note
4147      this is an heuristic and can thus get confused.  The real fix is
4148      to get the "stopped by SW BP and needs adjustment" info out of
4149      the target/kernel (and thus never reach here; see above).  */
4150   if (software_breakpoint_inserted_here_p (aspace, breakpoint_pc)
4151       || (target_is_non_stop_p ()
4152           && moribund_breakpoint_here_p (aspace, breakpoint_pc)))
4153     {
4154       gdb::optional<scoped_restore_tmpl<int>> restore_operation_disable;
4155
4156       if (record_full_is_used ())
4157         restore_operation_disable.emplace
4158           (record_full_gdb_operation_disable_set ());
4159
4160       /* When using hardware single-step, a SIGTRAP is reported for both
4161          a completed single-step and a software breakpoint.  Need to
4162          differentiate between the two, as the latter needs adjusting
4163          but the former does not.
4164
4165          The SIGTRAP can be due to a completed hardware single-step only if 
4166           - we didn't insert software single-step breakpoints
4167           - this thread is currently being stepped
4168
4169          If any of these events did not occur, we must have stopped due
4170          to hitting a software breakpoint, and have to back up to the
4171          breakpoint address.
4172
4173          As a special case, we could have hardware single-stepped a
4174          software breakpoint.  In this case (prev_pc == breakpoint_pc),
4175          we also need to back up to the breakpoint address.  */
4176
4177       if (thread_has_single_step_breakpoints_set (thread)
4178           || !currently_stepping (thread)
4179           || (thread->stepped_breakpoint
4180               && thread->prev_pc == breakpoint_pc))
4181         regcache_write_pc (regcache, breakpoint_pc);
4182     }
4183 }
4184
4185 static int
4186 stepped_in_from (struct frame_info *frame, struct frame_id step_frame_id)
4187 {
4188   for (frame = get_prev_frame (frame);
4189        frame != NULL;
4190        frame = get_prev_frame (frame))
4191     {
4192       if (frame_id_eq (get_frame_id (frame), step_frame_id))
4193         return 1;
4194       if (get_frame_type (frame) != INLINE_FRAME)
4195         break;
4196     }
4197
4198   return 0;
4199 }
4200
4201 /* If the event thread has the stop requested flag set, pretend it
4202    stopped for a GDB_SIGNAL_0 (i.e., as if it stopped due to
4203    target_stop).  */
4204
4205 static bool
4206 handle_stop_requested (struct execution_control_state *ecs)
4207 {
4208   if (ecs->event_thread->stop_requested)
4209     {
4210       ecs->ws.kind = TARGET_WAITKIND_STOPPED;
4211       ecs->ws.value.sig = GDB_SIGNAL_0;
4212       handle_signal_stop (ecs);
4213       return true;
4214     }
4215   return false;
4216 }
4217
4218 /* Auxiliary function that handles syscall entry/return events.
4219    It returns 1 if the inferior should keep going (and GDB
4220    should ignore the event), or 0 if the event deserves to be
4221    processed.  */
4222
4223 static int
4224 handle_syscall_event (struct execution_control_state *ecs)
4225 {
4226   struct regcache *regcache;
4227   int syscall_number;
4228
4229   if (!ptid_equal (ecs->ptid, inferior_ptid))
4230     context_switch (ecs->ptid);
4231
4232   regcache = get_thread_regcache (ecs->ptid);
4233   syscall_number = ecs->ws.value.syscall_number;
4234   stop_pc = regcache_read_pc (regcache);
4235
4236   if (catch_syscall_enabled () > 0
4237       && catching_syscall_number (syscall_number) > 0)
4238     {
4239       if (debug_infrun)
4240         fprintf_unfiltered (gdb_stdlog, "infrun: syscall number = '%d'\n",
4241                             syscall_number);
4242
4243       ecs->event_thread->control.stop_bpstat
4244         = bpstat_stop_status (regcache->aspace (),
4245                               stop_pc, ecs->ptid, &ecs->ws);
4246
4247       if (handle_stop_requested (ecs))
4248         return 0;
4249
4250       if (bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
4251         {
4252           /* Catchpoint hit.  */
4253           return 0;
4254         }
4255     }
4256
4257   if (handle_stop_requested (ecs))
4258     return 0;
4259
4260   /* If no catchpoint triggered for this, then keep going.  */
4261   keep_going (ecs);
4262   return 1;
4263 }
4264
4265 /* Lazily fill in the execution_control_state's stop_func_* fields.  */
4266
4267 static void
4268 fill_in_stop_func (struct gdbarch *gdbarch,
4269                    struct execution_control_state *ecs)
4270 {
4271   if (!ecs->stop_func_filled_in)
4272     {
4273       /* Don't care about return value; stop_func_start and stop_func_name
4274          will both be 0 if it doesn't work.  */
4275       find_pc_partial_function (stop_pc, &ecs->stop_func_name,
4276                                 &ecs->stop_func_start, &ecs->stop_func_end);
4277       ecs->stop_func_start
4278         += gdbarch_deprecated_function_start_offset (gdbarch);
4279
4280       if (gdbarch_skip_entrypoint_p (gdbarch))
4281         ecs->stop_func_start = gdbarch_skip_entrypoint (gdbarch,
4282                                                         ecs->stop_func_start);
4283
4284       ecs->stop_func_filled_in = 1;
4285     }
4286 }
4287
4288
4289 /* Return the STOP_SOON field of the inferior pointed at by PTID.  */
4290
4291 static enum stop_kind
4292 get_inferior_stop_soon (ptid_t ptid)
4293 {
4294   struct inferior *inf = find_inferior_ptid (ptid);
4295
4296   gdb_assert (inf != NULL);
4297   return inf->control.stop_soon;
4298 }
4299
4300 /* Wait for one event.  Store the resulting waitstatus in WS, and
4301    return the event ptid.  */
4302
4303 static ptid_t
4304 wait_one (struct target_waitstatus *ws)
4305 {
4306   ptid_t event_ptid;
4307   ptid_t wait_ptid = minus_one_ptid;
4308
4309   overlay_cache_invalid = 1;
4310
4311   /* Flush target cache before starting to handle each event.
4312      Target was running and cache could be stale.  This is just a
4313      heuristic.  Running threads may modify target memory, but we
4314      don't get any event.  */
4315   target_dcache_invalidate ();
4316
4317   if (deprecated_target_wait_hook)
4318     event_ptid = deprecated_target_wait_hook (wait_ptid, ws, 0);
4319   else
4320     event_ptid = target_wait (wait_ptid, ws, 0);
4321
4322   if (debug_infrun)
4323     print_target_wait_results (wait_ptid, event_ptid, ws);
4324
4325   return event_ptid;
4326 }
4327
4328 /* Generate a wrapper for target_stopped_by_REASON that works on PTID
4329    instead of the current thread.  */
4330 #define THREAD_STOPPED_BY(REASON)               \
4331 static int                                      \
4332 thread_stopped_by_ ## REASON (ptid_t ptid)      \
4333 {                                               \
4334   scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid); \
4335   inferior_ptid = ptid;                         \
4336                                                 \
4337   return target_stopped_by_ ## REASON ();       \
4338 }
4339
4340 /* Generate thread_stopped_by_watchpoint.  */
4341 THREAD_STOPPED_BY (watchpoint)
4342 /* Generate thread_stopped_by_sw_breakpoint.  */
4343 THREAD_STOPPED_BY (sw_breakpoint)
4344 /* Generate thread_stopped_by_hw_breakpoint.  */
4345 THREAD_STOPPED_BY (hw_breakpoint)
4346
4347 /* Cleanups that switches to the PTID pointed at by PTID_P.  */
4348
4349 static void
4350 switch_to_thread_cleanup (void *ptid_p)
4351 {
4352   ptid_t ptid = *(ptid_t *) ptid_p;
4353
4354   switch_to_thread (ptid);
4355 }
4356
4357 /* Save the thread's event and stop reason to process it later.  */
4358
4359 static void
4360 save_waitstatus (struct thread_info *tp, struct target_waitstatus *ws)
4361 {
4362   struct regcache *regcache;
4363
4364   if (debug_infrun)
4365     {
4366       std::string statstr = target_waitstatus_to_string (ws);
4367
4368       fprintf_unfiltered (gdb_stdlog,
4369                           "infrun: saving status %s for %d.%ld.%ld\n",
4370                           statstr.c_str (),
4371                           ptid_get_pid (tp->ptid),
4372                           ptid_get_lwp (tp->ptid),
4373                           ptid_get_tid (tp->ptid));
4374     }
4375
4376   /* Record for later.  */
4377   tp->suspend.waitstatus = *ws;
4378   tp->suspend.waitstatus_pending_p = 1;
4379
4380   regcache = get_thread_regcache (tp->ptid);
4381   const address_space *aspace = regcache->aspace ();
4382
4383   if (ws->kind == TARGET_WAITKIND_STOPPED
4384       && ws->value.sig == GDB_SIGNAL_TRAP)
4385     {
4386       CORE_ADDR pc = regcache_read_pc (regcache);
4387
4388       adjust_pc_after_break (tp, &tp->suspend.waitstatus);
4389
4390       if (thread_stopped_by_watchpoint (tp->ptid))
4391         {
4392           tp->suspend.stop_reason
4393             = TARGET_STOPPED_BY_WATCHPOINT;
4394         }
4395       else if (target_supports_stopped_by_sw_breakpoint ()
4396                && thread_stopped_by_sw_breakpoint (tp->ptid))
4397         {
4398           tp->suspend.stop_reason
4399             = TARGET_STOPPED_BY_SW_BREAKPOINT;
4400         }
4401       else if (target_supports_stopped_by_hw_breakpoint ()
4402                && thread_stopped_by_hw_breakpoint (tp->ptid))
4403         {
4404           tp->suspend.stop_reason
4405             = TARGET_STOPPED_BY_HW_BREAKPOINT;
4406         }
4407       else if (!target_supports_stopped_by_hw_breakpoint ()
4408                && hardware_breakpoint_inserted_here_p (aspace,
4409                                                        pc))
4410         {
4411           tp->suspend.stop_reason
4412             = TARGET_STOPPED_BY_HW_BREAKPOINT;
4413         }
4414       else if (!target_supports_stopped_by_sw_breakpoint ()
4415                && software_breakpoint_inserted_here_p (aspace,
4416                                                        pc))
4417         {
4418           tp->suspend.stop_reason
4419             = TARGET_STOPPED_BY_SW_BREAKPOINT;
4420         }
4421       else if (!thread_has_single_step_breakpoints_set (tp)
4422                && currently_stepping (tp))
4423         {
4424           tp->suspend.stop_reason
4425             = TARGET_STOPPED_BY_SINGLE_STEP;
4426         }
4427     }
4428 }
4429
4430 /* A cleanup that disables thread create/exit events.  */
4431
4432 static void
4433 disable_thread_events (void *arg)
4434 {
4435   target_thread_events (0);
4436 }
4437
4438 /* See infrun.h.  */
4439
4440 void
4441 stop_all_threads (void)
4442 {
4443   /* We may need multiple passes to discover all threads.  */
4444   int pass;
4445   int iterations = 0;
4446   ptid_t entry_ptid;
4447   struct cleanup *old_chain;
4448
4449   gdb_assert (target_is_non_stop_p ());
4450
4451   if (debug_infrun)
4452     fprintf_unfiltered (gdb_stdlog, "infrun: stop_all_threads\n");
4453
4454   entry_ptid = inferior_ptid;
4455   old_chain = make_cleanup (switch_to_thread_cleanup, &entry_ptid);
4456
4457   target_thread_events (1);
4458   make_cleanup (disable_thread_events, NULL);
4459
4460   /* Request threads to stop, and then wait for the stops.  Because
4461      threads we already know about can spawn more threads while we're
4462      trying to stop them, and we only learn about new threads when we
4463      update the thread list, do this in a loop, and keep iterating
4464      until two passes find no threads that need to be stopped.  */
4465   for (pass = 0; pass < 2; pass++, iterations++)
4466     {
4467       if (debug_infrun)
4468         fprintf_unfiltered (gdb_stdlog,
4469                             "infrun: stop_all_threads, pass=%d, "
4470                             "iterations=%d\n", pass, iterations);
4471       while (1)
4472         {
4473           ptid_t event_ptid;
4474           struct target_waitstatus ws;
4475           int need_wait = 0;
4476           struct thread_info *t;
4477
4478           update_thread_list ();
4479
4480           /* Go through all threads looking for threads that we need
4481              to tell the target to stop.  */
4482           ALL_NON_EXITED_THREADS (t)
4483             {
4484               if (t->executing)
4485                 {
4486                   /* If already stopping, don't request a stop again.
4487                      We just haven't seen the notification yet.  */
4488                   if (!t->stop_requested)
4489                     {
4490                       if (debug_infrun)
4491                         fprintf_unfiltered (gdb_stdlog,
4492                                             "infrun:   %s executing, "
4493                                             "need stop\n",
4494                                             target_pid_to_str (t->ptid));
4495                       target_stop (t->ptid);
4496                       t->stop_requested = 1;
4497                     }
4498                   else
4499                     {
4500                       if (debug_infrun)
4501                         fprintf_unfiltered (gdb_stdlog,
4502                                             "infrun:   %s executing, "
4503                                             "already stopping\n",
4504                                             target_pid_to_str (t->ptid));
4505                     }
4506
4507                   if (t->stop_requested)
4508                     need_wait = 1;
4509                 }
4510               else
4511                 {
4512                   if (debug_infrun)
4513                     fprintf_unfiltered (gdb_stdlog,
4514                                         "infrun:   %s not executing\n",
4515                                         target_pid_to_str (t->ptid));
4516
4517                   /* The thread may be not executing, but still be
4518                      resumed with a pending status to process.  */
4519                   t->resumed = 0;
4520                 }
4521             }
4522
4523           if (!need_wait)
4524             break;
4525
4526           /* If we find new threads on the second iteration, restart
4527              over.  We want to see two iterations in a row with all
4528              threads stopped.  */
4529           if (pass > 0)
4530             pass = -1;
4531
4532           event_ptid = wait_one (&ws);
4533           if (ws.kind == TARGET_WAITKIND_NO_RESUMED)
4534             {
4535               /* All resumed threads exited.  */
4536             }
4537           else if (ws.kind == TARGET_WAITKIND_THREAD_EXITED
4538                    || ws.kind == TARGET_WAITKIND_EXITED
4539                    || ws.kind == TARGET_WAITKIND_SIGNALLED)
4540             {
4541               if (debug_infrun)
4542                 {
4543                   ptid_t ptid = pid_to_ptid (ws.value.integer);
4544
4545                   fprintf_unfiltered (gdb_stdlog,
4546                                       "infrun: %s exited while "
4547                                       "stopping threads\n",
4548                                       target_pid_to_str (ptid));
4549                 }
4550             }
4551           else
4552             {
4553               struct inferior *inf;
4554
4555               t = find_thread_ptid (event_ptid);
4556               if (t == NULL)
4557                 t = add_thread (event_ptid);
4558
4559               t->stop_requested = 0;
4560               t->executing = 0;
4561               t->resumed = 0;
4562               t->control.may_range_step = 0;
4563
4564               /* This may be the first time we see the inferior report
4565                  a stop.  */
4566               inf = find_inferior_ptid (event_ptid);
4567               if (inf->needs_setup)
4568                 {
4569                   switch_to_thread_no_regs (t);
4570                   setup_inferior (0);
4571                 }
4572
4573               if (ws.kind == TARGET_WAITKIND_STOPPED
4574                   && ws.value.sig == GDB_SIGNAL_0)
4575                 {
4576                   /* We caught the event that we intended to catch, so
4577                      there's no event pending.  */
4578                   t->suspend.waitstatus.kind = TARGET_WAITKIND_IGNORE;
4579                   t->suspend.waitstatus_pending_p = 0;
4580
4581                   if (displaced_step_fixup (t->ptid, GDB_SIGNAL_0) < 0)
4582                     {
4583                       /* Add it back to the step-over queue.  */
4584                       if (debug_infrun)
4585                         {
4586                           fprintf_unfiltered (gdb_stdlog,
4587                                               "infrun: displaced-step of %s "
4588                                               "canceled: adding back to the "
4589                                               "step-over queue\n",
4590                                               target_pid_to_str (t->ptid));
4591                         }
4592                       t->control.trap_expected = 0;
4593                       thread_step_over_chain_enqueue (t);
4594                     }
4595                 }
4596               else
4597                 {
4598                   enum gdb_signal sig;
4599                   struct regcache *regcache;
4600
4601                   if (debug_infrun)
4602                     {
4603                       std::string statstr = target_waitstatus_to_string (&ws);
4604
4605                       fprintf_unfiltered (gdb_stdlog,
4606                                           "infrun: target_wait %s, saving "
4607                                           "status for %d.%ld.%ld\n",
4608                                           statstr.c_str (),
4609                                           ptid_get_pid (t->ptid),
4610                                           ptid_get_lwp (t->ptid),
4611                                           ptid_get_tid (t->ptid));
4612                     }
4613
4614                   /* Record for later.  */
4615                   save_waitstatus (t, &ws);
4616
4617                   sig = (ws.kind == TARGET_WAITKIND_STOPPED
4618                          ? ws.value.sig : GDB_SIGNAL_0);
4619
4620                   if (displaced_step_fixup (t->ptid, sig) < 0)
4621                     {
4622                       /* Add it back to the step-over queue.  */
4623                       t->control.trap_expected = 0;
4624                       thread_step_over_chain_enqueue (t);
4625                     }
4626
4627                   regcache = get_thread_regcache (t->ptid);
4628                   t->suspend.stop_pc = regcache_read_pc (regcache);
4629
4630                   if (debug_infrun)
4631                     {
4632                       fprintf_unfiltered (gdb_stdlog,
4633                                           "infrun: saved stop_pc=%s for %s "
4634                                           "(currently_stepping=%d)\n",
4635                                           paddress (target_gdbarch (),
4636                                                     t->suspend.stop_pc),
4637                                           target_pid_to_str (t->ptid),
4638                                           currently_stepping (t));
4639                     }
4640                 }
4641             }
4642         }
4643     }
4644
4645   do_cleanups (old_chain);
4646
4647   if (debug_infrun)
4648     fprintf_unfiltered (gdb_stdlog, "infrun: stop_all_threads done\n");
4649 }
4650
4651 /* Handle a TARGET_WAITKIND_NO_RESUMED event.  */
4652
4653 static int
4654 handle_no_resumed (struct execution_control_state *ecs)
4655 {
4656   struct inferior *inf;
4657   struct thread_info *thread;
4658
4659   if (target_can_async_p ())
4660     {
4661       struct ui *ui;
4662       int any_sync = 0;
4663
4664       ALL_UIS (ui)
4665         {
4666           if (ui->prompt_state == PROMPT_BLOCKED)
4667             {
4668               any_sync = 1;
4669               break;
4670             }
4671         }
4672       if (!any_sync)
4673         {
4674           /* There were no unwaited-for children left in the target, but,
4675              we're not synchronously waiting for events either.  Just
4676              ignore.  */
4677
4678           if (debug_infrun)
4679             fprintf_unfiltered (gdb_stdlog,
4680                                 "infrun: TARGET_WAITKIND_NO_RESUMED "
4681                                 "(ignoring: bg)\n");
4682           prepare_to_wait (ecs);
4683           return 1;
4684         }
4685     }
4686
4687   /* Otherwise, if we were running a synchronous execution command, we
4688      may need to cancel it and give the user back the terminal.
4689
4690      In non-stop mode, the target can't tell whether we've already
4691      consumed previous stop events, so it can end up sending us a
4692      no-resumed event like so:
4693
4694        #0 - thread 1 is left stopped
4695
4696        #1 - thread 2 is resumed and hits breakpoint
4697                -> TARGET_WAITKIND_STOPPED
4698
4699        #2 - thread 3 is resumed and exits
4700             this is the last resumed thread, so
4701                -> TARGET_WAITKIND_NO_RESUMED
4702
4703        #3 - gdb processes stop for thread 2 and decides to re-resume
4704             it.
4705
4706        #4 - gdb processes the TARGET_WAITKIND_NO_RESUMED event.
4707             thread 2 is now resumed, so the event should be ignored.
4708
4709      IOW, if the stop for thread 2 doesn't end a foreground command,
4710      then we need to ignore the following TARGET_WAITKIND_NO_RESUMED
4711      event.  But it could be that the event meant that thread 2 itself
4712      (or whatever other thread was the last resumed thread) exited.
4713
4714      To address this we refresh the thread list and check whether we
4715      have resumed threads _now_.  In the example above, this removes
4716      thread 3 from the thread list.  If thread 2 was re-resumed, we
4717      ignore this event.  If we find no thread resumed, then we cancel
4718      the synchronous command show "no unwaited-for " to the user.  */
4719   update_thread_list ();
4720
4721   ALL_NON_EXITED_THREADS (thread)
4722     {
4723       if (thread->executing
4724           || thread->suspend.waitstatus_pending_p)
4725         {
4726           /* There were no unwaited-for children left in the target at
4727              some point, but there are now.  Just ignore.  */
4728           if (debug_infrun)
4729             fprintf_unfiltered (gdb_stdlog,
4730                                 "infrun: TARGET_WAITKIND_NO_RESUMED "
4731                                 "(ignoring: found resumed)\n");
4732           prepare_to_wait (ecs);
4733           return 1;
4734         }
4735     }
4736
4737   /* Note however that we may find no resumed thread because the whole
4738      process exited meanwhile (thus updating the thread list results
4739      in an empty thread list).  In this case we know we'll be getting
4740      a process exit event shortly.  */
4741   ALL_INFERIORS (inf)
4742     {
4743       if (inf->pid == 0)
4744         continue;
4745
4746       thread = any_live_thread_of_process (inf->pid);
4747       if (thread == NULL)
4748         {
4749           if (debug_infrun)
4750             fprintf_unfiltered (gdb_stdlog,
4751                                 "infrun: TARGET_WAITKIND_NO_RESUMED "
4752                                 "(expect process exit)\n");
4753           prepare_to_wait (ecs);
4754           return 1;
4755         }
4756     }
4757
4758   /* Go ahead and report the event.  */
4759   return 0;
4760 }
4761
4762 /* Given an execution control state that has been freshly filled in by
4763    an event from the inferior, figure out what it means and take
4764    appropriate action.
4765
4766    The alternatives are:
4767
4768    1) stop_waiting and return; to really stop and return to the
4769    debugger.
4770
4771    2) keep_going and return; to wait for the next event (set
4772    ecs->event_thread->stepping_over_breakpoint to 1 to single step
4773    once).  */
4774
4775 static void
4776 handle_inferior_event_1 (struct execution_control_state *ecs)
4777 {
4778   enum stop_kind stop_soon;
4779
4780   if (ecs->ws.kind == TARGET_WAITKIND_IGNORE)
4781     {
4782       /* We had an event in the inferior, but we are not interested in
4783          handling it at this level.  The lower layers have already
4784          done what needs to be done, if anything.
4785
4786          One of the possible circumstances for this is when the
4787          inferior produces output for the console.  The inferior has
4788          not stopped, and we are ignoring the event.  Another possible
4789          circumstance is any event which the lower level knows will be
4790          reported multiple times without an intervening resume.  */
4791       if (debug_infrun)
4792         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_IGNORE\n");
4793       prepare_to_wait (ecs);
4794       return;
4795     }
4796
4797   if (ecs->ws.kind == TARGET_WAITKIND_THREAD_EXITED)
4798     {
4799       if (debug_infrun)
4800         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_THREAD_EXITED\n");
4801       prepare_to_wait (ecs);
4802       return;
4803     }
4804
4805   if (ecs->ws.kind == TARGET_WAITKIND_NO_RESUMED
4806       && handle_no_resumed (ecs))
4807     return;
4808
4809   /* Cache the last pid/waitstatus.  */
4810   set_last_target_status (ecs->ptid, ecs->ws);
4811
4812   /* Always clear state belonging to the previous time we stopped.  */
4813   stop_stack_dummy = STOP_NONE;
4814
4815   if (ecs->ws.kind == TARGET_WAITKIND_NO_RESUMED)
4816     {
4817       /* No unwaited-for children left.  IOW, all resumed children
4818          have exited.  */
4819       if (debug_infrun)
4820         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_NO_RESUMED\n");
4821
4822       stop_print_frame = 0;
4823       stop_waiting (ecs);
4824       return;
4825     }
4826
4827   if (ecs->ws.kind != TARGET_WAITKIND_EXITED
4828       && ecs->ws.kind != TARGET_WAITKIND_SIGNALLED)
4829     {
4830       ecs->event_thread = find_thread_ptid (ecs->ptid);
4831       /* If it's a new thread, add it to the thread database.  */
4832       if (ecs->event_thread == NULL)
4833         ecs->event_thread = add_thread (ecs->ptid);
4834
4835       /* Disable range stepping.  If the next step request could use a
4836          range, this will be end up re-enabled then.  */
4837       ecs->event_thread->control.may_range_step = 0;
4838     }
4839
4840   /* Dependent on valid ECS->EVENT_THREAD.  */
4841   adjust_pc_after_break (ecs->event_thread, &ecs->ws);
4842
4843   /* Dependent on the current PC value modified by adjust_pc_after_break.  */
4844   reinit_frame_cache ();
4845
4846   breakpoint_retire_moribund ();
4847
4848   /* First, distinguish signals caused by the debugger from signals
4849      that have to do with the program's own actions.  Note that
4850      breakpoint insns may cause SIGTRAP or SIGILL or SIGEMT, depending
4851      on the operating system version.  Here we detect when a SIGILL or
4852      SIGEMT is really a breakpoint and change it to SIGTRAP.  We do
4853      something similar for SIGSEGV, since a SIGSEGV will be generated
4854      when we're trying to execute a breakpoint instruction on a
4855      non-executable stack.  This happens for call dummy breakpoints
4856      for architectures like SPARC that place call dummies on the
4857      stack.  */
4858   if (ecs->ws.kind == TARGET_WAITKIND_STOPPED
4859       && (ecs->ws.value.sig == GDB_SIGNAL_ILL
4860           || ecs->ws.value.sig == GDB_SIGNAL_SEGV
4861           || ecs->ws.value.sig == GDB_SIGNAL_EMT))
4862     {
4863       struct regcache *regcache = get_thread_regcache (ecs->ptid);
4864
4865       if (breakpoint_inserted_here_p (regcache->aspace (),
4866                                       regcache_read_pc (regcache)))
4867         {
4868           if (debug_infrun)
4869             fprintf_unfiltered (gdb_stdlog,
4870                                 "infrun: Treating signal as SIGTRAP\n");
4871           ecs->ws.value.sig = GDB_SIGNAL_TRAP;
4872         }
4873     }
4874
4875   /* Mark the non-executing threads accordingly.  In all-stop, all
4876      threads of all processes are stopped when we get any event
4877      reported.  In non-stop mode, only the event thread stops.  */
4878   {
4879     ptid_t mark_ptid;
4880
4881     if (!target_is_non_stop_p ())
4882       mark_ptid = minus_one_ptid;
4883     else if (ecs->ws.kind == TARGET_WAITKIND_SIGNALLED
4884              || ecs->ws.kind == TARGET_WAITKIND_EXITED)
4885       {
4886         /* If we're handling a process exit in non-stop mode, even
4887            though threads haven't been deleted yet, one would think
4888            that there is nothing to do, as threads of the dead process
4889            will be soon deleted, and threads of any other process were
4890            left running.  However, on some targets, threads survive a
4891            process exit event.  E.g., for the "checkpoint" command,
4892            when the current checkpoint/fork exits, linux-fork.c
4893            automatically switches to another fork from within
4894            target_mourn_inferior, by associating the same
4895            inferior/thread to another fork.  We haven't mourned yet at
4896            this point, but we must mark any threads left in the
4897            process as not-executing so that finish_thread_state marks
4898            them stopped (in the user's perspective) if/when we present
4899            the stop to the user.  */
4900         mark_ptid = pid_to_ptid (ptid_get_pid (ecs->ptid));
4901       }
4902     else
4903       mark_ptid = ecs->ptid;
4904
4905     set_executing (mark_ptid, 0);
4906
4907     /* Likewise the resumed flag.  */
4908     set_resumed (mark_ptid, 0);
4909   }
4910
4911   switch (ecs->ws.kind)
4912     {
4913     case TARGET_WAITKIND_LOADED:
4914       if (debug_infrun)
4915         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_LOADED\n");
4916       if (!ptid_equal (ecs->ptid, inferior_ptid))
4917         context_switch (ecs->ptid);
4918       /* Ignore gracefully during startup of the inferior, as it might
4919          be the shell which has just loaded some objects, otherwise
4920          add the symbols for the newly loaded objects.  Also ignore at
4921          the beginning of an attach or remote session; we will query
4922          the full list of libraries once the connection is
4923          established.  */
4924
4925       stop_soon = get_inferior_stop_soon (ecs->ptid);
4926       if (stop_soon == NO_STOP_QUIETLY)
4927         {
4928           struct regcache *regcache;
4929
4930           regcache = get_thread_regcache (ecs->ptid);
4931
4932           handle_solib_event ();
4933
4934           ecs->event_thread->control.stop_bpstat
4935             = bpstat_stop_status (regcache->aspace (),
4936                                   stop_pc, ecs->ptid, &ecs->ws);
4937
4938           if (handle_stop_requested (ecs))
4939             return;
4940
4941           if (bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
4942             {
4943               /* A catchpoint triggered.  */
4944               process_event_stop_test (ecs);
4945               return;
4946             }
4947
4948           /* If requested, stop when the dynamic linker notifies
4949              gdb of events.  This allows the user to get control
4950              and place breakpoints in initializer routines for
4951              dynamically loaded objects (among other things).  */
4952           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
4953           if (stop_on_solib_events)
4954             {
4955               /* Make sure we print "Stopped due to solib-event" in
4956                  normal_stop.  */
4957               stop_print_frame = 1;
4958
4959               stop_waiting (ecs);
4960               return;
4961             }
4962         }
4963
4964       /* If we are skipping through a shell, or through shared library
4965          loading that we aren't interested in, resume the program.  If
4966          we're running the program normally, also resume.  */
4967       if (stop_soon == STOP_QUIETLY || stop_soon == NO_STOP_QUIETLY)
4968         {
4969           /* Loading of shared libraries might have changed breakpoint
4970              addresses.  Make sure new breakpoints are inserted.  */
4971           if (stop_soon == NO_STOP_QUIETLY)
4972             insert_breakpoints ();
4973           resume (GDB_SIGNAL_0);
4974           prepare_to_wait (ecs);
4975           return;
4976         }
4977
4978       /* But stop if we're attaching or setting up a remote
4979          connection.  */
4980       if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
4981           || stop_soon == STOP_QUIETLY_REMOTE)
4982         {
4983           if (debug_infrun)
4984             fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
4985           stop_waiting (ecs);
4986           return;
4987         }
4988
4989       internal_error (__FILE__, __LINE__,
4990                       _("unhandled stop_soon: %d"), (int) stop_soon);
4991
4992     case TARGET_WAITKIND_SPURIOUS:
4993       if (debug_infrun)
4994         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_SPURIOUS\n");
4995       if (handle_stop_requested (ecs))
4996         return;
4997       if (!ptid_equal (ecs->ptid, inferior_ptid))
4998         context_switch (ecs->ptid);
4999       resume (GDB_SIGNAL_0);
5000       prepare_to_wait (ecs);
5001       return;
5002
5003     case TARGET_WAITKIND_THREAD_CREATED:
5004       if (debug_infrun)
5005         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_THREAD_CREATED\n");
5006       if (handle_stop_requested (ecs))
5007         return;
5008       if (!ptid_equal (ecs->ptid, inferior_ptid))
5009         context_switch (ecs->ptid);
5010       if (!switch_back_to_stepped_thread (ecs))
5011         keep_going (ecs);
5012       return;
5013
5014     case TARGET_WAITKIND_EXITED:
5015     case TARGET_WAITKIND_SIGNALLED:
5016       if (debug_infrun)
5017         {
5018           if (ecs->ws.kind == TARGET_WAITKIND_EXITED)
5019             fprintf_unfiltered (gdb_stdlog,
5020                                 "infrun: TARGET_WAITKIND_EXITED\n");
5021           else
5022             fprintf_unfiltered (gdb_stdlog,
5023                                 "infrun: TARGET_WAITKIND_SIGNALLED\n");
5024         }
5025
5026       inferior_ptid = ecs->ptid;
5027       set_current_inferior (find_inferior_ptid (ecs->ptid));
5028       set_current_program_space (current_inferior ()->pspace);
5029       handle_vfork_child_exec_or_exit (0);
5030       target_terminal::ours (); /* Must do this before mourn anyway.  */
5031
5032       /* Clearing any previous state of convenience variables.  */
5033       clear_exit_convenience_vars ();
5034
5035       if (ecs->ws.kind == TARGET_WAITKIND_EXITED)
5036         {
5037           /* Record the exit code in the convenience variable $_exitcode, so
5038              that the user can inspect this again later.  */
5039           set_internalvar_integer (lookup_internalvar ("_exitcode"),
5040                                    (LONGEST) ecs->ws.value.integer);
5041
5042           /* Also record this in the inferior itself.  */
5043           current_inferior ()->has_exit_code = 1;
5044           current_inferior ()->exit_code = (LONGEST) ecs->ws.value.integer;
5045
5046           /* Support the --return-child-result option.  */
5047           return_child_result_value = ecs->ws.value.integer;
5048
5049           observer_notify_exited (ecs->ws.value.integer);
5050         }
5051       else
5052         {
5053           struct regcache *regcache = get_thread_regcache (ecs->ptid);
5054           struct gdbarch *gdbarch = regcache->arch ();
5055
5056           if (gdbarch_gdb_signal_to_target_p (gdbarch))
5057             {
5058               /* Set the value of the internal variable $_exitsignal,
5059                  which holds the signal uncaught by the inferior.  */
5060               set_internalvar_integer (lookup_internalvar ("_exitsignal"),
5061                                        gdbarch_gdb_signal_to_target (gdbarch,
5062                                                           ecs->ws.value.sig));
5063             }
5064           else
5065             {
5066               /* We don't have access to the target's method used for
5067                  converting between signal numbers (GDB's internal
5068                  representation <-> target's representation).
5069                  Therefore, we cannot do a good job at displaying this
5070                  information to the user.  It's better to just warn
5071                  her about it (if infrun debugging is enabled), and
5072                  give up.  */
5073               if (debug_infrun)
5074                 fprintf_filtered (gdb_stdlog, _("\
5075 Cannot fill $_exitsignal with the correct signal number.\n"));
5076             }
5077
5078           observer_notify_signal_exited (ecs->ws.value.sig);
5079         }
5080
5081       gdb_flush (gdb_stdout);
5082       target_mourn_inferior (inferior_ptid);
5083       stop_print_frame = 0;
5084       stop_waiting (ecs);
5085       return;
5086
5087       /* The following are the only cases in which we keep going;
5088          the above cases end in a continue or goto.  */
5089     case TARGET_WAITKIND_FORKED:
5090     case TARGET_WAITKIND_VFORKED:
5091       if (debug_infrun)
5092         {
5093           if (ecs->ws.kind == TARGET_WAITKIND_FORKED)
5094             fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_FORKED\n");
5095           else
5096             fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_VFORKED\n");
5097         }
5098
5099       /* Check whether the inferior is displaced stepping.  */
5100       {
5101         struct regcache *regcache = get_thread_regcache (ecs->ptid);
5102         struct gdbarch *gdbarch = regcache->arch ();
5103
5104         /* If checking displaced stepping is supported, and thread
5105            ecs->ptid is displaced stepping.  */
5106         if (displaced_step_in_progress_thread (ecs->ptid))
5107           {
5108             struct inferior *parent_inf
5109               = find_inferior_ptid (ecs->ptid);
5110             struct regcache *child_regcache;
5111             CORE_ADDR parent_pc;
5112
5113             /* GDB has got TARGET_WAITKIND_FORKED or TARGET_WAITKIND_VFORKED,
5114                indicating that the displaced stepping of syscall instruction
5115                has been done.  Perform cleanup for parent process here.  Note
5116                that this operation also cleans up the child process for vfork,
5117                because their pages are shared.  */
5118             displaced_step_fixup (ecs->ptid, GDB_SIGNAL_TRAP);
5119             /* Start a new step-over in another thread if there's one
5120                that needs it.  */
5121             start_step_over ();
5122
5123             if (ecs->ws.kind == TARGET_WAITKIND_FORKED)
5124               {
5125                 struct displaced_step_inferior_state *displaced
5126                   = get_displaced_stepping_state (ptid_get_pid (ecs->ptid));
5127
5128                 /* Restore scratch pad for child process.  */
5129                 displaced_step_restore (displaced, ecs->ws.value.related_pid);
5130               }
5131
5132             /* Since the vfork/fork syscall instruction was executed in the scratchpad,
5133                the child's PC is also within the scratchpad.  Set the child's PC
5134                to the parent's PC value, which has already been fixed up.
5135                FIXME: we use the parent's aspace here, although we're touching
5136                the child, because the child hasn't been added to the inferior
5137                list yet at this point.  */
5138
5139             child_regcache
5140               = get_thread_arch_aspace_regcache (ecs->ws.value.related_pid,
5141                                                  gdbarch,
5142                                                  parent_inf->aspace);
5143             /* Read PC value of parent process.  */
5144             parent_pc = regcache_read_pc (regcache);
5145
5146             if (debug_displaced)
5147               fprintf_unfiltered (gdb_stdlog,
5148                                   "displaced: write child pc from %s to %s\n",
5149                                   paddress (gdbarch,
5150                                             regcache_read_pc (child_regcache)),
5151                                   paddress (gdbarch, parent_pc));
5152
5153             regcache_write_pc (child_regcache, parent_pc);
5154           }
5155       }
5156
5157       if (!ptid_equal (ecs->ptid, inferior_ptid))
5158         context_switch (ecs->ptid);
5159
5160       /* Immediately detach breakpoints from the child before there's
5161          any chance of letting the user delete breakpoints from the
5162          breakpoint lists.  If we don't do this early, it's easy to
5163          leave left over traps in the child, vis: "break foo; catch
5164          fork; c; <fork>; del; c; <child calls foo>".  We only follow
5165          the fork on the last `continue', and by that time the
5166          breakpoint at "foo" is long gone from the breakpoint table.
5167          If we vforked, then we don't need to unpatch here, since both
5168          parent and child are sharing the same memory pages; we'll
5169          need to unpatch at follow/detach time instead to be certain
5170          that new breakpoints added between catchpoint hit time and
5171          vfork follow are detached.  */
5172       if (ecs->ws.kind != TARGET_WAITKIND_VFORKED)
5173         {
5174           /* This won't actually modify the breakpoint list, but will
5175              physically remove the breakpoints from the child.  */
5176           detach_breakpoints (ecs->ws.value.related_pid);
5177         }
5178
5179       delete_just_stopped_threads_single_step_breakpoints ();
5180
5181       /* In case the event is caught by a catchpoint, remember that
5182          the event is to be followed at the next resume of the thread,
5183          and not immediately.  */
5184       ecs->event_thread->pending_follow = ecs->ws;
5185
5186       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
5187
5188       ecs->event_thread->control.stop_bpstat
5189         = bpstat_stop_status (get_current_regcache ()->aspace (),
5190                               stop_pc, ecs->ptid, &ecs->ws);
5191
5192       if (handle_stop_requested (ecs))
5193         return;
5194
5195       /* If no catchpoint triggered for this, then keep going.  Note
5196          that we're interested in knowing the bpstat actually causes a
5197          stop, not just if it may explain the signal.  Software
5198          watchpoints, for example, always appear in the bpstat.  */
5199       if (!bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5200         {
5201           ptid_t parent;
5202           ptid_t child;
5203           int should_resume;
5204           int follow_child
5205             = (follow_fork_mode_string == follow_fork_mode_child);
5206
5207           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5208
5209           should_resume = follow_fork ();
5210
5211           parent = ecs->ptid;
5212           child = ecs->ws.value.related_pid;
5213
5214           /* At this point, the parent is marked running, and the
5215              child is marked stopped.  */
5216
5217           /* If not resuming the parent, mark it stopped.  */
5218           if (follow_child && !detach_fork && !non_stop && !sched_multi)
5219             set_running (parent, 0);
5220
5221           /* If resuming the child, mark it running.  */
5222           if (follow_child || (!detach_fork && (non_stop || sched_multi)))
5223             set_running (child, 1);
5224
5225           /* In non-stop mode, also resume the other branch.  */
5226           if (!detach_fork && (non_stop
5227                                || (sched_multi && target_is_non_stop_p ())))
5228             {
5229               if (follow_child)
5230                 switch_to_thread (parent);
5231               else
5232                 switch_to_thread (child);
5233
5234               ecs->event_thread = inferior_thread ();
5235               ecs->ptid = inferior_ptid;
5236               keep_going (ecs);
5237             }
5238
5239           if (follow_child)
5240             switch_to_thread (child);
5241           else
5242             switch_to_thread (parent);
5243
5244           ecs->event_thread = inferior_thread ();
5245           ecs->ptid = inferior_ptid;
5246
5247           if (should_resume)
5248             keep_going (ecs);
5249           else
5250             stop_waiting (ecs);
5251           return;
5252         }
5253       process_event_stop_test (ecs);
5254       return;
5255
5256     case TARGET_WAITKIND_VFORK_DONE:
5257       /* Done with the shared memory region.  Re-insert breakpoints in
5258          the parent, and keep going.  */
5259
5260       if (debug_infrun)
5261         fprintf_unfiltered (gdb_stdlog,
5262                             "infrun: TARGET_WAITKIND_VFORK_DONE\n");
5263
5264       if (!ptid_equal (ecs->ptid, inferior_ptid))
5265         context_switch (ecs->ptid);
5266
5267       current_inferior ()->waiting_for_vfork_done = 0;
5268       current_inferior ()->pspace->breakpoints_not_allowed = 0;
5269
5270       if (handle_stop_requested (ecs))
5271         return;
5272
5273       /* This also takes care of reinserting breakpoints in the
5274          previously locked inferior.  */
5275       keep_going (ecs);
5276       return;
5277
5278     case TARGET_WAITKIND_EXECD:
5279       if (debug_infrun)
5280         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_EXECD\n");
5281
5282       /* Note we can't read registers yet (the stop_pc), because we
5283          don't yet know the inferior's post-exec architecture.
5284          'stop_pc' is explicitly read below instead.  */
5285       if (!ptid_equal (ecs->ptid, inferior_ptid))
5286         switch_to_thread_no_regs (ecs->event_thread);
5287
5288       /* Do whatever is necessary to the parent branch of the vfork.  */
5289       handle_vfork_child_exec_or_exit (1);
5290
5291       /* This causes the eventpoints and symbol table to be reset.
5292          Must do this now, before trying to determine whether to
5293          stop.  */
5294       follow_exec (inferior_ptid, ecs->ws.value.execd_pathname);
5295
5296       stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
5297
5298       /* In follow_exec we may have deleted the original thread and
5299          created a new one.  Make sure that the event thread is the
5300          execd thread for that case (this is a nop otherwise).  */
5301       ecs->event_thread = inferior_thread ();
5302
5303       ecs->event_thread->control.stop_bpstat
5304         = bpstat_stop_status (get_current_regcache ()->aspace (),
5305                               stop_pc, ecs->ptid, &ecs->ws);
5306
5307       /* Note that this may be referenced from inside
5308          bpstat_stop_status above, through inferior_has_execd.  */
5309       xfree (ecs->ws.value.execd_pathname);
5310       ecs->ws.value.execd_pathname = NULL;
5311
5312       if (handle_stop_requested (ecs))
5313         return;
5314
5315       /* If no catchpoint triggered for this, then keep going.  */
5316       if (!bpstat_causes_stop (ecs->event_thread->control.stop_bpstat))
5317         {
5318           ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5319           keep_going (ecs);
5320           return;
5321         }
5322       process_event_stop_test (ecs);
5323       return;
5324
5325       /* Be careful not to try to gather much state about a thread
5326          that's in a syscall.  It's frequently a losing proposition.  */
5327     case TARGET_WAITKIND_SYSCALL_ENTRY:
5328       if (debug_infrun)
5329         fprintf_unfiltered (gdb_stdlog,
5330                             "infrun: TARGET_WAITKIND_SYSCALL_ENTRY\n");
5331       /* Getting the current syscall number.  */
5332       if (handle_syscall_event (ecs) == 0)
5333         process_event_stop_test (ecs);
5334       return;
5335
5336       /* Before examining the threads further, step this thread to
5337          get it entirely out of the syscall.  (We get notice of the
5338          event when the thread is just on the verge of exiting a
5339          syscall.  Stepping one instruction seems to get it back
5340          into user code.)  */
5341     case TARGET_WAITKIND_SYSCALL_RETURN:
5342       if (debug_infrun)
5343         fprintf_unfiltered (gdb_stdlog,
5344                             "infrun: TARGET_WAITKIND_SYSCALL_RETURN\n");
5345       if (handle_syscall_event (ecs) == 0)
5346         process_event_stop_test (ecs);
5347       return;
5348
5349     case TARGET_WAITKIND_STOPPED:
5350       if (debug_infrun)
5351         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_STOPPED\n");
5352       handle_signal_stop (ecs);
5353       return;
5354
5355     case TARGET_WAITKIND_NO_HISTORY:
5356       if (debug_infrun)
5357         fprintf_unfiltered (gdb_stdlog, "infrun: TARGET_WAITKIND_NO_HISTORY\n");
5358       /* Reverse execution: target ran out of history info.  */
5359
5360       /* Switch to the stopped thread.  */
5361       if (!ptid_equal (ecs->ptid, inferior_ptid))
5362         context_switch (ecs->ptid);
5363       if (debug_infrun)
5364         fprintf_unfiltered (gdb_stdlog, "infrun: stopped\n");
5365
5366       delete_just_stopped_threads_single_step_breakpoints ();
5367       stop_pc = regcache_read_pc (get_thread_regcache (inferior_ptid));
5368
5369       if (handle_stop_requested (ecs))
5370         return;
5371
5372       observer_notify_no_history ();
5373       stop_waiting (ecs);
5374       return;
5375     }
5376 }
5377
5378 /* A wrapper around handle_inferior_event_1, which also makes sure
5379    that all temporary struct value objects that were created during
5380    the handling of the event get deleted at the end.  */
5381
5382 static void
5383 handle_inferior_event (struct execution_control_state *ecs)
5384 {
5385   struct value *mark = value_mark ();
5386
5387   handle_inferior_event_1 (ecs);
5388   /* Purge all temporary values created during the event handling,
5389      as it could be a long time before we return to the command level
5390      where such values would otherwise be purged.  */
5391   value_free_to_mark (mark);
5392 }
5393
5394 /* Restart threads back to what they were trying to do back when we
5395    paused them for an in-line step-over.  The EVENT_THREAD thread is
5396    ignored.  */
5397
5398 static void
5399 restart_threads (struct thread_info *event_thread)
5400 {
5401   struct thread_info *tp;
5402
5403   /* In case the instruction just stepped spawned a new thread.  */
5404   update_thread_list ();
5405
5406   ALL_NON_EXITED_THREADS (tp)
5407     {
5408       if (tp == event_thread)
5409         {
5410           if (debug_infrun)
5411             fprintf_unfiltered (gdb_stdlog,
5412                                 "infrun: restart threads: "
5413                                 "[%s] is event thread\n",
5414                                 target_pid_to_str (tp->ptid));
5415           continue;
5416         }
5417
5418       if (!(tp->state == THREAD_RUNNING || tp->control.in_infcall))
5419         {
5420           if (debug_infrun)
5421             fprintf_unfiltered (gdb_stdlog,
5422                                 "infrun: restart threads: "
5423                                 "[%s] not meant to be running\n",
5424                                 target_pid_to_str (tp->ptid));
5425           continue;
5426         }
5427
5428       if (tp->resumed)
5429         {
5430           if (debug_infrun)
5431             fprintf_unfiltered (gdb_stdlog,
5432                                 "infrun: restart threads: [%s] resumed\n",
5433                                 target_pid_to_str (tp->ptid));
5434           gdb_assert (tp->executing || tp->suspend.waitstatus_pending_p);
5435           continue;
5436         }
5437
5438       if (thread_is_in_step_over_chain (tp))
5439         {
5440           if (debug_infrun)
5441             fprintf_unfiltered (gdb_stdlog,
5442                                 "infrun: restart threads: "
5443                                 "[%s] needs step-over\n",
5444                                 target_pid_to_str (tp->ptid));
5445           gdb_assert (!tp->resumed);
5446           continue;
5447         }
5448
5449
5450       if (tp->suspend.waitstatus_pending_p)
5451         {
5452           if (debug_infrun)
5453             fprintf_unfiltered (gdb_stdlog,
5454                                 "infrun: restart threads: "
5455                                 "[%s] has pending status\n",
5456                                 target_pid_to_str (tp->ptid));
5457           tp->resumed = 1;
5458           continue;
5459         }
5460
5461       gdb_assert (!tp->stop_requested);
5462
5463       /* If some thread needs to start a step-over at this point, it
5464          should still be in the step-over queue, and thus skipped
5465          above.  */
5466       if (thread_still_needs_step_over (tp))
5467         {
5468           internal_error (__FILE__, __LINE__,
5469                           "thread [%s] needs a step-over, but not in "
5470                           "step-over queue\n",
5471                           target_pid_to_str (tp->ptid));
5472         }
5473
5474       if (currently_stepping (tp))
5475         {
5476           if (debug_infrun)
5477             fprintf_unfiltered (gdb_stdlog,
5478                                 "infrun: restart threads: [%s] was stepping\n",
5479                                 target_pid_to_str (tp->ptid));
5480           keep_going_stepped_thread (tp);
5481         }
5482       else
5483         {
5484           struct execution_control_state ecss;
5485           struct execution_control_state *ecs = &ecss;
5486
5487           if (debug_infrun)
5488             fprintf_unfiltered (gdb_stdlog,
5489                                 "infrun: restart threads: [%s] continuing\n",
5490                                 target_pid_to_str (tp->ptid));
5491           reset_ecs (ecs, tp);
5492           switch_to_thread (tp->ptid);
5493           keep_going_pass_signal (ecs);
5494         }
5495     }
5496 }
5497
5498 /* Callback for iterate_over_threads.  Find a resumed thread that has
5499    a pending waitstatus.  */
5500
5501 static int
5502 resumed_thread_with_pending_status (struct thread_info *tp,
5503                                     void *arg)
5504 {
5505   return (tp->resumed
5506           && tp->suspend.waitstatus_pending_p);
5507 }
5508
5509 /* Called when we get an event that may finish an in-line or
5510    out-of-line (displaced stepping) step-over started previously.
5511    Return true if the event is processed and we should go back to the
5512    event loop; false if the caller should continue processing the
5513    event.  */
5514
5515 static int
5516 finish_step_over (struct execution_control_state *ecs)
5517 {
5518   int had_step_over_info;
5519
5520   displaced_step_fixup (ecs->ptid,
5521                         ecs->event_thread->suspend.stop_signal);
5522
5523   had_step_over_info = step_over_info_valid_p ();
5524
5525   if (had_step_over_info)
5526     {
5527       /* If we're stepping over a breakpoint with all threads locked,
5528          then only the thread that was stepped should be reporting
5529          back an event.  */
5530       gdb_assert (ecs->event_thread->control.trap_expected);
5531
5532       clear_step_over_info ();
5533     }
5534
5535   if (!target_is_non_stop_p ())
5536     return 0;
5537
5538   /* Start a new step-over in another thread if there's one that
5539      needs it.  */
5540   start_step_over ();
5541
5542   /* If we were stepping over a breakpoint before, and haven't started
5543      a new in-line step-over sequence, then restart all other threads
5544      (except the event thread).  We can't do this in all-stop, as then
5545      e.g., we wouldn't be able to issue any other remote packet until
5546      these other threads stop.  */
5547   if (had_step_over_info && !step_over_info_valid_p ())
5548     {
5549       struct thread_info *pending;
5550
5551       /* If we only have threads with pending statuses, the restart
5552          below won't restart any thread and so nothing re-inserts the
5553          breakpoint we just stepped over.  But we need it inserted
5554          when we later process the pending events, otherwise if
5555          another thread has a pending event for this breakpoint too,
5556          we'd discard its event (because the breakpoint that
5557          originally caused the event was no longer inserted).  */
5558       context_switch (ecs->ptid);
5559       insert_breakpoints ();
5560
5561       restart_threads (ecs->event_thread);
5562
5563       /* If we have events pending, go through handle_inferior_event
5564          again, picking up a pending event at random.  This avoids
5565          thread starvation.  */
5566
5567       /* But not if we just stepped over a watchpoint in order to let
5568          the instruction execute so we can evaluate its expression.
5569          The set of watchpoints that triggered is recorded in the
5570          breakpoint objects themselves (see bp->watchpoint_triggered).
5571          If we processed another event first, that other event could
5572          clobber this info.  */
5573       if (ecs->event_thread->stepping_over_watchpoint)
5574         return 0;
5575
5576       pending = iterate_over_threads (resumed_thread_with_pending_status,
5577                                       NULL);
5578       if (pending != NULL)
5579         {
5580           struct thread_info *tp = ecs->event_thread;
5581           struct regcache *regcache;
5582
5583           if (debug_infrun)
5584             {
5585               fprintf_unfiltered (gdb_stdlog,
5586                                   "infrun: found resumed threads with "
5587                                   "pending events, saving status\n");
5588             }
5589
5590           gdb_assert (pending != tp);
5591
5592           /* Record the event thread's event for later.  */
5593           save_waitstatus (tp, &ecs->ws);
5594           /* This was cleared early, by handle_inferior_event.  Set it
5595              so this pending event is considered by
5596              do_target_wait.  */
5597           tp->resumed = 1;
5598
5599           gdb_assert (!tp->executing);
5600
5601           regcache = get_thread_regcache (tp->ptid);
5602           tp->suspend.stop_pc = regcache_read_pc (regcache);
5603
5604           if (debug_infrun)
5605             {
5606               fprintf_unfiltered (gdb_stdlog,
5607                                   "infrun: saved stop_pc=%s for %s "
5608                                   "(currently_stepping=%d)\n",
5609                                   paddress (target_gdbarch (),
5610                                             tp->suspend.stop_pc),
5611                                   target_pid_to_str (tp->ptid),
5612                                   currently_stepping (tp));
5613             }
5614
5615           /* This in-line step-over finished; clear this so we won't
5616              start a new one.  This is what handle_signal_stop would
5617              do, if we returned false.  */
5618           tp->stepping_over_breakpoint = 0;
5619
5620           /* Wake up the event loop again.  */
5621           mark_async_event_handler (infrun_async_inferior_event_token);
5622
5623           prepare_to_wait (ecs);
5624           return 1;
5625         }
5626     }
5627
5628   return 0;
5629 }
5630
5631 /* Come here when the program has stopped with a signal.  */
5632
5633 static void
5634 handle_signal_stop (struct execution_control_state *ecs)
5635 {
5636   struct frame_info *frame;
5637   struct gdbarch *gdbarch;
5638   int stopped_by_watchpoint;
5639   enum stop_kind stop_soon;
5640   int random_signal;
5641
5642   gdb_assert (ecs->ws.kind == TARGET_WAITKIND_STOPPED);
5643
5644   ecs->event_thread->suspend.stop_signal = ecs->ws.value.sig;
5645
5646   /* Do we need to clean up the state of a thread that has
5647      completed a displaced single-step?  (Doing so usually affects
5648      the PC, so do it here, before we set stop_pc.)  */
5649   if (finish_step_over (ecs))
5650     return;
5651
5652   /* If we either finished a single-step or hit a breakpoint, but
5653      the user wanted this thread to be stopped, pretend we got a
5654      SIG0 (generic unsignaled stop).  */
5655   if (ecs->event_thread->stop_requested
5656       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
5657     ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5658
5659   stop_pc = regcache_read_pc (get_thread_regcache (ecs->ptid));
5660
5661   if (debug_infrun)
5662     {
5663       struct regcache *regcache = get_thread_regcache (ecs->ptid);
5664       struct gdbarch *gdbarch = regcache->arch ();
5665       scoped_restore save_inferior_ptid = make_scoped_restore (&inferior_ptid);
5666
5667       inferior_ptid = ecs->ptid;
5668
5669       fprintf_unfiltered (gdb_stdlog, "infrun: stop_pc = %s\n",
5670                           paddress (gdbarch, stop_pc));
5671       if (target_stopped_by_watchpoint ())
5672         {
5673           CORE_ADDR addr;
5674
5675           fprintf_unfiltered (gdb_stdlog, "infrun: stopped by watchpoint\n");
5676
5677           if (target_stopped_data_address (&current_target, &addr))
5678             fprintf_unfiltered (gdb_stdlog,
5679                                 "infrun: stopped data address = %s\n",
5680                                 paddress (gdbarch, addr));
5681           else
5682             fprintf_unfiltered (gdb_stdlog,
5683                                 "infrun: (no data address available)\n");
5684         }
5685     }
5686
5687   /* This is originated from start_remote(), start_inferior() and
5688      shared libraries hook functions.  */
5689   stop_soon = get_inferior_stop_soon (ecs->ptid);
5690   if (stop_soon == STOP_QUIETLY || stop_soon == STOP_QUIETLY_REMOTE)
5691     {
5692       if (!ptid_equal (ecs->ptid, inferior_ptid))
5693         context_switch (ecs->ptid);
5694       if (debug_infrun)
5695         fprintf_unfiltered (gdb_stdlog, "infrun: quietly stopped\n");
5696       stop_print_frame = 1;
5697       stop_waiting (ecs);
5698       return;
5699     }
5700
5701   /* This originates from attach_command().  We need to overwrite
5702      the stop_signal here, because some kernels don't ignore a
5703      SIGSTOP in a subsequent ptrace(PTRACE_CONT,SIGSTOP) call.
5704      See more comments in inferior.h.  On the other hand, if we
5705      get a non-SIGSTOP, report it to the user - assume the backend
5706      will handle the SIGSTOP if it should show up later.
5707
5708      Also consider that the attach is complete when we see a
5709      SIGTRAP.  Some systems (e.g. Windows), and stubs supporting
5710      target extended-remote report it instead of a SIGSTOP
5711      (e.g. gdbserver).  We already rely on SIGTRAP being our
5712      signal, so this is no exception.
5713
5714      Also consider that the attach is complete when we see a
5715      GDB_SIGNAL_0.  In non-stop mode, GDB will explicitly tell
5716      the target to stop all threads of the inferior, in case the
5717      low level attach operation doesn't stop them implicitly.  If
5718      they weren't stopped implicitly, then the stub will report a
5719      GDB_SIGNAL_0, meaning: stopped for no particular reason
5720      other than GDB's request.  */
5721   if (stop_soon == STOP_QUIETLY_NO_SIGSTOP
5722       && (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_STOP
5723           || ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5724           || ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_0))
5725     {
5726       stop_print_frame = 1;
5727       stop_waiting (ecs);
5728       ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
5729       return;
5730     }
5731
5732   /* See if something interesting happened to the non-current thread.  If
5733      so, then switch to that thread.  */
5734   if (!ptid_equal (ecs->ptid, inferior_ptid))
5735     {
5736       if (debug_infrun)
5737         fprintf_unfiltered (gdb_stdlog, "infrun: context switch\n");
5738
5739       context_switch (ecs->ptid);
5740
5741       if (deprecated_context_hook)
5742         deprecated_context_hook (ptid_to_global_thread_id (ecs->ptid));
5743     }
5744
5745   /* At this point, get hold of the now-current thread's frame.  */
5746   frame = get_current_frame ();
5747   gdbarch = get_frame_arch (frame);
5748
5749   /* Pull the single step breakpoints out of the target.  */
5750   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
5751     {
5752       struct regcache *regcache;
5753       CORE_ADDR pc;
5754
5755       regcache = get_thread_regcache (ecs->ptid);
5756       const address_space *aspace = regcache->aspace ();
5757
5758       pc = regcache_read_pc (regcache);
5759
5760       /* However, before doing so, if this single-step breakpoint was
5761          actually for another thread, set this thread up for moving
5762          past it.  */
5763       if (!thread_has_single_step_breakpoint_here (ecs->event_thread,
5764                                                    aspace, pc))
5765         {
5766           if (single_step_breakpoint_inserted_here_p (aspace, pc))
5767             {
5768               if (debug_infrun)
5769                 {
5770                   fprintf_unfiltered (gdb_stdlog,
5771                                       "infrun: [%s] hit another thread's "
5772                                       "single-step breakpoint\n",
5773                                       target_pid_to_str (ecs->ptid));
5774                 }
5775               ecs->hit_singlestep_breakpoint = 1;
5776             }
5777         }
5778       else
5779         {
5780           if (debug_infrun)
5781             {
5782               fprintf_unfiltered (gdb_stdlog,
5783                                   "infrun: [%s] hit its "
5784                                   "single-step breakpoint\n",
5785                                   target_pid_to_str (ecs->ptid));
5786             }
5787         }
5788     }
5789   delete_just_stopped_threads_single_step_breakpoints ();
5790
5791   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5792       && ecs->event_thread->control.trap_expected
5793       && ecs->event_thread->stepping_over_watchpoint)
5794     stopped_by_watchpoint = 0;
5795   else
5796     stopped_by_watchpoint = watchpoints_triggered (&ecs->ws);
5797
5798   /* If necessary, step over this watchpoint.  We'll be back to display
5799      it in a moment.  */
5800   if (stopped_by_watchpoint
5801       && (target_have_steppable_watchpoint
5802           || gdbarch_have_nonsteppable_watchpoint (gdbarch)))
5803     {
5804       /* At this point, we are stopped at an instruction which has
5805          attempted to write to a piece of memory under control of
5806          a watchpoint.  The instruction hasn't actually executed
5807          yet.  If we were to evaluate the watchpoint expression
5808          now, we would get the old value, and therefore no change
5809          would seem to have occurred.
5810
5811          In order to make watchpoints work `right', we really need
5812          to complete the memory write, and then evaluate the
5813          watchpoint expression.  We do this by single-stepping the
5814          target.
5815
5816          It may not be necessary to disable the watchpoint to step over
5817          it.  For example, the PA can (with some kernel cooperation)
5818          single step over a watchpoint without disabling the watchpoint.
5819
5820          It is far more common to need to disable a watchpoint to step
5821          the inferior over it.  If we have non-steppable watchpoints,
5822          we must disable the current watchpoint; it's simplest to
5823          disable all watchpoints.
5824
5825          Any breakpoint at PC must also be stepped over -- if there's
5826          one, it will have already triggered before the watchpoint
5827          triggered, and we either already reported it to the user, or
5828          it didn't cause a stop and we called keep_going.  In either
5829          case, if there was a breakpoint at PC, we must be trying to
5830          step past it.  */
5831       ecs->event_thread->stepping_over_watchpoint = 1;
5832       keep_going (ecs);
5833       return;
5834     }
5835
5836   ecs->event_thread->stepping_over_breakpoint = 0;
5837   ecs->event_thread->stepping_over_watchpoint = 0;
5838   bpstat_clear (&ecs->event_thread->control.stop_bpstat);
5839   ecs->event_thread->control.stop_step = 0;
5840   stop_print_frame = 1;
5841   stopped_by_random_signal = 0;
5842
5843   /* Hide inlined functions starting here, unless we just performed stepi or
5844      nexti.  After stepi and nexti, always show the innermost frame (not any
5845      inline function call sites).  */
5846   if (ecs->event_thread->control.step_range_end != 1)
5847     {
5848       const address_space *aspace =
5849         get_thread_regcache (ecs->ptid)->aspace ();
5850
5851       /* skip_inline_frames is expensive, so we avoid it if we can
5852          determine that the address is one where functions cannot have
5853          been inlined.  This improves performance with inferiors that
5854          load a lot of shared libraries, because the solib event
5855          breakpoint is defined as the address of a function (i.e. not
5856          inline).  Note that we have to check the previous PC as well
5857          as the current one to catch cases when we have just
5858          single-stepped off a breakpoint prior to reinstating it.
5859          Note that we're assuming that the code we single-step to is
5860          not inline, but that's not definitive: there's nothing
5861          preventing the event breakpoint function from containing
5862          inlined code, and the single-step ending up there.  If the
5863          user had set a breakpoint on that inlined code, the missing
5864          skip_inline_frames call would break things.  Fortunately
5865          that's an extremely unlikely scenario.  */
5866       if (!pc_at_non_inline_function (aspace, stop_pc, &ecs->ws)
5867           && !(ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5868                && ecs->event_thread->control.trap_expected
5869                && pc_at_non_inline_function (aspace,
5870                                              ecs->event_thread->prev_pc,
5871                                              &ecs->ws)))
5872         {
5873           skip_inline_frames (ecs->ptid);
5874
5875           /* Re-fetch current thread's frame in case that invalidated
5876              the frame cache.  */
5877           frame = get_current_frame ();
5878           gdbarch = get_frame_arch (frame);
5879         }
5880     }
5881
5882   if (ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5883       && ecs->event_thread->control.trap_expected
5884       && gdbarch_single_step_through_delay_p (gdbarch)
5885       && currently_stepping (ecs->event_thread))
5886     {
5887       /* We're trying to step off a breakpoint.  Turns out that we're
5888          also on an instruction that needs to be stepped multiple
5889          times before it's been fully executing.  E.g., architectures
5890          with a delay slot.  It needs to be stepped twice, once for
5891          the instruction and once for the delay slot.  */
5892       int step_through_delay
5893         = gdbarch_single_step_through_delay (gdbarch, frame);
5894
5895       if (debug_infrun && step_through_delay)
5896         fprintf_unfiltered (gdb_stdlog, "infrun: step through delay\n");
5897       if (ecs->event_thread->control.step_range_end == 0
5898           && step_through_delay)
5899         {
5900           /* The user issued a continue when stopped at a breakpoint.
5901              Set up for another trap and get out of here.  */
5902          ecs->event_thread->stepping_over_breakpoint = 1;
5903          keep_going (ecs);
5904          return;
5905         }
5906       else if (step_through_delay)
5907         {
5908           /* The user issued a step when stopped at a breakpoint.
5909              Maybe we should stop, maybe we should not - the delay
5910              slot *might* correspond to a line of source.  In any
5911              case, don't decide that here, just set 
5912              ecs->stepping_over_breakpoint, making sure we 
5913              single-step again before breakpoints are re-inserted.  */
5914           ecs->event_thread->stepping_over_breakpoint = 1;
5915         }
5916     }
5917
5918   /* See if there is a breakpoint/watchpoint/catchpoint/etc. that
5919      handles this event.  */
5920   ecs->event_thread->control.stop_bpstat
5921     = bpstat_stop_status (get_current_regcache ()->aspace (),
5922                           stop_pc, ecs->ptid, &ecs->ws);
5923
5924   /* Following in case break condition called a
5925      function.  */
5926   stop_print_frame = 1;
5927
5928   /* This is where we handle "moribund" watchpoints.  Unlike
5929      software breakpoints traps, hardware watchpoint traps are
5930      always distinguishable from random traps.  If no high-level
5931      watchpoint is associated with the reported stop data address
5932      anymore, then the bpstat does not explain the signal ---
5933      simply make sure to ignore it if `stopped_by_watchpoint' is
5934      set.  */
5935
5936   if (debug_infrun
5937       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
5938       && !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat,
5939                                   GDB_SIGNAL_TRAP)
5940       && stopped_by_watchpoint)
5941     fprintf_unfiltered (gdb_stdlog,
5942                         "infrun: no user watchpoint explains "
5943                         "watchpoint SIGTRAP, ignoring\n");
5944
5945   /* NOTE: cagney/2003-03-29: These checks for a random signal
5946      at one stage in the past included checks for an inferior
5947      function call's call dummy's return breakpoint.  The original
5948      comment, that went with the test, read:
5949
5950      ``End of a stack dummy.  Some systems (e.g. Sony news) give
5951      another signal besides SIGTRAP, so check here as well as
5952      above.''
5953
5954      If someone ever tries to get call dummys on a
5955      non-executable stack to work (where the target would stop
5956      with something like a SIGSEGV), then those tests might need
5957      to be re-instated.  Given, however, that the tests were only
5958      enabled when momentary breakpoints were not being used, I
5959      suspect that it won't be the case.
5960
5961      NOTE: kettenis/2004-02-05: Indeed such checks don't seem to
5962      be necessary for call dummies on a non-executable stack on
5963      SPARC.  */
5964
5965   /* See if the breakpoints module can explain the signal.  */
5966   random_signal
5967     = !bpstat_explains_signal (ecs->event_thread->control.stop_bpstat,
5968                                ecs->event_thread->suspend.stop_signal);
5969
5970   /* Maybe this was a trap for a software breakpoint that has since
5971      been removed.  */
5972   if (random_signal && target_stopped_by_sw_breakpoint ())
5973     {
5974       if (program_breakpoint_here_p (gdbarch, stop_pc))
5975         {
5976           struct regcache *regcache;
5977           int decr_pc;
5978
5979           /* Re-adjust PC to what the program would see if GDB was not
5980              debugging it.  */
5981           regcache = get_thread_regcache (ecs->event_thread->ptid);
5982           decr_pc = gdbarch_decr_pc_after_break (gdbarch);
5983           if (decr_pc != 0)
5984             {
5985               gdb::optional<scoped_restore_tmpl<int>>
5986                 restore_operation_disable;
5987
5988               if (record_full_is_used ())
5989                 restore_operation_disable.emplace
5990                   (record_full_gdb_operation_disable_set ());
5991
5992               regcache_write_pc (regcache, stop_pc + decr_pc);
5993             }
5994         }
5995       else
5996         {
5997           /* A delayed software breakpoint event.  Ignore the trap.  */
5998           if (debug_infrun)
5999             fprintf_unfiltered (gdb_stdlog,
6000                                 "infrun: delayed software breakpoint "
6001                                 "trap, ignoring\n");
6002           random_signal = 0;
6003         }
6004     }
6005
6006   /* Maybe this was a trap for a hardware breakpoint/watchpoint that
6007      has since been removed.  */
6008   if (random_signal && target_stopped_by_hw_breakpoint ())
6009     {
6010       /* A delayed hardware breakpoint event.  Ignore the trap.  */
6011       if (debug_infrun)
6012         fprintf_unfiltered (gdb_stdlog,
6013                             "infrun: delayed hardware breakpoint/watchpoint "
6014                             "trap, ignoring\n");
6015       random_signal = 0;
6016     }
6017
6018   /* If not, perhaps stepping/nexting can.  */
6019   if (random_signal)
6020     random_signal = !(ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP
6021                       && currently_stepping (ecs->event_thread));
6022
6023   /* Perhaps the thread hit a single-step breakpoint of _another_
6024      thread.  Single-step breakpoints are transparent to the
6025      breakpoints module.  */
6026   if (random_signal)
6027     random_signal = !ecs->hit_singlestep_breakpoint;
6028
6029   /* No?  Perhaps we got a moribund watchpoint.  */
6030   if (random_signal)
6031     random_signal = !stopped_by_watchpoint;
6032
6033   /* Always stop if the user explicitly requested this thread to
6034      remain stopped.  */
6035   if (ecs->event_thread->stop_requested)
6036     {
6037       random_signal = 1;
6038       if (debug_infrun)
6039         fprintf_unfiltered (gdb_stdlog, "infrun: user-requested stop\n");
6040     }
6041
6042   /* For the program's own signals, act according to
6043      the signal handling tables.  */
6044
6045   if (random_signal)
6046     {
6047       /* Signal not for debugging purposes.  */
6048       struct inferior *inf = find_inferior_ptid (ecs->ptid);
6049       enum gdb_signal stop_signal = ecs->event_thread->suspend.stop_signal;
6050
6051       if (debug_infrun)
6052          fprintf_unfiltered (gdb_stdlog, "infrun: random signal (%s)\n",
6053                              gdb_signal_to_symbol_string (stop_signal));
6054
6055       stopped_by_random_signal = 1;
6056
6057       /* Always stop on signals if we're either just gaining control
6058          of the program, or the user explicitly requested this thread
6059          to remain stopped.  */
6060       if (stop_soon != NO_STOP_QUIETLY
6061           || ecs->event_thread->stop_requested
6062           || (!inf->detaching
6063               && signal_stop_state (ecs->event_thread->suspend.stop_signal)))
6064         {
6065           stop_waiting (ecs);
6066           return;
6067         }
6068
6069       /* Notify observers the signal has "handle print" set.  Note we
6070          returned early above if stopping; normal_stop handles the
6071          printing in that case.  */
6072       if (signal_print[ecs->event_thread->suspend.stop_signal])
6073         {
6074           /* The signal table tells us to print about this signal.  */
6075           target_terminal::ours_for_output ();
6076           observer_notify_signal_received (ecs->event_thread->suspend.stop_signal);
6077           target_terminal::inferior ();
6078         }
6079
6080       /* Clear the signal if it should not be passed.  */
6081       if (signal_program[ecs->event_thread->suspend.stop_signal] == 0)
6082         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
6083
6084       if (ecs->event_thread->prev_pc == stop_pc
6085           && ecs->event_thread->control.trap_expected
6086           && ecs->event_thread->control.step_resume_breakpoint == NULL)
6087         {
6088           /* We were just starting a new sequence, attempting to
6089              single-step off of a breakpoint and expecting a SIGTRAP.
6090              Instead this signal arrives.  This signal will take us out
6091              of the stepping range so GDB needs to remember to, when
6092              the signal handler returns, resume stepping off that
6093              breakpoint.  */
6094           /* To simplify things, "continue" is forced to use the same
6095              code paths as single-step - set a breakpoint at the
6096              signal return address and then, once hit, step off that
6097              breakpoint.  */
6098           if (debug_infrun)
6099             fprintf_unfiltered (gdb_stdlog,
6100                                 "infrun: signal arrived while stepping over "
6101                                 "breakpoint\n");
6102
6103           insert_hp_step_resume_breakpoint_at_frame (frame);
6104           ecs->event_thread->step_after_step_resume_breakpoint = 1;
6105           /* Reset trap_expected to ensure breakpoints are re-inserted.  */
6106           ecs->event_thread->control.trap_expected = 0;
6107
6108           /* If we were nexting/stepping some other thread, switch to
6109              it, so that we don't continue it, losing control.  */
6110           if (!switch_back_to_stepped_thread (ecs))
6111             keep_going (ecs);
6112           return;
6113         }
6114
6115       if (ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_0
6116           && (pc_in_thread_step_range (stop_pc, ecs->event_thread)
6117               || ecs->event_thread->control.step_range_end == 1)
6118           && frame_id_eq (get_stack_frame_id (frame),
6119                           ecs->event_thread->control.step_stack_frame_id)
6120           && ecs->event_thread->control.step_resume_breakpoint == NULL)
6121         {
6122           /* The inferior is about to take a signal that will take it
6123              out of the single step range.  Set a breakpoint at the
6124              current PC (which is presumably where the signal handler
6125              will eventually return) and then allow the inferior to
6126              run free.
6127
6128              Note that this is only needed for a signal delivered
6129              while in the single-step range.  Nested signals aren't a
6130              problem as they eventually all return.  */
6131           if (debug_infrun)
6132             fprintf_unfiltered (gdb_stdlog,
6133                                 "infrun: signal may take us out of "
6134                                 "single-step range\n");
6135
6136           clear_step_over_info ();
6137           insert_hp_step_resume_breakpoint_at_frame (frame);
6138           ecs->event_thread->step_after_step_resume_breakpoint = 1;
6139           /* Reset trap_expected to ensure breakpoints are re-inserted.  */
6140           ecs->event_thread->control.trap_expected = 0;
6141           keep_going (ecs);
6142           return;
6143         }
6144
6145       /* Note: step_resume_breakpoint may be non-NULL.  This occures
6146          when either there's a nested signal, or when there's a
6147          pending signal enabled just as the signal handler returns
6148          (leaving the inferior at the step-resume-breakpoint without
6149          actually executing it).  Either way continue until the
6150          breakpoint is really hit.  */
6151
6152       if (!switch_back_to_stepped_thread (ecs))
6153         {
6154           if (debug_infrun)
6155             fprintf_unfiltered (gdb_stdlog,
6156                                 "infrun: random signal, keep going\n");
6157
6158           keep_going (ecs);
6159         }
6160       return;
6161     }
6162
6163   process_event_stop_test (ecs);
6164 }
6165
6166 /* Come here when we've got some debug event / signal we can explain
6167    (IOW, not a random signal), and test whether it should cause a
6168    stop, or whether we should resume the inferior (transparently).
6169    E.g., could be a breakpoint whose condition evaluates false; we
6170    could be still stepping within the line; etc.  */
6171
6172 static void
6173 process_event_stop_test (struct execution_control_state *ecs)
6174 {
6175   struct symtab_and_line stop_pc_sal;
6176   struct frame_info *frame;
6177   struct gdbarch *gdbarch;
6178   CORE_ADDR jmp_buf_pc;
6179   struct bpstat_what what;
6180
6181   /* Handle cases caused by hitting a breakpoint.  */
6182
6183   frame = get_current_frame ();
6184   gdbarch = get_frame_arch (frame);
6185
6186   what = bpstat_what (ecs->event_thread->control.stop_bpstat);
6187
6188   if (what.call_dummy)
6189     {
6190       stop_stack_dummy = what.call_dummy;
6191     }
6192
6193   /* A few breakpoint types have callbacks associated (e.g.,
6194      bp_jit_event).  Run them now.  */
6195   bpstat_run_callbacks (ecs->event_thread->control.stop_bpstat);
6196
6197   /* If we hit an internal event that triggers symbol changes, the
6198      current frame will be invalidated within bpstat_what (e.g., if we
6199      hit an internal solib event).  Re-fetch it.  */
6200   frame = get_current_frame ();
6201   gdbarch = get_frame_arch (frame);
6202
6203   switch (what.main_action)
6204     {
6205     case BPSTAT_WHAT_SET_LONGJMP_RESUME:
6206       /* If we hit the breakpoint at longjmp while stepping, we
6207          install a momentary breakpoint at the target of the
6208          jmp_buf.  */
6209
6210       if (debug_infrun)
6211         fprintf_unfiltered (gdb_stdlog,
6212                             "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME\n");
6213
6214       ecs->event_thread->stepping_over_breakpoint = 1;
6215
6216       if (what.is_longjmp)
6217         {
6218           struct value *arg_value;
6219
6220           /* If we set the longjmp breakpoint via a SystemTap probe,
6221              then use it to extract the arguments.  The destination PC
6222              is the third argument to the probe.  */
6223           arg_value = probe_safe_evaluate_at_pc (frame, 2);
6224           if (arg_value)
6225             {
6226               jmp_buf_pc = value_as_address (arg_value);
6227               jmp_buf_pc = gdbarch_addr_bits_remove (gdbarch, jmp_buf_pc);
6228             }
6229           else if (!gdbarch_get_longjmp_target_p (gdbarch)
6230                    || !gdbarch_get_longjmp_target (gdbarch,
6231                                                    frame, &jmp_buf_pc))
6232             {
6233               if (debug_infrun)
6234                 fprintf_unfiltered (gdb_stdlog,
6235                                     "infrun: BPSTAT_WHAT_SET_LONGJMP_RESUME "
6236                                     "(!gdbarch_get_longjmp_target)\n");
6237               keep_going (ecs);
6238               return;
6239             }
6240
6241           /* Insert a breakpoint at resume address.  */
6242           insert_longjmp_resume_breakpoint (gdbarch, jmp_buf_pc);
6243         }
6244       else
6245         check_exception_resume (ecs, frame);
6246       keep_going (ecs);
6247       return;
6248
6249     case BPSTAT_WHAT_CLEAR_LONGJMP_RESUME:
6250       {
6251         struct frame_info *init_frame;
6252
6253         /* There are several cases to consider.
6254
6255            1. The initiating frame no longer exists.  In this case we
6256            must stop, because the exception or longjmp has gone too
6257            far.
6258
6259            2. The initiating frame exists, and is the same as the
6260            current frame.  We stop, because the exception or longjmp
6261            has been caught.
6262
6263            3. The initiating frame exists and is different from the
6264            current frame.  This means the exception or longjmp has
6265            been caught beneath the initiating frame, so keep going.
6266
6267            4. longjmp breakpoint has been placed just to protect
6268            against stale dummy frames and user is not interested in
6269            stopping around longjmps.  */
6270
6271         if (debug_infrun)
6272           fprintf_unfiltered (gdb_stdlog,
6273                               "infrun: BPSTAT_WHAT_CLEAR_LONGJMP_RESUME\n");
6274
6275         gdb_assert (ecs->event_thread->control.exception_resume_breakpoint
6276                     != NULL);
6277         delete_exception_resume_breakpoint (ecs->event_thread);
6278
6279         if (what.is_longjmp)
6280           {
6281             check_longjmp_breakpoint_for_call_dummy (ecs->event_thread);
6282
6283             if (!frame_id_p (ecs->event_thread->initiating_frame))
6284               {
6285                 /* Case 4.  */
6286                 keep_going (ecs);
6287                 return;
6288               }
6289           }
6290
6291         init_frame = frame_find_by_id (ecs->event_thread->initiating_frame);
6292
6293         if (init_frame)
6294           {
6295             struct frame_id current_id
6296               = get_frame_id (get_current_frame ());
6297             if (frame_id_eq (current_id,
6298                              ecs->event_thread->initiating_frame))
6299               {
6300                 /* Case 2.  Fall through.  */
6301               }
6302             else
6303               {
6304                 /* Case 3.  */
6305                 keep_going (ecs);
6306                 return;
6307               }
6308           }
6309
6310         /* For Cases 1 and 2, remove the step-resume breakpoint, if it
6311            exists.  */
6312         delete_step_resume_breakpoint (ecs->event_thread);
6313
6314         end_stepping_range (ecs);
6315       }
6316       return;
6317
6318     case BPSTAT_WHAT_SINGLE:
6319       if (debug_infrun)
6320         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_SINGLE\n");
6321       ecs->event_thread->stepping_over_breakpoint = 1;
6322       /* Still need to check other stuff, at least the case where we
6323          are stepping and step out of the right range.  */
6324       break;
6325
6326     case BPSTAT_WHAT_STEP_RESUME:
6327       if (debug_infrun)
6328         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STEP_RESUME\n");
6329
6330       delete_step_resume_breakpoint (ecs->event_thread);
6331       if (ecs->event_thread->control.proceed_to_finish
6332           && execution_direction == EXEC_REVERSE)
6333         {
6334           struct thread_info *tp = ecs->event_thread;
6335
6336           /* We are finishing a function in reverse, and just hit the
6337              step-resume breakpoint at the start address of the
6338              function, and we're almost there -- just need to back up
6339              by one more single-step, which should take us back to the
6340              function call.  */
6341           tp->control.step_range_start = tp->control.step_range_end = 1;
6342           keep_going (ecs);
6343           return;
6344         }
6345       fill_in_stop_func (gdbarch, ecs);
6346       if (stop_pc == ecs->stop_func_start
6347           && execution_direction == EXEC_REVERSE)
6348         {
6349           /* We are stepping over a function call in reverse, and just
6350              hit the step-resume breakpoint at the start address of
6351              the function.  Go back to single-stepping, which should
6352              take us back to the function call.  */
6353           ecs->event_thread->stepping_over_breakpoint = 1;
6354           keep_going (ecs);
6355           return;
6356         }
6357       break;
6358
6359     case BPSTAT_WHAT_STOP_NOISY:
6360       if (debug_infrun)
6361         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_NOISY\n");
6362       stop_print_frame = 1;
6363
6364       /* Assume the thread stopped for a breapoint.  We'll still check
6365          whether a/the breakpoint is there when the thread is next
6366          resumed.  */
6367       ecs->event_thread->stepping_over_breakpoint = 1;
6368
6369       stop_waiting (ecs);
6370       return;
6371
6372     case BPSTAT_WHAT_STOP_SILENT:
6373       if (debug_infrun)
6374         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_STOP_SILENT\n");
6375       stop_print_frame = 0;
6376
6377       /* Assume the thread stopped for a breapoint.  We'll still check
6378          whether a/the breakpoint is there when the thread is next
6379          resumed.  */
6380       ecs->event_thread->stepping_over_breakpoint = 1;
6381       stop_waiting (ecs);
6382       return;
6383
6384     case BPSTAT_WHAT_HP_STEP_RESUME:
6385       if (debug_infrun)
6386         fprintf_unfiltered (gdb_stdlog, "infrun: BPSTAT_WHAT_HP_STEP_RESUME\n");
6387
6388       delete_step_resume_breakpoint (ecs->event_thread);
6389       if (ecs->event_thread->step_after_step_resume_breakpoint)
6390         {
6391           /* Back when the step-resume breakpoint was inserted, we
6392              were trying to single-step off a breakpoint.  Go back to
6393              doing that.  */
6394           ecs->event_thread->step_after_step_resume_breakpoint = 0;
6395           ecs->event_thread->stepping_over_breakpoint = 1;
6396           keep_going (ecs);
6397           return;
6398         }
6399       break;
6400
6401     case BPSTAT_WHAT_KEEP_CHECKING:
6402       break;
6403     }
6404
6405   /* If we stepped a permanent breakpoint and we had a high priority
6406      step-resume breakpoint for the address we stepped, but we didn't
6407      hit it, then we must have stepped into the signal handler.  The
6408      step-resume was only necessary to catch the case of _not_
6409      stepping into the handler, so delete it, and fall through to
6410      checking whether the step finished.  */
6411   if (ecs->event_thread->stepped_breakpoint)
6412     {
6413       struct breakpoint *sr_bp
6414         = ecs->event_thread->control.step_resume_breakpoint;
6415
6416       if (sr_bp != NULL
6417           && sr_bp->loc->permanent
6418           && sr_bp->type == bp_hp_step_resume
6419           && sr_bp->loc->address == ecs->event_thread->prev_pc)
6420         {
6421           if (debug_infrun)
6422             fprintf_unfiltered (gdb_stdlog,
6423                                 "infrun: stepped permanent breakpoint, stopped in "
6424                                 "handler\n");
6425           delete_step_resume_breakpoint (ecs->event_thread);
6426           ecs->event_thread->step_after_step_resume_breakpoint = 0;
6427         }
6428     }
6429
6430   /* We come here if we hit a breakpoint but should not stop for it.
6431      Possibly we also were stepping and should stop for that.  So fall
6432      through and test for stepping.  But, if not stepping, do not
6433      stop.  */
6434
6435   /* In all-stop mode, if we're currently stepping but have stopped in
6436      some other thread, we need to switch back to the stepped thread.  */
6437   if (switch_back_to_stepped_thread (ecs))
6438     return;
6439
6440   if (ecs->event_thread->control.step_resume_breakpoint)
6441     {
6442       if (debug_infrun)
6443          fprintf_unfiltered (gdb_stdlog,
6444                              "infrun: step-resume breakpoint is inserted\n");
6445
6446       /* Having a step-resume breakpoint overrides anything
6447          else having to do with stepping commands until
6448          that breakpoint is reached.  */
6449       keep_going (ecs);
6450       return;
6451     }
6452
6453   if (ecs->event_thread->control.step_range_end == 0)
6454     {
6455       if (debug_infrun)
6456          fprintf_unfiltered (gdb_stdlog, "infrun: no stepping, continue\n");
6457       /* Likewise if we aren't even stepping.  */
6458       keep_going (ecs);
6459       return;
6460     }
6461
6462   /* Re-fetch current thread's frame in case the code above caused
6463      the frame cache to be re-initialized, making our FRAME variable
6464      a dangling pointer.  */
6465   frame = get_current_frame ();
6466   gdbarch = get_frame_arch (frame);
6467   fill_in_stop_func (gdbarch, ecs);
6468
6469   /* If stepping through a line, keep going if still within it.
6470
6471      Note that step_range_end is the address of the first instruction
6472      beyond the step range, and NOT the address of the last instruction
6473      within it!
6474
6475      Note also that during reverse execution, we may be stepping
6476      through a function epilogue and therefore must detect when
6477      the current-frame changes in the middle of a line.  */
6478
6479   if (pc_in_thread_step_range (stop_pc, ecs->event_thread)
6480       && (execution_direction != EXEC_REVERSE
6481           || frame_id_eq (get_frame_id (frame),
6482                           ecs->event_thread->control.step_frame_id)))
6483     {
6484       if (debug_infrun)
6485         fprintf_unfiltered
6486           (gdb_stdlog, "infrun: stepping inside range [%s-%s]\n",
6487            paddress (gdbarch, ecs->event_thread->control.step_range_start),
6488            paddress (gdbarch, ecs->event_thread->control.step_range_end));
6489
6490       /* Tentatively re-enable range stepping; `resume' disables it if
6491          necessary (e.g., if we're stepping over a breakpoint or we
6492          have software watchpoints).  */
6493       ecs->event_thread->control.may_range_step = 1;
6494
6495       /* When stepping backward, stop at beginning of line range
6496          (unless it's the function entry point, in which case
6497          keep going back to the call point).  */
6498       if (stop_pc == ecs->event_thread->control.step_range_start
6499           && stop_pc != ecs->stop_func_start
6500           && execution_direction == EXEC_REVERSE)
6501         end_stepping_range (ecs);
6502       else
6503         keep_going (ecs);
6504
6505       return;
6506     }
6507
6508   /* We stepped out of the stepping range.  */
6509
6510   /* If we are stepping at the source level and entered the runtime
6511      loader dynamic symbol resolution code...
6512
6513      EXEC_FORWARD: we keep on single stepping until we exit the run
6514      time loader code and reach the callee's address.
6515
6516      EXEC_REVERSE: we've already executed the callee (backward), and
6517      the runtime loader code is handled just like any other
6518      undebuggable function call.  Now we need only keep stepping
6519      backward through the trampoline code, and that's handled further
6520      down, so there is nothing for us to do here.  */
6521
6522   if (execution_direction != EXEC_REVERSE
6523       && ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6524       && in_solib_dynsym_resolve_code (stop_pc))
6525     {
6526       CORE_ADDR pc_after_resolver =
6527         gdbarch_skip_solib_resolver (gdbarch, stop_pc);
6528
6529       if (debug_infrun)
6530          fprintf_unfiltered (gdb_stdlog,
6531                              "infrun: stepped into dynsym resolve code\n");
6532
6533       if (pc_after_resolver)
6534         {
6535           /* Set up a step-resume breakpoint at the address
6536              indicated by SKIP_SOLIB_RESOLVER.  */
6537           symtab_and_line sr_sal;
6538           sr_sal.pc = pc_after_resolver;
6539           sr_sal.pspace = get_frame_program_space (frame);
6540
6541           insert_step_resume_breakpoint_at_sal (gdbarch,
6542                                                 sr_sal, null_frame_id);
6543         }
6544
6545       keep_going (ecs);
6546       return;
6547     }
6548
6549   if (ecs->event_thread->control.step_range_end != 1
6550       && (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6551           || ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6552       && get_frame_type (frame) == SIGTRAMP_FRAME)
6553     {
6554       if (debug_infrun)
6555          fprintf_unfiltered (gdb_stdlog,
6556                              "infrun: stepped into signal trampoline\n");
6557       /* The inferior, while doing a "step" or "next", has ended up in
6558          a signal trampoline (either by a signal being delivered or by
6559          the signal handler returning).  Just single-step until the
6560          inferior leaves the trampoline (either by calling the handler
6561          or returning).  */
6562       keep_going (ecs);
6563       return;
6564     }
6565
6566   /* If we're in the return path from a shared library trampoline,
6567      we want to proceed through the trampoline when stepping.  */
6568   /* macro/2012-04-25: This needs to come before the subroutine
6569      call check below as on some targets return trampolines look
6570      like subroutine calls (MIPS16 return thunks).  */
6571   if (gdbarch_in_solib_return_trampoline (gdbarch,
6572                                           stop_pc, ecs->stop_func_name)
6573       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
6574     {
6575       /* Determine where this trampoline returns.  */
6576       CORE_ADDR real_stop_pc;
6577
6578       real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
6579
6580       if (debug_infrun)
6581          fprintf_unfiltered (gdb_stdlog,
6582                              "infrun: stepped into solib return tramp\n");
6583
6584       /* Only proceed through if we know where it's going.  */
6585       if (real_stop_pc)
6586         {
6587           /* And put the step-breakpoint there and go until there.  */
6588           symtab_and_line sr_sal;
6589           sr_sal.pc = real_stop_pc;
6590           sr_sal.section = find_pc_overlay (sr_sal.pc);
6591           sr_sal.pspace = get_frame_program_space (frame);
6592
6593           /* Do not specify what the fp should be when we stop since
6594              on some machines the prologue is where the new fp value
6595              is established.  */
6596           insert_step_resume_breakpoint_at_sal (gdbarch,
6597                                                 sr_sal, null_frame_id);
6598
6599           /* Restart without fiddling with the step ranges or
6600              other state.  */
6601           keep_going (ecs);
6602           return;
6603         }
6604     }
6605
6606   /* Check for subroutine calls.  The check for the current frame
6607      equalling the step ID is not necessary - the check of the
6608      previous frame's ID is sufficient - but it is a common case and
6609      cheaper than checking the previous frame's ID.
6610
6611      NOTE: frame_id_eq will never report two invalid frame IDs as
6612      being equal, so to get into this block, both the current and
6613      previous frame must have valid frame IDs.  */
6614   /* The outer_frame_id check is a heuristic to detect stepping
6615      through startup code.  If we step over an instruction which
6616      sets the stack pointer from an invalid value to a valid value,
6617      we may detect that as a subroutine call from the mythical
6618      "outermost" function.  This could be fixed by marking
6619      outermost frames as !stack_p,code_p,special_p.  Then the
6620      initial outermost frame, before sp was valid, would
6621      have code_addr == &_start.  See the comment in frame_id_eq
6622      for more.  */
6623   if (!frame_id_eq (get_stack_frame_id (frame),
6624                     ecs->event_thread->control.step_stack_frame_id)
6625       && (frame_id_eq (frame_unwind_caller_id (get_current_frame ()),
6626                        ecs->event_thread->control.step_stack_frame_id)
6627           && (!frame_id_eq (ecs->event_thread->control.step_stack_frame_id,
6628                             outer_frame_id)
6629               || (ecs->event_thread->control.step_start_function
6630                   != find_pc_function (stop_pc)))))
6631     {
6632       CORE_ADDR real_stop_pc;
6633
6634       if (debug_infrun)
6635          fprintf_unfiltered (gdb_stdlog, "infrun: stepped into subroutine\n");
6636
6637       if (ecs->event_thread->control.step_over_calls == STEP_OVER_NONE)
6638         {
6639           /* I presume that step_over_calls is only 0 when we're
6640              supposed to be stepping at the assembly language level
6641              ("stepi").  Just stop.  */
6642           /* And this works the same backward as frontward.  MVS */
6643           end_stepping_range (ecs);
6644           return;
6645         }
6646
6647       /* Reverse stepping through solib trampolines.  */
6648
6649       if (execution_direction == EXEC_REVERSE
6650           && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE
6651           && (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
6652               || (ecs->stop_func_start == 0
6653                   && in_solib_dynsym_resolve_code (stop_pc))))
6654         {
6655           /* Any solib trampoline code can be handled in reverse
6656              by simply continuing to single-step.  We have already
6657              executed the solib function (backwards), and a few 
6658              steps will take us back through the trampoline to the
6659              caller.  */
6660           keep_going (ecs);
6661           return;
6662         }
6663
6664       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6665         {
6666           /* We're doing a "next".
6667
6668              Normal (forward) execution: set a breakpoint at the
6669              callee's return address (the address at which the caller
6670              will resume).
6671
6672              Reverse (backward) execution.  set the step-resume
6673              breakpoint at the start of the function that we just
6674              stepped into (backwards), and continue to there.  When we
6675              get there, we'll need to single-step back to the caller.  */
6676
6677           if (execution_direction == EXEC_REVERSE)
6678             {
6679               /* If we're already at the start of the function, we've either
6680                  just stepped backward into a single instruction function,
6681                  or stepped back out of a signal handler to the first instruction
6682                  of the function.  Just keep going, which will single-step back
6683                  to the caller.  */
6684               if (ecs->stop_func_start != stop_pc && ecs->stop_func_start != 0)
6685                 {
6686                   /* Normal function call return (static or dynamic).  */
6687                   symtab_and_line sr_sal;
6688                   sr_sal.pc = ecs->stop_func_start;
6689                   sr_sal.pspace = get_frame_program_space (frame);
6690                   insert_step_resume_breakpoint_at_sal (gdbarch,
6691                                                         sr_sal, null_frame_id);
6692                 }
6693             }
6694           else
6695             insert_step_resume_breakpoint_at_caller (frame);
6696
6697           keep_going (ecs);
6698           return;
6699         }
6700
6701       /* If we are in a function call trampoline (a stub between the
6702          calling routine and the real function), locate the real
6703          function.  That's what tells us (a) whether we want to step
6704          into it at all, and (b) what prologue we want to run to the
6705          end of, if we do step into it.  */
6706       real_stop_pc = skip_language_trampoline (frame, stop_pc);
6707       if (real_stop_pc == 0)
6708         real_stop_pc = gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc);
6709       if (real_stop_pc != 0)
6710         ecs->stop_func_start = real_stop_pc;
6711
6712       if (real_stop_pc != 0 && in_solib_dynsym_resolve_code (real_stop_pc))
6713         {
6714           symtab_and_line sr_sal;
6715           sr_sal.pc = ecs->stop_func_start;
6716           sr_sal.pspace = get_frame_program_space (frame);
6717
6718           insert_step_resume_breakpoint_at_sal (gdbarch,
6719                                                 sr_sal, null_frame_id);
6720           keep_going (ecs);
6721           return;
6722         }
6723
6724       /* If we have line number information for the function we are
6725          thinking of stepping into and the function isn't on the skip
6726          list, step into it.
6727
6728          If there are several symtabs at that PC (e.g. with include
6729          files), just want to know whether *any* of them have line
6730          numbers.  find_pc_line handles this.  */
6731       {
6732         struct symtab_and_line tmp_sal;
6733
6734         tmp_sal = find_pc_line (ecs->stop_func_start, 0);
6735         if (tmp_sal.line != 0
6736             && !function_name_is_marked_for_skip (ecs->stop_func_name,
6737                                                   tmp_sal))
6738           {
6739             if (execution_direction == EXEC_REVERSE)
6740               handle_step_into_function_backward (gdbarch, ecs);
6741             else
6742               handle_step_into_function (gdbarch, ecs);
6743             return;
6744           }
6745       }
6746
6747       /* If we have no line number and the step-stop-if-no-debug is
6748          set, we stop the step so that the user has a chance to switch
6749          in assembly mode.  */
6750       if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6751           && step_stop_if_no_debug)
6752         {
6753           end_stepping_range (ecs);
6754           return;
6755         }
6756
6757       if (execution_direction == EXEC_REVERSE)
6758         {
6759           /* If we're already at the start of the function, we've either just
6760              stepped backward into a single instruction function without line
6761              number info, or stepped back out of a signal handler to the first
6762              instruction of the function without line number info.  Just keep
6763              going, which will single-step back to the caller.  */
6764           if (ecs->stop_func_start != stop_pc)
6765             {
6766               /* Set a breakpoint at callee's start address.
6767                  From there we can step once and be back in the caller.  */
6768               symtab_and_line sr_sal;
6769               sr_sal.pc = ecs->stop_func_start;
6770               sr_sal.pspace = get_frame_program_space (frame);
6771               insert_step_resume_breakpoint_at_sal (gdbarch,
6772                                                     sr_sal, null_frame_id);
6773             }
6774         }
6775       else
6776         /* Set a breakpoint at callee's return address (the address
6777            at which the caller will resume).  */
6778         insert_step_resume_breakpoint_at_caller (frame);
6779
6780       keep_going (ecs);
6781       return;
6782     }
6783
6784   /* Reverse stepping through solib trampolines.  */
6785
6786   if (execution_direction == EXEC_REVERSE
6787       && ecs->event_thread->control.step_over_calls != STEP_OVER_NONE)
6788     {
6789       if (gdbarch_skip_trampoline_code (gdbarch, frame, stop_pc)
6790           || (ecs->stop_func_start == 0
6791               && in_solib_dynsym_resolve_code (stop_pc)))
6792         {
6793           /* Any solib trampoline code can be handled in reverse
6794              by simply continuing to single-step.  We have already
6795              executed the solib function (backwards), and a few 
6796              steps will take us back through the trampoline to the
6797              caller.  */
6798           keep_going (ecs);
6799           return;
6800         }
6801       else if (in_solib_dynsym_resolve_code (stop_pc))
6802         {
6803           /* Stepped backward into the solib dynsym resolver.
6804              Set a breakpoint at its start and continue, then
6805              one more step will take us out.  */
6806           symtab_and_line sr_sal;
6807           sr_sal.pc = ecs->stop_func_start;
6808           sr_sal.pspace = get_frame_program_space (frame);
6809           insert_step_resume_breakpoint_at_sal (gdbarch, 
6810                                                 sr_sal, null_frame_id);
6811           keep_going (ecs);
6812           return;
6813         }
6814     }
6815
6816   stop_pc_sal = find_pc_line (stop_pc, 0);
6817
6818   /* NOTE: tausq/2004-05-24: This if block used to be done before all
6819      the trampoline processing logic, however, there are some trampolines 
6820      that have no names, so we should do trampoline handling first.  */
6821   if (ecs->event_thread->control.step_over_calls == STEP_OVER_UNDEBUGGABLE
6822       && ecs->stop_func_name == NULL
6823       && stop_pc_sal.line == 0)
6824     {
6825       if (debug_infrun)
6826          fprintf_unfiltered (gdb_stdlog,
6827                              "infrun: stepped into undebuggable function\n");
6828
6829       /* The inferior just stepped into, or returned to, an
6830          undebuggable function (where there is no debugging information
6831          and no line number corresponding to the address where the
6832          inferior stopped).  Since we want to skip this kind of code,
6833          we keep going until the inferior returns from this
6834          function - unless the user has asked us not to (via
6835          set step-mode) or we no longer know how to get back
6836          to the call site.  */
6837       if (step_stop_if_no_debug
6838           || !frame_id_p (frame_unwind_caller_id (frame)))
6839         {
6840           /* If we have no line number and the step-stop-if-no-debug
6841              is set, we stop the step so that the user has a chance to
6842              switch in assembly mode.  */
6843           end_stepping_range (ecs);
6844           return;
6845         }
6846       else
6847         {
6848           /* Set a breakpoint at callee's return address (the address
6849              at which the caller will resume).  */
6850           insert_step_resume_breakpoint_at_caller (frame);
6851           keep_going (ecs);
6852           return;
6853         }
6854     }
6855
6856   if (ecs->event_thread->control.step_range_end == 1)
6857     {
6858       /* It is stepi or nexti.  We always want to stop stepping after
6859          one instruction.  */
6860       if (debug_infrun)
6861          fprintf_unfiltered (gdb_stdlog, "infrun: stepi/nexti\n");
6862       end_stepping_range (ecs);
6863       return;
6864     }
6865
6866   if (stop_pc_sal.line == 0)
6867     {
6868       /* We have no line number information.  That means to stop
6869          stepping (does this always happen right after one instruction,
6870          when we do "s" in a function with no line numbers,
6871          or can this happen as a result of a return or longjmp?).  */
6872       if (debug_infrun)
6873          fprintf_unfiltered (gdb_stdlog, "infrun: no line number info\n");
6874       end_stepping_range (ecs);
6875       return;
6876     }
6877
6878   /* Look for "calls" to inlined functions, part one.  If the inline
6879      frame machinery detected some skipped call sites, we have entered
6880      a new inline function.  */
6881
6882   if (frame_id_eq (get_frame_id (get_current_frame ()),
6883                    ecs->event_thread->control.step_frame_id)
6884       && inline_skipped_frames (ecs->ptid))
6885     {
6886       if (debug_infrun)
6887         fprintf_unfiltered (gdb_stdlog,
6888                             "infrun: stepped into inlined function\n");
6889
6890       symtab_and_line call_sal = find_frame_sal (get_current_frame ());
6891
6892       if (ecs->event_thread->control.step_over_calls != STEP_OVER_ALL)
6893         {
6894           /* For "step", we're going to stop.  But if the call site
6895              for this inlined function is on the same source line as
6896              we were previously stepping, go down into the function
6897              first.  Otherwise stop at the call site.  */
6898
6899           if (call_sal.line == ecs->event_thread->current_line
6900               && call_sal.symtab == ecs->event_thread->current_symtab)
6901             step_into_inline_frame (ecs->ptid);
6902
6903           end_stepping_range (ecs);
6904           return;
6905         }
6906       else
6907         {
6908           /* For "next", we should stop at the call site if it is on a
6909              different source line.  Otherwise continue through the
6910              inlined function.  */
6911           if (call_sal.line == ecs->event_thread->current_line
6912               && call_sal.symtab == ecs->event_thread->current_symtab)
6913             keep_going (ecs);
6914           else
6915             end_stepping_range (ecs);
6916           return;
6917         }
6918     }
6919
6920   /* Look for "calls" to inlined functions, part two.  If we are still
6921      in the same real function we were stepping through, but we have
6922      to go further up to find the exact frame ID, we are stepping
6923      through a more inlined call beyond its call site.  */
6924
6925   if (get_frame_type (get_current_frame ()) == INLINE_FRAME
6926       && !frame_id_eq (get_frame_id (get_current_frame ()),
6927                        ecs->event_thread->control.step_frame_id)
6928       && stepped_in_from (get_current_frame (),
6929                           ecs->event_thread->control.step_frame_id))
6930     {
6931       if (debug_infrun)
6932         fprintf_unfiltered (gdb_stdlog,
6933                             "infrun: stepping through inlined function\n");
6934
6935       if (ecs->event_thread->control.step_over_calls == STEP_OVER_ALL)
6936         keep_going (ecs);
6937       else
6938         end_stepping_range (ecs);
6939       return;
6940     }
6941
6942   if ((stop_pc == stop_pc_sal.pc)
6943       && (ecs->event_thread->current_line != stop_pc_sal.line
6944           || ecs->event_thread->current_symtab != stop_pc_sal.symtab))
6945     {
6946       /* We are at the start of a different line.  So stop.  Note that
6947          we don't stop if we step into the middle of a different line.
6948          That is said to make things like for (;;) statements work
6949          better.  */
6950       if (debug_infrun)
6951          fprintf_unfiltered (gdb_stdlog,
6952                              "infrun: stepped to a different line\n");
6953       end_stepping_range (ecs);
6954       return;
6955     }
6956
6957   /* We aren't done stepping.
6958
6959      Optimize by setting the stepping range to the line.
6960      (We might not be in the original line, but if we entered a
6961      new line in mid-statement, we continue stepping.  This makes
6962      things like for(;;) statements work better.)  */
6963
6964   ecs->event_thread->control.step_range_start = stop_pc_sal.pc;
6965   ecs->event_thread->control.step_range_end = stop_pc_sal.end;
6966   ecs->event_thread->control.may_range_step = 1;
6967   set_step_info (frame, stop_pc_sal);
6968
6969   if (debug_infrun)
6970      fprintf_unfiltered (gdb_stdlog, "infrun: keep going\n");
6971   keep_going (ecs);
6972 }
6973
6974 /* In all-stop mode, if we're currently stepping but have stopped in
6975    some other thread, we may need to switch back to the stepped
6976    thread.  Returns true we set the inferior running, false if we left
6977    it stopped (and the event needs further processing).  */
6978
6979 static int
6980 switch_back_to_stepped_thread (struct execution_control_state *ecs)
6981 {
6982   if (!target_is_non_stop_p ())
6983     {
6984       struct thread_info *tp;
6985       struct thread_info *stepping_thread;
6986
6987       /* If any thread is blocked on some internal breakpoint, and we
6988          simply need to step over that breakpoint to get it going
6989          again, do that first.  */
6990
6991       /* However, if we see an event for the stepping thread, then we
6992          know all other threads have been moved past their breakpoints
6993          already.  Let the caller check whether the step is finished,
6994          etc., before deciding to move it past a breakpoint.  */
6995       if (ecs->event_thread->control.step_range_end != 0)
6996         return 0;
6997
6998       /* Check if the current thread is blocked on an incomplete
6999          step-over, interrupted by a random signal.  */
7000       if (ecs->event_thread->control.trap_expected
7001           && ecs->event_thread->suspend.stop_signal != GDB_SIGNAL_TRAP)
7002         {
7003           if (debug_infrun)
7004             {
7005               fprintf_unfiltered (gdb_stdlog,
7006                                   "infrun: need to finish step-over of [%s]\n",
7007                                   target_pid_to_str (ecs->event_thread->ptid));
7008             }
7009           keep_going (ecs);
7010           return 1;
7011         }
7012
7013       /* Check if the current thread is blocked by a single-step
7014          breakpoint of another thread.  */
7015       if (ecs->hit_singlestep_breakpoint)
7016        {
7017          if (debug_infrun)
7018            {
7019              fprintf_unfiltered (gdb_stdlog,
7020                                  "infrun: need to step [%s] over single-step "
7021                                  "breakpoint\n",
7022                                  target_pid_to_str (ecs->ptid));
7023            }
7024          keep_going (ecs);
7025          return 1;
7026        }
7027
7028       /* If this thread needs yet another step-over (e.g., stepping
7029          through a delay slot), do it first before moving on to
7030          another thread.  */
7031       if (thread_still_needs_step_over (ecs->event_thread))
7032         {
7033           if (debug_infrun)
7034             {
7035               fprintf_unfiltered (gdb_stdlog,
7036                                   "infrun: thread [%s] still needs step-over\n",
7037                                   target_pid_to_str (ecs->event_thread->ptid));
7038             }
7039           keep_going (ecs);
7040           return 1;
7041         }
7042
7043       /* If scheduler locking applies even if not stepping, there's no
7044          need to walk over threads.  Above we've checked whether the
7045          current thread is stepping.  If some other thread not the
7046          event thread is stepping, then it must be that scheduler
7047          locking is not in effect.  */
7048       if (schedlock_applies (ecs->event_thread))
7049         return 0;
7050
7051       /* Otherwise, we no longer expect a trap in the current thread.
7052          Clear the trap_expected flag before switching back -- this is
7053          what keep_going does as well, if we call it.  */
7054       ecs->event_thread->control.trap_expected = 0;
7055
7056       /* Likewise, clear the signal if it should not be passed.  */
7057       if (!signal_program[ecs->event_thread->suspend.stop_signal])
7058         ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
7059
7060       /* Do all pending step-overs before actually proceeding with
7061          step/next/etc.  */
7062       if (start_step_over ())
7063         {
7064           prepare_to_wait (ecs);
7065           return 1;
7066         }
7067
7068       /* Look for the stepping/nexting thread.  */
7069       stepping_thread = NULL;
7070
7071       ALL_NON_EXITED_THREADS (tp)
7072         {
7073           /* Ignore threads of processes the caller is not
7074              resuming.  */
7075           if (!sched_multi
7076               && ptid_get_pid (tp->ptid) != ptid_get_pid (ecs->ptid))
7077             continue;
7078
7079           /* When stepping over a breakpoint, we lock all threads
7080              except the one that needs to move past the breakpoint.
7081              If a non-event thread has this set, the "incomplete
7082              step-over" check above should have caught it earlier.  */
7083           if (tp->control.trap_expected)
7084             {
7085               internal_error (__FILE__, __LINE__,
7086                               "[%s] has inconsistent state: "
7087                               "trap_expected=%d\n",
7088                               target_pid_to_str (tp->ptid),
7089                               tp->control.trap_expected);
7090             }
7091
7092           /* Did we find the stepping thread?  */
7093           if (tp->control.step_range_end)
7094             {
7095               /* Yep.  There should only one though.  */
7096               gdb_assert (stepping_thread == NULL);
7097
7098               /* The event thread is handled at the top, before we
7099                  enter this loop.  */
7100               gdb_assert (tp != ecs->event_thread);
7101
7102               /* If some thread other than the event thread is
7103                  stepping, then scheduler locking can't be in effect,
7104                  otherwise we wouldn't have resumed the current event
7105                  thread in the first place.  */
7106               gdb_assert (!schedlock_applies (tp));
7107
7108               stepping_thread = tp;
7109             }
7110         }
7111
7112       if (stepping_thread != NULL)
7113         {
7114           if (debug_infrun)
7115             fprintf_unfiltered (gdb_stdlog,
7116                                 "infrun: switching back to stepped thread\n");
7117
7118           if (keep_going_stepped_thread (stepping_thread))
7119             {
7120               prepare_to_wait (ecs);
7121               return 1;
7122             }
7123         }
7124     }
7125
7126   return 0;
7127 }
7128
7129 /* Set a previously stepped thread back to stepping.  Returns true on
7130    success, false if the resume is not possible (e.g., the thread
7131    vanished).  */
7132
7133 static int
7134 keep_going_stepped_thread (struct thread_info *tp)
7135 {
7136   struct frame_info *frame;
7137   struct execution_control_state ecss;
7138   struct execution_control_state *ecs = &ecss;
7139
7140   /* If the stepping thread exited, then don't try to switch back and
7141      resume it, which could fail in several different ways depending
7142      on the target.  Instead, just keep going.
7143
7144      We can find a stepping dead thread in the thread list in two
7145      cases:
7146
7147      - The target supports thread exit events, and when the target
7148        tries to delete the thread from the thread list, inferior_ptid
7149        pointed at the exiting thread.  In such case, calling
7150        delete_thread does not really remove the thread from the list;
7151        instead, the thread is left listed, with 'exited' state.
7152
7153      - The target's debug interface does not support thread exit
7154        events, and so we have no idea whatsoever if the previously
7155        stepping thread is still alive.  For that reason, we need to
7156        synchronously query the target now.  */
7157
7158   if (is_exited (tp->ptid)
7159       || !target_thread_alive (tp->ptid))
7160     {
7161       if (debug_infrun)
7162         fprintf_unfiltered (gdb_stdlog,
7163                             "infrun: not resuming previously  "
7164                             "stepped thread, it has vanished\n");
7165
7166       delete_thread (tp->ptid);
7167       return 0;
7168     }
7169
7170   if (debug_infrun)
7171     fprintf_unfiltered (gdb_stdlog,
7172                         "infrun: resuming previously stepped thread\n");
7173
7174   reset_ecs (ecs, tp);
7175   switch_to_thread (tp->ptid);
7176
7177   stop_pc = regcache_read_pc (get_thread_regcache (tp->ptid));
7178   frame = get_current_frame ();
7179
7180   /* If the PC of the thread we were trying to single-step has
7181      changed, then that thread has trapped or been signaled, but the
7182      event has not been reported to GDB yet.  Re-poll the target
7183      looking for this particular thread's event (i.e. temporarily
7184      enable schedlock) by:
7185
7186      - setting a break at the current PC
7187      - resuming that particular thread, only (by setting trap
7188      expected)
7189
7190      This prevents us continuously moving the single-step breakpoint
7191      forward, one instruction at a time, overstepping.  */
7192
7193   if (stop_pc != tp->prev_pc)
7194     {
7195       ptid_t resume_ptid;
7196
7197       if (debug_infrun)
7198         fprintf_unfiltered (gdb_stdlog,
7199                             "infrun: expected thread advanced also (%s -> %s)\n",
7200                             paddress (target_gdbarch (), tp->prev_pc),
7201                             paddress (target_gdbarch (), stop_pc));
7202
7203       /* Clear the info of the previous step-over, as it's no longer
7204          valid (if the thread was trying to step over a breakpoint, it
7205          has already succeeded).  It's what keep_going would do too,
7206          if we called it.  Do this before trying to insert the sss
7207          breakpoint, otherwise if we were previously trying to step
7208          over this exact address in another thread, the breakpoint is
7209          skipped.  */
7210       clear_step_over_info ();
7211       tp->control.trap_expected = 0;
7212
7213       insert_single_step_breakpoint (get_frame_arch (frame),
7214                                      get_frame_address_space (frame),
7215                                      stop_pc);
7216
7217       tp->resumed = 1;
7218       resume_ptid = internal_resume_ptid (tp->control.stepping_command);
7219       do_target_resume (resume_ptid, 0, GDB_SIGNAL_0);
7220     }
7221   else
7222     {
7223       if (debug_infrun)
7224         fprintf_unfiltered (gdb_stdlog,
7225                             "infrun: expected thread still hasn't advanced\n");
7226
7227       keep_going_pass_signal (ecs);
7228     }
7229   return 1;
7230 }
7231
7232 /* Is thread TP in the middle of (software or hardware)
7233    single-stepping?  (Note the result of this function must never be
7234    passed directly as target_resume's STEP parameter.)  */
7235
7236 static int
7237 currently_stepping (struct thread_info *tp)
7238 {
7239   return ((tp->control.step_range_end
7240            && tp->control.step_resume_breakpoint == NULL)
7241           || tp->control.trap_expected
7242           || tp->stepped_breakpoint
7243           || bpstat_should_step ());
7244 }
7245
7246 /* Inferior has stepped into a subroutine call with source code that
7247    we should not step over.  Do step to the first line of code in
7248    it.  */
7249
7250 static void
7251 handle_step_into_function (struct gdbarch *gdbarch,
7252                            struct execution_control_state *ecs)
7253 {
7254   fill_in_stop_func (gdbarch, ecs);
7255
7256   compunit_symtab *cust = find_pc_compunit_symtab (stop_pc);
7257   if (cust != NULL && compunit_language (cust) != language_asm)
7258     ecs->stop_func_start
7259       = gdbarch_skip_prologue_noexcept (gdbarch, ecs->stop_func_start);
7260
7261   symtab_and_line stop_func_sal = find_pc_line (ecs->stop_func_start, 0);
7262   /* Use the step_resume_break to step until the end of the prologue,
7263      even if that involves jumps (as it seems to on the vax under
7264      4.2).  */
7265   /* If the prologue ends in the middle of a source line, continue to
7266      the end of that source line (if it is still within the function).
7267      Otherwise, just go to end of prologue.  */
7268   if (stop_func_sal.end
7269       && stop_func_sal.pc != ecs->stop_func_start
7270       && stop_func_sal.end < ecs->stop_func_end)
7271     ecs->stop_func_start = stop_func_sal.end;
7272
7273   /* Architectures which require breakpoint adjustment might not be able
7274      to place a breakpoint at the computed address.  If so, the test
7275      ``ecs->stop_func_start == stop_pc'' will never succeed.  Adjust
7276      ecs->stop_func_start to an address at which a breakpoint may be
7277      legitimately placed.
7278
7279      Note:  kevinb/2004-01-19:  On FR-V, if this adjustment is not
7280      made, GDB will enter an infinite loop when stepping through
7281      optimized code consisting of VLIW instructions which contain
7282      subinstructions corresponding to different source lines.  On
7283      FR-V, it's not permitted to place a breakpoint on any but the
7284      first subinstruction of a VLIW instruction.  When a breakpoint is
7285      set, GDB will adjust the breakpoint address to the beginning of
7286      the VLIW instruction.  Thus, we need to make the corresponding
7287      adjustment here when computing the stop address.  */
7288
7289   if (gdbarch_adjust_breakpoint_address_p (gdbarch))
7290     {
7291       ecs->stop_func_start
7292         = gdbarch_adjust_breakpoint_address (gdbarch,
7293                                              ecs->stop_func_start);
7294     }
7295
7296   if (ecs->stop_func_start == stop_pc)
7297     {
7298       /* We are already there: stop now.  */
7299       end_stepping_range (ecs);
7300       return;
7301     }
7302   else
7303     {
7304       /* Put the step-breakpoint there and go until there.  */
7305       symtab_and_line sr_sal;
7306       sr_sal.pc = ecs->stop_func_start;
7307       sr_sal.section = find_pc_overlay (ecs->stop_func_start);
7308       sr_sal.pspace = get_frame_program_space (get_current_frame ());
7309
7310       /* Do not specify what the fp should be when we stop since on
7311          some machines the prologue is where the new fp value is
7312          established.  */
7313       insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal, null_frame_id);
7314
7315       /* And make sure stepping stops right away then.  */
7316       ecs->event_thread->control.step_range_end
7317         = ecs->event_thread->control.step_range_start;
7318     }
7319   keep_going (ecs);
7320 }
7321
7322 /* Inferior has stepped backward into a subroutine call with source
7323    code that we should not step over.  Do step to the beginning of the
7324    last line of code in it.  */
7325
7326 static void
7327 handle_step_into_function_backward (struct gdbarch *gdbarch,
7328                                     struct execution_control_state *ecs)
7329 {
7330   struct compunit_symtab *cust;
7331   struct symtab_and_line stop_func_sal;
7332
7333   fill_in_stop_func (gdbarch, ecs);
7334
7335   cust = find_pc_compunit_symtab (stop_pc);
7336   if (cust != NULL && compunit_language (cust) != language_asm)
7337     ecs->stop_func_start
7338       = gdbarch_skip_prologue_noexcept (gdbarch, ecs->stop_func_start);
7339
7340   stop_func_sal = find_pc_line (stop_pc, 0);
7341
7342   /* OK, we're just going to keep stepping here.  */
7343   if (stop_func_sal.pc == stop_pc)
7344     {
7345       /* We're there already.  Just stop stepping now.  */
7346       end_stepping_range (ecs);
7347     }
7348   else
7349     {
7350       /* Else just reset the step range and keep going.
7351          No step-resume breakpoint, they don't work for
7352          epilogues, which can have multiple entry paths.  */
7353       ecs->event_thread->control.step_range_start = stop_func_sal.pc;
7354       ecs->event_thread->control.step_range_end = stop_func_sal.end;
7355       keep_going (ecs);
7356     }
7357   return;
7358 }
7359
7360 /* Insert a "step-resume breakpoint" at SR_SAL with frame ID SR_ID.
7361    This is used to both functions and to skip over code.  */
7362
7363 static void
7364 insert_step_resume_breakpoint_at_sal_1 (struct gdbarch *gdbarch,
7365                                         struct symtab_and_line sr_sal,
7366                                         struct frame_id sr_id,
7367                                         enum bptype sr_type)
7368 {
7369   /* There should never be more than one step-resume or longjmp-resume
7370      breakpoint per thread, so we should never be setting a new
7371      step_resume_breakpoint when one is already active.  */
7372   gdb_assert (inferior_thread ()->control.step_resume_breakpoint == NULL);
7373   gdb_assert (sr_type == bp_step_resume || sr_type == bp_hp_step_resume);
7374
7375   if (debug_infrun)
7376     fprintf_unfiltered (gdb_stdlog,
7377                         "infrun: inserting step-resume breakpoint at %s\n",
7378                         paddress (gdbarch, sr_sal.pc));
7379
7380   inferior_thread ()->control.step_resume_breakpoint
7381     = set_momentary_breakpoint (gdbarch, sr_sal, sr_id, sr_type).release ();
7382 }
7383
7384 void
7385 insert_step_resume_breakpoint_at_sal (struct gdbarch *gdbarch,
7386                                       struct symtab_and_line sr_sal,
7387                                       struct frame_id sr_id)
7388 {
7389   insert_step_resume_breakpoint_at_sal_1 (gdbarch,
7390                                           sr_sal, sr_id,
7391                                           bp_step_resume);
7392 }
7393
7394 /* Insert a "high-priority step-resume breakpoint" at RETURN_FRAME.pc.
7395    This is used to skip a potential signal handler.
7396
7397    This is called with the interrupted function's frame.  The signal
7398    handler, when it returns, will resume the interrupted function at
7399    RETURN_FRAME.pc.  */
7400
7401 static void
7402 insert_hp_step_resume_breakpoint_at_frame (struct frame_info *return_frame)
7403 {
7404   gdb_assert (return_frame != NULL);
7405
7406   struct gdbarch *gdbarch = get_frame_arch (return_frame);
7407
7408   symtab_and_line sr_sal;
7409   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch, get_frame_pc (return_frame));
7410   sr_sal.section = find_pc_overlay (sr_sal.pc);
7411   sr_sal.pspace = get_frame_program_space (return_frame);
7412
7413   insert_step_resume_breakpoint_at_sal_1 (gdbarch, sr_sal,
7414                                           get_stack_frame_id (return_frame),
7415                                           bp_hp_step_resume);
7416 }
7417
7418 /* Insert a "step-resume breakpoint" at the previous frame's PC.  This
7419    is used to skip a function after stepping into it (for "next" or if
7420    the called function has no debugging information).
7421
7422    The current function has almost always been reached by single
7423    stepping a call or return instruction.  NEXT_FRAME belongs to the
7424    current function, and the breakpoint will be set at the caller's
7425    resume address.
7426
7427    This is a separate function rather than reusing
7428    insert_hp_step_resume_breakpoint_at_frame in order to avoid
7429    get_prev_frame, which may stop prematurely (see the implementation
7430    of frame_unwind_caller_id for an example).  */
7431
7432 static void
7433 insert_step_resume_breakpoint_at_caller (struct frame_info *next_frame)
7434 {
7435   /* We shouldn't have gotten here if we don't know where the call site
7436      is.  */
7437   gdb_assert (frame_id_p (frame_unwind_caller_id (next_frame)));
7438
7439   struct gdbarch *gdbarch = frame_unwind_caller_arch (next_frame);
7440
7441   symtab_and_line sr_sal;
7442   sr_sal.pc = gdbarch_addr_bits_remove (gdbarch,
7443                                         frame_unwind_caller_pc (next_frame));
7444   sr_sal.section = find_pc_overlay (sr_sal.pc);
7445   sr_sal.pspace = frame_unwind_program_space (next_frame);
7446
7447   insert_step_resume_breakpoint_at_sal (gdbarch, sr_sal,
7448                                         frame_unwind_caller_id (next_frame));
7449 }
7450
7451 /* Insert a "longjmp-resume" breakpoint at PC.  This is used to set a
7452    new breakpoint at the target of a jmp_buf.  The handling of
7453    longjmp-resume uses the same mechanisms used for handling
7454    "step-resume" breakpoints.  */
7455
7456 static void
7457 insert_longjmp_resume_breakpoint (struct gdbarch *gdbarch, CORE_ADDR pc)
7458 {
7459   /* There should never be more than one longjmp-resume breakpoint per
7460      thread, so we should never be setting a new
7461      longjmp_resume_breakpoint when one is already active.  */
7462   gdb_assert (inferior_thread ()->control.exception_resume_breakpoint == NULL);
7463
7464   if (debug_infrun)
7465     fprintf_unfiltered (gdb_stdlog,
7466                         "infrun: inserting longjmp-resume breakpoint at %s\n",
7467                         paddress (gdbarch, pc));
7468
7469   inferior_thread ()->control.exception_resume_breakpoint =
7470     set_momentary_breakpoint_at_pc (gdbarch, pc, bp_longjmp_resume).release ();
7471 }
7472
7473 /* Insert an exception resume breakpoint.  TP is the thread throwing
7474    the exception.  The block B is the block of the unwinder debug hook
7475    function.  FRAME is the frame corresponding to the call to this
7476    function.  SYM is the symbol of the function argument holding the
7477    target PC of the exception.  */
7478
7479 static void
7480 insert_exception_resume_breakpoint (struct thread_info *tp,
7481                                     const struct block *b,
7482                                     struct frame_info *frame,
7483                                     struct symbol *sym)
7484 {
7485   TRY
7486     {
7487       struct block_symbol vsym;
7488       struct value *value;
7489       CORE_ADDR handler;
7490       struct breakpoint *bp;
7491
7492       vsym = lookup_symbol_search_name (SYMBOL_SEARCH_NAME (sym),
7493                                         b, VAR_DOMAIN);
7494       value = read_var_value (vsym.symbol, vsym.block, frame);
7495       /* If the value was optimized out, revert to the old behavior.  */
7496       if (! value_optimized_out (value))
7497         {
7498           handler = value_as_address (value);
7499
7500           if (debug_infrun)
7501             fprintf_unfiltered (gdb_stdlog,
7502                                 "infrun: exception resume at %lx\n",
7503                                 (unsigned long) handler);
7504
7505           bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
7506                                                handler,
7507                                                bp_exception_resume).release ();
7508
7509           /* set_momentary_breakpoint_at_pc invalidates FRAME.  */
7510           frame = NULL;
7511
7512           bp->thread = tp->global_num;
7513           inferior_thread ()->control.exception_resume_breakpoint = bp;
7514         }
7515     }
7516   CATCH (e, RETURN_MASK_ERROR)
7517     {
7518       /* We want to ignore errors here.  */
7519     }
7520   END_CATCH
7521 }
7522
7523 /* A helper for check_exception_resume that sets an
7524    exception-breakpoint based on a SystemTap probe.  */
7525
7526 static void
7527 insert_exception_resume_from_probe (struct thread_info *tp,
7528                                     const struct bound_probe *probe,
7529                                     struct frame_info *frame)
7530 {
7531   struct value *arg_value;
7532   CORE_ADDR handler;
7533   struct breakpoint *bp;
7534
7535   arg_value = probe_safe_evaluate_at_pc (frame, 1);
7536   if (!arg_value)
7537     return;
7538
7539   handler = value_as_address (arg_value);
7540
7541   if (debug_infrun)
7542     fprintf_unfiltered (gdb_stdlog,
7543                         "infrun: exception resume at %s\n",
7544                         paddress (get_objfile_arch (probe->objfile),
7545                                   handler));
7546
7547   bp = set_momentary_breakpoint_at_pc (get_frame_arch (frame),
7548                                        handler, bp_exception_resume).release ();
7549   bp->thread = tp->global_num;
7550   inferior_thread ()->control.exception_resume_breakpoint = bp;
7551 }
7552
7553 /* This is called when an exception has been intercepted.  Check to
7554    see whether the exception's destination is of interest, and if so,
7555    set an exception resume breakpoint there.  */
7556
7557 static void
7558 check_exception_resume (struct execution_control_state *ecs,
7559                         struct frame_info *frame)
7560 {
7561   struct bound_probe probe;
7562   struct symbol *func;
7563
7564   /* First see if this exception unwinding breakpoint was set via a
7565      SystemTap probe point.  If so, the probe has two arguments: the
7566      CFA and the HANDLER.  We ignore the CFA, extract the handler, and
7567      set a breakpoint there.  */
7568   probe = find_probe_by_pc (get_frame_pc (frame));
7569   if (probe.prob)
7570     {
7571       insert_exception_resume_from_probe (ecs->event_thread, &probe, frame);
7572       return;
7573     }
7574
7575   func = get_frame_function (frame);
7576   if (!func)
7577     return;
7578
7579   TRY
7580     {
7581       const struct block *b;
7582       struct block_iterator iter;
7583       struct symbol *sym;
7584       int argno = 0;
7585
7586       /* The exception breakpoint is a thread-specific breakpoint on
7587          the unwinder's debug hook, declared as:
7588          
7589          void _Unwind_DebugHook (void *cfa, void *handler);
7590          
7591          The CFA argument indicates the frame to which control is
7592          about to be transferred.  HANDLER is the destination PC.
7593          
7594          We ignore the CFA and set a temporary breakpoint at HANDLER.
7595          This is not extremely efficient but it avoids issues in gdb
7596          with computing the DWARF CFA, and it also works even in weird
7597          cases such as throwing an exception from inside a signal
7598          handler.  */
7599
7600       b = SYMBOL_BLOCK_VALUE (func);
7601       ALL_BLOCK_SYMBOLS (b, iter, sym)
7602         {
7603           if (!SYMBOL_IS_ARGUMENT (sym))
7604             continue;
7605
7606           if (argno == 0)
7607             ++argno;
7608           else
7609             {
7610               insert_exception_resume_breakpoint (ecs->event_thread,
7611                                                   b, frame, sym);
7612               break;
7613             }
7614         }
7615     }
7616   CATCH (e, RETURN_MASK_ERROR)
7617     {
7618     }
7619   END_CATCH
7620 }
7621
7622 static void
7623 stop_waiting (struct execution_control_state *ecs)
7624 {
7625   if (debug_infrun)
7626     fprintf_unfiltered (gdb_stdlog, "infrun: stop_waiting\n");
7627
7628   /* Let callers know we don't want to wait for the inferior anymore.  */
7629   ecs->wait_some_more = 0;
7630
7631   /* If all-stop, but the target is always in non-stop mode, stop all
7632      threads now that we're presenting the stop to the user.  */
7633   if (!non_stop && target_is_non_stop_p ())
7634     stop_all_threads ();
7635 }
7636
7637 /* Like keep_going, but passes the signal to the inferior, even if the
7638    signal is set to nopass.  */
7639
7640 static void
7641 keep_going_pass_signal (struct execution_control_state *ecs)
7642 {
7643   gdb_assert (ptid_equal (ecs->event_thread->ptid, inferior_ptid));
7644   gdb_assert (!ecs->event_thread->resumed);
7645
7646   /* Save the pc before execution, to compare with pc after stop.  */
7647   ecs->event_thread->prev_pc
7648     = regcache_read_pc (get_thread_regcache (ecs->ptid));
7649
7650   if (ecs->event_thread->control.trap_expected)
7651     {
7652       struct thread_info *tp = ecs->event_thread;
7653
7654       if (debug_infrun)
7655         fprintf_unfiltered (gdb_stdlog,
7656                             "infrun: %s has trap_expected set, "
7657                             "resuming to collect trap\n",
7658                             target_pid_to_str (tp->ptid));
7659
7660       /* We haven't yet gotten our trap, and either: intercepted a
7661          non-signal event (e.g., a fork); or took a signal which we
7662          are supposed to pass through to the inferior.  Simply
7663          continue.  */
7664       resume (ecs->event_thread->suspend.stop_signal);
7665     }
7666   else if (step_over_info_valid_p ())
7667     {
7668       /* Another thread is stepping over a breakpoint in-line.  If
7669          this thread needs a step-over too, queue the request.  In
7670          either case, this resume must be deferred for later.  */
7671       struct thread_info *tp = ecs->event_thread;
7672
7673       if (ecs->hit_singlestep_breakpoint
7674           || thread_still_needs_step_over (tp))
7675         {
7676           if (debug_infrun)
7677             fprintf_unfiltered (gdb_stdlog,
7678                                 "infrun: step-over already in progress: "
7679                                 "step-over for %s deferred\n",
7680                                 target_pid_to_str (tp->ptid));
7681           thread_step_over_chain_enqueue (tp);
7682         }
7683       else
7684         {
7685           if (debug_infrun)
7686             fprintf_unfiltered (gdb_stdlog,
7687                                 "infrun: step-over in progress: "
7688                                 "resume of %s deferred\n",
7689                                 target_pid_to_str (tp->ptid));
7690         }
7691     }
7692   else
7693     {
7694       struct regcache *regcache = get_current_regcache ();
7695       int remove_bp;
7696       int remove_wps;
7697       step_over_what step_what;
7698
7699       /* Either the trap was not expected, but we are continuing
7700          anyway (if we got a signal, the user asked it be passed to
7701          the child)
7702          -- or --
7703          We got our expected trap, but decided we should resume from
7704          it.
7705
7706          We're going to run this baby now!
7707
7708          Note that insert_breakpoints won't try to re-insert
7709          already inserted breakpoints.  Therefore, we don't
7710          care if breakpoints were already inserted, or not.  */
7711
7712       /* If we need to step over a breakpoint, and we're not using
7713          displaced stepping to do so, insert all breakpoints
7714          (watchpoints, etc.) but the one we're stepping over, step one
7715          instruction, and then re-insert the breakpoint when that step
7716          is finished.  */
7717
7718       step_what = thread_still_needs_step_over (ecs->event_thread);
7719
7720       remove_bp = (ecs->hit_singlestep_breakpoint
7721                    || (step_what & STEP_OVER_BREAKPOINT));
7722       remove_wps = (step_what & STEP_OVER_WATCHPOINT);
7723
7724       /* We can't use displaced stepping if we need to step past a
7725          watchpoint.  The instruction copied to the scratch pad would
7726          still trigger the watchpoint.  */
7727       if (remove_bp
7728           && (remove_wps || !use_displaced_stepping (ecs->event_thread)))
7729         {
7730           set_step_over_info (regcache->aspace (),
7731                               regcache_read_pc (regcache), remove_wps,
7732                               ecs->event_thread->global_num);
7733         }
7734       else if (remove_wps)
7735         set_step_over_info (NULL, 0, remove_wps, -1);
7736
7737       /* If we now need to do an in-line step-over, we need to stop
7738          all other threads.  Note this must be done before
7739          insert_breakpoints below, because that removes the breakpoint
7740          we're about to step over, otherwise other threads could miss
7741          it.  */
7742       if (step_over_info_valid_p () && target_is_non_stop_p ())
7743         stop_all_threads ();
7744
7745       /* Stop stepping if inserting breakpoints fails.  */
7746       TRY
7747         {
7748           insert_breakpoints ();
7749         }
7750       CATCH (e, RETURN_MASK_ERROR)
7751         {
7752           exception_print (gdb_stderr, e);
7753           stop_waiting (ecs);
7754           return;
7755         }
7756       END_CATCH
7757
7758       ecs->event_thread->control.trap_expected = (remove_bp || remove_wps);
7759
7760       resume (ecs->event_thread->suspend.stop_signal);
7761     }
7762
7763   prepare_to_wait (ecs);
7764 }
7765
7766 /* Called when we should continue running the inferior, because the
7767    current event doesn't cause a user visible stop.  This does the
7768    resuming part; waiting for the next event is done elsewhere.  */
7769
7770 static void
7771 keep_going (struct execution_control_state *ecs)
7772 {
7773   if (ecs->event_thread->control.trap_expected
7774       && ecs->event_thread->suspend.stop_signal == GDB_SIGNAL_TRAP)
7775     ecs->event_thread->control.trap_expected = 0;
7776
7777   if (!signal_program[ecs->event_thread->suspend.stop_signal])
7778     ecs->event_thread->suspend.stop_signal = GDB_SIGNAL_0;
7779   keep_going_pass_signal (ecs);
7780 }
7781
7782 /* This function normally comes after a resume, before
7783    handle_inferior_event exits.  It takes care of any last bits of
7784    housekeeping, and sets the all-important wait_some_more flag.  */
7785
7786 static void
7787 prepare_to_wait (struct execution_control_state *ecs)
7788 {
7789   if (debug_infrun)
7790     fprintf_unfiltered (gdb_stdlog, "infrun: prepare_to_wait\n");
7791
7792   ecs->wait_some_more = 1;
7793
7794   if (!target_is_async_p ())
7795     mark_infrun_async_event_handler ();
7796 }
7797
7798 /* We are done with the step range of a step/next/si/ni command.
7799    Called once for each n of a "step n" operation.  */
7800
7801 static void
7802 end_stepping_range (struct execution_control_state *ecs)
7803 {
7804   ecs->event_thread->control.stop_step = 1;
7805   stop_waiting (ecs);
7806 }
7807
7808 /* Several print_*_reason functions to print why the inferior has stopped.
7809    We always print something when the inferior exits, or receives a signal.
7810    The rest of the cases are dealt with later on in normal_stop and
7811    print_it_typical.  Ideally there should be a call to one of these
7812    print_*_reason functions functions from handle_inferior_event each time
7813    stop_waiting is called.
7814
7815    Note that we don't call these directly, instead we delegate that to
7816    the interpreters, through observers.  Interpreters then call these
7817    with whatever uiout is right.  */
7818
7819 void
7820 print_end_stepping_range_reason (struct ui_out *uiout)
7821 {
7822   /* For CLI-like interpreters, print nothing.  */
7823
7824   if (uiout->is_mi_like_p ())
7825     {
7826       uiout->field_string ("reason",
7827                            async_reason_lookup (EXEC_ASYNC_END_STEPPING_RANGE));
7828     }
7829 }
7830
7831 void
7832 print_signal_exited_reason (struct ui_out *uiout, enum gdb_signal siggnal)
7833 {
7834   annotate_signalled ();
7835   if (uiout->is_mi_like_p ())
7836     uiout->field_string
7837       ("reason", async_reason_lookup (EXEC_ASYNC_EXITED_SIGNALLED));
7838   uiout->text ("\nProgram terminated with signal ");
7839   annotate_signal_name ();
7840   uiout->field_string ("signal-name",
7841                        gdb_signal_to_name (siggnal));
7842   annotate_signal_name_end ();
7843   uiout->text (", ");
7844   annotate_signal_string ();
7845   uiout->field_string ("signal-meaning",
7846                        gdb_signal_to_string (siggnal));
7847   annotate_signal_string_end ();
7848   uiout->text (".\n");
7849   uiout->text ("The program no longer exists.\n");
7850 }
7851
7852 void
7853 print_exited_reason (struct ui_out *uiout, int exitstatus)
7854 {
7855   struct inferior *inf = current_inferior ();
7856   const char *pidstr = target_pid_to_str (pid_to_ptid (inf->pid));
7857
7858   annotate_exited (exitstatus);
7859   if (exitstatus)
7860     {
7861       if (uiout->is_mi_like_p ())
7862         uiout->field_string ("reason", async_reason_lookup (EXEC_ASYNC_EXITED));
7863       uiout->text ("[Inferior ");
7864       uiout->text (plongest (inf->num));
7865       uiout->text (" (");
7866       uiout->text (pidstr);
7867       uiout->text (") exited with code ");
7868       uiout->field_fmt ("exit-code", "0%o", (unsigned int) exitstatus);
7869       uiout->text ("]\n");
7870     }
7871   else
7872     {
7873       if (uiout->is_mi_like_p ())
7874         uiout->field_string
7875           ("reason", async_reason_lookup (EXEC_ASYNC_EXITED_NORMALLY));
7876       uiout->text ("[Inferior ");
7877       uiout->text (plongest (inf->num));
7878       uiout->text (" (");
7879       uiout->text (pidstr);
7880       uiout->text (") exited normally]\n");
7881     }
7882 }
7883
7884 /* Some targets/architectures can do extra processing/display of
7885    segmentation faults.  E.g., Intel MPX boundary faults.
7886    Call the architecture dependent function to handle the fault.  */
7887
7888 static void
7889 handle_segmentation_fault (struct ui_out *uiout)
7890 {
7891   struct regcache *regcache = get_current_regcache ();
7892   struct gdbarch *gdbarch = regcache->arch ();
7893
7894   if (gdbarch_handle_segmentation_fault_p (gdbarch))
7895     gdbarch_handle_segmentation_fault (gdbarch, uiout);
7896 }
7897
7898 void
7899 print_signal_received_reason (struct ui_out *uiout, enum gdb_signal siggnal)
7900 {
7901   struct thread_info *thr = inferior_thread ();
7902
7903   annotate_signal ();
7904
7905   if (uiout->is_mi_like_p ())
7906     ;
7907   else if (show_thread_that_caused_stop ())
7908     {
7909       const char *name;
7910
7911       uiout->text ("\nThread ");
7912       uiout->field_fmt ("thread-id", "%s", print_thread_id (thr));
7913
7914       name = thr->name != NULL ? thr->name : target_thread_name (thr);
7915       if (name != NULL)
7916         {
7917           uiout->text (" \"");
7918           uiout->field_fmt ("name", "%s", name);
7919           uiout->text ("\"");
7920         }
7921     }
7922   else
7923     uiout->text ("\nProgram");
7924
7925   if (siggnal == GDB_SIGNAL_0 && !uiout->is_mi_like_p ())
7926     uiout->text (" stopped");
7927   else
7928     {
7929       uiout->text (" received signal ");
7930       annotate_signal_name ();
7931       if (uiout->is_mi_like_p ())
7932         uiout->field_string
7933           ("reason", async_reason_lookup (EXEC_ASYNC_SIGNAL_RECEIVED));
7934       uiout->field_string ("signal-name", gdb_signal_to_name (siggnal));
7935       annotate_signal_name_end ();
7936       uiout->text (", ");
7937       annotate_signal_string ();
7938       uiout->field_string ("signal-meaning", gdb_signal_to_string (siggnal));
7939
7940       if (siggnal == GDB_SIGNAL_SEGV)
7941         handle_segmentation_fault (uiout);
7942
7943       annotate_signal_string_end ();
7944     }
7945   uiout->text (".\n");
7946 }
7947
7948 void
7949 print_no_history_reason (struct ui_out *uiout)
7950 {
7951   uiout->text ("\nNo more reverse-execution history.\n");
7952 }
7953
7954 /* Print current location without a level number, if we have changed
7955    functions or hit a breakpoint.  Print source line if we have one.
7956    bpstat_print contains the logic deciding in detail what to print,
7957    based on the event(s) that just occurred.  */
7958
7959 static void
7960 print_stop_location (struct target_waitstatus *ws)
7961 {
7962   int bpstat_ret;
7963   enum print_what source_flag;
7964   int do_frame_printing = 1;
7965   struct thread_info *tp = inferior_thread ();
7966
7967   bpstat_ret = bpstat_print (tp->control.stop_bpstat, ws->kind);
7968   switch (bpstat_ret)
7969     {
7970     case PRINT_UNKNOWN:
7971       /* FIXME: cagney/2002-12-01: Given that a frame ID does (or
7972          should) carry around the function and does (or should) use
7973          that when doing a frame comparison.  */
7974       if (tp->control.stop_step
7975           && frame_id_eq (tp->control.step_frame_id,
7976                           get_frame_id (get_current_frame ()))
7977           && tp->control.step_start_function == find_pc_function (stop_pc))
7978         {
7979           /* Finished step, just print source line.  */
7980           source_flag = SRC_LINE;
7981         }
7982       else
7983         {
7984           /* Print location and source line.  */
7985           source_flag = SRC_AND_LOC;
7986         }
7987       break;
7988     case PRINT_SRC_AND_LOC:
7989       /* Print location and source line.  */
7990       source_flag = SRC_AND_LOC;
7991       break;
7992     case PRINT_SRC_ONLY:
7993       source_flag = SRC_LINE;
7994       break;
7995     case PRINT_NOTHING:
7996       /* Something bogus.  */
7997       source_flag = SRC_LINE;
7998       do_frame_printing = 0;
7999       break;
8000     default:
8001       internal_error (__FILE__, __LINE__, _("Unknown value."));
8002     }
8003
8004   /* The behavior of this routine with respect to the source
8005      flag is:
8006      SRC_LINE: Print only source line
8007      LOCATION: Print only location
8008      SRC_AND_LOC: Print location and source line.  */
8009   if (do_frame_printing)
8010     print_stack_frame (get_selected_frame (NULL), 0, source_flag, 1);
8011 }
8012
8013 /* See infrun.h.  */
8014
8015 void
8016 print_stop_event (struct ui_out *uiout)
8017 {
8018   struct target_waitstatus last;
8019   ptid_t last_ptid;
8020   struct thread_info *tp;
8021
8022   get_last_target_status (&last_ptid, &last);
8023
8024   {
8025     scoped_restore save_uiout = make_scoped_restore (&current_uiout, uiout);
8026
8027     print_stop_location (&last);
8028
8029     /* Display the auto-display expressions.  */
8030     do_displays ();
8031   }
8032
8033   tp = inferior_thread ();
8034   if (tp->thread_fsm != NULL
8035       && thread_fsm_finished_p (tp->thread_fsm))
8036     {
8037       struct return_value_info *rv;
8038
8039       rv = thread_fsm_return_value (tp->thread_fsm);
8040       if (rv != NULL)
8041         print_return_value (uiout, rv);
8042     }
8043 }
8044
8045 /* See infrun.h.  */
8046
8047 void
8048 maybe_remove_breakpoints (void)
8049 {
8050   if (!breakpoints_should_be_inserted_now () && target_has_execution)
8051     {
8052       if (remove_breakpoints ())
8053         {
8054           target_terminal::ours_for_output ();
8055           printf_filtered (_("Cannot remove breakpoints because "
8056                              "program is no longer writable.\nFurther "
8057                              "execution is probably impossible.\n"));
8058         }
8059     }
8060 }
8061
8062 /* The execution context that just caused a normal stop.  */
8063
8064 struct stop_context
8065 {
8066   /* The stop ID.  */
8067   ULONGEST stop_id;
8068
8069   /* The event PTID.  */
8070
8071   ptid_t ptid;
8072
8073   /* If stopp for a thread event, this is the thread that caused the
8074      stop.  */
8075   struct thread_info *thread;
8076
8077   /* The inferior that caused the stop.  */
8078   int inf_num;
8079 };
8080
8081 /* Returns a new stop context.  If stopped for a thread event, this
8082    takes a strong reference to the thread.  */
8083
8084 static struct stop_context *
8085 save_stop_context (void)
8086 {
8087   struct stop_context *sc = XNEW (struct stop_context);
8088
8089   sc->stop_id = get_stop_id ();
8090   sc->ptid = inferior_ptid;
8091   sc->inf_num = current_inferior ()->num;
8092
8093   if (!ptid_equal (inferior_ptid, null_ptid))
8094     {
8095       /* Take a strong reference so that the thread can't be deleted
8096          yet.  */
8097       sc->thread = inferior_thread ();
8098       sc->thread->incref ();
8099     }
8100   else
8101     sc->thread = NULL;
8102
8103   return sc;
8104 }
8105
8106 /* Release a stop context previously created with save_stop_context.
8107    Releases the strong reference to the thread as well. */
8108
8109 static void
8110 release_stop_context_cleanup (void *arg)
8111 {
8112   struct stop_context *sc = (struct stop_context *) arg;
8113
8114   if (sc->thread != NULL)
8115     sc->thread->decref ();
8116   xfree (sc);
8117 }
8118
8119 /* Return true if the current context no longer matches the saved stop
8120    context.  */
8121
8122 static int
8123 stop_context_changed (struct stop_context *prev)
8124 {
8125   if (!ptid_equal (prev->ptid, inferior_ptid))
8126     return 1;
8127   if (prev->inf_num != current_inferior ()->num)
8128     return 1;
8129   if (prev->thread != NULL && prev->thread->state != THREAD_STOPPED)
8130     return 1;
8131   if (get_stop_id () != prev->stop_id)
8132     return 1;
8133   return 0;
8134 }
8135
8136 /* See infrun.h.  */
8137
8138 int
8139 normal_stop (void)
8140 {
8141   struct target_waitstatus last;
8142   ptid_t last_ptid;
8143   struct cleanup *old_chain = make_cleanup (null_cleanup, NULL);
8144   ptid_t pid_ptid;
8145
8146   get_last_target_status (&last_ptid, &last);
8147
8148   new_stop_id ();
8149
8150   /* If an exception is thrown from this point on, make sure to
8151      propagate GDB's knowledge of the executing state to the
8152      frontend/user running state.  A QUIT is an easy exception to see
8153      here, so do this before any filtered output.  */
8154   if (!non_stop)
8155     make_cleanup (finish_thread_state_cleanup, &minus_one_ptid);
8156   else if (last.kind == TARGET_WAITKIND_SIGNALLED
8157            || last.kind == TARGET_WAITKIND_EXITED)
8158     {
8159       /* On some targets, we may still have live threads in the
8160          inferior when we get a process exit event.  E.g., for
8161          "checkpoint", when the current checkpoint/fork exits,
8162          linux-fork.c automatically switches to another fork from
8163          within target_mourn_inferior.  */
8164       if (!ptid_equal (inferior_ptid, null_ptid))
8165         {
8166           pid_ptid = pid_to_ptid (ptid_get_pid (inferior_ptid));
8167           make_cleanup (finish_thread_state_cleanup, &pid_ptid);
8168         }
8169     }
8170   else if (last.kind != TARGET_WAITKIND_NO_RESUMED)
8171     make_cleanup (finish_thread_state_cleanup, &inferior_ptid);
8172
8173   /* As we're presenting a stop, and potentially removing breakpoints,
8174      update the thread list so we can tell whether there are threads
8175      running on the target.  With target remote, for example, we can
8176      only learn about new threads when we explicitly update the thread
8177      list.  Do this before notifying the interpreters about signal
8178      stops, end of stepping ranges, etc., so that the "new thread"
8179      output is emitted before e.g., "Program received signal FOO",
8180      instead of after.  */
8181   update_thread_list ();
8182
8183   if (last.kind == TARGET_WAITKIND_STOPPED && stopped_by_random_signal)
8184     observer_notify_signal_received (inferior_thread ()->suspend.stop_signal);
8185
8186   /* As with the notification of thread events, we want to delay
8187      notifying the user that we've switched thread context until
8188      the inferior actually stops.
8189
8190      There's no point in saying anything if the inferior has exited.
8191      Note that SIGNALLED here means "exited with a signal", not
8192      "received a signal".
8193
8194      Also skip saying anything in non-stop mode.  In that mode, as we
8195      don't want GDB to switch threads behind the user's back, to avoid
8196      races where the user is typing a command to apply to thread x,
8197      but GDB switches to thread y before the user finishes entering
8198      the command, fetch_inferior_event installs a cleanup to restore
8199      the current thread back to the thread the user had selected right
8200      after this event is handled, so we're not really switching, only
8201      informing of a stop.  */
8202   if (!non_stop
8203       && !ptid_equal (previous_inferior_ptid, inferior_ptid)
8204       && target_has_execution
8205       && last.kind != TARGET_WAITKIND_SIGNALLED
8206       && last.kind != TARGET_WAITKIND_EXITED
8207       && last.kind != TARGET_WAITKIND_NO_RESUMED)
8208     {
8209       SWITCH_THRU_ALL_UIS ()
8210         {
8211           target_terminal::ours_for_output ();
8212           printf_filtered (_("[Switching to %s]\n"),
8213                            target_pid_to_str (inferior_ptid));
8214           annotate_thread_changed ();
8215         }
8216       previous_inferior_ptid = inferior_ptid;
8217     }
8218
8219   if (last.kind == TARGET_WAITKIND_NO_RESUMED)
8220     {
8221       SWITCH_THRU_ALL_UIS ()
8222         if (current_ui->prompt_state == PROMPT_BLOCKED)
8223           {
8224             target_terminal::ours_for_output ();
8225             printf_filtered (_("No unwaited-for children left.\n"));
8226           }
8227     }
8228
8229   /* Note: this depends on the update_thread_list call above.  */
8230   maybe_remove_breakpoints ();
8231
8232   /* If an auto-display called a function and that got a signal,
8233      delete that auto-display to avoid an infinite recursion.  */
8234
8235   if (stopped_by_random_signal)
8236     disable_current_display ();
8237
8238   SWITCH_THRU_ALL_UIS ()
8239     {
8240       async_enable_stdin ();
8241     }
8242
8243   /* Let the user/frontend see the threads as stopped.  */
8244   do_cleanups (old_chain);
8245
8246   /* Select innermost stack frame - i.e., current frame is frame 0,
8247      and current location is based on that.  Handle the case where the
8248      dummy call is returning after being stopped.  E.g. the dummy call
8249      previously hit a breakpoint.  (If the dummy call returns
8250      normally, we won't reach here.)  Do this before the stop hook is
8251      run, so that it doesn't get to see the temporary dummy frame,
8252      which is not where we'll present the stop.  */
8253   if (has_stack_frames ())
8254     {
8255       if (stop_stack_dummy == STOP_STACK_DUMMY)
8256         {
8257           /* Pop the empty frame that contains the stack dummy.  This
8258              also restores inferior state prior to the call (struct
8259              infcall_suspend_state).  */
8260           struct frame_info *frame = get_current_frame ();
8261
8262           gdb_assert (get_frame_type (frame) == DUMMY_FRAME);
8263           frame_pop (frame);
8264           /* frame_pop calls reinit_frame_cache as the last thing it
8265              does which means there's now no selected frame.  */
8266         }
8267
8268       select_frame (get_current_frame ());
8269
8270       /* Set the current source location.  */
8271       set_current_sal_from_frame (get_current_frame ());
8272     }
8273
8274   /* Look up the hook_stop and run it (CLI internally handles problem
8275      of stop_command's pre-hook not existing).  */
8276   if (stop_command != NULL)
8277     {
8278       struct stop_context *saved_context = save_stop_context ();
8279       struct cleanup *old_chain
8280         = make_cleanup (release_stop_context_cleanup, saved_context);
8281
8282       TRY
8283         {
8284           execute_cmd_pre_hook (stop_command);
8285         }
8286       CATCH (ex, RETURN_MASK_ALL)
8287         {
8288           exception_fprintf (gdb_stderr, ex,
8289                              "Error while running hook_stop:\n");
8290         }
8291       END_CATCH
8292
8293       /* If the stop hook resumes the target, then there's no point in
8294          trying to notify about the previous stop; its context is
8295          gone.  Likewise if the command switches thread or inferior --
8296          the observers would print a stop for the wrong
8297          thread/inferior.  */
8298       if (stop_context_changed (saved_context))
8299         {
8300           do_cleanups (old_chain);
8301           return 1;
8302         }
8303       do_cleanups (old_chain);
8304     }
8305
8306   /* Notify observers about the stop.  This is where the interpreters
8307      print the stop event.  */
8308   if (!ptid_equal (inferior_ptid, null_ptid))
8309     observer_notify_normal_stop (inferior_thread ()->control.stop_bpstat,
8310                                  stop_print_frame);
8311   else
8312     observer_notify_normal_stop (NULL, stop_print_frame);
8313
8314   annotate_stopped ();
8315
8316   if (target_has_execution)
8317     {
8318       if (last.kind != TARGET_WAITKIND_SIGNALLED
8319           && last.kind != TARGET_WAITKIND_EXITED)
8320         /* Delete the breakpoint we stopped at, if it wants to be deleted.
8321            Delete any breakpoint that is to be deleted at the next stop.  */
8322         breakpoint_auto_delete (inferior_thread ()->control.stop_bpstat);
8323     }
8324
8325   /* Try to get rid of automatically added inferiors that are no
8326      longer needed.  Keeping those around slows down things linearly.
8327      Note that this never removes the current inferior.  */
8328   prune_inferiors ();
8329
8330   return 0;
8331 }
8332 \f
8333 int
8334 signal_stop_state (int signo)
8335 {
8336   return signal_stop[signo];
8337 }
8338
8339 int
8340 signal_print_state (int signo)
8341 {
8342   return signal_print[signo];
8343 }
8344
8345 int
8346 signal_pass_state (int signo)
8347 {
8348   return signal_program[signo];
8349 }
8350
8351 static void
8352 signal_cache_update (int signo)
8353 {
8354   if (signo == -1)
8355     {
8356       for (signo = 0; signo < (int) GDB_SIGNAL_LAST; signo++)
8357         signal_cache_update (signo);
8358
8359       return;
8360     }
8361
8362   signal_pass[signo] = (signal_stop[signo] == 0
8363                         && signal_print[signo] == 0
8364                         && signal_program[signo] == 1
8365                         && signal_catch[signo] == 0);
8366 }
8367
8368 int
8369 signal_stop_update (int signo, int state)
8370 {
8371   int ret = signal_stop[signo];
8372
8373   signal_stop[signo] = state;
8374   signal_cache_update (signo);
8375   return ret;
8376 }
8377
8378 int
8379 signal_print_update (int signo, int state)
8380 {
8381   int ret = signal_print[signo];
8382
8383   signal_print[signo] = state;
8384   signal_cache_update (signo);
8385   return ret;
8386 }
8387
8388 int
8389 signal_pass_update (int signo, int state)
8390 {
8391   int ret = signal_program[signo];
8392
8393   signal_program[signo] = state;
8394   signal_cache_update (signo);
8395   return ret;
8396 }
8397
8398 /* Update the global 'signal_catch' from INFO and notify the
8399    target.  */
8400
8401 void
8402 signal_catch_update (const unsigned int *info)
8403 {
8404   int i;
8405
8406   for (i = 0; i < GDB_SIGNAL_LAST; ++i)
8407     signal_catch[i] = info[i] > 0;
8408   signal_cache_update (-1);
8409   target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
8410 }
8411
8412 static void
8413 sig_print_header (void)
8414 {
8415   printf_filtered (_("Signal        Stop\tPrint\tPass "
8416                      "to program\tDescription\n"));
8417 }
8418
8419 static void
8420 sig_print_info (enum gdb_signal oursig)
8421 {
8422   const char *name = gdb_signal_to_name (oursig);
8423   int name_padding = 13 - strlen (name);
8424
8425   if (name_padding <= 0)
8426     name_padding = 0;
8427
8428   printf_filtered ("%s", name);
8429   printf_filtered ("%*.*s ", name_padding, name_padding, "                 ");
8430   printf_filtered ("%s\t", signal_stop[oursig] ? "Yes" : "No");
8431   printf_filtered ("%s\t", signal_print[oursig] ? "Yes" : "No");
8432   printf_filtered ("%s\t\t", signal_program[oursig] ? "Yes" : "No");
8433   printf_filtered ("%s\n", gdb_signal_to_string (oursig));
8434 }
8435
8436 /* Specify how various signals in the inferior should be handled.  */
8437
8438 static void
8439 handle_command (const char *args, int from_tty)
8440 {
8441   int digits, wordlen;
8442   int sigfirst, signum, siglast;
8443   enum gdb_signal oursig;
8444   int allsigs;
8445   int nsigs;
8446   unsigned char *sigs;
8447
8448   if (args == NULL)
8449     {
8450       error_no_arg (_("signal to handle"));
8451     }
8452
8453   /* Allocate and zero an array of flags for which signals to handle.  */
8454
8455   nsigs = (int) GDB_SIGNAL_LAST;
8456   sigs = (unsigned char *) alloca (nsigs);
8457   memset (sigs, 0, nsigs);
8458
8459   /* Break the command line up into args.  */
8460
8461   gdb_argv built_argv (args);
8462
8463   /* Walk through the args, looking for signal oursigs, signal names, and
8464      actions.  Signal numbers and signal names may be interspersed with
8465      actions, with the actions being performed for all signals cumulatively
8466      specified.  Signal ranges can be specified as <LOW>-<HIGH>.  */
8467
8468   for (char *arg : built_argv)
8469     {
8470       wordlen = strlen (arg);
8471       for (digits = 0; isdigit (arg[digits]); digits++)
8472         {;
8473         }
8474       allsigs = 0;
8475       sigfirst = siglast = -1;
8476
8477       if (wordlen >= 1 && !strncmp (arg, "all", wordlen))
8478         {
8479           /* Apply action to all signals except those used by the
8480              debugger.  Silently skip those.  */
8481           allsigs = 1;
8482           sigfirst = 0;
8483           siglast = nsigs - 1;
8484         }
8485       else if (wordlen >= 1 && !strncmp (arg, "stop", wordlen))
8486         {
8487           SET_SIGS (nsigs, sigs, signal_stop);
8488           SET_SIGS (nsigs, sigs, signal_print);
8489         }
8490       else if (wordlen >= 1 && !strncmp (arg, "ignore", wordlen))
8491         {
8492           UNSET_SIGS (nsigs, sigs, signal_program);
8493         }
8494       else if (wordlen >= 2 && !strncmp (arg, "print", wordlen))
8495         {
8496           SET_SIGS (nsigs, sigs, signal_print);
8497         }
8498       else if (wordlen >= 2 && !strncmp (arg, "pass", wordlen))
8499         {
8500           SET_SIGS (nsigs, sigs, signal_program);
8501         }
8502       else if (wordlen >= 3 && !strncmp (arg, "nostop", wordlen))
8503         {
8504           UNSET_SIGS (nsigs, sigs, signal_stop);
8505         }
8506       else if (wordlen >= 3 && !strncmp (arg, "noignore", wordlen))
8507         {
8508           SET_SIGS (nsigs, sigs, signal_program);
8509         }
8510       else if (wordlen >= 4 && !strncmp (arg, "noprint", wordlen))
8511         {
8512           UNSET_SIGS (nsigs, sigs, signal_print);
8513           UNSET_SIGS (nsigs, sigs, signal_stop);
8514         }
8515       else if (wordlen >= 4 && !strncmp (arg, "nopass", wordlen))
8516         {
8517           UNSET_SIGS (nsigs, sigs, signal_program);
8518         }
8519       else if (digits > 0)
8520         {
8521           /* It is numeric.  The numeric signal refers to our own
8522              internal signal numbering from target.h, not to host/target
8523              signal  number.  This is a feature; users really should be
8524              using symbolic names anyway, and the common ones like
8525              SIGHUP, SIGINT, SIGALRM, etc. will work right anyway.  */
8526
8527           sigfirst = siglast = (int)
8528             gdb_signal_from_command (atoi (arg));
8529           if (arg[digits] == '-')
8530             {
8531               siglast = (int)
8532                 gdb_signal_from_command (atoi (arg + digits + 1));
8533             }
8534           if (sigfirst > siglast)
8535             {
8536               /* Bet he didn't figure we'd think of this case...  */
8537               signum = sigfirst;
8538               sigfirst = siglast;
8539               siglast = signum;
8540             }
8541         }
8542       else
8543         {
8544           oursig = gdb_signal_from_name (arg);
8545           if (oursig != GDB_SIGNAL_UNKNOWN)
8546             {
8547               sigfirst = siglast = (int) oursig;
8548             }
8549           else
8550             {
8551               /* Not a number and not a recognized flag word => complain.  */
8552               error (_("Unrecognized or ambiguous flag word: \"%s\"."), arg);
8553             }
8554         }
8555
8556       /* If any signal numbers or symbol names were found, set flags for
8557          which signals to apply actions to.  */
8558
8559       for (signum = sigfirst; signum >= 0 && signum <= siglast; signum++)
8560         {
8561           switch ((enum gdb_signal) signum)
8562             {
8563             case GDB_SIGNAL_TRAP:
8564             case GDB_SIGNAL_INT:
8565               if (!allsigs && !sigs[signum])
8566                 {
8567                   if (query (_("%s is used by the debugger.\n\
8568 Are you sure you want to change it? "),
8569                              gdb_signal_to_name ((enum gdb_signal) signum)))
8570                     {
8571                       sigs[signum] = 1;
8572                     }
8573                   else
8574                     {
8575                       printf_unfiltered (_("Not confirmed, unchanged.\n"));
8576                       gdb_flush (gdb_stdout);
8577                     }
8578                 }
8579               break;
8580             case GDB_SIGNAL_0:
8581             case GDB_SIGNAL_DEFAULT:
8582             case GDB_SIGNAL_UNKNOWN:
8583               /* Make sure that "all" doesn't print these.  */
8584               break;
8585             default:
8586               sigs[signum] = 1;
8587               break;
8588             }
8589         }
8590     }
8591
8592   for (signum = 0; signum < nsigs; signum++)
8593     if (sigs[signum])
8594       {
8595         signal_cache_update (-1);
8596         target_pass_signals ((int) GDB_SIGNAL_LAST, signal_pass);
8597         target_program_signals ((int) GDB_SIGNAL_LAST, signal_program);
8598
8599         if (from_tty)
8600           {
8601             /* Show the results.  */
8602             sig_print_header ();
8603             for (; signum < nsigs; signum++)
8604               if (sigs[signum])
8605                 sig_print_info ((enum gdb_signal) signum);
8606           }
8607
8608         break;
8609       }
8610 }
8611
8612 /* Complete the "handle" command.  */
8613
8614 static void
8615 handle_completer (struct cmd_list_element *ignore,
8616                   completion_tracker &tracker,
8617                   const char *text, const char *word)
8618 {
8619   static const char * const keywords[] =
8620     {
8621       "all",
8622       "stop",
8623       "ignore",
8624       "print",
8625       "pass",
8626       "nostop",
8627       "noignore",
8628       "noprint",
8629       "nopass",
8630       NULL,
8631     };
8632
8633   signal_completer (ignore, tracker, text, word);
8634   complete_on_enum (tracker, keywords, word, word);
8635 }
8636
8637 enum gdb_signal
8638 gdb_signal_from_command (int num)
8639 {
8640   if (num >= 1 && num <= 15)
8641     return (enum gdb_signal) num;
8642   error (_("Only signals 1-15 are valid as numeric signals.\n\
8643 Use \"info signals\" for a list of symbolic signals."));
8644 }
8645
8646 /* Print current contents of the tables set by the handle command.
8647    It is possible we should just be printing signals actually used
8648    by the current target (but for things to work right when switching
8649    targets, all signals should be in the signal tables).  */
8650
8651 static void
8652 info_signals_command (const char *signum_exp, int from_tty)
8653 {
8654   enum gdb_signal oursig;
8655
8656   sig_print_header ();
8657
8658   if (signum_exp)
8659     {
8660       /* First see if this is a symbol name.  */
8661       oursig = gdb_signal_from_name (signum_exp);
8662       if (oursig == GDB_SIGNAL_UNKNOWN)
8663         {
8664           /* No, try numeric.  */
8665           oursig =
8666             gdb_signal_from_command (parse_and_eval_long (signum_exp));
8667         }
8668       sig_print_info (oursig);
8669       return;
8670     }
8671
8672   printf_filtered ("\n");
8673   /* These ugly casts brought to you by the native VAX compiler.  */
8674   for (oursig = GDB_SIGNAL_FIRST;
8675        (int) oursig < (int) GDB_SIGNAL_LAST;
8676        oursig = (enum gdb_signal) ((int) oursig + 1))
8677     {
8678       QUIT;
8679
8680       if (oursig != GDB_SIGNAL_UNKNOWN
8681           && oursig != GDB_SIGNAL_DEFAULT && oursig != GDB_SIGNAL_0)
8682         sig_print_info (oursig);
8683     }
8684
8685   printf_filtered (_("\nUse the \"handle\" command "
8686                      "to change these tables.\n"));
8687 }
8688
8689 /* The $_siginfo convenience variable is a bit special.  We don't know
8690    for sure the type of the value until we actually have a chance to
8691    fetch the data.  The type can change depending on gdbarch, so it is
8692    also dependent on which thread you have selected.
8693
8694      1. making $_siginfo be an internalvar that creates a new value on
8695      access.
8696
8697      2. making the value of $_siginfo be an lval_computed value.  */
8698
8699 /* This function implements the lval_computed support for reading a
8700    $_siginfo value.  */
8701
8702 static void
8703 siginfo_value_read (struct value *v)
8704 {
8705   LONGEST transferred;
8706
8707   /* If we can access registers, so can we access $_siginfo.  Likewise
8708      vice versa.  */
8709   validate_registers_access ();
8710
8711   transferred =
8712     target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO,
8713                  NULL,
8714                  value_contents_all_raw (v),
8715                  value_offset (v),
8716                  TYPE_LENGTH (value_type (v)));
8717
8718   if (transferred != TYPE_LENGTH (value_type (v)))
8719     error (_("Unable to read siginfo"));
8720 }
8721
8722 /* This function implements the lval_computed support for writing a
8723    $_siginfo value.  */
8724
8725 static void
8726 siginfo_value_write (struct value *v, struct value *fromval)
8727 {
8728   LONGEST transferred;
8729
8730   /* If we can access registers, so can we access $_siginfo.  Likewise
8731      vice versa.  */
8732   validate_registers_access ();
8733
8734   transferred = target_write (&current_target,
8735                               TARGET_OBJECT_SIGNAL_INFO,
8736                               NULL,
8737                               value_contents_all_raw (fromval),
8738                               value_offset (v),
8739                               TYPE_LENGTH (value_type (fromval)));
8740
8741   if (transferred != TYPE_LENGTH (value_type (fromval)))
8742     error (_("Unable to write siginfo"));
8743 }
8744
8745 static const struct lval_funcs siginfo_value_funcs =
8746   {
8747     siginfo_value_read,
8748     siginfo_value_write
8749   };
8750
8751 /* Return a new value with the correct type for the siginfo object of
8752    the current thread using architecture GDBARCH.  Return a void value
8753    if there's no object available.  */
8754
8755 static struct value *
8756 siginfo_make_value (struct gdbarch *gdbarch, struct internalvar *var,
8757                     void *ignore)
8758 {
8759   if (target_has_stack
8760       && !ptid_equal (inferior_ptid, null_ptid)
8761       && gdbarch_get_siginfo_type_p (gdbarch))
8762     {
8763       struct type *type = gdbarch_get_siginfo_type (gdbarch);
8764
8765       return allocate_computed_value (type, &siginfo_value_funcs, NULL);
8766     }
8767
8768   return allocate_value (builtin_type (gdbarch)->builtin_void);
8769 }
8770
8771 \f
8772 /* infcall_suspend_state contains state about the program itself like its
8773    registers and any signal it received when it last stopped.
8774    This state must be restored regardless of how the inferior function call
8775    ends (either successfully, or after it hits a breakpoint or signal)
8776    if the program is to properly continue where it left off.  */
8777
8778 struct infcall_suspend_state
8779 {
8780   struct thread_suspend_state thread_suspend;
8781
8782   /* Other fields:  */
8783   CORE_ADDR stop_pc;
8784   struct regcache *registers;
8785
8786   /* Format of SIGINFO_DATA or NULL if it is not present.  */
8787   struct gdbarch *siginfo_gdbarch;
8788
8789   /* The inferior format depends on SIGINFO_GDBARCH and it has a length of
8790      TYPE_LENGTH (gdbarch_get_siginfo_type ()).  For different gdbarch the
8791      content would be invalid.  */
8792   gdb_byte *siginfo_data;
8793 };
8794
8795 struct infcall_suspend_state *
8796 save_infcall_suspend_state (void)
8797 {
8798   struct infcall_suspend_state *inf_state;
8799   struct thread_info *tp = inferior_thread ();
8800   struct regcache *regcache = get_current_regcache ();
8801   struct gdbarch *gdbarch = regcache->arch ();
8802   gdb_byte *siginfo_data = NULL;
8803
8804   if (gdbarch_get_siginfo_type_p (gdbarch))
8805     {
8806       struct type *type = gdbarch_get_siginfo_type (gdbarch);
8807       size_t len = TYPE_LENGTH (type);
8808       struct cleanup *back_to;
8809
8810       siginfo_data = (gdb_byte *) xmalloc (len);
8811       back_to = make_cleanup (xfree, siginfo_data);
8812
8813       if (target_read (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
8814                        siginfo_data, 0, len) == len)
8815         discard_cleanups (back_to);
8816       else
8817         {
8818           /* Errors ignored.  */
8819           do_cleanups (back_to);
8820           siginfo_data = NULL;
8821         }
8822     }
8823
8824   inf_state = XCNEW (struct infcall_suspend_state);
8825
8826   if (siginfo_data)
8827     {
8828       inf_state->siginfo_gdbarch = gdbarch;
8829       inf_state->siginfo_data = siginfo_data;
8830     }
8831
8832   inf_state->thread_suspend = tp->suspend;
8833
8834   /* run_inferior_call will not use the signal due to its `proceed' call with
8835      GDB_SIGNAL_0 anyway.  */
8836   tp->suspend.stop_signal = GDB_SIGNAL_0;
8837
8838   inf_state->stop_pc = stop_pc;
8839
8840   inf_state->registers = regcache_dup (regcache);
8841
8842   return inf_state;
8843 }
8844
8845 /* Restore inferior session state to INF_STATE.  */
8846
8847 void
8848 restore_infcall_suspend_state (struct infcall_suspend_state *inf_state)
8849 {
8850   struct thread_info *tp = inferior_thread ();
8851   struct regcache *regcache = get_current_regcache ();
8852   struct gdbarch *gdbarch = regcache->arch ();
8853
8854   tp->suspend = inf_state->thread_suspend;
8855
8856   stop_pc = inf_state->stop_pc;
8857
8858   if (inf_state->siginfo_gdbarch == gdbarch)
8859     {
8860       struct type *type = gdbarch_get_siginfo_type (gdbarch);
8861
8862       /* Errors ignored.  */
8863       target_write (&current_target, TARGET_OBJECT_SIGNAL_INFO, NULL,
8864                     inf_state->siginfo_data, 0, TYPE_LENGTH (type));
8865     }
8866
8867   /* The inferior can be gone if the user types "print exit(0)"
8868      (and perhaps other times).  */
8869   if (target_has_execution)
8870     /* NB: The register write goes through to the target.  */
8871     regcache_cpy (regcache, inf_state->registers);
8872
8873   discard_infcall_suspend_state (inf_state);
8874 }
8875
8876 static void
8877 do_restore_infcall_suspend_state_cleanup (void *state)
8878 {
8879   restore_infcall_suspend_state ((struct infcall_suspend_state *) state);
8880 }
8881
8882 struct cleanup *
8883 make_cleanup_restore_infcall_suspend_state
8884   (struct infcall_suspend_state *inf_state)
8885 {
8886   return make_cleanup (do_restore_infcall_suspend_state_cleanup, inf_state);
8887 }
8888
8889 void
8890 discard_infcall_suspend_state (struct infcall_suspend_state *inf_state)
8891 {
8892   delete inf_state->registers;
8893   xfree (inf_state->siginfo_data);
8894   xfree (inf_state);
8895 }
8896
8897 struct regcache *
8898 get_infcall_suspend_state_regcache (struct infcall_suspend_state *inf_state)
8899 {
8900   return inf_state->registers;
8901 }
8902
8903 /* infcall_control_state contains state regarding gdb's control of the
8904    inferior itself like stepping control.  It also contains session state like
8905    the user's currently selected frame.  */
8906
8907 struct infcall_control_state
8908 {
8909   struct thread_control_state thread_control;
8910   struct inferior_control_state inferior_control;
8911
8912   /* Other fields:  */
8913   enum stop_stack_kind stop_stack_dummy;
8914   int stopped_by_random_signal;
8915
8916   /* ID if the selected frame when the inferior function call was made.  */
8917   struct frame_id selected_frame_id;
8918 };
8919
8920 /* Save all of the information associated with the inferior<==>gdb
8921    connection.  */
8922
8923 struct infcall_control_state *
8924 save_infcall_control_state (void)
8925 {
8926   struct infcall_control_state *inf_status =
8927     XNEW (struct infcall_control_state);
8928   struct thread_info *tp = inferior_thread ();
8929   struct inferior *inf = current_inferior ();
8930
8931   inf_status->thread_control = tp->control;
8932   inf_status->inferior_control = inf->control;
8933
8934   tp->control.step_resume_breakpoint = NULL;
8935   tp->control.exception_resume_breakpoint = NULL;
8936
8937   /* Save original bpstat chain to INF_STATUS; replace it in TP with copy of
8938      chain.  If caller's caller is walking the chain, they'll be happier if we
8939      hand them back the original chain when restore_infcall_control_state is
8940      called.  */
8941   tp->control.stop_bpstat = bpstat_copy (tp->control.stop_bpstat);
8942
8943   /* Other fields:  */
8944   inf_status->stop_stack_dummy = stop_stack_dummy;
8945   inf_status->stopped_by_random_signal = stopped_by_random_signal;
8946
8947   inf_status->selected_frame_id = get_frame_id (get_selected_frame (NULL));
8948
8949   return inf_status;
8950 }
8951
8952 static void
8953 restore_selected_frame (const frame_id &fid)
8954 {
8955   frame_info *frame = frame_find_by_id (fid);
8956
8957   /* If inf_status->selected_frame_id is NULL, there was no previously
8958      selected frame.  */
8959   if (frame == NULL)
8960     {
8961       warning (_("Unable to restore previously selected frame."));
8962       return;
8963     }
8964
8965   select_frame (frame);
8966 }
8967
8968 /* Restore inferior session state to INF_STATUS.  */
8969
8970 void
8971 restore_infcall_control_state (struct infcall_control_state *inf_status)
8972 {
8973   struct thread_info *tp = inferior_thread ();
8974   struct inferior *inf = current_inferior ();
8975
8976   if (tp->control.step_resume_breakpoint)
8977     tp->control.step_resume_breakpoint->disposition = disp_del_at_next_stop;
8978
8979   if (tp->control.exception_resume_breakpoint)
8980     tp->control.exception_resume_breakpoint->disposition
8981       = disp_del_at_next_stop;
8982
8983   /* Handle the bpstat_copy of the chain.  */
8984   bpstat_clear (&tp->control.stop_bpstat);
8985
8986   tp->control = inf_status->thread_control;
8987   inf->control = inf_status->inferior_control;
8988
8989   /* Other fields:  */
8990   stop_stack_dummy = inf_status->stop_stack_dummy;
8991   stopped_by_random_signal = inf_status->stopped_by_random_signal;
8992
8993   if (target_has_stack)
8994     {
8995       /* The point of the try/catch is that if the stack is clobbered,
8996          walking the stack might encounter a garbage pointer and
8997          error() trying to dereference it.  */
8998       TRY
8999         {
9000           restore_selected_frame (inf_status->selected_frame_id);
9001         }
9002       CATCH (ex, RETURN_MASK_ERROR)
9003         {
9004           exception_fprintf (gdb_stderr, ex,
9005                              "Unable to restore previously selected frame:\n");
9006           /* Error in restoring the selected frame.  Select the
9007              innermost frame.  */
9008           select_frame (get_current_frame ());
9009         }
9010       END_CATCH
9011     }
9012
9013   xfree (inf_status);
9014 }
9015
9016 static void
9017 do_restore_infcall_control_state_cleanup (void *sts)
9018 {
9019   restore_infcall_control_state ((struct infcall_control_state *) sts);
9020 }
9021
9022 struct cleanup *
9023 make_cleanup_restore_infcall_control_state
9024   (struct infcall_control_state *inf_status)
9025 {
9026   return make_cleanup (do_restore_infcall_control_state_cleanup, inf_status);
9027 }
9028
9029 void
9030 discard_infcall_control_state (struct infcall_control_state *inf_status)
9031 {
9032   if (inf_status->thread_control.step_resume_breakpoint)
9033     inf_status->thread_control.step_resume_breakpoint->disposition
9034       = disp_del_at_next_stop;
9035
9036   if (inf_status->thread_control.exception_resume_breakpoint)
9037     inf_status->thread_control.exception_resume_breakpoint->disposition
9038       = disp_del_at_next_stop;
9039
9040   /* See save_infcall_control_state for info on stop_bpstat.  */
9041   bpstat_clear (&inf_status->thread_control.stop_bpstat);
9042
9043   xfree (inf_status);
9044 }
9045 \f
9046 /* See infrun.h.  */
9047
9048 void
9049 clear_exit_convenience_vars (void)
9050 {
9051   clear_internalvar (lookup_internalvar ("_exitsignal"));
9052   clear_internalvar (lookup_internalvar ("_exitcode"));
9053 }
9054 \f
9055
9056 /* User interface for reverse debugging:
9057    Set exec-direction / show exec-direction commands
9058    (returns error unless target implements to_set_exec_direction method).  */
9059
9060 enum exec_direction_kind execution_direction = EXEC_FORWARD;
9061 static const char exec_forward[] = "forward";
9062 static const char exec_reverse[] = "reverse";
9063 static const char *exec_direction = exec_forward;
9064 static const char *const exec_direction_names[] = {
9065   exec_forward,
9066   exec_reverse,
9067   NULL
9068 };
9069
9070 static void
9071 set_exec_direction_func (const char *args, int from_tty,
9072                          struct cmd_list_element *cmd)
9073 {
9074   if (target_can_execute_reverse)
9075     {
9076       if (!strcmp (exec_direction, exec_forward))
9077         execution_direction = EXEC_FORWARD;
9078       else if (!strcmp (exec_direction, exec_reverse))
9079         execution_direction = EXEC_REVERSE;
9080     }
9081   else
9082     {
9083       exec_direction = exec_forward;
9084       error (_("Target does not support this operation."));
9085     }
9086 }
9087
9088 static void
9089 show_exec_direction_func (struct ui_file *out, int from_tty,
9090                           struct cmd_list_element *cmd, const char *value)
9091 {
9092   switch (execution_direction) {
9093   case EXEC_FORWARD:
9094     fprintf_filtered (out, _("Forward.\n"));
9095     break;
9096   case EXEC_REVERSE:
9097     fprintf_filtered (out, _("Reverse.\n"));
9098     break;
9099   default:
9100     internal_error (__FILE__, __LINE__,
9101                     _("bogus execution_direction value: %d"),
9102                     (int) execution_direction);
9103   }
9104 }
9105
9106 static void
9107 show_schedule_multiple (struct ui_file *file, int from_tty,
9108                         struct cmd_list_element *c, const char *value)
9109 {
9110   fprintf_filtered (file, _("Resuming the execution of threads "
9111                             "of all processes is %s.\n"), value);
9112 }
9113
9114 /* Implementation of `siginfo' variable.  */
9115
9116 static const struct internalvar_funcs siginfo_funcs =
9117 {
9118   siginfo_make_value,
9119   NULL,
9120   NULL
9121 };
9122
9123 /* Callback for infrun's target events source.  This is marked when a
9124    thread has a pending status to process.  */
9125
9126 static void
9127 infrun_async_inferior_event_handler (gdb_client_data data)
9128 {
9129   inferior_event_handler (INF_REG_EVENT, NULL);
9130 }
9131
9132 void
9133 _initialize_infrun (void)
9134 {
9135   int i;
9136   int numsigs;
9137   struct cmd_list_element *c;
9138
9139   /* Register extra event sources in the event loop.  */
9140   infrun_async_inferior_event_token
9141     = create_async_event_handler (infrun_async_inferior_event_handler, NULL);
9142
9143   add_info ("signals", info_signals_command, _("\
9144 What debugger does when program gets various signals.\n\
9145 Specify a signal as argument to print info on that signal only."));
9146   add_info_alias ("handle", "signals", 0);
9147
9148   c = add_com ("handle", class_run, handle_command, _("\
9149 Specify how to handle signals.\n\
9150 Usage: handle SIGNAL [ACTIONS]\n\
9151 Args are signals and actions to apply to those signals.\n\
9152 If no actions are specified, the current settings for the specified signals\n\
9153 will be displayed instead.\n\
9154 \n\
9155 Symbolic signals (e.g. SIGSEGV) are recommended but numeric signals\n\
9156 from 1-15 are allowed for compatibility with old versions of GDB.\n\
9157 Numeric ranges may be specified with the form LOW-HIGH (e.g. 1-5).\n\
9158 The special arg \"all\" is recognized to mean all signals except those\n\
9159 used by the debugger, typically SIGTRAP and SIGINT.\n\
9160 \n\
9161 Recognized actions include \"stop\", \"nostop\", \"print\", \"noprint\",\n\
9162 \"pass\", \"nopass\", \"ignore\", or \"noignore\".\n\
9163 Stop means reenter debugger if this signal happens (implies print).\n\
9164 Print means print a message if this signal happens.\n\
9165 Pass means let program see this signal; otherwise program doesn't know.\n\
9166 Ignore is a synonym for nopass and noignore is a synonym for pass.\n\
9167 Pass and Stop may be combined.\n\
9168 \n\
9169 Multiple signals may be specified.  Signal numbers and signal names\n\
9170 may be interspersed with actions, with the actions being performed for\n\
9171 all signals cumulatively specified."));
9172   set_cmd_completer (c, handle_completer);
9173
9174   if (!dbx_commands)
9175     stop_command = add_cmd ("stop", class_obscure,
9176                             not_just_help_class_command, _("\
9177 There is no `stop' command, but you can set a hook on `stop'.\n\
9178 This allows you to set a list of commands to be run each time execution\n\
9179 of the program stops."), &cmdlist);
9180
9181   add_setshow_zuinteger_cmd ("infrun", class_maintenance, &debug_infrun, _("\
9182 Set inferior debugging."), _("\
9183 Show inferior debugging."), _("\
9184 When non-zero, inferior specific debugging is enabled."),
9185                              NULL,
9186                              show_debug_infrun,
9187                              &setdebuglist, &showdebuglist);
9188
9189   add_setshow_boolean_cmd ("displaced", class_maintenance,
9190                            &debug_displaced, _("\
9191 Set displaced stepping debugging."), _("\
9192 Show displaced stepping debugging."), _("\
9193 When non-zero, displaced stepping specific debugging is enabled."),
9194                             NULL,
9195                             show_debug_displaced,
9196                             &setdebuglist, &showdebuglist);
9197
9198   add_setshow_boolean_cmd ("non-stop", no_class,
9199                            &non_stop_1, _("\
9200 Set whether gdb controls the inferior in non-stop mode."), _("\
9201 Show whether gdb controls the inferior in non-stop mode."), _("\
9202 When debugging a multi-threaded program and this setting is\n\
9203 off (the default, also called all-stop mode), when one thread stops\n\
9204 (for a breakpoint, watchpoint, exception, or similar events), GDB stops\n\
9205 all other threads in the program while you interact with the thread of\n\
9206 interest.  When you continue or step a thread, you can allow the other\n\
9207 threads to run, or have them remain stopped, but while you inspect any\n\
9208 thread's state, all threads stop.\n\
9209 \n\
9210 In non-stop mode, when one thread stops, other threads can continue\n\
9211 to run freely.  You'll be able to step each thread independently,\n\
9212 leave it stopped or free to run as needed."),
9213                            set_non_stop,
9214                            show_non_stop,
9215                            &setlist,
9216                            &showlist);
9217
9218   numsigs = (int) GDB_SIGNAL_LAST;
9219   signal_stop = XNEWVEC (unsigned char, numsigs);
9220   signal_print = XNEWVEC (unsigned char, numsigs);
9221   signal_program = XNEWVEC (unsigned char, numsigs);
9222   signal_catch = XNEWVEC (unsigned char, numsigs);
9223   signal_pass = XNEWVEC (unsigned char, numsigs);
9224   for (i = 0; i < numsigs; i++)
9225     {
9226       signal_stop[i] = 1;
9227       signal_print[i] = 1;
9228       signal_program[i] = 1;
9229       signal_catch[i] = 0;
9230     }
9231
9232   /* Signals caused by debugger's own actions should not be given to
9233      the program afterwards.
9234
9235      Do not deliver GDB_SIGNAL_TRAP by default, except when the user
9236      explicitly specifies that it should be delivered to the target
9237      program.  Typically, that would occur when a user is debugging a
9238      target monitor on a simulator: the target monitor sets a
9239      breakpoint; the simulator encounters this breakpoint and halts
9240      the simulation handing control to GDB; GDB, noting that the stop
9241      address doesn't map to any known breakpoint, returns control back
9242      to the simulator; the simulator then delivers the hardware
9243      equivalent of a GDB_SIGNAL_TRAP to the program being
9244      debugged.  */
9245   signal_program[GDB_SIGNAL_TRAP] = 0;
9246   signal_program[GDB_SIGNAL_INT] = 0;
9247
9248   /* Signals that are not errors should not normally enter the debugger.  */
9249   signal_stop[GDB_SIGNAL_ALRM] = 0;
9250   signal_print[GDB_SIGNAL_ALRM] = 0;
9251   signal_stop[GDB_SIGNAL_VTALRM] = 0;
9252   signal_print[GDB_SIGNAL_VTALRM] = 0;
9253   signal_stop[GDB_SIGNAL_PROF] = 0;
9254   signal_print[GDB_SIGNAL_PROF] = 0;
9255   signal_stop[GDB_SIGNAL_CHLD] = 0;
9256   signal_print[GDB_SIGNAL_CHLD] = 0;
9257   signal_stop[GDB_SIGNAL_IO] = 0;
9258   signal_print[GDB_SIGNAL_IO] = 0;
9259   signal_stop[GDB_SIGNAL_POLL] = 0;
9260   signal_print[GDB_SIGNAL_POLL] = 0;
9261   signal_stop[GDB_SIGNAL_URG] = 0;
9262   signal_print[GDB_SIGNAL_URG] = 0;
9263   signal_stop[GDB_SIGNAL_WINCH] = 0;
9264   signal_print[GDB_SIGNAL_WINCH] = 0;
9265   signal_stop[GDB_SIGNAL_PRIO] = 0;
9266   signal_print[GDB_SIGNAL_PRIO] = 0;
9267
9268   /* These signals are used internally by user-level thread
9269      implementations.  (See signal(5) on Solaris.)  Like the above
9270      signals, a healthy program receives and handles them as part of
9271      its normal operation.  */
9272   signal_stop[GDB_SIGNAL_LWP] = 0;
9273   signal_print[GDB_SIGNAL_LWP] = 0;
9274   signal_stop[GDB_SIGNAL_WAITING] = 0;
9275   signal_print[GDB_SIGNAL_WAITING] = 0;
9276   signal_stop[GDB_SIGNAL_CANCEL] = 0;
9277   signal_print[GDB_SIGNAL_CANCEL] = 0;
9278   signal_stop[GDB_SIGNAL_LIBRT] = 0;
9279   signal_print[GDB_SIGNAL_LIBRT] = 0;
9280
9281   /* Update cached state.  */
9282   signal_cache_update (-1);
9283
9284   add_setshow_zinteger_cmd ("stop-on-solib-events", class_support,
9285                             &stop_on_solib_events, _("\
9286 Set stopping for shared library events."), _("\
9287 Show stopping for shared library events."), _("\
9288 If nonzero, gdb will give control to the user when the dynamic linker\n\
9289 notifies gdb of shared library events.  The most common event of interest\n\
9290 to the user would be loading/unloading of a new library."),
9291                             set_stop_on_solib_events,
9292                             show_stop_on_solib_events,
9293                             &setlist, &showlist);
9294
9295   add_setshow_enum_cmd ("follow-fork-mode", class_run,
9296                         follow_fork_mode_kind_names,
9297                         &follow_fork_mode_string, _("\
9298 Set debugger response to a program call of fork or vfork."), _("\
9299 Show debugger response to a program call of fork or vfork."), _("\
9300 A fork or vfork creates a new process.  follow-fork-mode can be:\n\
9301   parent  - the original process is debugged after a fork\n\
9302   child   - the new process is debugged after a fork\n\
9303 The unfollowed process will continue to run.\n\
9304 By default, the debugger will follow the parent process."),
9305                         NULL,
9306                         show_follow_fork_mode_string,
9307                         &setlist, &showlist);
9308
9309   add_setshow_enum_cmd ("follow-exec-mode", class_run,
9310                         follow_exec_mode_names,
9311                         &follow_exec_mode_string, _("\
9312 Set debugger response to a program call of exec."), _("\
9313 Show debugger response to a program call of exec."), _("\
9314 An exec call replaces the program image of a process.\n\
9315 \n\
9316 follow-exec-mode can be:\n\
9317 \n\
9318   new - the debugger creates a new inferior and rebinds the process\n\
9319 to this new inferior.  The program the process was running before\n\
9320 the exec call can be restarted afterwards by restarting the original\n\
9321 inferior.\n\
9322 \n\
9323   same - the debugger keeps the process bound to the same inferior.\n\
9324 The new executable image replaces the previous executable loaded in\n\
9325 the inferior.  Restarting the inferior after the exec call restarts\n\
9326 the executable the process was running after the exec call.\n\
9327 \n\
9328 By default, the debugger will use the same inferior."),
9329                         NULL,
9330                         show_follow_exec_mode_string,
9331                         &setlist, &showlist);
9332
9333   add_setshow_enum_cmd ("scheduler-locking", class_run, 
9334                         scheduler_enums, &scheduler_mode, _("\
9335 Set mode for locking scheduler during execution."), _("\
9336 Show mode for locking scheduler during execution."), _("\
9337 off    == no locking (threads may preempt at any time)\n\
9338 on     == full locking (no thread except the current thread may run)\n\
9339           This applies to both normal execution and replay mode.\n\
9340 step   == scheduler locked during stepping commands (step, next, stepi, nexti).\n\
9341           In this mode, other threads may run during other commands.\n\
9342           This applies to both normal execution and replay mode.\n\
9343 replay == scheduler locked in replay mode and unlocked during normal execution."),
9344                         set_schedlock_func,     /* traps on target vector */
9345                         show_scheduler_mode,
9346                         &setlist, &showlist);
9347
9348   add_setshow_boolean_cmd ("schedule-multiple", class_run, &sched_multi, _("\
9349 Set mode for resuming threads of all processes."), _("\
9350 Show mode for resuming threads of all processes."), _("\
9351 When on, execution commands (such as 'continue' or 'next') resume all\n\
9352 threads of all processes.  When off (which is the default), execution\n\
9353 commands only resume the threads of the current process.  The set of\n\
9354 threads that are resumed is further refined by the scheduler-locking\n\
9355 mode (see help set scheduler-locking)."),
9356                            NULL,
9357                            show_schedule_multiple,
9358                            &setlist, &showlist);
9359
9360   add_setshow_boolean_cmd ("step-mode", class_run, &step_stop_if_no_debug, _("\
9361 Set mode of the step operation."), _("\
9362 Show mode of the step operation."), _("\
9363 When set, doing a step over a function without debug line information\n\
9364 will stop at the first instruction of that function. Otherwise, the\n\
9365 function is skipped and the step command stops at a different source line."),
9366                            NULL,
9367                            show_step_stop_if_no_debug,
9368                            &setlist, &showlist);
9369
9370   add_setshow_auto_boolean_cmd ("displaced-stepping", class_run,
9371                                 &can_use_displaced_stepping, _("\
9372 Set debugger's willingness to use displaced stepping."), _("\
9373 Show debugger's willingness to use displaced stepping."), _("\
9374 If on, gdb will use displaced stepping to step over breakpoints if it is\n\
9375 supported by the target architecture.  If off, gdb will not use displaced\n\
9376 stepping to step over breakpoints, even if such is supported by the target\n\
9377 architecture.  If auto (which is the default), gdb will use displaced stepping\n\
9378 if the target architecture supports it and non-stop mode is active, but will not\n\
9379 use it in all-stop mode (see help set non-stop)."),
9380                                 NULL,
9381                                 show_can_use_displaced_stepping,
9382                                 &setlist, &showlist);
9383
9384   add_setshow_enum_cmd ("exec-direction", class_run, exec_direction_names,
9385                         &exec_direction, _("Set direction of execution.\n\
9386 Options are 'forward' or 'reverse'."),
9387                         _("Show direction of execution (forward/reverse)."),
9388                         _("Tells gdb whether to execute forward or backward."),
9389                         set_exec_direction_func, show_exec_direction_func,
9390                         &setlist, &showlist);
9391
9392   /* Set/show detach-on-fork: user-settable mode.  */
9393
9394   add_setshow_boolean_cmd ("detach-on-fork", class_run, &detach_fork, _("\
9395 Set whether gdb will detach the child of a fork."), _("\
9396 Show whether gdb will detach the child of a fork."), _("\
9397 Tells gdb whether to detach the child of a fork."),
9398                            NULL, NULL, &setlist, &showlist);
9399
9400   /* Set/show disable address space randomization mode.  */
9401
9402   add_setshow_boolean_cmd ("disable-randomization", class_support,
9403                            &disable_randomization, _("\
9404 Set disabling of debuggee's virtual address space randomization."), _("\
9405 Show disabling of debuggee's virtual address space randomization."), _("\
9406 When this mode is on (which is the default), randomization of the virtual\n\
9407 address space is disabled.  Standalone programs run with the randomization\n\
9408 enabled by default on some platforms."),
9409                            &set_disable_randomization,
9410                            &show_disable_randomization,
9411                            &setlist, &showlist);
9412
9413   /* ptid initializations */
9414   inferior_ptid = null_ptid;
9415   target_last_wait_ptid = minus_one_ptid;
9416
9417   observer_attach_thread_ptid_changed (infrun_thread_ptid_changed);
9418   observer_attach_thread_stop_requested (infrun_thread_stop_requested);
9419   observer_attach_thread_exit (infrun_thread_thread_exit);
9420   observer_attach_inferior_exit (infrun_inferior_exit);
9421
9422   /* Explicitly create without lookup, since that tries to create a
9423      value with a void typed value, and when we get here, gdbarch
9424      isn't initialized yet.  At this point, we're quite sure there
9425      isn't another convenience variable of the same name.  */
9426   create_internalvar_type_lazy ("_siginfo", &siginfo_funcs, NULL);
9427
9428   add_setshow_boolean_cmd ("observer", no_class,
9429                            &observer_mode_1, _("\
9430 Set whether gdb controls the inferior in observer mode."), _("\
9431 Show whether gdb controls the inferior in observer mode."), _("\
9432 In observer mode, GDB can get data from the inferior, but not\n\
9433 affect its execution.  Registers and memory may not be changed,\n\
9434 breakpoints may not be set, and the program cannot be interrupted\n\
9435 or signalled."),
9436                            set_observer_mode,
9437                            show_observer_mode,
9438                            &setlist,
9439                            &showlist);
9440 }