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