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