* inf-ptrace.c: Include "gdbthread.h".
[external/binutils.git] / gdb / linux-nat.c
1 /* GNU/Linux native-dependent code common to multiple platforms.
2
3    Copyright (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008
4    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 "inferior.h"
23 #include "target.h"
24 #include "gdb_string.h"
25 #include "gdb_wait.h"
26 #include "gdb_assert.h"
27 #ifdef HAVE_TKILL_SYSCALL
28 #include <unistd.h>
29 #include <sys/syscall.h>
30 #endif
31 #include <sys/ptrace.h>
32 #include "linux-nat.h"
33 #include "linux-fork.h"
34 #include "gdbthread.h"
35 #include "gdbcmd.h"
36 #include "regcache.h"
37 #include "regset.h"
38 #include "inf-ptrace.h"
39 #include "auxv.h"
40 #include <sys/param.h>          /* for MAXPATHLEN */
41 #include <sys/procfs.h>         /* for elf_gregset etc. */
42 #include "elf-bfd.h"            /* for elfcore_write_* */
43 #include "gregset.h"            /* for gregset */
44 #include "gdbcore.h"            /* for get_exec_file */
45 #include <ctype.h>              /* for isdigit */
46 #include "gdbthread.h"          /* for struct thread_info etc. */
47 #include "gdb_stat.h"           /* for struct stat */
48 #include <fcntl.h>              /* for O_RDONLY */
49 #include "inf-loop.h"
50 #include "event-loop.h"
51 #include "event-top.h"
52
53 #ifdef HAVE_PERSONALITY
54 # include <sys/personality.h>
55 # if !HAVE_DECL_ADDR_NO_RANDOMIZE
56 #  define ADDR_NO_RANDOMIZE 0x0040000
57 # endif
58 #endif /* HAVE_PERSONALITY */
59
60 /* This comment documents high-level logic of this file. 
61
62 Waiting for events in sync mode
63 ===============================
64
65 When waiting for an event in a specific thread, we just use waitpid, passing
66 the specific pid, and not passing WNOHANG.
67
68 When waiting for an event in all threads, waitpid is not quite good. Prior to
69 version 2.4, Linux can either wait for event in main thread, or in secondary
70 threads. (2.4 has the __WALL flag).  So, if we use blocking waitpid, we might
71 miss an event.  The solution is to use non-blocking waitpid, together with
72 sigsuspend.  First, we use non-blocking waitpid to get an event in the main 
73 process, if any. Second, we use non-blocking waitpid with the __WCLONED
74 flag to check for events in cloned processes.  If nothing is found, we use
75 sigsuspend to wait for SIGCHLD.  When SIGCHLD arrives, it means something
76 happened to a child process -- and SIGCHLD will be delivered both for events
77 in main debugged process and in cloned processes.  As soon as we know there's
78 an event, we get back to calling nonblocking waitpid with and without __WCLONED.
79
80 Note that SIGCHLD should be blocked between waitpid and sigsuspend calls,
81 so that we don't miss a signal. If SIGCHLD arrives in between, when it's
82 blocked, the signal becomes pending and sigsuspend immediately
83 notices it and returns.
84
85 Waiting for events in async mode
86 ================================
87
88 In async mode, GDB should always be ready to handle both user input and target
89 events, so neither blocking waitpid nor sigsuspend are viable
90 options. Instead, we should notify the GDB main event loop whenever there's
91 unprocessed event from the target.  The only way to notify this event loop is
92 to make it wait on input from a pipe, and write something to the pipe whenever
93 there's event. Obviously, if we fail to notify the event loop if there's
94 target event, it's bad.  If we notify the event loop when there's no event
95 from target, linux-nat.c will detect that there's no event, actually, and
96 report event of type TARGET_WAITKIND_IGNORE, but it will waste time and
97 better avoided.
98
99 The main design point is that every time GDB is outside linux-nat.c, we have a
100 SIGCHLD handler installed that is called when something happens to the target
101 and notifies the GDB event loop. Also, the event is extracted from the target
102 using waitpid and stored for future use.  Whenever GDB core decides to handle
103 the event, and calls into linux-nat.c, we disable SIGCHLD and process things
104 as in sync mode, except that before waitpid call we check if there are any
105 previously read events.
106
107 It could happen that during event processing, we'll try to get more events
108 than there are events in the local queue, which will result to waitpid call.
109 Those waitpid calls, while blocking, are guarantied to always have
110 something for waitpid to return.  E.g., stopping a thread with SIGSTOP, and
111 waiting for the lwp to stop.
112
113 The event loop is notified about new events using a pipe. SIGCHLD handler does
114 waitpid and writes the results in to a pipe. GDB event loop has the other end
115 of the pipe among the sources. When event loop starts to process the event
116 and calls a function in linux-nat.c, all events from the pipe are transferred
117 into a local queue and SIGCHLD is blocked. Further processing goes as in sync
118 mode. Before we return from linux_nat_wait, we transfer all unprocessed events
119 from local queue back to the pipe, so that when we get back to event loop,
120 event loop will notice there's something more to do.
121
122 SIGCHLD is blocked when we're inside target_wait, so that should we actually
123 want to wait for some more events, SIGCHLD handler does not steal them from
124 us. Technically, it would be possible to add new events to the local queue but
125 it's about the same amount of work as blocking SIGCHLD.
126
127 This moving of events from pipe into local queue and back into pipe when we
128 enter/leave linux-nat.c is somewhat ugly. Unfortunately, GDB event loop is
129 home-grown and incapable to wait on any queue.
130
131 Use of signals
132 ==============
133
134 We stop threads by sending a SIGSTOP.  The use of SIGSTOP instead of another
135 signal is not entirely significant; we just need for a signal to be delivered,
136 so that we can intercept it.  SIGSTOP's advantage is that it can not be
137 blocked.  A disadvantage is that it is not a real-time signal, so it can only
138 be queued once; we do not keep track of other sources of SIGSTOP.
139
140 Two other signals that can't be blocked are SIGCONT and SIGKILL.  But we can't
141 use them, because they have special behavior when the signal is generated -
142 not when it is delivered.  SIGCONT resumes the entire thread group and SIGKILL
143 kills the entire thread group.
144
145 A delivered SIGSTOP would stop the entire thread group, not just the thread we
146 tkill'd.  But we never let the SIGSTOP be delivered; we always intercept and 
147 cancel it (by PTRACE_CONT without passing SIGSTOP).
148
149 We could use a real-time signal instead.  This would solve those problems; we
150 could use PTRACE_GETSIGINFO to locate the specific stop signals sent by GDB.
151 But we would still have to have some support for SIGSTOP, since PTRACE_ATTACH
152 generates it, and there are races with trying to find a signal that is not
153 blocked.  */
154
155 #ifndef O_LARGEFILE
156 #define O_LARGEFILE 0
157 #endif
158
159 /* If the system headers did not provide the constants, hard-code the normal
160    values.  */
161 #ifndef PTRACE_EVENT_FORK
162
163 #define PTRACE_SETOPTIONS       0x4200
164 #define PTRACE_GETEVENTMSG      0x4201
165
166 /* options set using PTRACE_SETOPTIONS */
167 #define PTRACE_O_TRACESYSGOOD   0x00000001
168 #define PTRACE_O_TRACEFORK      0x00000002
169 #define PTRACE_O_TRACEVFORK     0x00000004
170 #define PTRACE_O_TRACECLONE     0x00000008
171 #define PTRACE_O_TRACEEXEC      0x00000010
172 #define PTRACE_O_TRACEVFORKDONE 0x00000020
173 #define PTRACE_O_TRACEEXIT      0x00000040
174
175 /* Wait extended result codes for the above trace options.  */
176 #define PTRACE_EVENT_FORK       1
177 #define PTRACE_EVENT_VFORK      2
178 #define PTRACE_EVENT_CLONE      3
179 #define PTRACE_EVENT_EXEC       4
180 #define PTRACE_EVENT_VFORK_DONE 5
181 #define PTRACE_EVENT_EXIT       6
182
183 #endif /* PTRACE_EVENT_FORK */
184
185 /* We can't always assume that this flag is available, but all systems
186    with the ptrace event handlers also have __WALL, so it's safe to use
187    here.  */
188 #ifndef __WALL
189 #define __WALL          0x40000000 /* Wait for any child.  */
190 #endif
191
192 #ifndef PTRACE_GETSIGINFO
193 #define PTRACE_GETSIGINFO    0x4202
194 #endif
195
196 /* The single-threaded native GNU/Linux target_ops.  We save a pointer for
197    the use of the multi-threaded target.  */
198 static struct target_ops *linux_ops;
199 static struct target_ops linux_ops_saved;
200
201 /* The method to call, if any, when a new thread is attached.  */
202 static void (*linux_nat_new_thread) (ptid_t);
203
204 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
205    Called by our to_xfer_partial.  */
206 static LONGEST (*super_xfer_partial) (struct target_ops *, 
207                                       enum target_object,
208                                       const char *, gdb_byte *, 
209                                       const gdb_byte *,
210                                       ULONGEST, LONGEST);
211
212 static int debug_linux_nat;
213 static void
214 show_debug_linux_nat (struct ui_file *file, int from_tty,
215                       struct cmd_list_element *c, const char *value)
216 {
217   fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
218                     value);
219 }
220
221 static int debug_linux_nat_async = 0;
222 static void
223 show_debug_linux_nat_async (struct ui_file *file, int from_tty,
224                             struct cmd_list_element *c, const char *value)
225 {
226   fprintf_filtered (file, _("Debugging of GNU/Linux async lwp module is %s.\n"),
227                     value);
228 }
229
230 static int disable_randomization = 1;
231
232 static void
233 show_disable_randomization (struct ui_file *file, int from_tty,
234                             struct cmd_list_element *c, const char *value)
235 {
236 #ifdef HAVE_PERSONALITY
237   fprintf_filtered (file, _("\
238 Disabling randomization of debuggee's virtual address space is %s.\n"),
239                     value);
240 #else /* !HAVE_PERSONALITY */
241   fputs_filtered (_("\
242 Disabling randomization of debuggee's virtual address space is unsupported on\n\
243 this platform.\n"), file);
244 #endif /* !HAVE_PERSONALITY */
245 }
246
247 static void
248 set_disable_randomization (char *args, int from_tty, struct cmd_list_element *c)
249 {
250 #ifndef HAVE_PERSONALITY
251   error (_("\
252 Disabling randomization of debuggee's virtual address space is unsupported on\n\
253 this platform."));
254 #endif /* !HAVE_PERSONALITY */
255 }
256
257 static int linux_parent_pid;
258
259 struct simple_pid_list
260 {
261   int pid;
262   int status;
263   struct simple_pid_list *next;
264 };
265 struct simple_pid_list *stopped_pids;
266
267 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
268    can not be used, 1 if it can.  */
269
270 static int linux_supports_tracefork_flag = -1;
271
272 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
273    PTRACE_O_TRACEVFORKDONE.  */
274
275 static int linux_supports_tracevforkdone_flag = -1;
276
277 /* Async mode support */
278
279 /* Zero if the async mode, although enabled, is masked, which means
280    linux_nat_wait should behave as if async mode was off.  */
281 static int linux_nat_async_mask_value = 1;
282
283 /* The read/write ends of the pipe registered as waitable file in the
284    event loop.  */
285 static int linux_nat_event_pipe[2] = { -1, -1 };
286
287 /* Number of queued events in the pipe.  */
288 static volatile int linux_nat_num_queued_events;
289
290 /* The possible SIGCHLD handling states.  */
291
292 enum sigchld_state
293 {
294   /* SIGCHLD disabled, with action set to sigchld_handler, for the
295      sigsuspend in linux_nat_wait.  */
296   sigchld_sync,
297   /* SIGCHLD enabled, with action set to async_sigchld_handler.  */
298   sigchld_async,
299   /* Set SIGCHLD to default action.  Used while creating an
300      inferior.  */
301   sigchld_default
302 };
303
304 /* The current SIGCHLD handling state.  */
305 static enum sigchld_state linux_nat_async_events_state;
306
307 static enum sigchld_state linux_nat_async_events (enum sigchld_state enable);
308 static void pipe_to_local_event_queue (void);
309 static void local_event_queue_to_pipe (void);
310 static void linux_nat_event_pipe_push (int pid, int status, int options);
311 static int linux_nat_event_pipe_pop (int* ptr_status, int* ptr_options);
312 static void linux_nat_set_async_mode (int on);
313 static void linux_nat_async (void (*callback)
314                              (enum inferior_event_type event_type, void *context),
315                              void *context);
316 static int linux_nat_async_mask (int mask);
317 static int kill_lwp (int lwpid, int signo);
318
319 static int send_sigint_callback (struct lwp_info *lp, void *data);
320 static int stop_callback (struct lwp_info *lp, void *data);
321
322 /* Captures the result of a successful waitpid call, along with the
323    options used in that call.  */
324 struct waitpid_result
325 {
326   int pid;
327   int status;
328   int options;
329   struct waitpid_result *next;
330 };
331
332 /* A singly-linked list of the results of the waitpid calls performed
333    in the async SIGCHLD handler.  */
334 static struct waitpid_result *waitpid_queue = NULL;
335
336 static int
337 queued_waitpid (int pid, int *status, int flags)
338 {
339   struct waitpid_result *msg = waitpid_queue, *prev = NULL;
340
341   if (debug_linux_nat_async)
342     fprintf_unfiltered (gdb_stdlog,
343                         "\
344 QWPID: linux_nat_async_events_state(%d), linux_nat_num_queued_events(%d)\n",
345                         linux_nat_async_events_state,
346                         linux_nat_num_queued_events);
347
348   if (flags & __WALL)
349     {
350       for (; msg; prev = msg, msg = msg->next)
351         if (pid == -1 || pid == msg->pid)
352           break;
353     }
354   else if (flags & __WCLONE)
355     {
356       for (; msg; prev = msg, msg = msg->next)
357         if (msg->options & __WCLONE
358             && (pid == -1 || pid == msg->pid))
359           break;
360     }
361   else
362     {
363       for (; msg; prev = msg, msg = msg->next)
364         if ((msg->options & __WCLONE) == 0
365             && (pid == -1 || pid == msg->pid))
366           break;
367     }
368
369   if (msg)
370     {
371       int pid;
372
373       if (prev)
374         prev->next = msg->next;
375       else
376         waitpid_queue = msg->next;
377
378       msg->next = NULL;
379       if (status)
380         *status = msg->status;
381       pid = msg->pid;
382
383       if (debug_linux_nat_async)
384         fprintf_unfiltered (gdb_stdlog, "QWPID: pid(%d), status(%x)\n",
385                             pid, msg->status);
386       xfree (msg);
387
388       return pid;
389     }
390
391   if (debug_linux_nat_async)
392     fprintf_unfiltered (gdb_stdlog, "QWPID: miss\n");
393
394   if (status)
395     *status = 0;
396   return -1;
397 }
398
399 static void
400 push_waitpid (int pid, int status, int options)
401 {
402   struct waitpid_result *event, *new_event;
403
404   new_event = xmalloc (sizeof (*new_event));
405   new_event->pid = pid;
406   new_event->status = status;
407   new_event->options = options;
408   new_event->next = NULL;
409
410   if (waitpid_queue)
411     {
412       for (event = waitpid_queue;
413            event && event->next;
414            event = event->next)
415         ;
416
417       event->next = new_event;
418     }
419   else
420     waitpid_queue = new_event;
421 }
422
423 /* Drain all queued events of PID.  If PID is -1, the effect is of
424    draining all events.  */
425 static void
426 drain_queued_events (int pid)
427 {
428   while (queued_waitpid (pid, NULL, __WALL) != -1)
429     ;
430 }
431
432 \f
433 /* Trivial list manipulation functions to keep track of a list of
434    new stopped processes.  */
435 static void
436 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
437 {
438   struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
439   new_pid->pid = pid;
440   new_pid->status = status;
441   new_pid->next = *listp;
442   *listp = new_pid;
443 }
444
445 static int
446 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *status)
447 {
448   struct simple_pid_list **p;
449
450   for (p = listp; *p != NULL; p = &(*p)->next)
451     if ((*p)->pid == pid)
452       {
453         struct simple_pid_list *next = (*p)->next;
454         *status = (*p)->status;
455         xfree (*p);
456         *p = next;
457         return 1;
458       }
459   return 0;
460 }
461
462 static void
463 linux_record_stopped_pid (int pid, int status)
464 {
465   add_to_pid_list (&stopped_pids, pid, status);
466 }
467
468 \f
469 /* A helper function for linux_test_for_tracefork, called after fork ().  */
470
471 static void
472 linux_tracefork_child (void)
473 {
474   int ret;
475
476   ptrace (PTRACE_TRACEME, 0, 0, 0);
477   kill (getpid (), SIGSTOP);
478   fork ();
479   _exit (0);
480 }
481
482 /* Wrapper function for waitpid which handles EINTR, and checks for
483    locally queued events.  */
484
485 static int
486 my_waitpid (int pid, int *status, int flags)
487 {
488   int ret;
489
490   /* There should be no concurrent calls to waitpid.  */
491   gdb_assert (linux_nat_async_events_state == sigchld_sync);
492
493   ret = queued_waitpid (pid, status, flags);
494   if (ret != -1)
495     return ret;
496
497   do
498     {
499       ret = waitpid (pid, status, flags);
500     }
501   while (ret == -1 && errno == EINTR);
502
503   return ret;
504 }
505
506 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
507
508    First, we try to enable fork tracing on ORIGINAL_PID.  If this fails,
509    we know that the feature is not available.  This may change the tracing
510    options for ORIGINAL_PID, but we'll be setting them shortly anyway.
511
512    However, if it succeeds, we don't know for sure that the feature is
513    available; old versions of PTRACE_SETOPTIONS ignored unknown options.  We
514    create a child process, attach to it, use PTRACE_SETOPTIONS to enable
515    fork tracing, and let it fork.  If the process exits, we assume that we
516    can't use TRACEFORK; if we get the fork notification, and we can extract
517    the new child's PID, then we assume that we can.  */
518
519 static void
520 linux_test_for_tracefork (int original_pid)
521 {
522   int child_pid, ret, status;
523   long second_pid;
524   enum sigchld_state async_events_original_state;
525
526   async_events_original_state = linux_nat_async_events (sigchld_sync);
527
528   linux_supports_tracefork_flag = 0;
529   linux_supports_tracevforkdone_flag = 0;
530
531   ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
532   if (ret != 0)
533     return;
534
535   child_pid = fork ();
536   if (child_pid == -1)
537     perror_with_name (("fork"));
538
539   if (child_pid == 0)
540     linux_tracefork_child ();
541
542   ret = my_waitpid (child_pid, &status, 0);
543   if (ret == -1)
544     perror_with_name (("waitpid"));
545   else if (ret != child_pid)
546     error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
547   if (! WIFSTOPPED (status))
548     error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
549
550   ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
551   if (ret != 0)
552     {
553       ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
554       if (ret != 0)
555         {
556           warning (_("linux_test_for_tracefork: failed to kill child"));
557           linux_nat_async_events (async_events_original_state);
558           return;
559         }
560
561       ret = my_waitpid (child_pid, &status, 0);
562       if (ret != child_pid)
563         warning (_("linux_test_for_tracefork: failed to wait for killed child"));
564       else if (!WIFSIGNALED (status))
565         warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
566                  "killed child"), status);
567
568       linux_nat_async_events (async_events_original_state);
569       return;
570     }
571
572   /* Check whether PTRACE_O_TRACEVFORKDONE is available.  */
573   ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
574                 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
575   linux_supports_tracevforkdone_flag = (ret == 0);
576
577   ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
578   if (ret != 0)
579     warning (_("linux_test_for_tracefork: failed to resume child"));
580
581   ret = my_waitpid (child_pid, &status, 0);
582
583   if (ret == child_pid && WIFSTOPPED (status)
584       && status >> 16 == PTRACE_EVENT_FORK)
585     {
586       second_pid = 0;
587       ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
588       if (ret == 0 && second_pid != 0)
589         {
590           int second_status;
591
592           linux_supports_tracefork_flag = 1;
593           my_waitpid (second_pid, &second_status, 0);
594           ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
595           if (ret != 0)
596             warning (_("linux_test_for_tracefork: failed to kill second child"));
597           my_waitpid (second_pid, &status, 0);
598         }
599     }
600   else
601     warning (_("linux_test_for_tracefork: unexpected result from waitpid "
602              "(%d, status 0x%x)"), ret, status);
603
604   ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
605   if (ret != 0)
606     warning (_("linux_test_for_tracefork: failed to kill child"));
607   my_waitpid (child_pid, &status, 0);
608
609   linux_nat_async_events (async_events_original_state);
610 }
611
612 /* Return non-zero iff we have tracefork functionality available.
613    This function also sets linux_supports_tracefork_flag.  */
614
615 static int
616 linux_supports_tracefork (int pid)
617 {
618   if (linux_supports_tracefork_flag == -1)
619     linux_test_for_tracefork (pid);
620   return linux_supports_tracefork_flag;
621 }
622
623 static int
624 linux_supports_tracevforkdone (int pid)
625 {
626   if (linux_supports_tracefork_flag == -1)
627     linux_test_for_tracefork (pid);
628   return linux_supports_tracevforkdone_flag;
629 }
630
631 \f
632 void
633 linux_enable_event_reporting (ptid_t ptid)
634 {
635   int pid = ptid_get_lwp (ptid);
636   int options;
637
638   if (pid == 0)
639     pid = ptid_get_pid (ptid);
640
641   if (! linux_supports_tracefork (pid))
642     return;
643
644   options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
645     | PTRACE_O_TRACECLONE;
646   if (linux_supports_tracevforkdone (pid))
647     options |= PTRACE_O_TRACEVFORKDONE;
648
649   /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
650      read-only process state.  */
651
652   ptrace (PTRACE_SETOPTIONS, pid, 0, options);
653 }
654
655 static void
656 linux_child_post_attach (int pid)
657 {
658   linux_enable_event_reporting (pid_to_ptid (pid));
659   check_for_thread_db ();
660 }
661
662 static void
663 linux_child_post_startup_inferior (ptid_t ptid)
664 {
665   linux_enable_event_reporting (ptid);
666   check_for_thread_db ();
667 }
668
669 static int
670 linux_child_follow_fork (struct target_ops *ops, int follow_child)
671 {
672   ptid_t last_ptid;
673   struct target_waitstatus last_status;
674   int has_vforked;
675   int parent_pid, child_pid;
676
677   if (target_can_async_p ())
678     target_async (NULL, 0);
679
680   get_last_target_status (&last_ptid, &last_status);
681   has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
682   parent_pid = ptid_get_lwp (last_ptid);
683   if (parent_pid == 0)
684     parent_pid = ptid_get_pid (last_ptid);
685   child_pid = PIDGET (last_status.value.related_pid);
686
687   if (! follow_child)
688     {
689       /* We're already attached to the parent, by default. */
690
691       /* Before detaching from the child, remove all breakpoints from
692          it.  (This won't actually modify the breakpoint list, but will
693          physically remove the breakpoints from the child.) */
694       /* If we vforked this will remove the breakpoints from the parent
695          also, but they'll be reinserted below.  */
696       detach_breakpoints (child_pid);
697
698       /* Detach new forked process?  */
699       if (detach_fork)
700         {
701           if (info_verbose || debug_linux_nat)
702             {
703               target_terminal_ours ();
704               fprintf_filtered (gdb_stdlog,
705                                 "Detaching after fork from child process %d.\n",
706                                 child_pid);
707             }
708
709           ptrace (PTRACE_DETACH, child_pid, 0, 0);
710         }
711       else
712         {
713           struct fork_info *fp;
714           /* Retain child fork in ptrace (stopped) state.  */
715           fp = find_fork_pid (child_pid);
716           if (!fp)
717             fp = add_fork (child_pid);
718           fork_save_infrun_state (fp, 0);
719         }
720
721       if (has_vforked)
722         {
723           gdb_assert (linux_supports_tracefork_flag >= 0);
724           if (linux_supports_tracevforkdone (0))
725             {
726               int status;
727
728               ptrace (PTRACE_CONT, parent_pid, 0, 0);
729               my_waitpid (parent_pid, &status, __WALL);
730               if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
731                 warning (_("Unexpected waitpid result %06x when waiting for "
732                          "vfork-done"), status);
733             }
734           else
735             {
736               /* We can't insert breakpoints until the child has
737                  finished with the shared memory region.  We need to
738                  wait until that happens.  Ideal would be to just
739                  call:
740                  - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
741                  - waitpid (parent_pid, &status, __WALL);
742                  However, most architectures can't handle a syscall
743                  being traced on the way out if it wasn't traced on
744                  the way in.
745
746                  We might also think to loop, continuing the child
747                  until it exits or gets a SIGTRAP.  One problem is
748                  that the child might call ptrace with PTRACE_TRACEME.
749
750                  There's no simple and reliable way to figure out when
751                  the vforked child will be done with its copy of the
752                  shared memory.  We could step it out of the syscall,
753                  two instructions, let it go, and then single-step the
754                  parent once.  When we have hardware single-step, this
755                  would work; with software single-step it could still
756                  be made to work but we'd have to be able to insert
757                  single-step breakpoints in the child, and we'd have
758                  to insert -just- the single-step breakpoint in the
759                  parent.  Very awkward.
760
761                  In the end, the best we can do is to make sure it
762                  runs for a little while.  Hopefully it will be out of
763                  range of any breakpoints we reinsert.  Usually this
764                  is only the single-step breakpoint at vfork's return
765                  point.  */
766
767               usleep (10000);
768             }
769
770           /* Since we vforked, breakpoints were removed in the parent
771              too.  Put them back.  */
772           reattach_breakpoints (parent_pid);
773         }
774     }
775   else
776     {
777       char child_pid_spelling[40];
778
779       /* Needed to keep the breakpoint lists in sync.  */
780       if (! has_vforked)
781         detach_breakpoints (child_pid);
782
783       /* Before detaching from the parent, remove all breakpoints from it. */
784       remove_breakpoints ();
785
786       if (info_verbose || debug_linux_nat)
787         {
788           target_terminal_ours ();
789           fprintf_filtered (gdb_stdlog,
790                             "Attaching after fork to child process %d.\n",
791                             child_pid);
792         }
793
794       /* If we're vforking, we may want to hold on to the parent until
795          the child exits or execs.  At exec time we can remove the old
796          breakpoints from the parent and detach it; at exit time we
797          could do the same (or even, sneakily, resume debugging it - the
798          child's exec has failed, or something similar).
799
800          This doesn't clean up "properly", because we can't call
801          target_detach, but that's OK; if the current target is "child",
802          then it doesn't need any further cleanups, and lin_lwp will
803          generally not encounter vfork (vfork is defined to fork
804          in libpthread.so).
805
806          The holding part is very easy if we have VFORKDONE events;
807          but keeping track of both processes is beyond GDB at the
808          moment.  So we don't expose the parent to the rest of GDB.
809          Instead we quietly hold onto it until such time as we can
810          safely resume it.  */
811
812       if (has_vforked)
813         linux_parent_pid = parent_pid;
814       else if (!detach_fork)
815         {
816           struct fork_info *fp;
817           /* Retain parent fork in ptrace (stopped) state.  */
818           fp = find_fork_pid (parent_pid);
819           if (!fp)
820             fp = add_fork (parent_pid);
821           fork_save_infrun_state (fp, 0);
822         }
823       else
824         target_detach (NULL, 0);
825
826       inferior_ptid = ptid_build (child_pid, child_pid, 0);
827
828       /* Reinstall ourselves, since we might have been removed in
829          target_detach (which does other necessary cleanup).  */
830
831       push_target (ops);
832       linux_nat_switch_fork (inferior_ptid);
833       check_for_thread_db ();
834
835       /* Reset breakpoints in the child as appropriate.  */
836       follow_inferior_reset_breakpoints ();
837     }
838
839   if (target_can_async_p ())
840     target_async (inferior_event_handler, 0);
841
842   return 0;
843 }
844
845 \f
846 static void
847 linux_child_insert_fork_catchpoint (int pid)
848 {
849   if (! linux_supports_tracefork (pid))
850     error (_("Your system does not support fork catchpoints."));
851 }
852
853 static void
854 linux_child_insert_vfork_catchpoint (int pid)
855 {
856   if (!linux_supports_tracefork (pid))
857     error (_("Your system does not support vfork catchpoints."));
858 }
859
860 static void
861 linux_child_insert_exec_catchpoint (int pid)
862 {
863   if (!linux_supports_tracefork (pid))
864     error (_("Your system does not support exec catchpoints."));
865 }
866
867 /* On GNU/Linux there are no real LWP's.  The closest thing to LWP's
868    are processes sharing the same VM space.  A multi-threaded process
869    is basically a group of such processes.  However, such a grouping
870    is almost entirely a user-space issue; the kernel doesn't enforce
871    such a grouping at all (this might change in the future).  In
872    general, we'll rely on the threads library (i.e. the GNU/Linux
873    Threads library) to provide such a grouping.
874
875    It is perfectly well possible to write a multi-threaded application
876    without the assistance of a threads library, by using the clone
877    system call directly.  This module should be able to give some
878    rudimentary support for debugging such applications if developers
879    specify the CLONE_PTRACE flag in the clone system call, and are
880    using the Linux kernel 2.4 or above.
881
882    Note that there are some peculiarities in GNU/Linux that affect
883    this code:
884
885    - In general one should specify the __WCLONE flag to waitpid in
886      order to make it report events for any of the cloned processes
887      (and leave it out for the initial process).  However, if a cloned
888      process has exited the exit status is only reported if the
889      __WCLONE flag is absent.  Linux kernel 2.4 has a __WALL flag, but
890      we cannot use it since GDB must work on older systems too.
891
892    - When a traced, cloned process exits and is waited for by the
893      debugger, the kernel reassigns it to the original parent and
894      keeps it around as a "zombie".  Somehow, the GNU/Linux Threads
895      library doesn't notice this, which leads to the "zombie problem":
896      When debugged a multi-threaded process that spawns a lot of
897      threads will run out of processes, even if the threads exit,
898      because the "zombies" stay around.  */
899
900 /* List of known LWPs.  */
901 struct lwp_info *lwp_list;
902
903 /* Number of LWPs in the list.  */
904 static int num_lwps;
905 \f
906
907 /* Original signal mask.  */
908 static sigset_t normal_mask;
909
910 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
911    _initialize_linux_nat.  */
912 static sigset_t suspend_mask;
913
914 /* SIGCHLD action for synchronous mode.  */
915 struct sigaction sync_sigchld_action;
916
917 /* SIGCHLD action for asynchronous mode.  */
918 static struct sigaction async_sigchld_action;
919
920 /* SIGCHLD default action, to pass to new inferiors.  */
921 static struct sigaction sigchld_default_action;
922 \f
923
924 /* Prototypes for local functions.  */
925 static int stop_wait_callback (struct lwp_info *lp, void *data);
926 static int linux_nat_thread_alive (ptid_t ptid);
927 static char *linux_child_pid_to_exec_file (int pid);
928 static int cancel_breakpoint (struct lwp_info *lp);
929
930 \f
931 /* Convert wait status STATUS to a string.  Used for printing debug
932    messages only.  */
933
934 static char *
935 status_to_str (int status)
936 {
937   static char buf[64];
938
939   if (WIFSTOPPED (status))
940     snprintf (buf, sizeof (buf), "%s (stopped)",
941               strsignal (WSTOPSIG (status)));
942   else if (WIFSIGNALED (status))
943     snprintf (buf, sizeof (buf), "%s (terminated)",
944               strsignal (WSTOPSIG (status)));
945   else
946     snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
947
948   return buf;
949 }
950
951 /* Initialize the list of LWPs.  Note that this module, contrary to
952    what GDB's generic threads layer does for its thread list,
953    re-initializes the LWP lists whenever we mourn or detach (which
954    doesn't involve mourning) the inferior.  */
955
956 static void
957 init_lwp_list (void)
958 {
959   struct lwp_info *lp, *lpnext;
960
961   for (lp = lwp_list; lp; lp = lpnext)
962     {
963       lpnext = lp->next;
964       xfree (lp);
965     }
966
967   lwp_list = NULL;
968   num_lwps = 0;
969 }
970
971 /* Add the LWP specified by PID to the list.  Return a pointer to the
972    structure describing the new LWP.  The LWP should already be stopped
973    (with an exception for the very first LWP).  */
974
975 static struct lwp_info *
976 add_lwp (ptid_t ptid)
977 {
978   struct lwp_info *lp;
979
980   gdb_assert (is_lwp (ptid));
981
982   lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
983
984   memset (lp, 0, sizeof (struct lwp_info));
985
986   lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
987
988   lp->ptid = ptid;
989
990   lp->next = lwp_list;
991   lwp_list = lp;
992   ++num_lwps;
993
994   if (num_lwps > 1 && linux_nat_new_thread != NULL)
995     linux_nat_new_thread (ptid);
996
997   return lp;
998 }
999
1000 /* Remove the LWP specified by PID from the list.  */
1001
1002 static void
1003 delete_lwp (ptid_t ptid)
1004 {
1005   struct lwp_info *lp, *lpprev;
1006
1007   lpprev = NULL;
1008
1009   for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
1010     if (ptid_equal (lp->ptid, ptid))
1011       break;
1012
1013   if (!lp)
1014     return;
1015
1016   num_lwps--;
1017
1018   if (lpprev)
1019     lpprev->next = lp->next;
1020   else
1021     lwp_list = lp->next;
1022
1023   xfree (lp);
1024 }
1025
1026 /* Return a pointer to the structure describing the LWP corresponding
1027    to PID.  If no corresponding LWP could be found, return NULL.  */
1028
1029 static struct lwp_info *
1030 find_lwp_pid (ptid_t ptid)
1031 {
1032   struct lwp_info *lp;
1033   int lwp;
1034
1035   if (is_lwp (ptid))
1036     lwp = GET_LWP (ptid);
1037   else
1038     lwp = GET_PID (ptid);
1039
1040   for (lp = lwp_list; lp; lp = lp->next)
1041     if (lwp == GET_LWP (lp->ptid))
1042       return lp;
1043
1044   return NULL;
1045 }
1046
1047 /* Call CALLBACK with its second argument set to DATA for every LWP in
1048    the list.  If CALLBACK returns 1 for a particular LWP, return a
1049    pointer to the structure describing that LWP immediately.
1050    Otherwise return NULL.  */
1051
1052 struct lwp_info *
1053 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
1054 {
1055   struct lwp_info *lp, *lpnext;
1056
1057   for (lp = lwp_list; lp; lp = lpnext)
1058     {
1059       lpnext = lp->next;
1060       if ((*callback) (lp, data))
1061         return lp;
1062     }
1063
1064   return NULL;
1065 }
1066
1067 /* Update our internal state when changing from one fork (checkpoint,
1068    et cetera) to another indicated by NEW_PTID.  We can only switch
1069    single-threaded applications, so we only create one new LWP, and
1070    the previous list is discarded.  */
1071
1072 void
1073 linux_nat_switch_fork (ptid_t new_ptid)
1074 {
1075   struct lwp_info *lp;
1076
1077   init_lwp_list ();
1078   lp = add_lwp (new_ptid);
1079   lp->stopped = 1;
1080
1081   init_thread_list ();
1082   add_thread_silent (new_ptid);
1083 }
1084
1085 /* Handle the exit of a single thread LP.  */
1086
1087 static void
1088 exit_lwp (struct lwp_info *lp)
1089 {
1090   struct thread_info *th = find_thread_pid (lp->ptid);
1091
1092   if (th)
1093     {
1094       if (print_thread_events)
1095         printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));
1096
1097       delete_thread (lp->ptid);
1098     }
1099
1100   delete_lwp (lp->ptid);
1101 }
1102
1103 /* Detect `T (stopped)' in `/proc/PID/status'.
1104    Other states including `T (tracing stop)' are reported as false.  */
1105
1106 static int
1107 pid_is_stopped (pid_t pid)
1108 {
1109   FILE *status_file;
1110   char buf[100];
1111   int retval = 0;
1112
1113   snprintf (buf, sizeof (buf), "/proc/%d/status", (int) pid);
1114   status_file = fopen (buf, "r");
1115   if (status_file != NULL)
1116     {
1117       int have_state = 0;
1118
1119       while (fgets (buf, sizeof (buf), status_file))
1120         {
1121           if (strncmp (buf, "State:", 6) == 0)
1122             {
1123               have_state = 1;
1124               break;
1125             }
1126         }
1127       if (have_state && strstr (buf, "T (stopped)") != NULL)
1128         retval = 1;
1129       fclose (status_file);
1130     }
1131   return retval;
1132 }
1133
1134 /* Wait for the LWP specified by LP, which we have just attached to.
1135    Returns a wait status for that LWP, to cache.  */
1136
1137 static int
1138 linux_nat_post_attach_wait (ptid_t ptid, int first, int *cloned,
1139                             int *signalled)
1140 {
1141   pid_t new_pid, pid = GET_LWP (ptid);
1142   int status;
1143
1144   if (pid_is_stopped (pid))
1145     {
1146       if (debug_linux_nat)
1147         fprintf_unfiltered (gdb_stdlog,
1148                             "LNPAW: Attaching to a stopped process\n");
1149
1150       /* The process is definitely stopped.  It is in a job control
1151          stop, unless the kernel predates the TASK_STOPPED /
1152          TASK_TRACED distinction, in which case it might be in a
1153          ptrace stop.  Make sure it is in a ptrace stop; from there we
1154          can kill it, signal it, et cetera.
1155
1156          First make sure there is a pending SIGSTOP.  Since we are
1157          already attached, the process can not transition from stopped
1158          to running without a PTRACE_CONT; so we know this signal will
1159          go into the queue.  The SIGSTOP generated by PTRACE_ATTACH is
1160          probably already in the queue (unless this kernel is old
1161          enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
1162          is not an RT signal, it can only be queued once.  */
1163       kill_lwp (pid, SIGSTOP);
1164
1165       /* Finally, resume the stopped process.  This will deliver the SIGSTOP
1166          (or a higher priority signal, just like normal PTRACE_ATTACH).  */
1167       ptrace (PTRACE_CONT, pid, 0, 0);
1168     }
1169
1170   /* Make sure the initial process is stopped.  The user-level threads
1171      layer might want to poke around in the inferior, and that won't
1172      work if things haven't stabilized yet.  */
1173   new_pid = my_waitpid (pid, &status, 0);
1174   if (new_pid == -1 && errno == ECHILD)
1175     {
1176       if (first)
1177         warning (_("%s is a cloned process"), target_pid_to_str (ptid));
1178
1179       /* Try again with __WCLONE to check cloned processes.  */
1180       new_pid = my_waitpid (pid, &status, __WCLONE);
1181       *cloned = 1;
1182     }
1183
1184   gdb_assert (pid == new_pid && WIFSTOPPED (status));
1185
1186   if (WSTOPSIG (status) != SIGSTOP)
1187     {
1188       *signalled = 1;
1189       if (debug_linux_nat)
1190         fprintf_unfiltered (gdb_stdlog,
1191                             "LNPAW: Received %s after attaching\n",
1192                             status_to_str (status));
1193     }
1194
1195   return status;
1196 }
1197
1198 /* Attach to the LWP specified by PID.  Return 0 if successful or -1
1199    if the new LWP could not be attached.  */
1200
1201 int
1202 lin_lwp_attach_lwp (ptid_t ptid)
1203 {
1204   struct lwp_info *lp;
1205   enum sigchld_state async_events_original_state;
1206
1207   gdb_assert (is_lwp (ptid));
1208
1209   async_events_original_state = linux_nat_async_events (sigchld_sync);
1210
1211   lp = find_lwp_pid (ptid);
1212
1213   /* We assume that we're already attached to any LWP that has an id
1214      equal to the overall process id, and to any LWP that is already
1215      in our list of LWPs.  If we're not seeing exit events from threads
1216      and we've had PID wraparound since we last tried to stop all threads,
1217      this assumption might be wrong; fortunately, this is very unlikely
1218      to happen.  */
1219   if (GET_LWP (ptid) != GET_PID (ptid) && lp == NULL)
1220     {
1221       int status, cloned = 0, signalled = 0;
1222
1223       if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
1224         {
1225           /* If we fail to attach to the thread, issue a warning,
1226              but continue.  One way this can happen is if thread
1227              creation is interrupted; as of Linux kernel 2.6.19, a
1228              bug may place threads in the thread list and then fail
1229              to create them.  */
1230           warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
1231                    safe_strerror (errno));
1232           return -1;
1233         }
1234
1235       if (debug_linux_nat)
1236         fprintf_unfiltered (gdb_stdlog,
1237                             "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
1238                             target_pid_to_str (ptid));
1239
1240       status = linux_nat_post_attach_wait (ptid, 0, &cloned, &signalled);
1241       lp = add_lwp (ptid);
1242       lp->stopped = 1;
1243       lp->cloned = cloned;
1244       lp->signalled = signalled;
1245       if (WSTOPSIG (status) != SIGSTOP)
1246         {
1247           lp->resumed = 1;
1248           lp->status = status;
1249         }
1250
1251       target_post_attach (GET_LWP (lp->ptid));
1252
1253       if (debug_linux_nat)
1254         {
1255           fprintf_unfiltered (gdb_stdlog,
1256                               "LLAL: waitpid %s received %s\n",
1257                               target_pid_to_str (ptid),
1258                               status_to_str (status));
1259         }
1260     }
1261   else
1262     {
1263       /* We assume that the LWP representing the original process is
1264          already stopped.  Mark it as stopped in the data structure
1265          that the GNU/linux ptrace layer uses to keep track of
1266          threads.  Note that this won't have already been done since
1267          the main thread will have, we assume, been stopped by an
1268          attach from a different layer.  */
1269       if (lp == NULL)
1270         lp = add_lwp (ptid);
1271       lp->stopped = 1;
1272     }
1273
1274   linux_nat_async_events (async_events_original_state);
1275   return 0;
1276 }
1277
1278 static void
1279 linux_nat_create_inferior (char *exec_file, char *allargs, char **env,
1280                            int from_tty)
1281 {
1282   int saved_async = 0;
1283 #ifdef HAVE_PERSONALITY
1284   int personality_orig = 0, personality_set = 0;
1285 #endif /* HAVE_PERSONALITY */
1286
1287   /* The fork_child mechanism is synchronous and calls target_wait, so
1288      we have to mask the async mode.  */
1289
1290   if (target_can_async_p ())
1291     /* Mask async mode.  Creating a child requires a loop calling
1292        wait_for_inferior currently.  */
1293     saved_async = linux_nat_async_mask (0);
1294   else
1295     {
1296       /* Restore the original signal mask.  */
1297       sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1298       /* Make sure we don't block SIGCHLD during a sigsuspend.  */
1299       suspend_mask = normal_mask;
1300       sigdelset (&suspend_mask, SIGCHLD);
1301     }
1302
1303   /* Set SIGCHLD to the default action, until after execing the child,
1304      since the inferior inherits the superior's signal mask.  It will
1305      be blocked again in linux_nat_wait, which is only reached after
1306      the inferior execing.  */
1307   linux_nat_async_events (sigchld_default);
1308
1309 #ifdef HAVE_PERSONALITY
1310   if (disable_randomization)
1311     {
1312       errno = 0;
1313       personality_orig = personality (0xffffffff);
1314       if (errno == 0 && !(personality_orig & ADDR_NO_RANDOMIZE))
1315         {
1316           personality_set = 1;
1317           personality (personality_orig | ADDR_NO_RANDOMIZE);
1318         }
1319       if (errno != 0 || (personality_set
1320                          && !(personality (0xffffffff) & ADDR_NO_RANDOMIZE)))
1321         warning (_("Error disabling address space randomization: %s"),
1322                  safe_strerror (errno));
1323     }
1324 #endif /* HAVE_PERSONALITY */
1325
1326   linux_ops->to_create_inferior (exec_file, allargs, env, from_tty);
1327
1328 #ifdef HAVE_PERSONALITY
1329   if (personality_set)
1330     {
1331       errno = 0;
1332       personality (personality_orig);
1333       if (errno != 0)
1334         warning (_("Error restoring address space randomization: %s"),
1335                  safe_strerror (errno));
1336     }
1337 #endif /* HAVE_PERSONALITY */
1338
1339   if (saved_async)
1340     linux_nat_async_mask (saved_async);
1341 }
1342
1343 static void
1344 linux_nat_attach (char *args, int from_tty)
1345 {
1346   struct lwp_info *lp;
1347   int status;
1348   ptid_t ptid;
1349
1350   /* FIXME: We should probably accept a list of process id's, and
1351      attach all of them.  */
1352   linux_ops->to_attach (args, from_tty);
1353
1354   if (!target_can_async_p ())
1355     {
1356       /* Restore the original signal mask.  */
1357       sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1358       /* Make sure we don't block SIGCHLD during a sigsuspend.  */
1359       suspend_mask = normal_mask;
1360       sigdelset (&suspend_mask, SIGCHLD);
1361     }
1362
1363   /* The ptrace base target adds the main thread with (pid,0,0)
1364      format.  Decorate it with lwp info.  */
1365   ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1366   thread_change_ptid (inferior_ptid, ptid);
1367
1368   /* Add the initial process as the first LWP to the list.  */
1369   lp = add_lwp (ptid);
1370
1371   status = linux_nat_post_attach_wait (lp->ptid, 1, &lp->cloned,
1372                                        &lp->signalled);
1373   lp->stopped = 1;
1374
1375   /* Save the wait status to report later.  */
1376   lp->resumed = 1;
1377   if (debug_linux_nat)
1378     fprintf_unfiltered (gdb_stdlog,
1379                         "LNA: waitpid %ld, saving status %s\n",
1380                         (long) GET_PID (lp->ptid), status_to_str (status));
1381
1382   if (!target_can_async_p ())
1383     lp->status = status;
1384   else
1385     {
1386       /* We already waited for this LWP, so put the wait result on the
1387          pipe.  The event loop will wake up and gets us to handling
1388          this event.  */
1389       linux_nat_event_pipe_push (GET_PID (lp->ptid), status,
1390                                  lp->cloned ? __WCLONE : 0);
1391       /* Register in the event loop.  */
1392       target_async (inferior_event_handler, 0);
1393     }
1394 }
1395
1396 /* Get pending status of LP.  */
1397 static int
1398 get_pending_status (struct lwp_info *lp, int *status)
1399 {
1400   struct target_waitstatus last;
1401   ptid_t last_ptid;
1402
1403   get_last_target_status (&last_ptid, &last);
1404
1405   /* If this lwp is the ptid that GDB is processing an event from, the
1406      signal will be in stop_signal.  Otherwise, in all-stop + sync
1407      mode, we may cache pending events in lp->status while trying to
1408      stop all threads (see stop_wait_callback).  In async mode, the
1409      events are always cached in waitpid_queue.  */
1410
1411   *status = 0;
1412
1413   if (non_stop)
1414     {
1415       enum target_signal signo = TARGET_SIGNAL_0;
1416
1417       if (is_executing (lp->ptid))
1418         {
1419           /* If the core thought this lwp was executing --- e.g., the
1420              executing property hasn't been updated yet, but the
1421              thread has been stopped with a stop_callback /
1422              stop_wait_callback sequence (see linux_nat_detach for
1423              example) --- we can only have pending events in the local
1424              queue.  */
1425           if (queued_waitpid (GET_LWP (lp->ptid), status, __WALL) != -1)
1426             {
1427               if (WIFSTOPPED (status))
1428                 signo = target_signal_from_host (WSTOPSIG (status));
1429
1430               /* If not stopped, then the lwp is gone, no use in
1431                  resending a signal.  */
1432             }
1433         }
1434       else
1435         {
1436           /* If the core knows the thread is not executing, then we
1437              have the last signal recorded in
1438              thread_info->stop_signal, unless this is inferior_ptid,
1439              in which case, it's in the global stop_signal, due to
1440              context switching.  */
1441
1442           if (ptid_equal (lp->ptid, inferior_ptid))
1443             signo = stop_signal;
1444           else
1445             {
1446               struct thread_info *tp = find_thread_pid (lp->ptid);
1447               gdb_assert (tp);
1448               signo = tp->stop_signal;
1449             }
1450         }
1451
1452       if (signo != TARGET_SIGNAL_0
1453           && !signal_pass_state (signo))
1454         {
1455           if (debug_linux_nat)
1456             fprintf_unfiltered (gdb_stdlog, "\
1457 GPT: lwp %s had signal %s, but it is in no pass state\n",
1458                                 target_pid_to_str (lp->ptid),
1459                                 target_signal_to_string (signo));
1460         }
1461       else
1462         {
1463           if (signo != TARGET_SIGNAL_0)
1464             *status = W_STOPCODE (target_signal_to_host (signo));
1465
1466           if (debug_linux_nat)
1467             fprintf_unfiltered (gdb_stdlog,
1468                                 "GPT: lwp %s as pending signal %s\n",
1469                                 target_pid_to_str (lp->ptid),
1470                                 target_signal_to_string (signo));
1471         }
1472     }
1473   else
1474     {
1475       if (GET_LWP (lp->ptid) == GET_LWP (last_ptid))
1476         {
1477           if (stop_signal != TARGET_SIGNAL_0
1478               && signal_pass_state (stop_signal))
1479             *status = W_STOPCODE (target_signal_to_host (stop_signal));
1480         }
1481       else if (target_can_async_p ())
1482         queued_waitpid (GET_LWP (lp->ptid), status, __WALL);
1483       else
1484         *status = lp->status;
1485     }
1486
1487   return 0;
1488 }
1489
1490 static int
1491 detach_callback (struct lwp_info *lp, void *data)
1492 {
1493   gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1494
1495   if (debug_linux_nat && lp->status)
1496     fprintf_unfiltered (gdb_stdlog, "DC:  Pending %s for %s on detach.\n",
1497                         strsignal (WSTOPSIG (lp->status)),
1498                         target_pid_to_str (lp->ptid));
1499
1500   /* If there is a pending SIGSTOP, get rid of it.  */
1501   if (lp->signalled)
1502     {
1503       if (debug_linux_nat)
1504         fprintf_unfiltered (gdb_stdlog,
1505                             "DC: Sending SIGCONT to %s\n",
1506                             target_pid_to_str (lp->ptid));
1507
1508       kill_lwp (GET_LWP (lp->ptid), SIGCONT);
1509       lp->signalled = 0;
1510     }
1511
1512   /* We don't actually detach from the LWP that has an id equal to the
1513      overall process id just yet.  */
1514   if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1515     {
1516       int status = 0;
1517
1518       /* Pass on any pending signal for this LWP.  */
1519       get_pending_status (lp, &status);
1520
1521       errno = 0;
1522       if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1523                   WSTOPSIG (status)) < 0)
1524         error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1525                safe_strerror (errno));
1526
1527       if (debug_linux_nat)
1528         fprintf_unfiltered (gdb_stdlog,
1529                             "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1530                             target_pid_to_str (lp->ptid),
1531                             strsignal (WSTOPSIG (lp->status)));
1532
1533       delete_lwp (lp->ptid);
1534     }
1535
1536   return 0;
1537 }
1538
1539 static void
1540 linux_nat_detach (char *args, int from_tty)
1541 {
1542   int pid;
1543   int status;
1544   enum target_signal sig;
1545
1546   if (target_can_async_p ())
1547     linux_nat_async (NULL, 0);
1548
1549   /* Stop all threads before detaching.  ptrace requires that the
1550      thread is stopped to sucessfully detach.  */
1551   iterate_over_lwps (stop_callback, NULL);
1552   /* ... and wait until all of them have reported back that
1553      they're no longer running.  */
1554   iterate_over_lwps (stop_wait_callback, NULL);
1555
1556   iterate_over_lwps (detach_callback, NULL);
1557
1558   /* Only the initial process should be left right now.  */
1559   gdb_assert (num_lwps == 1);
1560
1561   /* Pass on any pending signal for the last LWP.  */
1562   if ((args == NULL || *args == '\0')
1563       && get_pending_status (lwp_list, &status) != -1
1564       && WIFSTOPPED (status))
1565     {
1566       /* Put the signal number in ARGS so that inf_ptrace_detach will
1567          pass it along with PTRACE_DETACH.  */
1568       args = alloca (8);
1569       sprintf (args, "%d", (int) WSTOPSIG (status));
1570       fprintf_unfiltered (gdb_stdlog,
1571                           "LND: Sending signal %s to %s\n",
1572                           args,
1573                           target_pid_to_str (lwp_list->ptid));
1574     }
1575
1576   /* Destroy LWP info; it's no longer valid.  */
1577   init_lwp_list ();
1578
1579   pid = GET_PID (inferior_ptid);
1580   inferior_ptid = pid_to_ptid (pid);
1581   linux_ops->to_detach (args, from_tty);
1582
1583   if (target_can_async_p ())
1584     drain_queued_events (pid);
1585 }
1586
1587 /* Resume LP.  */
1588
1589 static int
1590 resume_callback (struct lwp_info *lp, void *data)
1591 {
1592   if (lp->stopped && lp->status == 0)
1593     {
1594       linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1595                             0, TARGET_SIGNAL_0);
1596       if (debug_linux_nat)
1597         fprintf_unfiltered (gdb_stdlog,
1598                             "RC:  PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1599                             target_pid_to_str (lp->ptid));
1600       lp->stopped = 0;
1601       lp->step = 0;
1602       memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1603     }
1604   else if (lp->stopped && debug_linux_nat)
1605     fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (has pending)\n",
1606                         target_pid_to_str (lp->ptid));
1607   else if (debug_linux_nat)
1608     fprintf_unfiltered (gdb_stdlog, "RC: Not resuming sibling %s (not stopped)\n",
1609                         target_pid_to_str (lp->ptid));
1610
1611   return 0;
1612 }
1613
1614 static int
1615 resume_clear_callback (struct lwp_info *lp, void *data)
1616 {
1617   lp->resumed = 0;
1618   return 0;
1619 }
1620
1621 static int
1622 resume_set_callback (struct lwp_info *lp, void *data)
1623 {
1624   lp->resumed = 1;
1625   return 0;
1626 }
1627
1628 static void
1629 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1630 {
1631   struct lwp_info *lp;
1632   int resume_all;
1633
1634   if (debug_linux_nat)
1635     fprintf_unfiltered (gdb_stdlog,
1636                         "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1637                         step ? "step" : "resume",
1638                         target_pid_to_str (ptid),
1639                         signo ? strsignal (signo) : "0",
1640                         target_pid_to_str (inferior_ptid));
1641
1642   if (target_can_async_p ())
1643     /* Block events while we're here.  */
1644     linux_nat_async_events (sigchld_sync);
1645
1646   /* A specific PTID means `step only this process id'.  */
1647   resume_all = (PIDGET (ptid) == -1);
1648
1649   if (non_stop && resume_all)
1650     internal_error (__FILE__, __LINE__,
1651                     "can't resume all in non-stop mode");
1652
1653   if (!non_stop)
1654     {
1655       if (resume_all)
1656         iterate_over_lwps (resume_set_callback, NULL);
1657       else
1658         iterate_over_lwps (resume_clear_callback, NULL);
1659     }
1660
1661   /* If PID is -1, it's the current inferior that should be
1662      handled specially.  */
1663   if (PIDGET (ptid) == -1)
1664     ptid = inferior_ptid;
1665
1666   lp = find_lwp_pid (ptid);
1667   gdb_assert (lp != NULL);
1668
1669   /* Convert to something the lower layer understands.  */
1670   ptid = pid_to_ptid (GET_LWP (lp->ptid));
1671
1672   /* Remember if we're stepping.  */
1673   lp->step = step;
1674
1675   /* Mark this LWP as resumed.  */
1676   lp->resumed = 1;
1677
1678   /* If we have a pending wait status for this thread, there is no
1679      point in resuming the process.  But first make sure that
1680      linux_nat_wait won't preemptively handle the event - we
1681      should never take this short-circuit if we are going to
1682      leave LP running, since we have skipped resuming all the
1683      other threads.  This bit of code needs to be synchronized
1684      with linux_nat_wait.  */
1685
1686   /* In async mode, we never have pending wait status.  */
1687   if (target_can_async_p () && lp->status)
1688     internal_error (__FILE__, __LINE__, "Pending status in async mode");
1689
1690   if (lp->status && WIFSTOPPED (lp->status))
1691     {
1692       int saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1693
1694       if (signal_stop_state (saved_signo) == 0
1695           && signal_print_state (saved_signo) == 0
1696           && signal_pass_state (saved_signo) == 1)
1697         {
1698           if (debug_linux_nat)
1699             fprintf_unfiltered (gdb_stdlog,
1700                                 "LLR: Not short circuiting for ignored "
1701                                 "status 0x%x\n", lp->status);
1702
1703           /* FIXME: What should we do if we are supposed to continue
1704              this thread with a signal?  */
1705           gdb_assert (signo == TARGET_SIGNAL_0);
1706           signo = saved_signo;
1707           lp->status = 0;
1708         }
1709     }
1710
1711   if (lp->status)
1712     {
1713       /* FIXME: What should we do if we are supposed to continue
1714          this thread with a signal?  */
1715       gdb_assert (signo == TARGET_SIGNAL_0);
1716
1717       if (debug_linux_nat)
1718         fprintf_unfiltered (gdb_stdlog,
1719                             "LLR: Short circuiting for status 0x%x\n",
1720                             lp->status);
1721
1722       return;
1723     }
1724
1725   /* Mark LWP as not stopped to prevent it from being continued by
1726      resume_callback.  */
1727   lp->stopped = 0;
1728
1729   if (resume_all)
1730     iterate_over_lwps (resume_callback, NULL);
1731
1732   linux_ops->to_resume (ptid, step, signo);
1733   memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1734
1735   if (debug_linux_nat)
1736     fprintf_unfiltered (gdb_stdlog,
1737                         "LLR: %s %s, %s (resume event thread)\n",
1738                         step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1739                         target_pid_to_str (ptid),
1740                         signo ? strsignal (signo) : "0");
1741
1742   if (target_can_async_p ())
1743     target_async (inferior_event_handler, 0);
1744 }
1745
1746 /* Issue kill to specified lwp.  */
1747
1748 static int tkill_failed;
1749
1750 static int
1751 kill_lwp (int lwpid, int signo)
1752 {
1753   errno = 0;
1754
1755 /* Use tkill, if possible, in case we are using nptl threads.  If tkill
1756    fails, then we are not using nptl threads and we should be using kill.  */
1757
1758 #ifdef HAVE_TKILL_SYSCALL
1759   if (!tkill_failed)
1760     {
1761       int ret = syscall (__NR_tkill, lwpid, signo);
1762       if (errno != ENOSYS)
1763         return ret;
1764       errno = 0;
1765       tkill_failed = 1;
1766     }
1767 #endif
1768
1769   return kill (lwpid, signo);
1770 }
1771
1772 /* Handle a GNU/Linux extended wait response.  If we see a clone
1773    event, we need to add the new LWP to our list (and not report the
1774    trap to higher layers).  This function returns non-zero if the
1775    event should be ignored and we should wait again.  If STOPPING is
1776    true, the new LWP remains stopped, otherwise it is continued.  */
1777
1778 static int
1779 linux_handle_extended_wait (struct lwp_info *lp, int status,
1780                             int stopping)
1781 {
1782   int pid = GET_LWP (lp->ptid);
1783   struct target_waitstatus *ourstatus = &lp->waitstatus;
1784   struct lwp_info *new_lp = NULL;
1785   int event = status >> 16;
1786
1787   if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
1788       || event == PTRACE_EVENT_CLONE)
1789     {
1790       unsigned long new_pid;
1791       int ret;
1792
1793       ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
1794
1795       /* If we haven't already seen the new PID stop, wait for it now.  */
1796       if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
1797         {
1798           /* The new child has a pending SIGSTOP.  We can't affect it until it
1799              hits the SIGSTOP, but we're already attached.  */
1800           ret = my_waitpid (new_pid, &status,
1801                             (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
1802           if (ret == -1)
1803             perror_with_name (_("waiting for new child"));
1804           else if (ret != new_pid)
1805             internal_error (__FILE__, __LINE__,
1806                             _("wait returned unexpected PID %d"), ret);
1807           else if (!WIFSTOPPED (status))
1808             internal_error (__FILE__, __LINE__,
1809                             _("wait returned unexpected status 0x%x"), status);
1810         }
1811
1812       ourstatus->value.related_pid = ptid_build (new_pid, new_pid, 0);
1813
1814       if (event == PTRACE_EVENT_FORK)
1815         ourstatus->kind = TARGET_WAITKIND_FORKED;
1816       else if (event == PTRACE_EVENT_VFORK)
1817         ourstatus->kind = TARGET_WAITKIND_VFORKED;
1818       else
1819         {
1820           struct cleanup *old_chain;
1821
1822           ourstatus->kind = TARGET_WAITKIND_IGNORE;
1823           new_lp = add_lwp (BUILD_LWP (new_pid, GET_PID (inferior_ptid)));
1824           new_lp->cloned = 1;
1825           new_lp->stopped = 1;
1826
1827           if (WSTOPSIG (status) != SIGSTOP)
1828             {
1829               /* This can happen if someone starts sending signals to
1830                  the new thread before it gets a chance to run, which
1831                  have a lower number than SIGSTOP (e.g. SIGUSR1).
1832                  This is an unlikely case, and harder to handle for
1833                  fork / vfork than for clone, so we do not try - but
1834                  we handle it for clone events here.  We'll send
1835                  the other signal on to the thread below.  */
1836
1837               new_lp->signalled = 1;
1838             }
1839           else
1840             status = 0;
1841
1842           if (non_stop)
1843             {
1844               /* Add the new thread to GDB's lists as soon as possible
1845                  so that:
1846
1847                  1) the frontend doesn't have to wait for a stop to
1848                  display them, and,
1849
1850                  2) we tag it with the correct running state.  */
1851
1852               /* If the thread_db layer is active, let it know about
1853                  this new thread, and add it to GDB's list.  */
1854               if (!thread_db_attach_lwp (new_lp->ptid))
1855                 {
1856                   /* We're not using thread_db.  Add it to GDB's
1857                      list.  */
1858                   target_post_attach (GET_LWP (new_lp->ptid));
1859                   add_thread (new_lp->ptid);
1860                 }
1861
1862               if (!stopping)
1863                 {
1864                   set_running (new_lp->ptid, 1);
1865                   set_executing (new_lp->ptid, 1);
1866                 }
1867             }
1868
1869           if (!stopping)
1870             {
1871               new_lp->stopped = 0;
1872               new_lp->resumed = 1;
1873               ptrace (PTRACE_CONT, new_pid, 0,
1874                       status ? WSTOPSIG (status) : 0);
1875             }
1876
1877           if (debug_linux_nat)
1878             fprintf_unfiltered (gdb_stdlog,
1879                                 "LHEW: Got clone event from LWP %ld, resuming\n",
1880                                 GET_LWP (lp->ptid));
1881           ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1882
1883           return 1;
1884         }
1885
1886       return 0;
1887     }
1888
1889   if (event == PTRACE_EVENT_EXEC)
1890     {
1891       ourstatus->kind = TARGET_WAITKIND_EXECD;
1892       ourstatus->value.execd_pathname
1893         = xstrdup (linux_child_pid_to_exec_file (pid));
1894
1895       if (linux_parent_pid)
1896         {
1897           detach_breakpoints (linux_parent_pid);
1898           ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
1899
1900           linux_parent_pid = 0;
1901         }
1902
1903       /* At this point, all inserted breakpoints are gone.  Doing this
1904          as soon as we detect an exec prevents the badness of deleting
1905          a breakpoint writing the current "shadow contents" to lift
1906          the bp.  That shadow is NOT valid after an exec.
1907
1908          Note that we have to do this after the detach_breakpoints
1909          call above, otherwise breakpoints wouldn't be lifted from the
1910          parent on a vfork, because detach_breakpoints would think
1911          that breakpoints are not inserted.  */
1912       mark_breakpoints_out ();
1913       return 0;
1914     }
1915
1916   internal_error (__FILE__, __LINE__,
1917                   _("unknown ptrace event %d"), event);
1918 }
1919
1920 /* Wait for LP to stop.  Returns the wait status, or 0 if the LWP has
1921    exited.  */
1922
1923 static int
1924 wait_lwp (struct lwp_info *lp)
1925 {
1926   pid_t pid;
1927   int status;
1928   int thread_dead = 0;
1929
1930   gdb_assert (!lp->stopped);
1931   gdb_assert (lp->status == 0);
1932
1933   pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1934   if (pid == -1 && errno == ECHILD)
1935     {
1936       pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
1937       if (pid == -1 && errno == ECHILD)
1938         {
1939           /* The thread has previously exited.  We need to delete it
1940              now because, for some vendor 2.4 kernels with NPTL
1941              support backported, there won't be an exit event unless
1942              it is the main thread.  2.6 kernels will report an exit
1943              event for each thread that exits, as expected.  */
1944           thread_dead = 1;
1945           if (debug_linux_nat)
1946             fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1947                                 target_pid_to_str (lp->ptid));
1948         }
1949     }
1950
1951   if (!thread_dead)
1952     {
1953       gdb_assert (pid == GET_LWP (lp->ptid));
1954
1955       if (debug_linux_nat)
1956         {
1957           fprintf_unfiltered (gdb_stdlog,
1958                               "WL: waitpid %s received %s\n",
1959                               target_pid_to_str (lp->ptid),
1960                               status_to_str (status));
1961         }
1962     }
1963
1964   /* Check if the thread has exited.  */
1965   if (WIFEXITED (status) || WIFSIGNALED (status))
1966     {
1967       thread_dead = 1;
1968       if (debug_linux_nat)
1969         fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1970                             target_pid_to_str (lp->ptid));
1971     }
1972
1973   if (thread_dead)
1974     {
1975       exit_lwp (lp);
1976       return 0;
1977     }
1978
1979   gdb_assert (WIFSTOPPED (status));
1980
1981   /* Handle GNU/Linux's extended waitstatus for trace events.  */
1982   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1983     {
1984       if (debug_linux_nat)
1985         fprintf_unfiltered (gdb_stdlog,
1986                             "WL: Handling extended status 0x%06x\n",
1987                             status);
1988       if (linux_handle_extended_wait (lp, status, 1))
1989         return wait_lwp (lp);
1990     }
1991
1992   return status;
1993 }
1994
1995 /* Save the most recent siginfo for LP.  This is currently only called
1996    for SIGTRAP; some ports use the si_addr field for
1997    target_stopped_data_address.  In the future, it may also be used to
1998    restore the siginfo of requeued signals.  */
1999
2000 static void
2001 save_siginfo (struct lwp_info *lp)
2002 {
2003   errno = 0;
2004   ptrace (PTRACE_GETSIGINFO, GET_LWP (lp->ptid),
2005           (PTRACE_TYPE_ARG3) 0, &lp->siginfo);
2006
2007   if (errno != 0)
2008     memset (&lp->siginfo, 0, sizeof (lp->siginfo));
2009 }
2010
2011 /* Send a SIGSTOP to LP.  */
2012
2013 static int
2014 stop_callback (struct lwp_info *lp, void *data)
2015 {
2016   if (!lp->stopped && !lp->signalled)
2017     {
2018       int ret;
2019
2020       if (debug_linux_nat)
2021         {
2022           fprintf_unfiltered (gdb_stdlog,
2023                               "SC:  kill %s **<SIGSTOP>**\n",
2024                               target_pid_to_str (lp->ptid));
2025         }
2026       errno = 0;
2027       ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
2028       if (debug_linux_nat)
2029         {
2030           fprintf_unfiltered (gdb_stdlog,
2031                               "SC:  lwp kill %d %s\n",
2032                               ret,
2033                               errno ? safe_strerror (errno) : "ERRNO-OK");
2034         }
2035
2036       lp->signalled = 1;
2037       gdb_assert (lp->status == 0);
2038     }
2039
2040   return 0;
2041 }
2042
2043 /* Return non-zero if LWP PID has a pending SIGINT.  */
2044
2045 static int
2046 linux_nat_has_pending_sigint (int pid)
2047 {
2048   sigset_t pending, blocked, ignored;
2049   int i;
2050
2051   linux_proc_pending_signals (pid, &pending, &blocked, &ignored);
2052
2053   if (sigismember (&pending, SIGINT)
2054       && !sigismember (&ignored, SIGINT))
2055     return 1;
2056
2057   return 0;
2058 }
2059
2060 /* Set a flag in LP indicating that we should ignore its next SIGINT.  */
2061
2062 static int
2063 set_ignore_sigint (struct lwp_info *lp, void *data)
2064 {
2065   /* If a thread has a pending SIGINT, consume it; otherwise, set a
2066      flag to consume the next one.  */
2067   if (lp->stopped && lp->status != 0 && WIFSTOPPED (lp->status)
2068       && WSTOPSIG (lp->status) == SIGINT)
2069     lp->status = 0;
2070   else
2071     lp->ignore_sigint = 1;
2072
2073   return 0;
2074 }
2075
2076 /* If LP does not have a SIGINT pending, then clear the ignore_sigint flag.
2077    This function is called after we know the LWP has stopped; if the LWP
2078    stopped before the expected SIGINT was delivered, then it will never have
2079    arrived.  Also, if the signal was delivered to a shared queue and consumed
2080    by a different thread, it will never be delivered to this LWP.  */
2081
2082 static void
2083 maybe_clear_ignore_sigint (struct lwp_info *lp)
2084 {
2085   if (!lp->ignore_sigint)
2086     return;
2087
2088   if (!linux_nat_has_pending_sigint (GET_LWP (lp->ptid)))
2089     {
2090       if (debug_linux_nat)
2091         fprintf_unfiltered (gdb_stdlog,
2092                             "MCIS: Clearing bogus flag for %s\n",
2093                             target_pid_to_str (lp->ptid));
2094       lp->ignore_sigint = 0;
2095     }
2096 }
2097
2098 /* Wait until LP is stopped.  */
2099
2100 static int
2101 stop_wait_callback (struct lwp_info *lp, void *data)
2102 {
2103   if (!lp->stopped)
2104     {
2105       int status;
2106
2107       status = wait_lwp (lp);
2108       if (status == 0)
2109         return 0;
2110
2111       if (lp->ignore_sigint && WIFSTOPPED (status)
2112           && WSTOPSIG (status) == SIGINT)
2113         {
2114           lp->ignore_sigint = 0;
2115
2116           errno = 0;
2117           ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2118           if (debug_linux_nat)
2119             fprintf_unfiltered (gdb_stdlog,
2120                                 "PTRACE_CONT %s, 0, 0 (%s) (discarding SIGINT)\n",
2121                                 target_pid_to_str (lp->ptid),
2122                                 errno ? safe_strerror (errno) : "OK");
2123
2124           return stop_wait_callback (lp, NULL);
2125         }
2126
2127       maybe_clear_ignore_sigint (lp);
2128
2129       if (WSTOPSIG (status) != SIGSTOP)
2130         {
2131           if (WSTOPSIG (status) == SIGTRAP)
2132             {
2133               /* If a LWP other than the LWP that we're reporting an
2134                  event for has hit a GDB breakpoint (as opposed to
2135                  some random trap signal), then just arrange for it to
2136                  hit it again later.  We don't keep the SIGTRAP status
2137                  and don't forward the SIGTRAP signal to the LWP.  We
2138                  will handle the current event, eventually we will
2139                  resume all LWPs, and this one will get its breakpoint
2140                  trap again.
2141
2142                  If we do not do this, then we run the risk that the
2143                  user will delete or disable the breakpoint, but the
2144                  thread will have already tripped on it.  */
2145
2146               /* Save the trap's siginfo in case we need it later.  */
2147               save_siginfo (lp);
2148
2149               /* Now resume this LWP and get the SIGSTOP event. */
2150               errno = 0;
2151               ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2152               if (debug_linux_nat)
2153                 {
2154                   fprintf_unfiltered (gdb_stdlog,
2155                                       "PTRACE_CONT %s, 0, 0 (%s)\n",
2156                                       target_pid_to_str (lp->ptid),
2157                                       errno ? safe_strerror (errno) : "OK");
2158
2159                   fprintf_unfiltered (gdb_stdlog,
2160                                       "SWC: Candidate SIGTRAP event in %s\n",
2161                                       target_pid_to_str (lp->ptid));
2162                 }
2163               /* Hold this event/waitstatus while we check to see if
2164                  there are any more (we still want to get that SIGSTOP). */
2165               stop_wait_callback (lp, NULL);
2166
2167               if (target_can_async_p ())
2168                 {
2169                   /* Don't leave a pending wait status in async mode.
2170                      Retrigger the breakpoint.  */
2171                   if (!cancel_breakpoint (lp))
2172                     {
2173                       /* There was no gdb breakpoint set at pc.  Put
2174                          the event back in the queue.  */
2175                       if (debug_linux_nat)
2176                         fprintf_unfiltered (gdb_stdlog,
2177                                             "SWC: kill %s, %s\n",
2178                                             target_pid_to_str (lp->ptid),
2179                                             status_to_str ((int) status));
2180                       kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
2181                     }
2182                 }
2183               else
2184                 {
2185                   /* Hold the SIGTRAP for handling by
2186                      linux_nat_wait. */
2187                   /* If there's another event, throw it back into the
2188                      queue. */
2189                   if (lp->status)
2190                     {
2191                       if (debug_linux_nat)
2192                         fprintf_unfiltered (gdb_stdlog,
2193                                             "SWC: kill %s, %s\n",
2194                                             target_pid_to_str (lp->ptid),
2195                                             status_to_str ((int) status));
2196                       kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
2197                     }
2198                   /* Save the sigtrap event. */
2199                   lp->status = status;
2200                 }
2201               return 0;
2202             }
2203           else
2204             {
2205               /* The thread was stopped with a signal other than
2206                  SIGSTOP, and didn't accidentally trip a breakpoint. */
2207
2208               if (debug_linux_nat)
2209                 {
2210                   fprintf_unfiltered (gdb_stdlog,
2211                                       "SWC: Pending event %s in %s\n",
2212                                       status_to_str ((int) status),
2213                                       target_pid_to_str (lp->ptid));
2214                 }
2215               /* Now resume this LWP and get the SIGSTOP event. */
2216               errno = 0;
2217               ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2218               if (debug_linux_nat)
2219                 fprintf_unfiltered (gdb_stdlog,
2220                                     "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
2221                                     target_pid_to_str (lp->ptid),
2222                                     errno ? safe_strerror (errno) : "OK");
2223
2224               /* Hold this event/waitstatus while we check to see if
2225                  there are any more (we still want to get that SIGSTOP). */
2226               stop_wait_callback (lp, NULL);
2227
2228               /* If the lp->status field is still empty, use it to
2229                  hold this event.  If not, then this event must be
2230                  returned to the event queue of the LWP.  */
2231               if (lp->status || target_can_async_p ())
2232                 {
2233                   if (debug_linux_nat)
2234                     {
2235                       fprintf_unfiltered (gdb_stdlog,
2236                                           "SWC: kill %s, %s\n",
2237                                           target_pid_to_str (lp->ptid),
2238                                           status_to_str ((int) status));
2239                     }
2240                   kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
2241                 }
2242               else
2243                 lp->status = status;
2244               return 0;
2245             }
2246         }
2247       else
2248         {
2249           /* We caught the SIGSTOP that we intended to catch, so
2250              there's no SIGSTOP pending.  */
2251           lp->stopped = 1;
2252           lp->signalled = 0;
2253         }
2254     }
2255
2256   return 0;
2257 }
2258
2259 /* Return non-zero if LP has a wait status pending.  */
2260
2261 static int
2262 status_callback (struct lwp_info *lp, void *data)
2263 {
2264   /* Only report a pending wait status if we pretend that this has
2265      indeed been resumed.  */
2266   return (lp->status != 0 && lp->resumed);
2267 }
2268
2269 /* Return non-zero if LP isn't stopped.  */
2270
2271 static int
2272 running_callback (struct lwp_info *lp, void *data)
2273 {
2274   return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
2275 }
2276
2277 /* Count the LWP's that have had events.  */
2278
2279 static int
2280 count_events_callback (struct lwp_info *lp, void *data)
2281 {
2282   int *count = data;
2283
2284   gdb_assert (count != NULL);
2285
2286   /* Count only resumed LWPs that have a SIGTRAP event pending.  */
2287   if (lp->status != 0 && lp->resumed
2288       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2289     (*count)++;
2290
2291   return 0;
2292 }
2293
2294 /* Select the LWP (if any) that is currently being single-stepped.  */
2295
2296 static int
2297 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
2298 {
2299   if (lp->step && lp->status != 0)
2300     return 1;
2301   else
2302     return 0;
2303 }
2304
2305 /* Select the Nth LWP that has had a SIGTRAP event.  */
2306
2307 static int
2308 select_event_lwp_callback (struct lwp_info *lp, void *data)
2309 {
2310   int *selector = data;
2311
2312   gdb_assert (selector != NULL);
2313
2314   /* Select only resumed LWPs that have a SIGTRAP event pending. */
2315   if (lp->status != 0 && lp->resumed
2316       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2317     if ((*selector)-- == 0)
2318       return 1;
2319
2320   return 0;
2321 }
2322
2323 static int
2324 cancel_breakpoint (struct lwp_info *lp)
2325 {
2326   /* Arrange for a breakpoint to be hit again later.  We don't keep
2327      the SIGTRAP status and don't forward the SIGTRAP signal to the
2328      LWP.  We will handle the current event, eventually we will resume
2329      this LWP, and this breakpoint will trap again.
2330
2331      If we do not do this, then we run the risk that the user will
2332      delete or disable the breakpoint, but the LWP will have already
2333      tripped on it.  */
2334
2335   struct regcache *regcache = get_thread_regcache (lp->ptid);
2336   struct gdbarch *gdbarch = get_regcache_arch (regcache);
2337   CORE_ADDR pc;
2338
2339   pc = regcache_read_pc (regcache) - gdbarch_decr_pc_after_break (gdbarch);
2340   if (breakpoint_inserted_here_p (pc))
2341     {
2342       if (debug_linux_nat)
2343         fprintf_unfiltered (gdb_stdlog,
2344                             "CB: Push back breakpoint for %s\n",
2345                             target_pid_to_str (lp->ptid));
2346
2347       /* Back up the PC if necessary.  */
2348       if (gdbarch_decr_pc_after_break (gdbarch))
2349         regcache_write_pc (regcache, pc);
2350
2351       return 1;
2352     }
2353   return 0;
2354 }
2355
2356 static int
2357 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
2358 {
2359   struct lwp_info *event_lp = data;
2360
2361   /* Leave the LWP that has been elected to receive a SIGTRAP alone.  */
2362   if (lp == event_lp)
2363     return 0;
2364
2365   /* If a LWP other than the LWP that we're reporting an event for has
2366      hit a GDB breakpoint (as opposed to some random trap signal),
2367      then just arrange for it to hit it again later.  We don't keep
2368      the SIGTRAP status and don't forward the SIGTRAP signal to the
2369      LWP.  We will handle the current event, eventually we will resume
2370      all LWPs, and this one will get its breakpoint trap again.
2371
2372      If we do not do this, then we run the risk that the user will
2373      delete or disable the breakpoint, but the LWP will have already
2374      tripped on it.  */
2375
2376   if (lp->status != 0
2377       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
2378       && cancel_breakpoint (lp))
2379     /* Throw away the SIGTRAP.  */
2380     lp->status = 0;
2381
2382   return 0;
2383 }
2384
2385 /* Select one LWP out of those that have events pending.  */
2386
2387 static void
2388 select_event_lwp (struct lwp_info **orig_lp, int *status)
2389 {
2390   int num_events = 0;
2391   int random_selector;
2392   struct lwp_info *event_lp;
2393
2394   /* Record the wait status for the original LWP.  */
2395   (*orig_lp)->status = *status;
2396
2397   /* Give preference to any LWP that is being single-stepped.  */
2398   event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
2399   if (event_lp != NULL)
2400     {
2401       if (debug_linux_nat)
2402         fprintf_unfiltered (gdb_stdlog,
2403                             "SEL: Select single-step %s\n",
2404                             target_pid_to_str (event_lp->ptid));
2405     }
2406   else
2407     {
2408       /* No single-stepping LWP.  Select one at random, out of those
2409          which have had SIGTRAP events.  */
2410
2411       /* First see how many SIGTRAP events we have.  */
2412       iterate_over_lwps (count_events_callback, &num_events);
2413
2414       /* Now randomly pick a LWP out of those that have had a SIGTRAP.  */
2415       random_selector = (int)
2416         ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2417
2418       if (debug_linux_nat && num_events > 1)
2419         fprintf_unfiltered (gdb_stdlog,
2420                             "SEL: Found %d SIGTRAP events, selecting #%d\n",
2421                             num_events, random_selector);
2422
2423       event_lp = iterate_over_lwps (select_event_lwp_callback,
2424                                     &random_selector);
2425     }
2426
2427   if (event_lp != NULL)
2428     {
2429       /* Switch the event LWP.  */
2430       *orig_lp = event_lp;
2431       *status = event_lp->status;
2432     }
2433
2434   /* Flush the wait status for the event LWP.  */
2435   (*orig_lp)->status = 0;
2436 }
2437
2438 /* Return non-zero if LP has been resumed.  */
2439
2440 static int
2441 resumed_callback (struct lwp_info *lp, void *data)
2442 {
2443   return lp->resumed;
2444 }
2445
2446 /* Stop an active thread, verify it still exists, then resume it.  */
2447
2448 static int
2449 stop_and_resume_callback (struct lwp_info *lp, void *data)
2450 {
2451   struct lwp_info *ptr;
2452
2453   if (!lp->stopped && !lp->signalled)
2454     {
2455       stop_callback (lp, NULL);
2456       stop_wait_callback (lp, NULL);
2457       /* Resume if the lwp still exists.  */
2458       for (ptr = lwp_list; ptr; ptr = ptr->next)
2459         if (lp == ptr)
2460           {
2461             resume_callback (lp, NULL);
2462             resume_set_callback (lp, NULL);
2463           }
2464     }
2465   return 0;
2466 }
2467
2468 /* Check if we should go on and pass this event to common code.
2469    Return the affected lwp if we are, or NULL otherwise.  */
2470 static struct lwp_info *
2471 linux_nat_filter_event (int lwpid, int status, int options)
2472 {
2473   struct lwp_info *lp;
2474
2475   lp = find_lwp_pid (pid_to_ptid (lwpid));
2476
2477   /* Check for stop events reported by a process we didn't already
2478      know about - anything not already in our LWP list.
2479
2480      If we're expecting to receive stopped processes after
2481      fork, vfork, and clone events, then we'll just add the
2482      new one to our list and go back to waiting for the event
2483      to be reported - the stopped process might be returned
2484      from waitpid before or after the event is.  */
2485   if (WIFSTOPPED (status) && !lp)
2486     {
2487       linux_record_stopped_pid (lwpid, status);
2488       return NULL;
2489     }
2490
2491   /* Make sure we don't report an event for the exit of an LWP not in
2492      our list, i.e.  not part of the current process.  This can happen
2493      if we detach from a program we original forked and then it
2494      exits.  */
2495   if (!WIFSTOPPED (status) && !lp)
2496     return NULL;
2497
2498   /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2499      CLONE_PTRACE processes which do not use the thread library -
2500      otherwise we wouldn't find the new LWP this way.  That doesn't
2501      currently work, and the following code is currently unreachable
2502      due to the two blocks above.  If it's fixed some day, this code
2503      should be broken out into a function so that we can also pick up
2504      LWPs from the new interface.  */
2505   if (!lp)
2506     {
2507       lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2508       if (options & __WCLONE)
2509         lp->cloned = 1;
2510
2511       gdb_assert (WIFSTOPPED (status)
2512                   && WSTOPSIG (status) == SIGSTOP);
2513       lp->signalled = 1;
2514
2515       if (!in_thread_list (inferior_ptid))
2516         {
2517           inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2518                                      GET_PID (inferior_ptid));
2519           add_thread (inferior_ptid);
2520         }
2521
2522       add_thread (lp->ptid);
2523     }
2524
2525   /* Save the trap's siginfo in case we need it later.  */
2526   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2527     save_siginfo (lp);
2528
2529   /* Handle GNU/Linux's extended waitstatus for trace events.  */
2530   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2531     {
2532       if (debug_linux_nat)
2533         fprintf_unfiltered (gdb_stdlog,
2534                             "LLW: Handling extended status 0x%06x\n",
2535                             status);
2536       if (linux_handle_extended_wait (lp, status, 0))
2537         return NULL;
2538     }
2539
2540   /* Check if the thread has exited.  */
2541   if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2542     {
2543       /* If this is the main thread, we must stop all threads and
2544          verify if they are still alive.  This is because in the nptl
2545          thread model, there is no signal issued for exiting LWPs
2546          other than the main thread.  We only get the main thread exit
2547          signal once all child threads have already exited.  If we
2548          stop all the threads and use the stop_wait_callback to check
2549          if they have exited we can determine whether this signal
2550          should be ignored or whether it means the end of the debugged
2551          application, regardless of which threading model is being
2552          used.  */
2553       if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2554         {
2555           lp->stopped = 1;
2556           iterate_over_lwps (stop_and_resume_callback, NULL);
2557         }
2558
2559       if (debug_linux_nat)
2560         fprintf_unfiltered (gdb_stdlog,
2561                             "LLW: %s exited.\n",
2562                             target_pid_to_str (lp->ptid));
2563
2564       exit_lwp (lp);
2565
2566       /* If there is at least one more LWP, then the exit signal was
2567          not the end of the debugged application and should be
2568          ignored.  */
2569       if (num_lwps > 0)
2570         return NULL;
2571     }
2572
2573   /* Check if the current LWP has previously exited.  In the nptl
2574      thread model, LWPs other than the main thread do not issue
2575      signals when they exit so we must check whenever the thread has
2576      stopped.  A similar check is made in stop_wait_callback().  */
2577   if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2578     {
2579       if (debug_linux_nat)
2580         fprintf_unfiltered (gdb_stdlog,
2581                             "LLW: %s exited.\n",
2582                             target_pid_to_str (lp->ptid));
2583
2584       exit_lwp (lp);
2585
2586       /* Make sure there is at least one thread running.  */
2587       gdb_assert (iterate_over_lwps (running_callback, NULL));
2588
2589       /* Discard the event.  */
2590       return NULL;
2591     }
2592
2593   /* Make sure we don't report a SIGSTOP that we sent ourselves in
2594      an attempt to stop an LWP.  */
2595   if (lp->signalled
2596       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2597     {
2598       if (debug_linux_nat)
2599         fprintf_unfiltered (gdb_stdlog,
2600                             "LLW: Delayed SIGSTOP caught for %s.\n",
2601                             target_pid_to_str (lp->ptid));
2602
2603       /* This is a delayed SIGSTOP.  */
2604       lp->signalled = 0;
2605
2606       registers_changed ();
2607
2608       linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2609                             lp->step, TARGET_SIGNAL_0);
2610       if (debug_linux_nat)
2611         fprintf_unfiltered (gdb_stdlog,
2612                             "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2613                             lp->step ?
2614                             "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2615                             target_pid_to_str (lp->ptid));
2616
2617       lp->stopped = 0;
2618       gdb_assert (lp->resumed);
2619
2620       /* Discard the event.  */
2621       return NULL;
2622     }
2623
2624   /* Make sure we don't report a SIGINT that we have already displayed
2625      for another thread.  */
2626   if (lp->ignore_sigint
2627       && WIFSTOPPED (status) && WSTOPSIG (status) == SIGINT)
2628     {
2629       if (debug_linux_nat)
2630         fprintf_unfiltered (gdb_stdlog,
2631                             "LLW: Delayed SIGINT caught for %s.\n",
2632                             target_pid_to_str (lp->ptid));
2633
2634       /* This is a delayed SIGINT.  */
2635       lp->ignore_sigint = 0;
2636
2637       registers_changed ();
2638       linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2639                             lp->step, TARGET_SIGNAL_0);
2640       if (debug_linux_nat)
2641         fprintf_unfiltered (gdb_stdlog,
2642                             "LLW: %s %s, 0, 0 (discard SIGINT)\n",
2643                             lp->step ?
2644                             "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2645                             target_pid_to_str (lp->ptid));
2646
2647       lp->stopped = 0;
2648       gdb_assert (lp->resumed);
2649
2650       /* Discard the event.  */
2651       return NULL;
2652     }
2653
2654   /* An interesting event.  */
2655   gdb_assert (lp);
2656   return lp;
2657 }
2658
2659 /* Get the events stored in the pipe into the local queue, so they are
2660    accessible to queued_waitpid.  We need to do this, since it is not
2661    always the case that the event at the head of the pipe is the event
2662    we want.  */
2663
2664 static void
2665 pipe_to_local_event_queue (void)
2666 {
2667   if (debug_linux_nat_async)
2668     fprintf_unfiltered (gdb_stdlog,
2669                         "PTLEQ: linux_nat_num_queued_events(%d)\n",
2670                         linux_nat_num_queued_events);
2671   while (linux_nat_num_queued_events)
2672     {
2673       int lwpid, status, options;
2674       lwpid = linux_nat_event_pipe_pop (&status, &options);
2675       gdb_assert (lwpid > 0);
2676       push_waitpid (lwpid, status, options);
2677     }
2678 }
2679
2680 /* Get the unprocessed events stored in the local queue back into the
2681    pipe, so the event loop realizes there's something else to
2682    process.  */
2683
2684 static void
2685 local_event_queue_to_pipe (void)
2686 {
2687   struct waitpid_result *w = waitpid_queue;
2688   while (w)
2689     {
2690       struct waitpid_result *next = w->next;
2691       linux_nat_event_pipe_push (w->pid,
2692                                  w->status,
2693                                  w->options);
2694       xfree (w);
2695       w = next;
2696     }
2697   waitpid_queue = NULL;
2698
2699   if (debug_linux_nat_async)
2700     fprintf_unfiltered (gdb_stdlog,
2701                         "LEQTP: linux_nat_num_queued_events(%d)\n",
2702                         linux_nat_num_queued_events);
2703 }
2704
2705 static ptid_t
2706 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
2707 {
2708   struct lwp_info *lp = NULL;
2709   int options = 0;
2710   int status = 0;
2711   pid_t pid = PIDGET (ptid);
2712
2713   if (debug_linux_nat_async)
2714     fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
2715
2716   /* The first time we get here after starting a new inferior, we may
2717      not have added it to the LWP list yet - this is the earliest
2718      moment at which we know its PID.  */
2719   if (num_lwps == 0)
2720     {
2721       gdb_assert (!is_lwp (inferior_ptid));
2722
2723       /* Upgrade the main thread's ptid.  */
2724       thread_change_ptid (inferior_ptid,
2725                           BUILD_LWP (GET_PID (inferior_ptid),
2726                                      GET_PID (inferior_ptid)));
2727
2728       lp = add_lwp (inferior_ptid);
2729       lp->resumed = 1;
2730     }
2731
2732   /* Block events while we're here.  */
2733   linux_nat_async_events (sigchld_sync);
2734
2735 retry:
2736
2737   /* Make sure there is at least one LWP that has been resumed.  */
2738   gdb_assert (iterate_over_lwps (resumed_callback, NULL));
2739
2740   /* First check if there is a LWP with a wait status pending.  */
2741   if (pid == -1)
2742     {
2743       /* Any LWP that's been resumed will do.  */
2744       lp = iterate_over_lwps (status_callback, NULL);
2745       if (lp)
2746         {
2747           if (target_can_async_p ())
2748             internal_error (__FILE__, __LINE__,
2749                             "Found an LWP with a pending status in async mode.");
2750
2751           status = lp->status;
2752           lp->status = 0;
2753
2754           if (debug_linux_nat && status)
2755             fprintf_unfiltered (gdb_stdlog,
2756                                 "LLW: Using pending wait status %s for %s.\n",
2757                                 status_to_str (status),
2758                                 target_pid_to_str (lp->ptid));
2759         }
2760
2761       /* But if we don't find one, we'll have to wait, and check both
2762          cloned and uncloned processes.  We start with the cloned
2763          processes.  */
2764       options = __WCLONE | WNOHANG;
2765     }
2766   else if (is_lwp (ptid))
2767     {
2768       if (debug_linux_nat)
2769         fprintf_unfiltered (gdb_stdlog,
2770                             "LLW: Waiting for specific LWP %s.\n",
2771                             target_pid_to_str (ptid));
2772
2773       /* We have a specific LWP to check.  */
2774       lp = find_lwp_pid (ptid);
2775       gdb_assert (lp);
2776       status = lp->status;
2777       lp->status = 0;
2778
2779       if (debug_linux_nat && status)
2780         fprintf_unfiltered (gdb_stdlog,
2781                             "LLW: Using pending wait status %s for %s.\n",
2782                             status_to_str (status),
2783                             target_pid_to_str (lp->ptid));
2784
2785       /* If we have to wait, take into account whether PID is a cloned
2786          process or not.  And we have to convert it to something that
2787          the layer beneath us can understand.  */
2788       options = lp->cloned ? __WCLONE : 0;
2789       pid = GET_LWP (ptid);
2790     }
2791
2792   if (status && lp->signalled)
2793     {
2794       /* A pending SIGSTOP may interfere with the normal stream of
2795          events.  In a typical case where interference is a problem,
2796          we have a SIGSTOP signal pending for LWP A while
2797          single-stepping it, encounter an event in LWP B, and take the
2798          pending SIGSTOP while trying to stop LWP A.  After processing
2799          the event in LWP B, LWP A is continued, and we'll never see
2800          the SIGTRAP associated with the last time we were
2801          single-stepping LWP A.  */
2802
2803       /* Resume the thread.  It should halt immediately returning the
2804          pending SIGSTOP.  */
2805       registers_changed ();
2806       linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2807                             lp->step, TARGET_SIGNAL_0);
2808       if (debug_linux_nat)
2809         fprintf_unfiltered (gdb_stdlog,
2810                             "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
2811                             lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2812                             target_pid_to_str (lp->ptid));
2813       lp->stopped = 0;
2814       gdb_assert (lp->resumed);
2815
2816       /* This should catch the pending SIGSTOP.  */
2817       stop_wait_callback (lp, NULL);
2818     }
2819
2820   if (!target_can_async_p ())
2821     {
2822       /* Causes SIGINT to be passed on to the attached process.  */
2823       set_sigint_trap ();
2824       set_sigio_trap ();
2825     }
2826
2827   while (status == 0)
2828     {
2829       pid_t lwpid;
2830
2831       if (target_can_async_p ())
2832         /* In async mode, don't ever block.  Only look at the locally
2833            queued events.  */
2834         lwpid = queued_waitpid (pid, &status, options);
2835       else
2836         lwpid = my_waitpid (pid, &status, options);
2837
2838       if (lwpid > 0)
2839         {
2840           gdb_assert (pid == -1 || lwpid == pid);
2841
2842           if (debug_linux_nat)
2843             {
2844               fprintf_unfiltered (gdb_stdlog,
2845                                   "LLW: waitpid %ld received %s\n",
2846                                   (long) lwpid, status_to_str (status));
2847             }
2848
2849           lp = linux_nat_filter_event (lwpid, status, options);
2850           if (!lp)
2851             {
2852               /* A discarded event.  */
2853               status = 0;
2854               continue;
2855             }
2856
2857           break;
2858         }
2859
2860       if (pid == -1)
2861         {
2862           /* Alternate between checking cloned and uncloned processes.  */
2863           options ^= __WCLONE;
2864
2865           /* And every time we have checked both:
2866              In async mode, return to event loop;
2867              In sync mode, suspend waiting for a SIGCHLD signal.  */
2868           if (options & __WCLONE)
2869             {
2870               if (target_can_async_p ())
2871                 {
2872                   /* No interesting event.  */
2873                   ourstatus->kind = TARGET_WAITKIND_IGNORE;
2874
2875                   /* Get ready for the next event.  */
2876                   target_async (inferior_event_handler, 0);
2877
2878                   if (debug_linux_nat_async)
2879                     fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
2880
2881                   return minus_one_ptid;
2882                 }
2883
2884               sigsuspend (&suspend_mask);
2885             }
2886         }
2887
2888       /* We shouldn't end up here unless we want to try again.  */
2889       gdb_assert (status == 0);
2890     }
2891
2892   if (!target_can_async_p ())
2893     {
2894       clear_sigio_trap ();
2895       clear_sigint_trap ();
2896     }
2897
2898   gdb_assert (lp);
2899
2900   /* Don't report signals that GDB isn't interested in, such as
2901      signals that are neither printed nor stopped upon.  Stopping all
2902      threads can be a bit time-consuming so if we want decent
2903      performance with heavily multi-threaded programs, especially when
2904      they're using a high frequency timer, we'd better avoid it if we
2905      can.  */
2906
2907   if (WIFSTOPPED (status))
2908     {
2909       int signo = target_signal_from_host (WSTOPSIG (status));
2910
2911       /* If we get a signal while single-stepping, we may need special
2912          care, e.g. to skip the signal handler.  Defer to common code.  */
2913       if (!lp->step
2914           && signal_stop_state (signo) == 0
2915           && signal_print_state (signo) == 0
2916           && signal_pass_state (signo) == 1)
2917         {
2918           /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2919              here?  It is not clear we should.  GDB may not expect
2920              other threads to run.  On the other hand, not resuming
2921              newly attached threads may cause an unwanted delay in
2922              getting them running.  */
2923           registers_changed ();
2924           linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2925                                 lp->step, signo);
2926           if (debug_linux_nat)
2927             fprintf_unfiltered (gdb_stdlog,
2928                                 "LLW: %s %s, %s (preempt 'handle')\n",
2929                                 lp->step ?
2930                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2931                                 target_pid_to_str (lp->ptid),
2932                                 signo ? strsignal (signo) : "0");
2933           lp->stopped = 0;
2934           status = 0;
2935           goto retry;
2936         }
2937
2938       if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2939         {
2940           /* If ^C/BREAK is typed at the tty/console, SIGINT gets
2941              forwarded to the entire process group, that is, all LWPs
2942              will receive it - unless they're using CLONE_THREAD to
2943              share signals.  Since we only want to report it once, we
2944              mark it as ignored for all LWPs except this one.  */
2945           iterate_over_lwps (set_ignore_sigint, NULL);
2946           lp->ignore_sigint = 0;
2947         }
2948       else
2949         maybe_clear_ignore_sigint (lp);
2950     }
2951
2952   /* This LWP is stopped now.  */
2953   lp->stopped = 1;
2954
2955   if (debug_linux_nat)
2956     fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
2957                         status_to_str (status), target_pid_to_str (lp->ptid));
2958
2959   if (!non_stop)
2960     {
2961       /* Now stop all other LWP's ...  */
2962       iterate_over_lwps (stop_callback, NULL);
2963
2964       /* ... and wait until all of them have reported back that
2965          they're no longer running.  */
2966       iterate_over_lwps (stop_wait_callback, NULL);
2967
2968       /* If we're not waiting for a specific LWP, choose an event LWP
2969          from among those that have had events.  Giving equal priority
2970          to all LWPs that have had events helps prevent
2971          starvation.  */
2972       if (pid == -1)
2973         select_event_lwp (&lp, &status);
2974     }
2975
2976   /* Now that we've selected our final event LWP, cancel any
2977      breakpoints in other LWPs that have hit a GDB breakpoint.  See
2978      the comment in cancel_breakpoints_callback to find out why.  */
2979   iterate_over_lwps (cancel_breakpoints_callback, lp);
2980
2981   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2982     {
2983       if (debug_linux_nat)
2984         fprintf_unfiltered (gdb_stdlog,
2985                             "LLW: trap ptid is %s.\n",
2986                             target_pid_to_str (lp->ptid));
2987     }
2988
2989   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2990     {
2991       *ourstatus = lp->waitstatus;
2992       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
2993     }
2994   else
2995     store_waitstatus (ourstatus, status);
2996
2997   /* Get ready for the next event.  */
2998   if (target_can_async_p ())
2999     target_async (inferior_event_handler, 0);
3000
3001   if (debug_linux_nat_async)
3002     fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
3003
3004   return lp->ptid;
3005 }
3006
3007 static int
3008 kill_callback (struct lwp_info *lp, void *data)
3009 {
3010   errno = 0;
3011   ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
3012   if (debug_linux_nat)
3013     fprintf_unfiltered (gdb_stdlog,
3014                         "KC:  PTRACE_KILL %s, 0, 0 (%s)\n",
3015                         target_pid_to_str (lp->ptid),
3016                         errno ? safe_strerror (errno) : "OK");
3017
3018   return 0;
3019 }
3020
3021 static int
3022 kill_wait_callback (struct lwp_info *lp, void *data)
3023 {
3024   pid_t pid;
3025
3026   /* We must make sure that there are no pending events (delayed
3027      SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
3028      program doesn't interfere with any following debugging session.  */
3029
3030   /* For cloned processes we must check both with __WCLONE and
3031      without, since the exit status of a cloned process isn't reported
3032      with __WCLONE.  */
3033   if (lp->cloned)
3034     {
3035       do
3036         {
3037           pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
3038           if (pid != (pid_t) -1)
3039             {
3040               if (debug_linux_nat)
3041                 fprintf_unfiltered (gdb_stdlog,
3042                                     "KWC: wait %s received unknown.\n",
3043                                     target_pid_to_str (lp->ptid));
3044               /* The Linux kernel sometimes fails to kill a thread
3045                  completely after PTRACE_KILL; that goes from the stop
3046                  point in do_fork out to the one in
3047                  get_signal_to_deliever and waits again.  So kill it
3048                  again.  */
3049               kill_callback (lp, NULL);
3050             }
3051         }
3052       while (pid == GET_LWP (lp->ptid));
3053
3054       gdb_assert (pid == -1 && errno == ECHILD);
3055     }
3056
3057   do
3058     {
3059       pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
3060       if (pid != (pid_t) -1)
3061         {
3062           if (debug_linux_nat)
3063             fprintf_unfiltered (gdb_stdlog,
3064                                 "KWC: wait %s received unk.\n",
3065                                 target_pid_to_str (lp->ptid));
3066           /* See the call to kill_callback above.  */
3067           kill_callback (lp, NULL);
3068         }
3069     }
3070   while (pid == GET_LWP (lp->ptid));
3071
3072   gdb_assert (pid == -1 && errno == ECHILD);
3073   return 0;
3074 }
3075
3076 static void
3077 linux_nat_kill (void)
3078 {
3079   struct target_waitstatus last;
3080   ptid_t last_ptid;
3081   int status;
3082
3083   if (target_can_async_p ())
3084     target_async (NULL, 0);
3085
3086   /* If we're stopped while forking and we haven't followed yet,
3087      kill the other task.  We need to do this first because the
3088      parent will be sleeping if this is a vfork.  */
3089
3090   get_last_target_status (&last_ptid, &last);
3091
3092   if (last.kind == TARGET_WAITKIND_FORKED
3093       || last.kind == TARGET_WAITKIND_VFORKED)
3094     {
3095       ptrace (PT_KILL, PIDGET (last.value.related_pid), 0, 0);
3096       wait (&status);
3097     }
3098
3099   if (forks_exist_p ())
3100     {
3101       linux_fork_killall ();
3102       drain_queued_events (-1);
3103     }
3104   else
3105     {
3106       /* Stop all threads before killing them, since ptrace requires
3107          that the thread is stopped to sucessfully PTRACE_KILL.  */
3108       iterate_over_lwps (stop_callback, NULL);
3109       /* ... and wait until all of them have reported back that
3110          they're no longer running.  */
3111       iterate_over_lwps (stop_wait_callback, NULL);
3112
3113       /* Kill all LWP's ...  */
3114       iterate_over_lwps (kill_callback, NULL);
3115
3116       /* ... and wait until we've flushed all events.  */
3117       iterate_over_lwps (kill_wait_callback, NULL);
3118     }
3119
3120   target_mourn_inferior ();
3121 }
3122
3123 static void
3124 linux_nat_mourn_inferior (void)
3125 {
3126   /* Destroy LWP info; it's no longer valid.  */
3127   init_lwp_list ();
3128
3129   if (! forks_exist_p ())
3130     {
3131       /* Normal case, no other forks available.  */
3132       if (target_can_async_p ())
3133         linux_nat_async (NULL, 0);
3134       linux_ops->to_mourn_inferior ();
3135     }
3136   else
3137     /* Multi-fork case.  The current inferior_ptid has exited, but
3138        there are other viable forks to debug.  Delete the exiting
3139        one and context-switch to the first available.  */
3140     linux_fork_mourn_inferior ();
3141 }
3142
3143 static LONGEST
3144 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
3145                         const char *annex, gdb_byte *readbuf,
3146                         const gdb_byte *writebuf,
3147                         ULONGEST offset, LONGEST len)
3148 {
3149   struct cleanup *old_chain = save_inferior_ptid ();
3150   LONGEST xfer;
3151
3152   if (is_lwp (inferior_ptid))
3153     inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
3154
3155   xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
3156                                      offset, len);
3157
3158   do_cleanups (old_chain);
3159   return xfer;
3160 }
3161
3162 static int
3163 linux_nat_thread_alive (ptid_t ptid)
3164 {
3165   int err;
3166
3167   gdb_assert (is_lwp (ptid));
3168
3169   /* Send signal 0 instead of anything ptrace, because ptracing a
3170      running thread errors out claiming that the thread doesn't
3171      exist.  */
3172   err = kill_lwp (GET_LWP (ptid), 0);
3173
3174   if (debug_linux_nat)
3175     fprintf_unfiltered (gdb_stdlog,
3176                         "LLTA: KILL(SIG0) %s (%s)\n",
3177                         target_pid_to_str (ptid),
3178                         err ? safe_strerror (err) : "OK");
3179
3180   if (err != 0)
3181     return 0;
3182
3183   return 1;
3184 }
3185
3186 static char *
3187 linux_nat_pid_to_str (ptid_t ptid)
3188 {
3189   static char buf[64];
3190
3191   if (is_lwp (ptid)
3192       && ((lwp_list && lwp_list->next)
3193           || GET_PID (ptid) != GET_LWP (ptid)))
3194     {
3195       snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
3196       return buf;
3197     }
3198
3199   return normal_pid_to_str (ptid);
3200 }
3201
3202 static void
3203 sigchld_handler (int signo)
3204 {
3205   if (target_async_permitted
3206       && linux_nat_async_events_state != sigchld_sync
3207       && signo == SIGCHLD)
3208     /* It is *always* a bug to hit this.  */
3209     internal_error (__FILE__, __LINE__,
3210                     "sigchld_handler called when async events are enabled");
3211
3212   /* Do nothing.  The only reason for this handler is that it allows
3213      us to use sigsuspend in linux_nat_wait above to wait for the
3214      arrival of a SIGCHLD.  */
3215 }
3216
3217 /* Accepts an integer PID; Returns a string representing a file that
3218    can be opened to get the symbols for the child process.  */
3219
3220 static char *
3221 linux_child_pid_to_exec_file (int pid)
3222 {
3223   char *name1, *name2;
3224
3225   name1 = xmalloc (MAXPATHLEN);
3226   name2 = xmalloc (MAXPATHLEN);
3227   make_cleanup (xfree, name1);
3228   make_cleanup (xfree, name2);
3229   memset (name2, 0, MAXPATHLEN);
3230
3231   sprintf (name1, "/proc/%d/exe", pid);
3232   if (readlink (name1, name2, MAXPATHLEN) > 0)
3233     return name2;
3234   else
3235     return name1;
3236 }
3237
3238 /* Service function for corefiles and info proc.  */
3239
3240 static int
3241 read_mapping (FILE *mapfile,
3242               long long *addr,
3243               long long *endaddr,
3244               char *permissions,
3245               long long *offset,
3246               char *device, long long *inode, char *filename)
3247 {
3248   int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
3249                     addr, endaddr, permissions, offset, device, inode);
3250
3251   filename[0] = '\0';
3252   if (ret > 0 && ret != EOF)
3253     {
3254       /* Eat everything up to EOL for the filename.  This will prevent
3255          weird filenames (such as one with embedded whitespace) from
3256          confusing this code.  It also makes this code more robust in
3257          respect to annotations the kernel may add after the filename.
3258
3259          Note the filename is used for informational purposes
3260          only.  */
3261       ret += fscanf (mapfile, "%[^\n]\n", filename);
3262     }
3263
3264   return (ret != 0 && ret != EOF);
3265 }
3266
3267 /* Fills the "to_find_memory_regions" target vector.  Lists the memory
3268    regions in the inferior for a corefile.  */
3269
3270 static int
3271 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
3272                                             unsigned long,
3273                                             int, int, int, void *), void *obfd)
3274 {
3275   long long pid = PIDGET (inferior_ptid);
3276   char mapsfilename[MAXPATHLEN];
3277   FILE *mapsfile;
3278   long long addr, endaddr, size, offset, inode;
3279   char permissions[8], device[8], filename[MAXPATHLEN];
3280   int read, write, exec;
3281   int ret;
3282
3283   /* Compose the filename for the /proc memory map, and open it.  */
3284   sprintf (mapsfilename, "/proc/%lld/maps", pid);
3285   if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
3286     error (_("Could not open %s."), mapsfilename);
3287
3288   if (info_verbose)
3289     fprintf_filtered (gdb_stdout,
3290                       "Reading memory regions from %s\n", mapsfilename);
3291
3292   /* Now iterate until end-of-file.  */
3293   while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
3294                        &offset, &device[0], &inode, &filename[0]))
3295     {
3296       size = endaddr - addr;
3297
3298       /* Get the segment's permissions.  */
3299       read = (strchr (permissions, 'r') != 0);
3300       write = (strchr (permissions, 'w') != 0);
3301       exec = (strchr (permissions, 'x') != 0);
3302
3303       if (info_verbose)
3304         {
3305           fprintf_filtered (gdb_stdout,
3306                             "Save segment, %lld bytes at 0x%s (%c%c%c)",
3307                             size, paddr_nz (addr),
3308                             read ? 'r' : ' ',
3309                             write ? 'w' : ' ', exec ? 'x' : ' ');
3310           if (filename[0])
3311             fprintf_filtered (gdb_stdout, " for %s", filename);
3312           fprintf_filtered (gdb_stdout, "\n");
3313         }
3314
3315       /* Invoke the callback function to create the corefile
3316          segment.  */
3317       func (addr, size, read, write, exec, obfd);
3318     }
3319   fclose (mapsfile);
3320   return 0;
3321 }
3322
3323 /* Records the thread's register state for the corefile note
3324    section.  */
3325
3326 static char *
3327 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
3328                                char *note_data, int *note_size)
3329 {
3330   gdb_gregset_t gregs;
3331   gdb_fpregset_t fpregs;
3332   unsigned long lwp = ptid_get_lwp (ptid);
3333   struct regcache *regcache = get_thread_regcache (ptid);
3334   struct gdbarch *gdbarch = get_regcache_arch (regcache);
3335   const struct regset *regset;
3336   int core_regset_p;
3337   struct cleanup *old_chain;
3338   struct core_regset_section *sect_list;
3339   char *gdb_regset;
3340
3341   old_chain = save_inferior_ptid ();
3342   inferior_ptid = ptid;
3343   target_fetch_registers (regcache, -1);
3344   do_cleanups (old_chain);
3345
3346   core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
3347   sect_list = gdbarch_core_regset_sections (gdbarch);
3348
3349   if (core_regset_p
3350       && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
3351                                                      sizeof (gregs))) != NULL
3352       && regset->collect_regset != NULL)
3353     regset->collect_regset (regset, regcache, -1,
3354                             &gregs, sizeof (gregs));
3355   else
3356     fill_gregset (regcache, &gregs, -1);
3357
3358   note_data = (char *) elfcore_write_prstatus (obfd,
3359                                                note_data,
3360                                                note_size,
3361                                                lwp,
3362                                                stop_signal, &gregs);
3363
3364   /* The loop below uses the new struct core_regset_section, which stores
3365      the supported section names and sizes for the core file.  Note that
3366      note PRSTATUS needs to be treated specially.  But the other notes are
3367      structurally the same, so they can benefit from the new struct.  */
3368   if (core_regset_p && sect_list != NULL)
3369     while (sect_list->sect_name != NULL)
3370       {
3371         /* .reg was already handled above.  */
3372         if (strcmp (sect_list->sect_name, ".reg") == 0)
3373           {
3374             sect_list++;
3375             continue;
3376           }
3377         regset = gdbarch_regset_from_core_section (gdbarch,
3378                                                    sect_list->sect_name,
3379                                                    sect_list->size);
3380         gdb_assert (regset && regset->collect_regset);
3381         gdb_regset = xmalloc (sect_list->size);
3382         regset->collect_regset (regset, regcache, -1,
3383                                 gdb_regset, sect_list->size);
3384         note_data = (char *) elfcore_write_register_note (obfd,
3385                                                           note_data,
3386                                                           note_size,
3387                                                           sect_list->sect_name,
3388                                                           gdb_regset,
3389                                                           sect_list->size);
3390         xfree (gdb_regset);
3391         sect_list++;
3392       }
3393
3394   /* For architectures that does not have the struct core_regset_section
3395      implemented, we use the old method.  When all the architectures have
3396      the new support, the code below should be deleted.  */
3397   else
3398     {
3399       if (core_regset_p
3400           && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
3401                                                          sizeof (fpregs))) != NULL
3402           && regset->collect_regset != NULL)
3403         regset->collect_regset (regset, regcache, -1,
3404                                 &fpregs, sizeof (fpregs));
3405       else
3406         fill_fpregset (regcache, &fpregs, -1);
3407
3408       note_data = (char *) elfcore_write_prfpreg (obfd,
3409                                                   note_data,
3410                                                   note_size,
3411                                                   &fpregs, sizeof (fpregs));
3412     }
3413
3414   return note_data;
3415 }
3416
3417 struct linux_nat_corefile_thread_data
3418 {
3419   bfd *obfd;
3420   char *note_data;
3421   int *note_size;
3422   int num_notes;
3423 };
3424
3425 /* Called by gdbthread.c once per thread.  Records the thread's
3426    register state for the corefile note section.  */
3427
3428 static int
3429 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
3430 {
3431   struct linux_nat_corefile_thread_data *args = data;
3432
3433   args->note_data = linux_nat_do_thread_registers (args->obfd,
3434                                                    ti->ptid,
3435                                                    args->note_data,
3436                                                    args->note_size);
3437   args->num_notes++;
3438
3439   return 0;
3440 }
3441
3442 /* Records the register state for the corefile note section.  */
3443
3444 static char *
3445 linux_nat_do_registers (bfd *obfd, ptid_t ptid,
3446                         char *note_data, int *note_size)
3447 {
3448   return linux_nat_do_thread_registers (obfd,
3449                                         ptid_build (ptid_get_pid (inferior_ptid),
3450                                                     ptid_get_pid (inferior_ptid),
3451                                                     0),
3452                                         note_data, note_size);
3453 }
3454
3455 /* Fills the "to_make_corefile_note" target vector.  Builds the note
3456    section for a corefile, and returns it in a malloc buffer.  */
3457
3458 static char *
3459 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
3460 {
3461   struct linux_nat_corefile_thread_data thread_args;
3462   struct cleanup *old_chain;
3463   /* The variable size must be >= sizeof (prpsinfo_t.pr_fname).  */
3464   char fname[16] = { '\0' };
3465   /* The variable size must be >= sizeof (prpsinfo_t.pr_psargs).  */
3466   char psargs[80] = { '\0' };
3467   char *note_data = NULL;
3468   ptid_t current_ptid = inferior_ptid;
3469   gdb_byte *auxv;
3470   int auxv_len;
3471
3472   if (get_exec_file (0))
3473     {
3474       strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
3475       strncpy (psargs, get_exec_file (0), sizeof (psargs));
3476       if (get_inferior_args ())
3477         {
3478           char *string_end;
3479           char *psargs_end = psargs + sizeof (psargs);
3480
3481           /* linux_elfcore_write_prpsinfo () handles zero unterminated
3482              strings fine.  */
3483           string_end = memchr (psargs, 0, sizeof (psargs));
3484           if (string_end != NULL)
3485             {
3486               *string_end++ = ' ';
3487               strncpy (string_end, get_inferior_args (),
3488                        psargs_end - string_end);
3489             }
3490         }
3491       note_data = (char *) elfcore_write_prpsinfo (obfd,
3492                                                    note_data,
3493                                                    note_size, fname, psargs);
3494     }
3495
3496   /* Dump information for threads.  */
3497   thread_args.obfd = obfd;
3498   thread_args.note_data = note_data;
3499   thread_args.note_size = note_size;
3500   thread_args.num_notes = 0;
3501   iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
3502   if (thread_args.num_notes == 0)
3503     {
3504       /* iterate_over_threads didn't come up with any threads; just
3505          use inferior_ptid.  */
3506       note_data = linux_nat_do_registers (obfd, inferior_ptid,
3507                                           note_data, note_size);
3508     }
3509   else
3510     {
3511       note_data = thread_args.note_data;
3512     }
3513
3514   auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
3515                                 NULL, &auxv);
3516   if (auxv_len > 0)
3517     {
3518       note_data = elfcore_write_note (obfd, note_data, note_size,
3519                                       "CORE", NT_AUXV, auxv, auxv_len);
3520       xfree (auxv);
3521     }
3522
3523   make_cleanup (xfree, note_data);
3524   return note_data;
3525 }
3526
3527 /* Implement the "info proc" command.  */
3528
3529 static void
3530 linux_nat_info_proc_cmd (char *args, int from_tty)
3531 {
3532   long long pid = PIDGET (inferior_ptid);
3533   FILE *procfile;
3534   char **argv = NULL;
3535   char buffer[MAXPATHLEN];
3536   char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
3537   int cmdline_f = 1;
3538   int cwd_f = 1;
3539   int exe_f = 1;
3540   int mappings_f = 0;
3541   int environ_f = 0;
3542   int status_f = 0;
3543   int stat_f = 0;
3544   int all = 0;
3545   struct stat dummy;
3546
3547   if (args)
3548     {
3549       /* Break up 'args' into an argv array.  */
3550       if ((argv = buildargv (args)) == NULL)
3551         nomem (0);
3552       else
3553         make_cleanup_freeargv (argv);
3554     }
3555   while (argv != NULL && *argv != NULL)
3556     {
3557       if (isdigit (argv[0][0]))
3558         {
3559           pid = strtoul (argv[0], NULL, 10);
3560         }
3561       else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
3562         {
3563           mappings_f = 1;
3564         }
3565       else if (strcmp (argv[0], "status") == 0)
3566         {
3567           status_f = 1;
3568         }
3569       else if (strcmp (argv[0], "stat") == 0)
3570         {
3571           stat_f = 1;
3572         }
3573       else if (strcmp (argv[0], "cmd") == 0)
3574         {
3575           cmdline_f = 1;
3576         }
3577       else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
3578         {
3579           exe_f = 1;
3580         }
3581       else if (strcmp (argv[0], "cwd") == 0)
3582         {
3583           cwd_f = 1;
3584         }
3585       else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
3586         {
3587           all = 1;
3588         }
3589       else
3590         {
3591           /* [...] (future options here) */
3592         }
3593       argv++;
3594     }
3595   if (pid == 0)
3596     error (_("No current process: you must name one."));
3597
3598   sprintf (fname1, "/proc/%lld", pid);
3599   if (stat (fname1, &dummy) != 0)
3600     error (_("No /proc directory: '%s'"), fname1);
3601
3602   printf_filtered (_("process %lld\n"), pid);
3603   if (cmdline_f || all)
3604     {
3605       sprintf (fname1, "/proc/%lld/cmdline", pid);
3606       if ((procfile = fopen (fname1, "r")) != NULL)
3607         {
3608           fgets (buffer, sizeof (buffer), procfile);
3609           printf_filtered ("cmdline = '%s'\n", buffer);
3610           fclose (procfile);
3611         }
3612       else
3613         warning (_("unable to open /proc file '%s'"), fname1);
3614     }
3615   if (cwd_f || all)
3616     {
3617       sprintf (fname1, "/proc/%lld/cwd", pid);
3618       memset (fname2, 0, sizeof (fname2));
3619       if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3620         printf_filtered ("cwd = '%s'\n", fname2);
3621       else
3622         warning (_("unable to read link '%s'"), fname1);
3623     }
3624   if (exe_f || all)
3625     {
3626       sprintf (fname1, "/proc/%lld/exe", pid);
3627       memset (fname2, 0, sizeof (fname2));
3628       if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3629         printf_filtered ("exe = '%s'\n", fname2);
3630       else
3631         warning (_("unable to read link '%s'"), fname1);
3632     }
3633   if (mappings_f || all)
3634     {
3635       sprintf (fname1, "/proc/%lld/maps", pid);
3636       if ((procfile = fopen (fname1, "r")) != NULL)
3637         {
3638           long long addr, endaddr, size, offset, inode;
3639           char permissions[8], device[8], filename[MAXPATHLEN];
3640
3641           printf_filtered (_("Mapped address spaces:\n\n"));
3642           if (gdbarch_addr_bit (current_gdbarch) == 32)
3643             {
3644               printf_filtered ("\t%10s %10s %10s %10s %7s\n",
3645                            "Start Addr",
3646                            "  End Addr",
3647                            "      Size", "    Offset", "objfile");
3648             }
3649           else
3650             {
3651               printf_filtered ("  %18s %18s %10s %10s %7s\n",
3652                            "Start Addr",
3653                            "  End Addr",
3654                            "      Size", "    Offset", "objfile");
3655             }
3656
3657           while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
3658                                &offset, &device[0], &inode, &filename[0]))
3659             {
3660               size = endaddr - addr;
3661
3662               /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
3663                  calls here (and possibly above) should be abstracted
3664                  out into their own functions?  Andrew suggests using
3665                  a generic local_address_string instead to print out
3666                  the addresses; that makes sense to me, too.  */
3667
3668               if (gdbarch_addr_bit (current_gdbarch) == 32)
3669                 {
3670                   printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
3671                                (unsigned long) addr,    /* FIXME: pr_addr */
3672                                (unsigned long) endaddr,
3673                                (int) size,
3674                                (unsigned int) offset,
3675                                filename[0] ? filename : "");
3676                 }
3677               else
3678                 {
3679                   printf_filtered ("  %#18lx %#18lx %#10x %#10x %7s\n",
3680                                (unsigned long) addr,    /* FIXME: pr_addr */
3681                                (unsigned long) endaddr,
3682                                (int) size,
3683                                (unsigned int) offset,
3684                                filename[0] ? filename : "");
3685                 }
3686             }
3687
3688           fclose (procfile);
3689         }
3690       else
3691         warning (_("unable to open /proc file '%s'"), fname1);
3692     }
3693   if (status_f || all)
3694     {
3695       sprintf (fname1, "/proc/%lld/status", pid);
3696       if ((procfile = fopen (fname1, "r")) != NULL)
3697         {
3698           while (fgets (buffer, sizeof (buffer), procfile) != NULL)
3699             puts_filtered (buffer);
3700           fclose (procfile);
3701         }
3702       else
3703         warning (_("unable to open /proc file '%s'"), fname1);
3704     }
3705   if (stat_f || all)
3706     {
3707       sprintf (fname1, "/proc/%lld/stat", pid);
3708       if ((procfile = fopen (fname1, "r")) != NULL)
3709         {
3710           int itmp;
3711           char ctmp;
3712           long ltmp;
3713
3714           if (fscanf (procfile, "%d ", &itmp) > 0)
3715             printf_filtered (_("Process: %d\n"), itmp);
3716           if (fscanf (procfile, "(%[^)]) ", &buffer[0]) > 0)
3717             printf_filtered (_("Exec file: %s\n"), buffer);
3718           if (fscanf (procfile, "%c ", &ctmp) > 0)
3719             printf_filtered (_("State: %c\n"), ctmp);
3720           if (fscanf (procfile, "%d ", &itmp) > 0)
3721             printf_filtered (_("Parent process: %d\n"), itmp);
3722           if (fscanf (procfile, "%d ", &itmp) > 0)
3723             printf_filtered (_("Process group: %d\n"), itmp);
3724           if (fscanf (procfile, "%d ", &itmp) > 0)
3725             printf_filtered (_("Session id: %d\n"), itmp);
3726           if (fscanf (procfile, "%d ", &itmp) > 0)
3727             printf_filtered (_("TTY: %d\n"), itmp);
3728           if (fscanf (procfile, "%d ", &itmp) > 0)
3729             printf_filtered (_("TTY owner process group: %d\n"), itmp);
3730           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3731             printf_filtered (_("Flags: 0x%lx\n"), ltmp);
3732           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3733             printf_filtered (_("Minor faults (no memory page): %lu\n"),
3734                              (unsigned long) ltmp);
3735           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3736             printf_filtered (_("Minor faults, children: %lu\n"),
3737                              (unsigned long) ltmp);
3738           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3739             printf_filtered (_("Major faults (memory page faults): %lu\n"),
3740                              (unsigned long) ltmp);
3741           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3742             printf_filtered (_("Major faults, children: %lu\n"),
3743                              (unsigned long) ltmp);
3744           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3745             printf_filtered (_("utime: %ld\n"), ltmp);
3746           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3747             printf_filtered (_("stime: %ld\n"), ltmp);
3748           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3749             printf_filtered (_("utime, children: %ld\n"), ltmp);
3750           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3751             printf_filtered (_("stime, children: %ld\n"), ltmp);
3752           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3753             printf_filtered (_("jiffies remaining in current time slice: %ld\n"),
3754                              ltmp);
3755           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3756             printf_filtered (_("'nice' value: %ld\n"), ltmp);
3757           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3758             printf_filtered (_("jiffies until next timeout: %lu\n"),
3759                              (unsigned long) ltmp);
3760           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3761             printf_filtered (_("jiffies until next SIGALRM: %lu\n"),
3762                              (unsigned long) ltmp);
3763           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3764             printf_filtered (_("start time (jiffies since system boot): %ld\n"),
3765                              ltmp);
3766           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3767             printf_filtered (_("Virtual memory size: %lu\n"),
3768                              (unsigned long) ltmp);
3769           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3770             printf_filtered (_("Resident set size: %lu\n"), (unsigned long) ltmp);
3771           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3772             printf_filtered (_("rlim: %lu\n"), (unsigned long) ltmp);
3773           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3774             printf_filtered (_("Start of text: 0x%lx\n"), ltmp);
3775           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3776             printf_filtered (_("End of text: 0x%lx\n"), ltmp);
3777           if (fscanf (procfile, "%lu ", &ltmp) > 0)
3778             printf_filtered (_("Start of stack: 0x%lx\n"), ltmp);
3779 #if 0                           /* Don't know how architecture-dependent the rest is...
3780                                    Anyway the signal bitmap info is available from "status".  */
3781           if (fscanf (procfile, "%lu ", &ltmp) > 0)     /* FIXME arch? */
3782             printf_filtered (_("Kernel stack pointer: 0x%lx\n"), ltmp);
3783           if (fscanf (procfile, "%lu ", &ltmp) > 0)     /* FIXME arch? */
3784             printf_filtered (_("Kernel instr pointer: 0x%lx\n"), ltmp);
3785           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3786             printf_filtered (_("Pending signals bitmap: 0x%lx\n"), ltmp);
3787           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3788             printf_filtered (_("Blocked signals bitmap: 0x%lx\n"), ltmp);
3789           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3790             printf_filtered (_("Ignored signals bitmap: 0x%lx\n"), ltmp);
3791           if (fscanf (procfile, "%ld ", &ltmp) > 0)
3792             printf_filtered (_("Catched signals bitmap: 0x%lx\n"), ltmp);
3793           if (fscanf (procfile, "%lu ", &ltmp) > 0)     /* FIXME arch? */
3794             printf_filtered (_("wchan (system call): 0x%lx\n"), ltmp);
3795 #endif
3796           fclose (procfile);
3797         }
3798       else
3799         warning (_("unable to open /proc file '%s'"), fname1);
3800     }
3801 }
3802
3803 /* Implement the to_xfer_partial interface for memory reads using the /proc
3804    filesystem.  Because we can use a single read() call for /proc, this
3805    can be much more efficient than banging away at PTRACE_PEEKTEXT,
3806    but it doesn't support writes.  */
3807
3808 static LONGEST
3809 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
3810                          const char *annex, gdb_byte *readbuf,
3811                          const gdb_byte *writebuf,
3812                          ULONGEST offset, LONGEST len)
3813 {
3814   LONGEST ret;
3815   int fd;
3816   char filename[64];
3817
3818   if (object != TARGET_OBJECT_MEMORY || !readbuf)
3819     return 0;
3820
3821   /* Don't bother for one word.  */
3822   if (len < 3 * sizeof (long))
3823     return 0;
3824
3825   /* We could keep this file open and cache it - possibly one per
3826      thread.  That requires some juggling, but is even faster.  */
3827   sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
3828   fd = open (filename, O_RDONLY | O_LARGEFILE);
3829   if (fd == -1)
3830     return 0;
3831
3832   /* If pread64 is available, use it.  It's faster if the kernel
3833      supports it (only one syscall), and it's 64-bit safe even on
3834      32-bit platforms (for instance, SPARC debugging a SPARC64
3835      application).  */
3836 #ifdef HAVE_PREAD64
3837   if (pread64 (fd, readbuf, len, offset) != len)
3838 #else
3839   if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
3840 #endif
3841     ret = 0;
3842   else
3843     ret = len;
3844
3845   close (fd);
3846   return ret;
3847 }
3848
3849 /* Parse LINE as a signal set and add its set bits to SIGS.  */
3850
3851 static void
3852 add_line_to_sigset (const char *line, sigset_t *sigs)
3853 {
3854   int len = strlen (line) - 1;
3855   const char *p;
3856   int signum;
3857
3858   if (line[len] != '\n')
3859     error (_("Could not parse signal set: %s"), line);
3860
3861   p = line;
3862   signum = len * 4;
3863   while (len-- > 0)
3864     {
3865       int digit;
3866
3867       if (*p >= '0' && *p <= '9')
3868         digit = *p - '0';
3869       else if (*p >= 'a' && *p <= 'f')
3870         digit = *p - 'a' + 10;
3871       else
3872         error (_("Could not parse signal set: %s"), line);
3873
3874       signum -= 4;
3875
3876       if (digit & 1)
3877         sigaddset (sigs, signum + 1);
3878       if (digit & 2)
3879         sigaddset (sigs, signum + 2);
3880       if (digit & 4)
3881         sigaddset (sigs, signum + 3);
3882       if (digit & 8)
3883         sigaddset (sigs, signum + 4);
3884
3885       p++;
3886     }
3887 }
3888
3889 /* Find process PID's pending signals from /proc/pid/status and set
3890    SIGS to match.  */
3891
3892 void
3893 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3894 {
3895   FILE *procfile;
3896   char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3897   int signum;
3898
3899   sigemptyset (pending);
3900   sigemptyset (blocked);
3901   sigemptyset (ignored);
3902   sprintf (fname, "/proc/%d/status", pid);
3903   procfile = fopen (fname, "r");
3904   if (procfile == NULL)
3905     error (_("Could not open %s"), fname);
3906
3907   while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3908     {
3909       /* Normal queued signals are on the SigPnd line in the status
3910          file.  However, 2.6 kernels also have a "shared" pending
3911          queue for delivering signals to a thread group, so check for
3912          a ShdPnd line also.
3913
3914          Unfortunately some Red Hat kernels include the shared pending
3915          queue but not the ShdPnd status field.  */
3916
3917       if (strncmp (buffer, "SigPnd:\t", 8) == 0)
3918         add_line_to_sigset (buffer + 8, pending);
3919       else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
3920         add_line_to_sigset (buffer + 8, pending);
3921       else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
3922         add_line_to_sigset (buffer + 8, blocked);
3923       else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
3924         add_line_to_sigset (buffer + 8, ignored);
3925     }
3926
3927   fclose (procfile);
3928 }
3929
3930 static LONGEST
3931 linux_xfer_partial (struct target_ops *ops, enum target_object object,
3932                     const char *annex, gdb_byte *readbuf,
3933                     const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3934 {
3935   LONGEST xfer;
3936
3937   if (object == TARGET_OBJECT_AUXV)
3938     return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
3939                              offset, len);
3940
3941   xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
3942                                   offset, len);
3943   if (xfer != 0)
3944     return xfer;
3945
3946   return super_xfer_partial (ops, object, annex, readbuf, writebuf,
3947                              offset, len);
3948 }
3949
3950 /* Create a prototype generic GNU/Linux target.  The client can override
3951    it with local methods.  */
3952
3953 static void
3954 linux_target_install_ops (struct target_ops *t)
3955 {
3956   t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
3957   t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
3958   t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
3959   t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
3960   t->to_post_startup_inferior = linux_child_post_startup_inferior;
3961   t->to_post_attach = linux_child_post_attach;
3962   t->to_follow_fork = linux_child_follow_fork;
3963   t->to_find_memory_regions = linux_nat_find_memory_regions;
3964   t->to_make_corefile_notes = linux_nat_make_corefile_notes;
3965
3966   super_xfer_partial = t->to_xfer_partial;
3967   t->to_xfer_partial = linux_xfer_partial;
3968 }
3969
3970 struct target_ops *
3971 linux_target (void)
3972 {
3973   struct target_ops *t;
3974
3975   t = inf_ptrace_target ();
3976   linux_target_install_ops (t);
3977
3978   return t;
3979 }
3980
3981 struct target_ops *
3982 linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
3983 {
3984   struct target_ops *t;
3985
3986   t = inf_ptrace_trad_target (register_u_offset);
3987   linux_target_install_ops (t);
3988
3989   return t;
3990 }
3991
3992 /* target_is_async_p implementation.  */
3993
3994 static int
3995 linux_nat_is_async_p (void)
3996 {
3997   /* NOTE: palves 2008-03-21: We're only async when the user requests
3998      it explicitly with the "maintenance set target-async" command.
3999      Someday, linux will always be async.  */
4000   if (!target_async_permitted)
4001     return 0;
4002
4003   return 1;
4004 }
4005
4006 /* target_can_async_p implementation.  */
4007
4008 static int
4009 linux_nat_can_async_p (void)
4010 {
4011   /* NOTE: palves 2008-03-21: We're only async when the user requests
4012      it explicitly with the "maintenance set target-async" command.
4013      Someday, linux will always be async.  */
4014   if (!target_async_permitted)
4015     return 0;
4016
4017   /* See target.h/target_async_mask.  */
4018   return linux_nat_async_mask_value;
4019 }
4020
4021 static int
4022 linux_nat_supports_non_stop (void)
4023 {
4024   return 1;
4025 }
4026
4027 /* target_async_mask implementation.  */
4028
4029 static int
4030 linux_nat_async_mask (int mask)
4031 {
4032   int current_state;
4033   current_state = linux_nat_async_mask_value;
4034
4035   if (current_state != mask)
4036     {
4037       if (mask == 0)
4038         {
4039           linux_nat_async (NULL, 0);
4040           linux_nat_async_mask_value = mask;
4041         }
4042       else
4043         {
4044           linux_nat_async_mask_value = mask;
4045           linux_nat_async (inferior_event_handler, 0);
4046         }
4047     }
4048
4049   return current_state;
4050 }
4051
4052 /* Pop an event from the event pipe.  */
4053
4054 static int
4055 linux_nat_event_pipe_pop (int* ptr_status, int* ptr_options)
4056 {
4057   struct waitpid_result event = {0};
4058   int ret;
4059
4060   do
4061     {
4062       ret = read (linux_nat_event_pipe[0], &event, sizeof (event));
4063     }
4064   while (ret == -1 && errno == EINTR);
4065
4066   gdb_assert (ret == sizeof (event));
4067
4068   *ptr_status = event.status;
4069   *ptr_options = event.options;
4070
4071   linux_nat_num_queued_events--;
4072
4073   return event.pid;
4074 }
4075
4076 /* Push an event into the event pipe.  */
4077
4078 static void
4079 linux_nat_event_pipe_push (int pid, int status, int options)
4080 {
4081   int ret;
4082   struct waitpid_result event = {0};
4083   event.pid = pid;
4084   event.status = status;
4085   event.options = options;
4086
4087   do
4088     {
4089       ret = write (linux_nat_event_pipe[1], &event, sizeof (event));
4090       gdb_assert ((ret == -1 && errno == EINTR) || ret == sizeof (event));
4091     } while (ret == -1 && errno == EINTR);
4092
4093   linux_nat_num_queued_events++;
4094 }
4095
4096 static void
4097 get_pending_events (void)
4098 {
4099   int status, options, pid;
4100
4101   if (!target_async_permitted
4102       || linux_nat_async_events_state != sigchld_async)
4103     internal_error (__FILE__, __LINE__,
4104                     "get_pending_events called with async masked");
4105
4106   while (1)
4107     {
4108       status = 0;
4109       options = __WCLONE | WNOHANG;
4110
4111       do
4112         {
4113           pid = waitpid (-1, &status, options);
4114         }
4115       while (pid == -1 && errno == EINTR);
4116
4117       if (pid <= 0)
4118         {
4119           options = WNOHANG;
4120           do
4121             {
4122               pid = waitpid (-1, &status, options);
4123             }
4124           while (pid == -1 && errno == EINTR);
4125         }
4126
4127       if (pid <= 0)
4128         /* No more children reporting events.  */
4129         break;
4130
4131       if (debug_linux_nat_async)
4132         fprintf_unfiltered (gdb_stdlog, "\
4133 get_pending_events: pid(%d), status(%x), options (%x)\n",
4134                             pid, status, options);
4135
4136       linux_nat_event_pipe_push (pid, status, options);
4137     }
4138
4139   if (debug_linux_nat_async)
4140     fprintf_unfiltered (gdb_stdlog, "\
4141 get_pending_events: linux_nat_num_queued_events(%d)\n",
4142                         linux_nat_num_queued_events);
4143 }
4144
4145 /* SIGCHLD handler for async mode.  */
4146
4147 static void
4148 async_sigchld_handler (int signo)
4149 {
4150   if (debug_linux_nat_async)
4151     fprintf_unfiltered (gdb_stdlog, "async_sigchld_handler\n");
4152
4153   get_pending_events ();
4154 }
4155
4156 /* Set SIGCHLD handling state to STATE.  Returns previous state.  */
4157
4158 static enum sigchld_state
4159 linux_nat_async_events (enum sigchld_state state)
4160 {
4161   enum sigchld_state current_state = linux_nat_async_events_state;
4162
4163   if (debug_linux_nat_async)
4164     fprintf_unfiltered (gdb_stdlog,
4165                         "LNAE: state(%d): linux_nat_async_events_state(%d), "
4166                         "linux_nat_num_queued_events(%d)\n",
4167                         state, linux_nat_async_events_state,
4168                         linux_nat_num_queued_events);
4169
4170   if (current_state != state)
4171     {
4172       sigset_t mask;
4173       sigemptyset (&mask);
4174       sigaddset (&mask, SIGCHLD);
4175
4176       /* Always block before changing state.  */
4177       sigprocmask (SIG_BLOCK, &mask, NULL);
4178
4179       /* Set new state.  */
4180       linux_nat_async_events_state = state;
4181
4182       switch (state)
4183         {
4184         case sigchld_sync:
4185           {
4186             /* Block target events.  */
4187             sigprocmask (SIG_BLOCK, &mask, NULL);
4188             sigaction (SIGCHLD, &sync_sigchld_action, NULL);
4189             /* Get events out of queue, and make them available to
4190                queued_waitpid / my_waitpid.  */
4191             pipe_to_local_event_queue ();
4192           }
4193           break;
4194         case sigchld_async:
4195           {
4196             /* Unblock target events for async mode.  */
4197
4198             sigprocmask (SIG_BLOCK, &mask, NULL);
4199
4200             /* Put events we already waited on, in the pipe first, so
4201                events are FIFO.  */
4202             local_event_queue_to_pipe ();
4203             /* While in masked async, we may have not collected all
4204                the pending events.  Get them out now.  */
4205             get_pending_events ();
4206
4207             /* Let'em come.   */
4208             sigaction (SIGCHLD, &async_sigchld_action, NULL);
4209             sigprocmask (SIG_UNBLOCK, &mask, NULL);
4210           }
4211           break;
4212         case sigchld_default:
4213           {
4214             /* SIGCHLD default mode.  */
4215             sigaction (SIGCHLD, &sigchld_default_action, NULL);
4216
4217             /* Get events out of queue, and make them available to
4218                queued_waitpid / my_waitpid.  */
4219             pipe_to_local_event_queue ();
4220
4221             /* Unblock SIGCHLD.  */
4222             sigprocmask (SIG_UNBLOCK, &mask, NULL);
4223           }
4224           break;
4225         }
4226     }
4227
4228   return current_state;
4229 }
4230
4231 static int async_terminal_is_ours = 1;
4232
4233 /* target_terminal_inferior implementation.  */
4234
4235 static void
4236 linux_nat_terminal_inferior (void)
4237 {
4238   if (!target_is_async_p ())
4239     {
4240       /* Async mode is disabled.  */
4241       terminal_inferior ();
4242       return;
4243     }
4244
4245   /* GDB should never give the terminal to the inferior, if the
4246      inferior is running in the background (run&, continue&, etc.).
4247      This check can be removed when the common code is fixed.  */
4248   if (!sync_execution)
4249     return;
4250
4251   terminal_inferior ();
4252
4253   if (!async_terminal_is_ours)
4254     return;
4255
4256   delete_file_handler (input_fd);
4257   async_terminal_is_ours = 0;
4258   set_sigint_trap ();
4259 }
4260
4261 /* target_terminal_ours implementation.  */
4262
4263 void
4264 linux_nat_terminal_ours (void)
4265 {
4266   if (!target_is_async_p ())
4267     {
4268       /* Async mode is disabled.  */
4269       terminal_ours ();
4270       return;
4271     }
4272
4273   /* GDB should never give the terminal to the inferior if the
4274      inferior is running in the background (run&, continue&, etc.),
4275      but claiming it sure should.  */
4276   terminal_ours ();
4277
4278   if (!sync_execution)
4279     return;
4280
4281   if (async_terminal_is_ours)
4282     return;
4283
4284   clear_sigint_trap ();
4285   add_file_handler (input_fd, stdin_event_handler, 0);
4286   async_terminal_is_ours = 1;
4287 }
4288
4289 static void (*async_client_callback) (enum inferior_event_type event_type,
4290                                       void *context);
4291 static void *async_client_context;
4292
4293 static void
4294 linux_nat_async_file_handler (int error, gdb_client_data client_data)
4295 {
4296   async_client_callback (INF_REG_EVENT, async_client_context);
4297 }
4298
4299 /* target_async implementation.  */
4300
4301 static void
4302 linux_nat_async (void (*callback) (enum inferior_event_type event_type,
4303                                    void *context), void *context)
4304 {
4305   if (linux_nat_async_mask_value == 0 || !target_async_permitted)
4306     internal_error (__FILE__, __LINE__,
4307                     "Calling target_async when async is masked");
4308
4309   if (callback != NULL)
4310     {
4311       async_client_callback = callback;
4312       async_client_context = context;
4313       add_file_handler (linux_nat_event_pipe[0],
4314                         linux_nat_async_file_handler, NULL);
4315
4316       linux_nat_async_events (sigchld_async);
4317     }
4318   else
4319     {
4320       async_client_callback = callback;
4321       async_client_context = context;
4322
4323       linux_nat_async_events (sigchld_sync);
4324       delete_file_handler (linux_nat_event_pipe[0]);
4325     }
4326   return;
4327 }
4328
4329 static int
4330 send_sigint_callback (struct lwp_info *lp, void *data)
4331 {
4332   /* Use is_running instead of !lp->stopped, because the lwp may be
4333      stopped due to an internal event, and we want to interrupt it in
4334      that case too.  What we want is to check if the thread is stopped
4335      from the point of view of the user.  */
4336   if (is_running (lp->ptid))
4337     kill_lwp (GET_LWP (lp->ptid), SIGINT);
4338   return 0;
4339 }
4340
4341 static void
4342 linux_nat_stop (ptid_t ptid)
4343 {
4344   if (non_stop)
4345     {
4346       if (ptid_equal (ptid, minus_one_ptid))
4347         iterate_over_lwps (send_sigint_callback, &ptid);
4348       else
4349         {
4350           struct lwp_info *lp = find_lwp_pid (ptid);
4351           send_sigint_callback (lp, NULL);
4352         }
4353     }
4354   else
4355     linux_ops->to_stop (ptid);
4356 }
4357
4358 void
4359 linux_nat_add_target (struct target_ops *t)
4360 {
4361   /* Save the provided single-threaded target.  We save this in a separate
4362      variable because another target we've inherited from (e.g. inf-ptrace)
4363      may have saved a pointer to T; we want to use it for the final
4364      process stratum target.  */
4365   linux_ops_saved = *t;
4366   linux_ops = &linux_ops_saved;
4367
4368   /* Override some methods for multithreading.  */
4369   t->to_create_inferior = linux_nat_create_inferior;
4370   t->to_attach = linux_nat_attach;
4371   t->to_detach = linux_nat_detach;
4372   t->to_resume = linux_nat_resume;
4373   t->to_wait = linux_nat_wait;
4374   t->to_xfer_partial = linux_nat_xfer_partial;
4375   t->to_kill = linux_nat_kill;
4376   t->to_mourn_inferior = linux_nat_mourn_inferior;
4377   t->to_thread_alive = linux_nat_thread_alive;
4378   t->to_pid_to_str = linux_nat_pid_to_str;
4379   t->to_has_thread_control = tc_schedlock;
4380
4381   t->to_can_async_p = linux_nat_can_async_p;
4382   t->to_is_async_p = linux_nat_is_async_p;
4383   t->to_supports_non_stop = linux_nat_supports_non_stop;
4384   t->to_async = linux_nat_async;
4385   t->to_async_mask = linux_nat_async_mask;
4386   t->to_terminal_inferior = linux_nat_terminal_inferior;
4387   t->to_terminal_ours = linux_nat_terminal_ours;
4388
4389   /* Methods for non-stop support.  */
4390   t->to_stop = linux_nat_stop;
4391
4392   /* We don't change the stratum; this target will sit at
4393      process_stratum and thread_db will set at thread_stratum.  This
4394      is a little strange, since this is a multi-threaded-capable
4395      target, but we want to be on the stack below thread_db, and we
4396      also want to be used for single-threaded processes.  */
4397
4398   add_target (t);
4399
4400   /* TODO: Eliminate this and have libthread_db use
4401      find_target_beneath.  */
4402   thread_db_init (t);
4403 }
4404
4405 /* Register a method to call whenever a new thread is attached.  */
4406 void
4407 linux_nat_set_new_thread (struct target_ops *t, void (*new_thread) (ptid_t))
4408 {
4409   /* Save the pointer.  We only support a single registered instance
4410      of the GNU/Linux native target, so we do not need to map this to
4411      T.  */
4412   linux_nat_new_thread = new_thread;
4413 }
4414
4415 /* Return the saved siginfo associated with PTID.  */
4416 struct siginfo *
4417 linux_nat_get_siginfo (ptid_t ptid)
4418 {
4419   struct lwp_info *lp = find_lwp_pid (ptid);
4420
4421   gdb_assert (lp != NULL);
4422
4423   return &lp->siginfo;
4424 }
4425
4426 /* Enable/Disable async mode.  */
4427
4428 static void
4429 linux_nat_setup_async (void)
4430 {
4431   if (pipe (linux_nat_event_pipe) == -1)
4432     internal_error (__FILE__, __LINE__,
4433                     "creating event pipe failed.");
4434   fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
4435   fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
4436 }
4437
4438 void
4439 _initialize_linux_nat (void)
4440 {
4441   sigset_t mask;
4442
4443   add_info ("proc", linux_nat_info_proc_cmd, _("\
4444 Show /proc process information about any running process.\n\
4445 Specify any process id, or use the program being debugged by default.\n\
4446 Specify any of the following keywords for detailed info:\n\
4447   mappings -- list of mapped memory regions.\n\
4448   stat     -- list a bunch of random process info.\n\
4449   status   -- list a different bunch of random process info.\n\
4450   all      -- list all available /proc info."));
4451
4452   add_setshow_zinteger_cmd ("lin-lwp", class_maintenance,
4453                             &debug_linux_nat, _("\
4454 Set debugging of GNU/Linux lwp module."), _("\
4455 Show debugging of GNU/Linux lwp module."), _("\
4456 Enables printf debugging output."),
4457                             NULL,
4458                             show_debug_linux_nat,
4459                             &setdebuglist, &showdebuglist);
4460
4461   add_setshow_zinteger_cmd ("lin-lwp-async", class_maintenance,
4462                             &debug_linux_nat_async, _("\
4463 Set debugging of GNU/Linux async lwp module."), _("\
4464 Show debugging of GNU/Linux async lwp module."), _("\
4465 Enables printf debugging output."),
4466                             NULL,
4467                             show_debug_linux_nat_async,
4468                             &setdebuglist, &showdebuglist);
4469
4470   /* Get the default SIGCHLD action.  Used while forking an inferior
4471      (see linux_nat_create_inferior/linux_nat_async_events).  */
4472   sigaction (SIGCHLD, NULL, &sigchld_default_action);
4473
4474   /* Block SIGCHLD by default.  Doing this early prevents it getting
4475      unblocked if an exception is thrown due to an error while the
4476      inferior is starting (sigsetjmp/siglongjmp).  */
4477   sigemptyset (&mask);
4478   sigaddset (&mask, SIGCHLD);
4479   sigprocmask (SIG_BLOCK, &mask, NULL);
4480
4481   /* Save this mask as the default.  */
4482   sigprocmask (SIG_SETMASK, NULL, &normal_mask);
4483
4484   /* The synchronous SIGCHLD handler.  */
4485   sync_sigchld_action.sa_handler = sigchld_handler;
4486   sigemptyset (&sync_sigchld_action.sa_mask);
4487   sync_sigchld_action.sa_flags = SA_RESTART;
4488
4489   /* Make it the default.  */
4490   sigaction (SIGCHLD, &sync_sigchld_action, NULL);
4491
4492   /* Make sure we don't block SIGCHLD during a sigsuspend.  */
4493   sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
4494   sigdelset (&suspend_mask, SIGCHLD);
4495
4496   /* SIGCHLD handler for async mode.  */
4497   async_sigchld_action.sa_handler = async_sigchld_handler;
4498   sigemptyset (&async_sigchld_action.sa_mask);
4499   async_sigchld_action.sa_flags = SA_RESTART;
4500
4501   linux_nat_setup_async ();
4502
4503   add_setshow_boolean_cmd ("disable-randomization", class_support,
4504                            &disable_randomization, _("\
4505 Set disabling of debuggee's virtual address space randomization."), _("\
4506 Show disabling of debuggee's virtual address space randomization."), _("\
4507 When this mode is on (which is the default), randomization of the virtual\n\
4508 address space is disabled.  Standalone programs run with the randomization\n\
4509 enabled by default on some platforms."),
4510                            &set_disable_randomization,
4511                            &show_disable_randomization,
4512                            &setlist, &showlist);
4513 }
4514 \f
4515
4516 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
4517    the GNU/Linux Threads library and therefore doesn't really belong
4518    here.  */
4519
4520 /* Read variable NAME in the target and return its value if found.
4521    Otherwise return zero.  It is assumed that the type of the variable
4522    is `int'.  */
4523
4524 static int
4525 get_signo (const char *name)
4526 {
4527   struct minimal_symbol *ms;
4528   int signo;
4529
4530   ms = lookup_minimal_symbol (name, NULL, NULL);
4531   if (ms == NULL)
4532     return 0;
4533
4534   if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
4535                           sizeof (signo)) != 0)
4536     return 0;
4537
4538   return signo;
4539 }
4540
4541 /* Return the set of signals used by the threads library in *SET.  */
4542
4543 void
4544 lin_thread_get_thread_signals (sigset_t *set)
4545 {
4546   struct sigaction action;
4547   int restart, cancel;
4548   sigset_t blocked_mask;
4549
4550   sigemptyset (&blocked_mask);
4551   sigemptyset (set);
4552
4553   restart = get_signo ("__pthread_sig_restart");
4554   cancel = get_signo ("__pthread_sig_cancel");
4555
4556   /* LinuxThreads normally uses the first two RT signals, but in some legacy
4557      cases may use SIGUSR1/SIGUSR2.  NPTL always uses RT signals, but does
4558      not provide any way for the debugger to query the signal numbers -
4559      fortunately they don't change!  */
4560
4561   if (restart == 0)
4562     restart = __SIGRTMIN;
4563
4564   if (cancel == 0)
4565     cancel = __SIGRTMIN + 1;
4566
4567   sigaddset (set, restart);
4568   sigaddset (set, cancel);
4569
4570   /* The GNU/Linux Threads library makes terminating threads send a
4571      special "cancel" signal instead of SIGCHLD.  Make sure we catch
4572      those (to prevent them from terminating GDB itself, which is
4573      likely to be their default action) and treat them the same way as
4574      SIGCHLD.  */
4575
4576   action.sa_handler = sigchld_handler;
4577   sigemptyset (&action.sa_mask);
4578   action.sa_flags = SA_RESTART;
4579   sigaction (cancel, &action, NULL);
4580
4581   /* We block the "cancel" signal throughout this code ...  */
4582   sigaddset (&blocked_mask, cancel);
4583   sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
4584
4585   /* ... except during a sigsuspend.  */
4586   sigdelset (&suspend_mask, cancel);
4587 }