* inf-child.c (inf_child_follow_fork): Add OPS argument.
[external/binutils.git] / gdb / linux-nat.c
1 /* GNU/Linux native-dependent code common to multiple platforms.
2
3    Copyright 2001, 2002, 2003, 2004, 2005 Free Software Foundation, Inc.
4
5    This file is part of GDB.
6
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 59 Temple Place - Suite 330,
20    Boston, MA 02111-1307, USA.  */
21
22 #include "defs.h"
23 #include "inferior.h"
24 #include "target.h"
25 #include "gdb_string.h"
26 #include "gdb_wait.h"
27 #include "gdb_assert.h"
28 #ifdef HAVE_TKILL_SYSCALL
29 #include <unistd.h>
30 #include <sys/syscall.h>
31 #endif
32 #include <sys/ptrace.h>
33 #include "linux-nat.h"
34 #include "gdbthread.h"
35 #include "gdbcmd.h"
36 #include "regcache.h"
37 #include <sys/param.h>          /* for MAXPATHLEN */
38 #include <sys/procfs.h>         /* for elf_gregset etc. */
39 #include "elf-bfd.h"            /* for elfcore_write_* */
40 #include "gregset.h"            /* for gregset */
41 #include "gdbcore.h"            /* for get_exec_file */
42 #include <ctype.h>              /* for isdigit */
43 #include "gdbthread.h"          /* for struct thread_info etc. */
44 #include "gdb_stat.h"           /* for struct stat */
45 #include <fcntl.h>              /* for O_RDONLY */
46
47 #ifndef O_LARGEFILE
48 #define O_LARGEFILE 0
49 #endif
50
51 /* If the system headers did not provide the constants, hard-code the normal
52    values.  */
53 #ifndef PTRACE_EVENT_FORK
54
55 #define PTRACE_SETOPTIONS       0x4200
56 #define PTRACE_GETEVENTMSG      0x4201
57
58 /* options set using PTRACE_SETOPTIONS */
59 #define PTRACE_O_TRACESYSGOOD   0x00000001
60 #define PTRACE_O_TRACEFORK      0x00000002
61 #define PTRACE_O_TRACEVFORK     0x00000004
62 #define PTRACE_O_TRACECLONE     0x00000008
63 #define PTRACE_O_TRACEEXEC      0x00000010
64 #define PTRACE_O_TRACEVFORKDONE 0x00000020
65 #define PTRACE_O_TRACEEXIT      0x00000040
66
67 /* Wait extended result codes for the above trace options.  */
68 #define PTRACE_EVENT_FORK       1
69 #define PTRACE_EVENT_VFORK      2
70 #define PTRACE_EVENT_CLONE      3
71 #define PTRACE_EVENT_EXEC       4
72 #define PTRACE_EVENT_VFORK_DONE 5
73 #define PTRACE_EVENT_EXIT       6
74
75 #endif /* PTRACE_EVENT_FORK */
76
77 /* We can't always assume that this flag is available, but all systems
78    with the ptrace event handlers also have __WALL, so it's safe to use
79    here.  */
80 #ifndef __WALL
81 #define __WALL          0x40000000 /* Wait for any child.  */
82 #endif
83
84 static int debug_linux_nat;
85 static void
86 show_debug_linux_nat (struct ui_file *file, int from_tty,
87                       struct cmd_list_element *c, const char *value)
88 {
89   fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
90                     value);
91 }
92
93 static int linux_parent_pid;
94
95 struct simple_pid_list
96 {
97   int pid;
98   struct simple_pid_list *next;
99 };
100 struct simple_pid_list *stopped_pids;
101
102 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
103    can not be used, 1 if it can.  */
104
105 static int linux_supports_tracefork_flag = -1;
106
107 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
108    PTRACE_O_TRACEVFORKDONE.  */
109
110 static int linux_supports_tracevforkdone_flag = -1;
111
112 \f
113 /* Trivial list manipulation functions to keep track of a list of
114    new stopped processes.  */
115 static void
116 add_to_pid_list (struct simple_pid_list **listp, int pid)
117 {
118   struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
119   new_pid->pid = pid;
120   new_pid->next = *listp;
121   *listp = new_pid;
122 }
123
124 static int
125 pull_pid_from_list (struct simple_pid_list **listp, int pid)
126 {
127   struct simple_pid_list **p;
128
129   for (p = listp; *p != NULL; p = &(*p)->next)
130     if ((*p)->pid == pid)
131       {
132         struct simple_pid_list *next = (*p)->next;
133         xfree (*p);
134         *p = next;
135         return 1;
136       }
137   return 0;
138 }
139
140 void
141 linux_record_stopped_pid (int pid)
142 {
143   add_to_pid_list (&stopped_pids, pid);
144 }
145
146 \f
147 /* A helper function for linux_test_for_tracefork, called after fork ().  */
148
149 static void
150 linux_tracefork_child (void)
151 {
152   int ret;
153
154   ptrace (PTRACE_TRACEME, 0, 0, 0);
155   kill (getpid (), SIGSTOP);
156   fork ();
157   _exit (0);
158 }
159
160 /* Wrapper function for waitpid which handles EINTR.  */
161
162 static int
163 my_waitpid (int pid, int *status, int flags)
164 {
165   int ret;
166   do
167     {
168       ret = waitpid (pid, status, flags);
169     }
170   while (ret == -1 && errno == EINTR);
171
172   return ret;
173 }
174
175 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
176
177    First, we try to enable fork tracing on ORIGINAL_PID.  If this fails,
178    we know that the feature is not available.  This may change the tracing
179    options for ORIGINAL_PID, but we'll be setting them shortly anyway.
180
181    However, if it succeeds, we don't know for sure that the feature is
182    available; old versions of PTRACE_SETOPTIONS ignored unknown options.  We
183    create a child process, attach to it, use PTRACE_SETOPTIONS to enable
184    fork tracing, and let it fork.  If the process exits, we assume that we
185    can't use TRACEFORK; if we get the fork notification, and we can extract
186    the new child's PID, then we assume that we can.  */
187
188 static void
189 linux_test_for_tracefork (int original_pid)
190 {
191   int child_pid, ret, status;
192   long second_pid;
193
194   linux_supports_tracefork_flag = 0;
195   linux_supports_tracevforkdone_flag = 0;
196
197   ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
198   if (ret != 0)
199     return;
200
201   child_pid = fork ();
202   if (child_pid == -1)
203     perror_with_name (("fork"));
204
205   if (child_pid == 0)
206     linux_tracefork_child ();
207
208   ret = my_waitpid (child_pid, &status, 0);
209   if (ret == -1)
210     perror_with_name (("waitpid"));
211   else if (ret != child_pid)
212     error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
213   if (! WIFSTOPPED (status))
214     error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
215
216   ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
217   if (ret != 0)
218     {
219       ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
220       if (ret != 0)
221         {
222           warning (_("linux_test_for_tracefork: failed to kill child"));
223           return;
224         }
225
226       ret = my_waitpid (child_pid, &status, 0);
227       if (ret != child_pid)
228         warning (_("linux_test_for_tracefork: failed to wait for killed child"));
229       else if (!WIFSIGNALED (status))
230         warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
231                  "killed child"), status);
232
233       return;
234     }
235
236   /* Check whether PTRACE_O_TRACEVFORKDONE is available.  */
237   ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
238                 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
239   linux_supports_tracevforkdone_flag = (ret == 0);
240
241   ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
242   if (ret != 0)
243     warning (_("linux_test_for_tracefork: failed to resume child"));
244
245   ret = my_waitpid (child_pid, &status, 0);
246
247   if (ret == child_pid && WIFSTOPPED (status)
248       && status >> 16 == PTRACE_EVENT_FORK)
249     {
250       second_pid = 0;
251       ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
252       if (ret == 0 && second_pid != 0)
253         {
254           int second_status;
255
256           linux_supports_tracefork_flag = 1;
257           my_waitpid (second_pid, &second_status, 0);
258           ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
259           if (ret != 0)
260             warning (_("linux_test_for_tracefork: failed to kill second child"));
261         }
262     }
263   else
264     warning (_("linux_test_for_tracefork: unexpected result from waitpid "
265              "(%d, status 0x%x)"), ret, status);
266
267   ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
268   if (ret != 0)
269     warning (_("linux_test_for_tracefork: failed to kill child"));
270   my_waitpid (child_pid, &status, 0);
271 }
272
273 /* Return non-zero iff we have tracefork functionality available.
274    This function also sets linux_supports_tracefork_flag.  */
275
276 static int
277 linux_supports_tracefork (int pid)
278 {
279   if (linux_supports_tracefork_flag == -1)
280     linux_test_for_tracefork (pid);
281   return linux_supports_tracefork_flag;
282 }
283
284 static int
285 linux_supports_tracevforkdone (int pid)
286 {
287   if (linux_supports_tracefork_flag == -1)
288     linux_test_for_tracefork (pid);
289   return linux_supports_tracevforkdone_flag;
290 }
291
292 \f
293 void
294 linux_enable_event_reporting (ptid_t ptid)
295 {
296   int pid = ptid_get_lwp (ptid);
297   int options;
298
299   if (pid == 0)
300     pid = ptid_get_pid (ptid);
301
302   if (! linux_supports_tracefork (pid))
303     return;
304
305   options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
306     | PTRACE_O_TRACECLONE;
307   if (linux_supports_tracevforkdone (pid))
308     options |= PTRACE_O_TRACEVFORKDONE;
309
310   /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
311      read-only process state.  */
312
313   ptrace (PTRACE_SETOPTIONS, pid, 0, options);
314 }
315
316 void
317 child_post_attach (int pid)
318 {
319   linux_enable_event_reporting (pid_to_ptid (pid));
320 }
321
322 void
323 linux_child_post_startup_inferior (ptid_t ptid)
324 {
325   linux_enable_event_reporting (ptid);
326 }
327
328 #ifndef LINUX_CHILD_POST_STARTUP_INFERIOR
329 void
330 child_post_startup_inferior (ptid_t ptid)
331 {
332   linux_child_post_startup_inferior (ptid);
333 }
334 #endif
335
336 int
337 child_follow_fork (struct target_ops *ops, int follow_child)
338 {
339   ptid_t last_ptid;
340   struct target_waitstatus last_status;
341   int has_vforked;
342   int parent_pid, child_pid;
343
344   get_last_target_status (&last_ptid, &last_status);
345   has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
346   parent_pid = ptid_get_lwp (last_ptid);
347   if (parent_pid == 0)
348     parent_pid = ptid_get_pid (last_ptid);
349   child_pid = last_status.value.related_pid;
350
351   if (! follow_child)
352     {
353       /* We're already attached to the parent, by default. */
354
355       /* Before detaching from the child, remove all breakpoints from
356          it.  (This won't actually modify the breakpoint list, but will
357          physically remove the breakpoints from the child.) */
358       /* If we vforked this will remove the breakpoints from the parent
359          also, but they'll be reinserted below.  */
360       detach_breakpoints (child_pid);
361
362       if (debug_linux_nat)
363         {
364           target_terminal_ours ();
365           fprintf_unfiltered (gdb_stdlog,
366                               "Detaching after fork from child process %d.\n",
367                               child_pid);
368         }
369
370       ptrace (PTRACE_DETACH, child_pid, 0, 0);
371
372       if (has_vforked)
373         {
374           gdb_assert (linux_supports_tracefork_flag >= 0);
375           if (linux_supports_tracevforkdone (0))
376             {
377               int status;
378
379               ptrace (PTRACE_CONT, parent_pid, 0, 0);
380               my_waitpid (parent_pid, &status, __WALL);
381               if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
382                 warning (_("Unexpected waitpid result %06x when waiting for "
383                          "vfork-done"), status);
384             }
385           else
386             {
387               /* We can't insert breakpoints until the child has
388                  finished with the shared memory region.  We need to
389                  wait until that happens.  Ideal would be to just
390                  call:
391                  - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
392                  - waitpid (parent_pid, &status, __WALL);
393                  However, most architectures can't handle a syscall
394                  being traced on the way out if it wasn't traced on
395                  the way in.
396
397                  We might also think to loop, continuing the child
398                  until it exits or gets a SIGTRAP.  One problem is
399                  that the child might call ptrace with PTRACE_TRACEME.
400
401                  There's no simple and reliable way to figure out when
402                  the vforked child will be done with its copy of the
403                  shared memory.  We could step it out of the syscall,
404                  two instructions, let it go, and then single-step the
405                  parent once.  When we have hardware single-step, this
406                  would work; with software single-step it could still
407                  be made to work but we'd have to be able to insert
408                  single-step breakpoints in the child, and we'd have
409                  to insert -just- the single-step breakpoint in the
410                  parent.  Very awkward.
411
412                  In the end, the best we can do is to make sure it
413                  runs for a little while.  Hopefully it will be out of
414                  range of any breakpoints we reinsert.  Usually this
415                  is only the single-step breakpoint at vfork's return
416                  point.  */
417
418               usleep (10000);
419             }
420
421           /* Since we vforked, breakpoints were removed in the parent
422              too.  Put them back.  */
423           reattach_breakpoints (parent_pid);
424         }
425     }
426   else
427     {
428       char child_pid_spelling[40];
429
430       /* Needed to keep the breakpoint lists in sync.  */
431       if (! has_vforked)
432         detach_breakpoints (child_pid);
433
434       /* Before detaching from the parent, remove all breakpoints from it. */
435       remove_breakpoints ();
436
437       if (debug_linux_nat)
438         {
439           target_terminal_ours ();
440           fprintf_unfiltered (gdb_stdlog,
441                               "Attaching after fork to child process %d.\n",
442                               child_pid);
443         }
444
445       /* If we're vforking, we may want to hold on to the parent until
446          the child exits or execs.  At exec time we can remove the old
447          breakpoints from the parent and detach it; at exit time we
448          could do the same (or even, sneakily, resume debugging it - the
449          child's exec has failed, or something similar).
450
451          This doesn't clean up "properly", because we can't call
452          target_detach, but that's OK; if the current target is "child",
453          then it doesn't need any further cleanups, and lin_lwp will
454          generally not encounter vfork (vfork is defined to fork
455          in libpthread.so).
456
457          The holding part is very easy if we have VFORKDONE events;
458          but keeping track of both processes is beyond GDB at the
459          moment.  So we don't expose the parent to the rest of GDB.
460          Instead we quietly hold onto it until such time as we can
461          safely resume it.  */
462
463       if (has_vforked)
464         linux_parent_pid = parent_pid;
465       else
466         target_detach (NULL, 0);
467
468       inferior_ptid = pid_to_ptid (child_pid);
469
470       /* Reinstall ourselves, since we might have been removed in
471          target_detach (which does other necessary cleanup).  */
472       push_target (ops);
473
474       /* Reset breakpoints in the child as appropriate.  */
475       follow_inferior_reset_breakpoints ();
476     }
477
478   return 0;
479 }
480
481 ptid_t
482 linux_handle_extended_wait (int pid, int status,
483                             struct target_waitstatus *ourstatus)
484 {
485   int event = status >> 16;
486
487   if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
488       || event == PTRACE_EVENT_CLONE)
489     {
490       unsigned long new_pid;
491       int ret;
492
493       ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
494
495       /* If we haven't already seen the new PID stop, wait for it now.  */
496       if (! pull_pid_from_list (&stopped_pids, new_pid))
497         {
498           /* The new child has a pending SIGSTOP.  We can't affect it until it
499              hits the SIGSTOP, but we're already attached.  */
500           ret = my_waitpid (new_pid, &status,
501                             (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
502           if (ret == -1)
503             perror_with_name (_("waiting for new child"));
504           else if (ret != new_pid)
505             internal_error (__FILE__, __LINE__,
506                             _("wait returned unexpected PID %d"), ret);
507           else if (!WIFSTOPPED (status) || WSTOPSIG (status) != SIGSTOP)
508             internal_error (__FILE__, __LINE__,
509                             _("wait returned unexpected status 0x%x"), status);
510         }
511
512       if (event == PTRACE_EVENT_FORK)
513         ourstatus->kind = TARGET_WAITKIND_FORKED;
514       else if (event == PTRACE_EVENT_VFORK)
515         ourstatus->kind = TARGET_WAITKIND_VFORKED;
516       else
517         ourstatus->kind = TARGET_WAITKIND_SPURIOUS;
518
519       ourstatus->value.related_pid = new_pid;
520       return inferior_ptid;
521     }
522
523   if (event == PTRACE_EVENT_EXEC)
524     {
525       ourstatus->kind = TARGET_WAITKIND_EXECD;
526       ourstatus->value.execd_pathname
527         = xstrdup (child_pid_to_exec_file (pid));
528
529       if (linux_parent_pid)
530         {
531           detach_breakpoints (linux_parent_pid);
532           ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
533
534           linux_parent_pid = 0;
535         }
536
537       return inferior_ptid;
538     }
539
540   internal_error (__FILE__, __LINE__,
541                   _("unknown ptrace event %d"), event);
542 }
543
544 \f
545 void
546 child_insert_fork_catchpoint (int pid)
547 {
548   if (! linux_supports_tracefork (pid))
549     error (_("Your system does not support fork catchpoints."));
550 }
551
552 void
553 child_insert_vfork_catchpoint (int pid)
554 {
555   if (!linux_supports_tracefork (pid))
556     error (_("Your system does not support vfork catchpoints."));
557 }
558
559 void
560 child_insert_exec_catchpoint (int pid)
561 {
562   if (!linux_supports_tracefork (pid))
563     error (_("Your system does not support exec catchpoints."));
564 }
565
566 void
567 kill_inferior (void)
568 {
569   int status;
570   int pid =  PIDGET (inferior_ptid);
571   struct target_waitstatus last;
572   ptid_t last_ptid;
573   int ret;
574
575   if (pid == 0)
576     return;
577
578   /* If we're stopped while forking and we haven't followed yet, kill the
579      other task.  We need to do this first because the parent will be
580      sleeping if this is a vfork.  */
581
582   get_last_target_status (&last_ptid, &last);
583
584   if (last.kind == TARGET_WAITKIND_FORKED
585       || last.kind == TARGET_WAITKIND_VFORKED)
586     {
587       ptrace (PT_KILL, last.value.related_pid, 0, 0);
588       wait (&status);
589     }
590
591   /* Kill the current process.  */
592   ptrace (PT_KILL, pid, 0, 0);
593   ret = wait (&status);
594
595   /* We might get a SIGCHLD instead of an exit status.  This is
596      aggravated by the first kill above - a child has just died.  */
597
598   while (ret == pid && WIFSTOPPED (status))
599     {
600       ptrace (PT_KILL, pid, 0, 0);
601       ret = wait (&status);
602     }
603
604   target_mourn_inferior ();
605 }
606
607 /* On GNU/Linux there are no real LWP's.  The closest thing to LWP's
608    are processes sharing the same VM space.  A multi-threaded process
609    is basically a group of such processes.  However, such a grouping
610    is almost entirely a user-space issue; the kernel doesn't enforce
611    such a grouping at all (this might change in the future).  In
612    general, we'll rely on the threads library (i.e. the GNU/Linux
613    Threads library) to provide such a grouping.
614
615    It is perfectly well possible to write a multi-threaded application
616    without the assistance of a threads library, by using the clone
617    system call directly.  This module should be able to give some
618    rudimentary support for debugging such applications if developers
619    specify the CLONE_PTRACE flag in the clone system call, and are
620    using the Linux kernel 2.4 or above.
621
622    Note that there are some peculiarities in GNU/Linux that affect
623    this code:
624
625    - In general one should specify the __WCLONE flag to waitpid in
626      order to make it report events for any of the cloned processes
627      (and leave it out for the initial process).  However, if a cloned
628      process has exited the exit status is only reported if the
629      __WCLONE flag is absent.  Linux kernel 2.4 has a __WALL flag, but
630      we cannot use it since GDB must work on older systems too.
631
632    - When a traced, cloned process exits and is waited for by the
633      debugger, the kernel reassigns it to the original parent and
634      keeps it around as a "zombie".  Somehow, the GNU/Linux Threads
635      library doesn't notice this, which leads to the "zombie problem":
636      When debugged a multi-threaded process that spawns a lot of
637      threads will run out of processes, even if the threads exit,
638      because the "zombies" stay around.  */
639
640 /* List of known LWPs.  */
641 static struct lwp_info *lwp_list;
642
643 /* Number of LWPs in the list.  */
644 static int num_lwps;
645
646 /* Non-zero if we're running in "threaded" mode.  */
647 static int threaded;
648 \f
649
650 #define GET_LWP(ptid)           ptid_get_lwp (ptid)
651 #define GET_PID(ptid)           ptid_get_pid (ptid)
652 #define is_lwp(ptid)            (GET_LWP (ptid) != 0)
653 #define BUILD_LWP(lwp, pid)     ptid_build (pid, lwp, 0)
654
655 /* If the last reported event was a SIGTRAP, this variable is set to
656    the process id of the LWP/thread that got it.  */
657 ptid_t trap_ptid;
658 \f
659
660 /* This module's target-specific operations.  */
661 static struct target_ops linux_nat_ops;
662
663 /* Since we cannot wait (in linux_nat_wait) for the initial process and
664    any cloned processes with a single call to waitpid, we have to use
665    the WNOHANG flag and call waitpid in a loop.  To optimize
666    things a bit we use `sigsuspend' to wake us up when a process has
667    something to report (it will send us a SIGCHLD if it has).  To make
668    this work we have to juggle with the signal mask.  We save the
669    original signal mask such that we can restore it before creating a
670    new process in order to avoid blocking certain signals in the
671    inferior.  We then block SIGCHLD during the waitpid/sigsuspend
672    loop.  */
673
674 /* Original signal mask.  */
675 static sigset_t normal_mask;
676
677 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
678    _initialize_linux_nat.  */
679 static sigset_t suspend_mask;
680
681 /* Signals to block to make that sigsuspend work.  */
682 static sigset_t blocked_mask;
683 \f
684
685 /* Prototypes for local functions.  */
686 static int stop_wait_callback (struct lwp_info *lp, void *data);
687 static int linux_nat_thread_alive (ptid_t ptid);
688 \f
689 /* Convert wait status STATUS to a string.  Used for printing debug
690    messages only.  */
691
692 static char *
693 status_to_str (int status)
694 {
695   static char buf[64];
696
697   if (WIFSTOPPED (status))
698     snprintf (buf, sizeof (buf), "%s (stopped)",
699               strsignal (WSTOPSIG (status)));
700   else if (WIFSIGNALED (status))
701     snprintf (buf, sizeof (buf), "%s (terminated)",
702               strsignal (WSTOPSIG (status)));
703   else
704     snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
705
706   return buf;
707 }
708
709 /* Initialize the list of LWPs.  Note that this module, contrary to
710    what GDB's generic threads layer does for its thread list,
711    re-initializes the LWP lists whenever we mourn or detach (which
712    doesn't involve mourning) the inferior.  */
713
714 static void
715 init_lwp_list (void)
716 {
717   struct lwp_info *lp, *lpnext;
718
719   for (lp = lwp_list; lp; lp = lpnext)
720     {
721       lpnext = lp->next;
722       xfree (lp);
723     }
724
725   lwp_list = NULL;
726   num_lwps = 0;
727   threaded = 0;
728 }
729
730 /* Add the LWP specified by PID to the list.  If this causes the
731    number of LWPs to become larger than one, go into "threaded" mode.
732    Return a pointer to the structure describing the new LWP.  */
733
734 static struct lwp_info *
735 add_lwp (ptid_t ptid)
736 {
737   struct lwp_info *lp;
738
739   gdb_assert (is_lwp (ptid));
740
741   lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
742
743   memset (lp, 0, sizeof (struct lwp_info));
744
745   lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
746
747   lp->ptid = ptid;
748
749   lp->next = lwp_list;
750   lwp_list = lp;
751   if (++num_lwps > 1)
752     threaded = 1;
753
754   return lp;
755 }
756
757 /* Remove the LWP specified by PID from the list.  */
758
759 static void
760 delete_lwp (ptid_t ptid)
761 {
762   struct lwp_info *lp, *lpprev;
763
764   lpprev = NULL;
765
766   for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
767     if (ptid_equal (lp->ptid, ptid))
768       break;
769
770   if (!lp)
771     return;
772
773   /* We don't go back to "non-threaded" mode if the number of threads
774      becomes less than two.  */
775   num_lwps--;
776
777   if (lpprev)
778     lpprev->next = lp->next;
779   else
780     lwp_list = lp->next;
781
782   xfree (lp);
783 }
784
785 /* Return a pointer to the structure describing the LWP corresponding
786    to PID.  If no corresponding LWP could be found, return NULL.  */
787
788 static struct lwp_info *
789 find_lwp_pid (ptid_t ptid)
790 {
791   struct lwp_info *lp;
792   int lwp;
793
794   if (is_lwp (ptid))
795     lwp = GET_LWP (ptid);
796   else
797     lwp = GET_PID (ptid);
798
799   for (lp = lwp_list; lp; lp = lp->next)
800     if (lwp == GET_LWP (lp->ptid))
801       return lp;
802
803   return NULL;
804 }
805
806 /* Call CALLBACK with its second argument set to DATA for every LWP in
807    the list.  If CALLBACK returns 1 for a particular LWP, return a
808    pointer to the structure describing that LWP immediately.
809    Otherwise return NULL.  */
810
811 struct lwp_info *
812 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
813 {
814   struct lwp_info *lp, *lpnext;
815
816   for (lp = lwp_list; lp; lp = lpnext)
817     {
818       lpnext = lp->next;
819       if ((*callback) (lp, data))
820         return lp;
821     }
822
823   return NULL;
824 }
825
826 /* Attach to the LWP specified by PID.  If VERBOSE is non-zero, print
827    a message telling the user that a new LWP has been added to the
828    process.  */
829
830 void
831 lin_lwp_attach_lwp (ptid_t ptid, int verbose)
832 {
833   struct lwp_info *lp, *found_lp;
834
835   gdb_assert (is_lwp (ptid));
836
837   /* Make sure SIGCHLD is blocked.  We don't want SIGCHLD events
838      to interrupt either the ptrace() or waitpid() calls below.  */
839   if (!sigismember (&blocked_mask, SIGCHLD))
840     {
841       sigaddset (&blocked_mask, SIGCHLD);
842       sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
843     }
844
845   if (verbose)
846     printf_filtered (_("[New %s]\n"), target_pid_to_str (ptid));
847
848   found_lp = lp = find_lwp_pid (ptid);
849   if (lp == NULL)
850     lp = add_lwp (ptid);
851
852   /* We assume that we're already attached to any LWP that has an id
853      equal to the overall process id, and to any LWP that is already
854      in our list of LWPs.  If we're not seeing exit events from threads
855      and we've had PID wraparound since we last tried to stop all threads,
856      this assumption might be wrong; fortunately, this is very unlikely
857      to happen.  */
858   if (GET_LWP (ptid) != GET_PID (ptid) && found_lp == NULL)
859     {
860       pid_t pid;
861       int status;
862
863       if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
864         error (_("Can't attach %s: %s"), target_pid_to_str (ptid),
865                safe_strerror (errno));
866
867       if (debug_linux_nat)
868         fprintf_unfiltered (gdb_stdlog,
869                             "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
870                             target_pid_to_str (ptid));
871
872       pid = my_waitpid (GET_LWP (ptid), &status, 0);
873       if (pid == -1 && errno == ECHILD)
874         {
875           /* Try again with __WCLONE to check cloned processes.  */
876           pid = my_waitpid (GET_LWP (ptid), &status, __WCLONE);
877           lp->cloned = 1;
878         }
879
880       gdb_assert (pid == GET_LWP (ptid)
881                   && WIFSTOPPED (status) && WSTOPSIG (status));
882
883       child_post_attach (pid);
884
885       lp->stopped = 1;
886
887       if (debug_linux_nat)
888         {
889           fprintf_unfiltered (gdb_stdlog,
890                               "LLAL: waitpid %s received %s\n",
891                               target_pid_to_str (ptid),
892                               status_to_str (status));
893         }
894     }
895   else
896     {
897       /* We assume that the LWP representing the original process is
898          already stopped.  Mark it as stopped in the data structure
899          that the linux ptrace layer uses to keep track of threads.
900          Note that this won't have already been done since the main
901          thread will have, we assume, been stopped by an attach from a
902          different layer.  */
903       lp->stopped = 1;
904     }
905 }
906
907 static void
908 linux_nat_attach (char *args, int from_tty)
909 {
910   struct lwp_info *lp;
911   pid_t pid;
912   int status;
913
914   /* FIXME: We should probably accept a list of process id's, and
915      attach all of them.  */
916   deprecated_child_ops.to_attach (args, from_tty);
917
918   /* Add the initial process as the first LWP to the list.  */
919   lp = add_lwp (BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid)));
920
921   /* Make sure the initial process is stopped.  The user-level threads
922      layer might want to poke around in the inferior, and that won't
923      work if things haven't stabilized yet.  */
924   pid = my_waitpid (GET_PID (inferior_ptid), &status, 0);
925   if (pid == -1 && errno == ECHILD)
926     {
927       warning (_("%s is a cloned process"), target_pid_to_str (inferior_ptid));
928
929       /* Try again with __WCLONE to check cloned processes.  */
930       pid = my_waitpid (GET_PID (inferior_ptid), &status, __WCLONE);
931       lp->cloned = 1;
932     }
933
934   gdb_assert (pid == GET_PID (inferior_ptid)
935               && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP);
936
937   lp->stopped = 1;
938
939   /* Fake the SIGSTOP that core GDB expects.  */
940   lp->status = W_STOPCODE (SIGSTOP);
941   lp->resumed = 1;
942   if (debug_linux_nat)
943     {
944       fprintf_unfiltered (gdb_stdlog,
945                           "LLA: waitpid %ld, faking SIGSTOP\n", (long) pid);
946     }
947 }
948
949 static int
950 detach_callback (struct lwp_info *lp, void *data)
951 {
952   gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
953
954   if (debug_linux_nat && lp->status)
955     fprintf_unfiltered (gdb_stdlog, "DC:  Pending %s for %s on detach.\n",
956                         strsignal (WSTOPSIG (lp->status)),
957                         target_pid_to_str (lp->ptid));
958
959   while (lp->signalled && lp->stopped)
960     {
961       errno = 0;
962       if (ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0,
963                   WSTOPSIG (lp->status)) < 0)
964         error (_("Can't continue %s: %s"), target_pid_to_str (lp->ptid),
965                safe_strerror (errno));
966
967       if (debug_linux_nat)
968         fprintf_unfiltered (gdb_stdlog,
969                             "DC:  PTRACE_CONTINUE (%s, 0, %s) (OK)\n",
970                             target_pid_to_str (lp->ptid),
971                             status_to_str (lp->status));
972
973       lp->stopped = 0;
974       lp->signalled = 0;
975       lp->status = 0;
976       /* FIXME drow/2003-08-26: There was a call to stop_wait_callback
977          here.  But since lp->signalled was cleared above,
978          stop_wait_callback didn't do anything; the process was left
979          running.  Shouldn't we be waiting for it to stop?
980          I've removed the call, since stop_wait_callback now does do
981          something when called with lp->signalled == 0.  */
982
983       gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
984     }
985
986   /* We don't actually detach from the LWP that has an id equal to the
987      overall process id just yet.  */
988   if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
989     {
990       errno = 0;
991       if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
992                   WSTOPSIG (lp->status)) < 0)
993         error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
994                safe_strerror (errno));
995
996       if (debug_linux_nat)
997         fprintf_unfiltered (gdb_stdlog,
998                             "PTRACE_DETACH (%s, %s, 0) (OK)\n",
999                             target_pid_to_str (lp->ptid),
1000                             strsignal (WSTOPSIG (lp->status)));
1001
1002       delete_lwp (lp->ptid);
1003     }
1004
1005   return 0;
1006 }
1007
1008 static void
1009 linux_nat_detach (char *args, int from_tty)
1010 {
1011   iterate_over_lwps (detach_callback, NULL);
1012
1013   /* Only the initial process should be left right now.  */
1014   gdb_assert (num_lwps == 1);
1015
1016   trap_ptid = null_ptid;
1017
1018   /* Destroy LWP info; it's no longer valid.  */
1019   init_lwp_list ();
1020
1021   /* Restore the original signal mask.  */
1022   sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1023   sigemptyset (&blocked_mask);
1024
1025   inferior_ptid = pid_to_ptid (GET_PID (inferior_ptid));
1026   deprecated_child_ops.to_detach (args, from_tty);
1027 }
1028
1029 /* Resume LP.  */
1030
1031 static int
1032 resume_callback (struct lwp_info *lp, void *data)
1033 {
1034   if (lp->stopped && lp->status == 0)
1035     {
1036       struct thread_info *tp;
1037
1038       child_resume (pid_to_ptid (GET_LWP (lp->ptid)), 0, TARGET_SIGNAL_0);
1039       if (debug_linux_nat)
1040         fprintf_unfiltered (gdb_stdlog,
1041                             "RC:  PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1042                             target_pid_to_str (lp->ptid));
1043       lp->stopped = 0;
1044       lp->step = 0;
1045     }
1046
1047   return 0;
1048 }
1049
1050 static int
1051 resume_clear_callback (struct lwp_info *lp, void *data)
1052 {
1053   lp->resumed = 0;
1054   return 0;
1055 }
1056
1057 static int
1058 resume_set_callback (struct lwp_info *lp, void *data)
1059 {
1060   lp->resumed = 1;
1061   return 0;
1062 }
1063
1064 static void
1065 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1066 {
1067   struct lwp_info *lp;
1068   int resume_all;
1069
1070   /* A specific PTID means `step only this process id'.  */
1071   resume_all = (PIDGET (ptid) == -1);
1072
1073   if (resume_all)
1074     iterate_over_lwps (resume_set_callback, NULL);
1075   else
1076     iterate_over_lwps (resume_clear_callback, NULL);
1077
1078   /* If PID is -1, it's the current inferior that should be
1079      handled specially.  */
1080   if (PIDGET (ptid) == -1)
1081     ptid = inferior_ptid;
1082
1083   lp = find_lwp_pid (ptid);
1084   if (lp)
1085     {
1086       ptid = pid_to_ptid (GET_LWP (lp->ptid));
1087
1088       /* Remember if we're stepping.  */
1089       lp->step = step;
1090
1091       /* Mark this LWP as resumed.  */
1092       lp->resumed = 1;
1093
1094       /* If we have a pending wait status for this thread, there is no
1095          point in resuming the process.  */
1096       if (lp->status)
1097         {
1098           /* FIXME: What should we do if we are supposed to continue
1099              this thread with a signal?  */
1100           gdb_assert (signo == TARGET_SIGNAL_0);
1101           return;
1102         }
1103
1104       /* Mark LWP as not stopped to prevent it from being continued by
1105          resume_callback.  */
1106       lp->stopped = 0;
1107     }
1108
1109   if (resume_all)
1110     iterate_over_lwps (resume_callback, NULL);
1111
1112   child_resume (ptid, step, signo);
1113   if (debug_linux_nat)
1114     fprintf_unfiltered (gdb_stdlog,
1115                         "LLR: %s %s, %s (resume event thread)\n",
1116                         step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1117                         target_pid_to_str (ptid),
1118                         signo ? strsignal (signo) : "0");
1119 }
1120
1121 /* Issue kill to specified lwp.  */
1122
1123 static int tkill_failed;
1124
1125 static int
1126 kill_lwp (int lwpid, int signo)
1127 {
1128   errno = 0;
1129
1130 /* Use tkill, if possible, in case we are using nptl threads.  If tkill
1131    fails, then we are not using nptl threads and we should be using kill.  */
1132
1133 #ifdef HAVE_TKILL_SYSCALL
1134   if (!tkill_failed)
1135     {
1136       int ret = syscall (__NR_tkill, lwpid, signo);
1137       if (errno != ENOSYS)
1138         return ret;
1139       errno = 0;
1140       tkill_failed = 1;
1141     }
1142 #endif
1143
1144   return kill (lwpid, signo);
1145 }
1146
1147 /* Handle a GNU/Linux extended wait response.  Most of the work we
1148    just pass off to linux_handle_extended_wait, but if it reports a
1149    clone event we need to add the new LWP to our list (and not report
1150    the trap to higher layers).  This function returns non-zero if
1151    the event should be ignored and we should wait again.  */
1152
1153 static int
1154 linux_nat_handle_extended (struct lwp_info *lp, int status)
1155 {
1156   linux_handle_extended_wait (GET_LWP (lp->ptid), status,
1157                               &lp->waitstatus);
1158
1159   /* TARGET_WAITKIND_SPURIOUS is used to indicate clone events.  */
1160   if (lp->waitstatus.kind == TARGET_WAITKIND_SPURIOUS)
1161     {
1162       struct lwp_info *new_lp;
1163       new_lp = add_lwp (BUILD_LWP (lp->waitstatus.value.related_pid,
1164                                    GET_PID (inferior_ptid)));
1165       new_lp->cloned = 1;
1166       new_lp->stopped = 1;
1167
1168       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
1169
1170       if (debug_linux_nat)
1171         fprintf_unfiltered (gdb_stdlog,
1172                             "LLHE: Got clone event from LWP %ld, resuming\n",
1173                             GET_LWP (lp->ptid));
1174       ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1175
1176       return 1;
1177     }
1178
1179   return 0;
1180 }
1181
1182 /* Wait for LP to stop.  Returns the wait status, or 0 if the LWP has
1183    exited.  */
1184
1185 static int
1186 wait_lwp (struct lwp_info *lp)
1187 {
1188   pid_t pid;
1189   int status;
1190   int thread_dead = 0;
1191
1192   gdb_assert (!lp->stopped);
1193   gdb_assert (lp->status == 0);
1194
1195   pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1196   if (pid == -1 && errno == ECHILD)
1197     {
1198       pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
1199       if (pid == -1 && errno == ECHILD)
1200         {
1201           /* The thread has previously exited.  We need to delete it
1202              now because, for some vendor 2.4 kernels with NPTL
1203              support backported, there won't be an exit event unless
1204              it is the main thread.  2.6 kernels will report an exit
1205              event for each thread that exits, as expected.  */
1206           thread_dead = 1;
1207           if (debug_linux_nat)
1208             fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1209                                 target_pid_to_str (lp->ptid));
1210         }
1211     }
1212
1213   if (!thread_dead)
1214     {
1215       gdb_assert (pid == GET_LWP (lp->ptid));
1216
1217       if (debug_linux_nat)
1218         {
1219           fprintf_unfiltered (gdb_stdlog,
1220                               "WL: waitpid %s received %s\n",
1221                               target_pid_to_str (lp->ptid),
1222                               status_to_str (status));
1223         }
1224     }
1225
1226   /* Check if the thread has exited.  */
1227   if (WIFEXITED (status) || WIFSIGNALED (status))
1228     {
1229       thread_dead = 1;
1230       if (debug_linux_nat)
1231         fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1232                             target_pid_to_str (lp->ptid));
1233     }
1234
1235   if (thread_dead)
1236     {
1237       if (in_thread_list (lp->ptid))
1238         {
1239           /* Core GDB cannot deal with us deleting the current thread.  */
1240           if (!ptid_equal (lp->ptid, inferior_ptid))
1241             delete_thread (lp->ptid);
1242           printf_unfiltered (_("[%s exited]\n"),
1243                              target_pid_to_str (lp->ptid));
1244         }
1245
1246       delete_lwp (lp->ptid);
1247       return 0;
1248     }
1249
1250   gdb_assert (WIFSTOPPED (status));
1251
1252   /* Handle GNU/Linux's extended waitstatus for trace events.  */
1253   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1254     {
1255       if (debug_linux_nat)
1256         fprintf_unfiltered (gdb_stdlog,
1257                             "WL: Handling extended status 0x%06x\n",
1258                             status);
1259       if (linux_nat_handle_extended (lp, status))
1260         return wait_lwp (lp);
1261     }
1262
1263   return status;
1264 }
1265
1266 /* Send a SIGSTOP to LP.  */
1267
1268 static int
1269 stop_callback (struct lwp_info *lp, void *data)
1270 {
1271   if (!lp->stopped && !lp->signalled)
1272     {
1273       int ret;
1274
1275       if (debug_linux_nat)
1276         {
1277           fprintf_unfiltered (gdb_stdlog,
1278                               "SC:  kill %s **<SIGSTOP>**\n",
1279                               target_pid_to_str (lp->ptid));
1280         }
1281       errno = 0;
1282       ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
1283       if (debug_linux_nat)
1284         {
1285           fprintf_unfiltered (gdb_stdlog,
1286                               "SC:  lwp kill %d %s\n",
1287                               ret,
1288                               errno ? safe_strerror (errno) : "ERRNO-OK");
1289         }
1290
1291       lp->signalled = 1;
1292       gdb_assert (lp->status == 0);
1293     }
1294
1295   return 0;
1296 }
1297
1298 /* Wait until LP is stopped.  If DATA is non-null it is interpreted as
1299    a pointer to a set of signals to be flushed immediately.  */
1300
1301 static int
1302 stop_wait_callback (struct lwp_info *lp, void *data)
1303 {
1304   sigset_t *flush_mask = data;
1305
1306   if (!lp->stopped)
1307     {
1308       int status;
1309
1310       status = wait_lwp (lp);
1311       if (status == 0)
1312         return 0;
1313
1314       /* Ignore any signals in FLUSH_MASK.  */
1315       if (flush_mask && sigismember (flush_mask, WSTOPSIG (status)))
1316         {
1317           if (!lp->signalled)
1318             {
1319               lp->stopped = 1;
1320               return 0;
1321             }
1322
1323           errno = 0;
1324           ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1325           if (debug_linux_nat)
1326             fprintf_unfiltered (gdb_stdlog,
1327                                 "PTRACE_CONT %s, 0, 0 (%s)\n",
1328                                 target_pid_to_str (lp->ptid),
1329                                 errno ? safe_strerror (errno) : "OK");
1330
1331           return stop_wait_callback (lp, flush_mask);
1332         }
1333
1334       if (WSTOPSIG (status) != SIGSTOP)
1335         {
1336           if (WSTOPSIG (status) == SIGTRAP)
1337             {
1338               /* If a LWP other than the LWP that we're reporting an
1339                  event for has hit a GDB breakpoint (as opposed to
1340                  some random trap signal), then just arrange for it to
1341                  hit it again later.  We don't keep the SIGTRAP status
1342                  and don't forward the SIGTRAP signal to the LWP.  We
1343                  will handle the current event, eventually we will
1344                  resume all LWPs, and this one will get its breakpoint
1345                  trap again.
1346
1347                  If we do not do this, then we run the risk that the
1348                  user will delete or disable the breakpoint, but the
1349                  thread will have already tripped on it.  */
1350
1351               /* Now resume this LWP and get the SIGSTOP event. */
1352               errno = 0;
1353               ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1354               if (debug_linux_nat)
1355                 {
1356                   fprintf_unfiltered (gdb_stdlog,
1357                                       "PTRACE_CONT %s, 0, 0 (%s)\n",
1358                                       target_pid_to_str (lp->ptid),
1359                                       errno ? safe_strerror (errno) : "OK");
1360
1361                   fprintf_unfiltered (gdb_stdlog,
1362                                       "SWC: Candidate SIGTRAP event in %s\n",
1363                                       target_pid_to_str (lp->ptid));
1364                 }
1365               /* Hold the SIGTRAP for handling by linux_nat_wait. */
1366               stop_wait_callback (lp, data);
1367               /* If there's another event, throw it back into the queue. */
1368               if (lp->status)
1369                 {
1370                   if (debug_linux_nat)
1371                     {
1372                       fprintf_unfiltered (gdb_stdlog,
1373                                           "SWC: kill %s, %s\n",
1374                                           target_pid_to_str (lp->ptid),
1375                                           status_to_str ((int) status));
1376                     }
1377                   kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
1378                 }
1379               /* Save the sigtrap event. */
1380               lp->status = status;
1381               return 0;
1382             }
1383           else
1384             {
1385               /* The thread was stopped with a signal other than
1386                  SIGSTOP, and didn't accidentally trip a breakpoint. */
1387
1388               if (debug_linux_nat)
1389                 {
1390                   fprintf_unfiltered (gdb_stdlog,
1391                                       "SWC: Pending event %s in %s\n",
1392                                       status_to_str ((int) status),
1393                                       target_pid_to_str (lp->ptid));
1394                 }
1395               /* Now resume this LWP and get the SIGSTOP event. */
1396               errno = 0;
1397               ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1398               if (debug_linux_nat)
1399                 fprintf_unfiltered (gdb_stdlog,
1400                                     "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
1401                                     target_pid_to_str (lp->ptid),
1402                                     errno ? safe_strerror (errno) : "OK");
1403
1404               /* Hold this event/waitstatus while we check to see if
1405                  there are any more (we still want to get that SIGSTOP). */
1406               stop_wait_callback (lp, data);
1407               /* If the lp->status field is still empty, use it to hold
1408                  this event.  If not, then this event must be returned
1409                  to the event queue of the LWP.  */
1410               if (lp->status == 0)
1411                 lp->status = status;
1412               else
1413                 {
1414                   if (debug_linux_nat)
1415                     {
1416                       fprintf_unfiltered (gdb_stdlog,
1417                                           "SWC: kill %s, %s\n",
1418                                           target_pid_to_str (lp->ptid),
1419                                           status_to_str ((int) status));
1420                     }
1421                   kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
1422                 }
1423               return 0;
1424             }
1425         }
1426       else
1427         {
1428           /* We caught the SIGSTOP that we intended to catch, so
1429              there's no SIGSTOP pending.  */
1430           lp->stopped = 1;
1431           lp->signalled = 0;
1432         }
1433     }
1434
1435   return 0;
1436 }
1437
1438 /* Check whether PID has any pending signals in FLUSH_MASK.  If so set
1439    the appropriate bits in PENDING, and return 1 - otherwise return 0.  */
1440
1441 static int
1442 linux_nat_has_pending (int pid, sigset_t *pending, sigset_t *flush_mask)
1443 {
1444   sigset_t blocked, ignored;
1445   int i;
1446
1447   linux_proc_pending_signals (pid, pending, &blocked, &ignored);
1448
1449   if (!flush_mask)
1450     return 0;
1451
1452   for (i = 1; i < NSIG; i++)
1453     if (sigismember (pending, i))
1454       if (!sigismember (flush_mask, i)
1455           || sigismember (&blocked, i)
1456           || sigismember (&ignored, i))
1457         sigdelset (pending, i);
1458
1459   if (sigisemptyset (pending))
1460     return 0;
1461
1462   return 1;
1463 }
1464
1465 /* DATA is interpreted as a mask of signals to flush.  If LP has
1466    signals pending, and they are all in the flush mask, then arrange
1467    to flush them.  LP should be stopped, as should all other threads
1468    it might share a signal queue with.  */
1469
1470 static int
1471 flush_callback (struct lwp_info *lp, void *data)
1472 {
1473   sigset_t *flush_mask = data;
1474   sigset_t pending, intersection, blocked, ignored;
1475   int pid, status;
1476
1477   /* Normally, when an LWP exits, it is removed from the LWP list.  The
1478      last LWP isn't removed till later, however.  So if there is only
1479      one LWP on the list, make sure it's alive.  */
1480   if (lwp_list == lp && lp->next == NULL)
1481     if (!linux_nat_thread_alive (lp->ptid))
1482       return 0;
1483
1484   /* Just because the LWP is stopped doesn't mean that new signals
1485      can't arrive from outside, so this function must be careful of
1486      race conditions.  However, because all threads are stopped, we
1487      can assume that the pending mask will not shrink unless we resume
1488      the LWP, and that it will then get another signal.  We can't
1489      control which one, however.  */
1490
1491   if (lp->status)
1492     {
1493       if (debug_linux_nat)
1494         printf_unfiltered (_("FC: LP has pending status %06x\n"), lp->status);
1495       if (WIFSTOPPED (lp->status) && sigismember (flush_mask, WSTOPSIG (lp->status)))
1496         lp->status = 0;
1497     }
1498
1499   while (linux_nat_has_pending (GET_LWP (lp->ptid), &pending, flush_mask))
1500     {
1501       int ret;
1502       
1503       errno = 0;
1504       ret = ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1505       if (debug_linux_nat)
1506         fprintf_unfiltered (gdb_stderr,
1507                             "FC: Sent PTRACE_CONT, ret %d %d\n", ret, errno);
1508
1509       lp->stopped = 0;
1510       stop_wait_callback (lp, flush_mask);
1511       if (debug_linux_nat)
1512         fprintf_unfiltered (gdb_stderr,
1513                             "FC: Wait finished; saved status is %d\n",
1514                             lp->status);
1515     }
1516
1517   return 0;
1518 }
1519
1520 /* Return non-zero if LP has a wait status pending.  */
1521
1522 static int
1523 status_callback (struct lwp_info *lp, void *data)
1524 {
1525   /* Only report a pending wait status if we pretend that this has
1526      indeed been resumed.  */
1527   return (lp->status != 0 && lp->resumed);
1528 }
1529
1530 /* Return non-zero if LP isn't stopped.  */
1531
1532 static int
1533 running_callback (struct lwp_info *lp, void *data)
1534 {
1535   return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
1536 }
1537
1538 /* Count the LWP's that have had events.  */
1539
1540 static int
1541 count_events_callback (struct lwp_info *lp, void *data)
1542 {
1543   int *count = data;
1544
1545   gdb_assert (count != NULL);
1546
1547   /* Count only LWPs that have a SIGTRAP event pending.  */
1548   if (lp->status != 0
1549       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1550     (*count)++;
1551
1552   return 0;
1553 }
1554
1555 /* Select the LWP (if any) that is currently being single-stepped.  */
1556
1557 static int
1558 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
1559 {
1560   if (lp->step && lp->status != 0)
1561     return 1;
1562   else
1563     return 0;
1564 }
1565
1566 /* Select the Nth LWP that has had a SIGTRAP event.  */
1567
1568 static int
1569 select_event_lwp_callback (struct lwp_info *lp, void *data)
1570 {
1571   int *selector = data;
1572
1573   gdb_assert (selector != NULL);
1574
1575   /* Select only LWPs that have a SIGTRAP event pending. */
1576   if (lp->status != 0
1577       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
1578     if ((*selector)-- == 0)
1579       return 1;
1580
1581   return 0;
1582 }
1583
1584 static int
1585 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
1586 {
1587   struct lwp_info *event_lp = data;
1588
1589   /* Leave the LWP that has been elected to receive a SIGTRAP alone.  */
1590   if (lp == event_lp)
1591     return 0;
1592
1593   /* If a LWP other than the LWP that we're reporting an event for has
1594      hit a GDB breakpoint (as opposed to some random trap signal),
1595      then just arrange for it to hit it again later.  We don't keep
1596      the SIGTRAP status and don't forward the SIGTRAP signal to the
1597      LWP.  We will handle the current event, eventually we will resume
1598      all LWPs, and this one will get its breakpoint trap again.
1599
1600      If we do not do this, then we run the risk that the user will
1601      delete or disable the breakpoint, but the LWP will have already
1602      tripped on it.  */
1603
1604   if (lp->status != 0
1605       && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
1606       && breakpoint_inserted_here_p (read_pc_pid (lp->ptid) -
1607                                      DECR_PC_AFTER_BREAK))
1608     {
1609       if (debug_linux_nat)
1610         fprintf_unfiltered (gdb_stdlog,
1611                             "CBC: Push back breakpoint for %s\n",
1612                             target_pid_to_str (lp->ptid));
1613
1614       /* Back up the PC if necessary.  */
1615       if (DECR_PC_AFTER_BREAK)
1616         write_pc_pid (read_pc_pid (lp->ptid) - DECR_PC_AFTER_BREAK, lp->ptid);
1617
1618       /* Throw away the SIGTRAP.  */
1619       lp->status = 0;
1620     }
1621
1622   return 0;
1623 }
1624
1625 /* Select one LWP out of those that have events pending.  */
1626
1627 static void
1628 select_event_lwp (struct lwp_info **orig_lp, int *status)
1629 {
1630   int num_events = 0;
1631   int random_selector;
1632   struct lwp_info *event_lp;
1633
1634   /* Record the wait status for the origional LWP.  */
1635   (*orig_lp)->status = *status;
1636
1637   /* Give preference to any LWP that is being single-stepped.  */
1638   event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
1639   if (event_lp != NULL)
1640     {
1641       if (debug_linux_nat)
1642         fprintf_unfiltered (gdb_stdlog,
1643                             "SEL: Select single-step %s\n",
1644                             target_pid_to_str (event_lp->ptid));
1645     }
1646   else
1647     {
1648       /* No single-stepping LWP.  Select one at random, out of those
1649          which have had SIGTRAP events.  */
1650
1651       /* First see how many SIGTRAP events we have.  */
1652       iterate_over_lwps (count_events_callback, &num_events);
1653
1654       /* Now randomly pick a LWP out of those that have had a SIGTRAP.  */
1655       random_selector = (int)
1656         ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
1657
1658       if (debug_linux_nat && num_events > 1)
1659         fprintf_unfiltered (gdb_stdlog,
1660                             "SEL: Found %d SIGTRAP events, selecting #%d\n",
1661                             num_events, random_selector);
1662
1663       event_lp = iterate_over_lwps (select_event_lwp_callback,
1664                                     &random_selector);
1665     }
1666
1667   if (event_lp != NULL)
1668     {
1669       /* Switch the event LWP.  */
1670       *orig_lp = event_lp;
1671       *status = event_lp->status;
1672     }
1673
1674   /* Flush the wait status for the event LWP.  */
1675   (*orig_lp)->status = 0;
1676 }
1677
1678 /* Return non-zero if LP has been resumed.  */
1679
1680 static int
1681 resumed_callback (struct lwp_info *lp, void *data)
1682 {
1683   return lp->resumed;
1684 }
1685
1686 #ifdef CHILD_WAIT
1687
1688 /* We need to override child_wait to support attaching to cloned
1689    processes, since a normal wait (as done by the default version)
1690    ignores those processes.  */
1691
1692 /* Wait for child PTID to do something.  Return id of the child,
1693    minus_one_ptid in case of error; store status into *OURSTATUS.  */
1694
1695 ptid_t
1696 child_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1697 {
1698   int save_errno;
1699   int status;
1700   pid_t pid;
1701
1702   ourstatus->kind = TARGET_WAITKIND_IGNORE;
1703
1704   do
1705     {
1706       set_sigint_trap ();       /* Causes SIGINT to be passed on to the
1707                                    attached process.  */
1708       set_sigio_trap ();
1709
1710       pid = my_waitpid (GET_PID (ptid), &status, 0);
1711       if (pid == -1 && errno == ECHILD)
1712         /* Try again with __WCLONE to check cloned processes.  */
1713         pid = my_waitpid (GET_PID (ptid), &status, __WCLONE);
1714
1715       if (debug_linux_nat)
1716         {
1717           fprintf_unfiltered (gdb_stdlog,
1718                               "CW:  waitpid %ld received %s\n",
1719                               (long) pid, status_to_str (status));
1720         }
1721
1722       save_errno = errno;
1723
1724       /* Make sure we don't report an event for the exit of the
1725          original program, if we've detached from it.  */
1726       if (pid != -1 && !WIFSTOPPED (status) && pid != GET_PID (inferior_ptid))
1727         {
1728           pid = -1;
1729           save_errno = EINTR;
1730         }
1731
1732       /* Check for stop events reported by a process we didn't already
1733          know about - in this case, anything other than inferior_ptid.
1734
1735          If we're expecting to receive stopped processes after fork,
1736          vfork, and clone events, then we'll just add the new one to
1737          our list and go back to waiting for the event to be reported
1738          - the stopped process might be returned from waitpid before
1739          or after the event is.  If we want to handle debugging of
1740          CLONE_PTRACE processes we need to do more here, i.e. switch
1741          to multi-threaded mode.  */
1742       if (pid != -1 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP
1743           && pid != GET_PID (inferior_ptid))
1744         {
1745           linux_record_stopped_pid (pid);
1746           pid = -1;
1747           save_errno = EINTR;
1748         }
1749
1750       /* Handle GNU/Linux's extended waitstatus for trace events.  */
1751       if (pid != -1 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP
1752           && status >> 16 != 0)
1753         {
1754           linux_handle_extended_wait (pid, status, ourstatus);
1755
1756           /* If we see a clone event, detach the child, and don't
1757              report the event.  It would be nice to offer some way to
1758              switch into a non-thread-db based threaded mode at this
1759              point.  */
1760           if (ourstatus->kind == TARGET_WAITKIND_SPURIOUS)
1761             {
1762               ptrace (PTRACE_DETACH, ourstatus->value.related_pid, 0, 0);
1763               ourstatus->kind = TARGET_WAITKIND_IGNORE;
1764               ptrace (PTRACE_CONT, pid, 0, 0);
1765               pid = -1;
1766               save_errno = EINTR;
1767             }
1768         }
1769
1770       clear_sigio_trap ();
1771       clear_sigint_trap ();
1772     }
1773   while (pid == -1 && save_errno == EINTR);
1774
1775   if (pid == -1)
1776     {
1777       warning (_("Child process unexpectedly missing: %s"),
1778                safe_strerror (errno));
1779
1780       /* Claim it exited with unknown signal.  */
1781       ourstatus->kind = TARGET_WAITKIND_SIGNALLED;
1782       ourstatus->value.sig = TARGET_SIGNAL_UNKNOWN;
1783       return minus_one_ptid;
1784     }
1785
1786   if (ourstatus->kind == TARGET_WAITKIND_IGNORE)
1787     store_waitstatus (ourstatus, status);
1788
1789   return pid_to_ptid (pid);
1790 }
1791
1792 #endif
1793
1794 /* Stop an active thread, verify it still exists, then resume it.  */
1795
1796 static int
1797 stop_and_resume_callback (struct lwp_info *lp, void *data)
1798 {
1799   struct lwp_info *ptr;
1800
1801   if (!lp->stopped && !lp->signalled)
1802     {
1803       stop_callback (lp, NULL);
1804       stop_wait_callback (lp, NULL);
1805       /* Resume if the lwp still exists.  */
1806       for (ptr = lwp_list; ptr; ptr = ptr->next)
1807         if (lp == ptr)
1808           {
1809             resume_callback (lp, NULL);
1810             resume_set_callback (lp, NULL);
1811           }
1812     }
1813   return 0;
1814 }
1815
1816 static ptid_t
1817 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
1818 {
1819   struct lwp_info *lp = NULL;
1820   int options = 0;
1821   int status = 0;
1822   pid_t pid = PIDGET (ptid);
1823   sigset_t flush_mask;
1824
1825   sigemptyset (&flush_mask);
1826
1827   /* Make sure SIGCHLD is blocked.  */
1828   if (!sigismember (&blocked_mask, SIGCHLD))
1829     {
1830       sigaddset (&blocked_mask, SIGCHLD);
1831       sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
1832     }
1833
1834 retry:
1835
1836   /* Make sure there is at least one LWP that has been resumed, at
1837      least if there are any LWPs at all.  */
1838   gdb_assert (num_lwps == 0 || iterate_over_lwps (resumed_callback, NULL));
1839
1840   /* First check if there is a LWP with a wait status pending.  */
1841   if (pid == -1)
1842     {
1843       /* Any LWP that's been resumed will do.  */
1844       lp = iterate_over_lwps (status_callback, NULL);
1845       if (lp)
1846         {
1847           status = lp->status;
1848           lp->status = 0;
1849
1850           if (debug_linux_nat && status)
1851             fprintf_unfiltered (gdb_stdlog,
1852                                 "LLW: Using pending wait status %s for %s.\n",
1853                                 status_to_str (status),
1854                                 target_pid_to_str (lp->ptid));
1855         }
1856
1857       /* But if we don't fine one, we'll have to wait, and check both
1858          cloned and uncloned processes.  We start with the cloned
1859          processes.  */
1860       options = __WCLONE | WNOHANG;
1861     }
1862   else if (is_lwp (ptid))
1863     {
1864       if (debug_linux_nat)
1865         fprintf_unfiltered (gdb_stdlog,
1866                             "LLW: Waiting for specific LWP %s.\n",
1867                             target_pid_to_str (ptid));
1868
1869       /* We have a specific LWP to check.  */
1870       lp = find_lwp_pid (ptid);
1871       gdb_assert (lp);
1872       status = lp->status;
1873       lp->status = 0;
1874
1875       if (debug_linux_nat && status)
1876         fprintf_unfiltered (gdb_stdlog,
1877                             "LLW: Using pending wait status %s for %s.\n",
1878                             status_to_str (status),
1879                             target_pid_to_str (lp->ptid));
1880
1881       /* If we have to wait, take into account whether PID is a cloned
1882          process or not.  And we have to convert it to something that
1883          the layer beneath us can understand.  */
1884       options = lp->cloned ? __WCLONE : 0;
1885       pid = GET_LWP (ptid);
1886     }
1887
1888   if (status && lp->signalled)
1889     {
1890       /* A pending SIGSTOP may interfere with the normal stream of
1891          events.  In a typical case where interference is a problem,
1892          we have a SIGSTOP signal pending for LWP A while
1893          single-stepping it, encounter an event in LWP B, and take the
1894          pending SIGSTOP while trying to stop LWP A.  After processing
1895          the event in LWP B, LWP A is continued, and we'll never see
1896          the SIGTRAP associated with the last time we were
1897          single-stepping LWP A.  */
1898
1899       /* Resume the thread.  It should halt immediately returning the
1900          pending SIGSTOP.  */
1901       registers_changed ();
1902       child_resume (pid_to_ptid (GET_LWP (lp->ptid)), lp->step,
1903                     TARGET_SIGNAL_0);
1904       if (debug_linux_nat)
1905         fprintf_unfiltered (gdb_stdlog,
1906                             "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
1907                             lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1908                             target_pid_to_str (lp->ptid));
1909       lp->stopped = 0;
1910       gdb_assert (lp->resumed);
1911
1912       /* This should catch the pending SIGSTOP.  */
1913       stop_wait_callback (lp, NULL);
1914     }
1915
1916   set_sigint_trap ();           /* Causes SIGINT to be passed on to the
1917                                    attached process. */
1918   set_sigio_trap ();
1919
1920   while (status == 0)
1921     {
1922       pid_t lwpid;
1923
1924       lwpid = my_waitpid (pid, &status, options);
1925       if (lwpid > 0)
1926         {
1927           gdb_assert (pid == -1 || lwpid == pid);
1928
1929           if (debug_linux_nat)
1930             {
1931               fprintf_unfiltered (gdb_stdlog,
1932                                   "LLW: waitpid %ld received %s\n",
1933                                   (long) lwpid, status_to_str (status));
1934             }
1935
1936           lp = find_lwp_pid (pid_to_ptid (lwpid));
1937
1938           /* Check for stop events reported by a process we didn't
1939              already know about - anything not already in our LWP
1940              list.
1941
1942              If we're expecting to receive stopped processes after
1943              fork, vfork, and clone events, then we'll just add the
1944              new one to our list and go back to waiting for the event
1945              to be reported - the stopped process might be returned
1946              from waitpid before or after the event is.  */
1947           if (WIFSTOPPED (status) && !lp)
1948             {
1949               linux_record_stopped_pid (lwpid);
1950               status = 0;
1951               continue;
1952             }
1953
1954           /* Make sure we don't report an event for the exit of an LWP not in
1955              our list, i.e.  not part of the current process.  This can happen
1956              if we detach from a program we original forked and then it
1957              exits.  */
1958           if (!WIFSTOPPED (status) && !lp)
1959             {
1960               status = 0;
1961               continue;
1962             }
1963
1964           /* NOTE drow/2003-06-17: This code seems to be meant for debugging
1965              CLONE_PTRACE processes which do not use the thread library -
1966              otherwise we wouldn't find the new LWP this way.  That doesn't
1967              currently work, and the following code is currently unreachable
1968              due to the two blocks above.  If it's fixed some day, this code
1969              should be broken out into a function so that we can also pick up
1970              LWPs from the new interface.  */
1971           if (!lp)
1972             {
1973               lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
1974               if (options & __WCLONE)
1975                 lp->cloned = 1;
1976
1977               if (threaded)
1978                 {
1979                   gdb_assert (WIFSTOPPED (status)
1980                               && WSTOPSIG (status) == SIGSTOP);
1981                   lp->signalled = 1;
1982
1983                   if (!in_thread_list (inferior_ptid))
1984                     {
1985                       inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
1986                                                  GET_PID (inferior_ptid));
1987                       add_thread (inferior_ptid);
1988                     }
1989
1990                   add_thread (lp->ptid);
1991                   printf_unfiltered (_("[New %s]\n"),
1992                                      target_pid_to_str (lp->ptid));
1993                 }
1994             }
1995
1996           /* Handle GNU/Linux's extended waitstatus for trace events.  */
1997           if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1998             {
1999               if (debug_linux_nat)
2000                 fprintf_unfiltered (gdb_stdlog,
2001                                     "LLW: Handling extended status 0x%06x\n",
2002                                     status);
2003               if (linux_nat_handle_extended (lp, status))
2004                 {
2005                   status = 0;
2006                   continue;
2007                 }
2008             }
2009
2010           /* Check if the thread has exited.  */
2011           if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2012             {
2013               if (in_thread_list (lp->ptid))
2014                 {
2015                   /* Core GDB cannot deal with us deleting the current
2016                      thread.  */
2017                   if (!ptid_equal (lp->ptid, inferior_ptid))
2018                     delete_thread (lp->ptid);
2019                   printf_unfiltered (_("[%s exited]\n"),
2020                                      target_pid_to_str (lp->ptid));
2021                 }
2022
2023               /* If this is the main thread, we must stop all threads and
2024                  verify if they are still alive.  This is because in the nptl
2025                  thread model, there is no signal issued for exiting LWPs
2026                  other than the main thread.  We only get the main thread
2027                  exit signal once all child threads have already exited.
2028                  If we stop all the threads and use the stop_wait_callback
2029                  to check if they have exited we can determine whether this
2030                  signal should be ignored or whether it means the end of the
2031                  debugged application, regardless of which threading model
2032                  is being used.  */
2033               if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2034                 {
2035                   lp->stopped = 1;
2036                   iterate_over_lwps (stop_and_resume_callback, NULL);
2037                 }
2038
2039               if (debug_linux_nat)
2040                 fprintf_unfiltered (gdb_stdlog,
2041                                     "LLW: %s exited.\n",
2042                                     target_pid_to_str (lp->ptid));
2043
2044               delete_lwp (lp->ptid);
2045
2046               /* If there is at least one more LWP, then the exit signal
2047                  was not the end of the debugged application and should be
2048                  ignored.  */
2049               if (num_lwps > 0)
2050                 {
2051                   /* Make sure there is at least one thread running.  */
2052                   gdb_assert (iterate_over_lwps (running_callback, NULL));
2053
2054                   /* Discard the event.  */
2055                   status = 0;
2056                   continue;
2057                 }
2058             }
2059
2060           /* Check if the current LWP has previously exited.  In the nptl
2061              thread model, LWPs other than the main thread do not issue
2062              signals when they exit so we must check whenever the thread
2063              has stopped.  A similar check is made in stop_wait_callback().  */
2064           if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2065             {
2066               if (in_thread_list (lp->ptid))
2067                 {
2068                   /* Core GDB cannot deal with us deleting the current
2069                      thread.  */
2070                   if (!ptid_equal (lp->ptid, inferior_ptid))
2071                     delete_thread (lp->ptid);
2072                   printf_unfiltered (_("[%s exited]\n"),
2073                                      target_pid_to_str (lp->ptid));
2074                 }
2075               if (debug_linux_nat)
2076                 fprintf_unfiltered (gdb_stdlog,
2077                                     "LLW: %s exited.\n",
2078                                     target_pid_to_str (lp->ptid));
2079
2080               delete_lwp (lp->ptid);
2081
2082               /* Make sure there is at least one thread running.  */
2083               gdb_assert (iterate_over_lwps (running_callback, NULL));
2084
2085               /* Discard the event.  */
2086               status = 0;
2087               continue;
2088             }
2089
2090           /* Make sure we don't report a SIGSTOP that we sent
2091              ourselves in an attempt to stop an LWP.  */
2092           if (lp->signalled
2093               && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2094             {
2095               if (debug_linux_nat)
2096                 fprintf_unfiltered (gdb_stdlog,
2097                                     "LLW: Delayed SIGSTOP caught for %s.\n",
2098                                     target_pid_to_str (lp->ptid));
2099
2100               /* This is a delayed SIGSTOP.  */
2101               lp->signalled = 0;
2102
2103               registers_changed ();
2104               child_resume (pid_to_ptid (GET_LWP (lp->ptid)), lp->step,
2105                             TARGET_SIGNAL_0);
2106               if (debug_linux_nat)
2107                 fprintf_unfiltered (gdb_stdlog,
2108                                     "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2109                                     lp->step ?
2110                                     "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2111                                     target_pid_to_str (lp->ptid));
2112
2113               lp->stopped = 0;
2114               gdb_assert (lp->resumed);
2115
2116               /* Discard the event.  */
2117               status = 0;
2118               continue;
2119             }
2120
2121           break;
2122         }
2123
2124       if (pid == -1)
2125         {
2126           /* Alternate between checking cloned and uncloned processes.  */
2127           options ^= __WCLONE;
2128
2129           /* And suspend every time we have checked both.  */
2130           if (options & __WCLONE)
2131             sigsuspend (&suspend_mask);
2132         }
2133
2134       /* We shouldn't end up here unless we want to try again.  */
2135       gdb_assert (status == 0);
2136     }
2137
2138   clear_sigio_trap ();
2139   clear_sigint_trap ();
2140
2141   gdb_assert (lp);
2142
2143   /* Don't report signals that GDB isn't interested in, such as
2144      signals that are neither printed nor stopped upon.  Stopping all
2145      threads can be a bit time-consuming so if we want decent
2146      performance with heavily multi-threaded programs, especially when
2147      they're using a high frequency timer, we'd better avoid it if we
2148      can.  */
2149
2150   if (WIFSTOPPED (status))
2151     {
2152       int signo = target_signal_from_host (WSTOPSIG (status));
2153
2154       if (signal_stop_state (signo) == 0
2155           && signal_print_state (signo) == 0
2156           && signal_pass_state (signo) == 1)
2157         {
2158           /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2159              here?  It is not clear we should.  GDB may not expect
2160              other threads to run.  On the other hand, not resuming
2161              newly attached threads may cause an unwanted delay in
2162              getting them running.  */
2163           registers_changed ();
2164           child_resume (pid_to_ptid (GET_LWP (lp->ptid)), lp->step, signo);
2165           if (debug_linux_nat)
2166             fprintf_unfiltered (gdb_stdlog,
2167                                 "LLW: %s %s, %s (preempt 'handle')\n",
2168                                 lp->step ?
2169                                 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2170                                 target_pid_to_str (lp->ptid),
2171                                 signo ? strsignal (signo) : "0");
2172           lp->stopped = 0;
2173           status = 0;
2174           goto retry;
2175         }
2176
2177       if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2178         {
2179           /* If ^C/BREAK is typed at the tty/console, SIGINT gets
2180              forwarded to the entire process group, that is, all LWP's
2181              will receive it.  Since we only want to report it once,
2182              we try to flush it from all LWPs except this one.  */
2183           sigaddset (&flush_mask, SIGINT);
2184         }
2185     }
2186
2187   /* This LWP is stopped now.  */
2188   lp->stopped = 1;
2189
2190   if (debug_linux_nat)
2191     fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
2192                         status_to_str (status), target_pid_to_str (lp->ptid));
2193
2194   /* Now stop all other LWP's ...  */
2195   iterate_over_lwps (stop_callback, NULL);
2196
2197   /* ... and wait until all of them have reported back that they're no
2198      longer running.  */
2199   iterate_over_lwps (stop_wait_callback, &flush_mask);
2200   iterate_over_lwps (flush_callback, &flush_mask);
2201
2202   /* If we're not waiting for a specific LWP, choose an event LWP from
2203      among those that have had events.  Giving equal priority to all
2204      LWPs that have had events helps prevent starvation.  */
2205   if (pid == -1)
2206     select_event_lwp (&lp, &status);
2207
2208   /* Now that we've selected our final event LWP, cancel any
2209      breakpoints in other LWPs that have hit a GDB breakpoint.  See
2210      the comment in cancel_breakpoints_callback to find out why.  */
2211   iterate_over_lwps (cancel_breakpoints_callback, lp);
2212
2213   /* If we're not running in "threaded" mode, we'll report the bare
2214      process id.  */
2215
2216   if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2217     {
2218       trap_ptid = (threaded ? lp->ptid : pid_to_ptid (GET_LWP (lp->ptid)));
2219       if (debug_linux_nat)
2220         fprintf_unfiltered (gdb_stdlog,
2221                             "LLW: trap_ptid is %s.\n",
2222                             target_pid_to_str (trap_ptid));
2223     }
2224   else
2225     trap_ptid = null_ptid;
2226
2227   if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2228     {
2229       *ourstatus = lp->waitstatus;
2230       lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
2231     }
2232   else
2233     store_waitstatus (ourstatus, status);
2234
2235   return (threaded ? lp->ptid : pid_to_ptid (GET_LWP (lp->ptid)));
2236 }
2237
2238 static int
2239 kill_callback (struct lwp_info *lp, void *data)
2240 {
2241   errno = 0;
2242   ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
2243   if (debug_linux_nat)
2244     fprintf_unfiltered (gdb_stdlog,
2245                         "KC:  PTRACE_KILL %s, 0, 0 (%s)\n",
2246                         target_pid_to_str (lp->ptid),
2247                         errno ? safe_strerror (errno) : "OK");
2248
2249   return 0;
2250 }
2251
2252 static int
2253 kill_wait_callback (struct lwp_info *lp, void *data)
2254 {
2255   pid_t pid;
2256
2257   /* We must make sure that there are no pending events (delayed
2258      SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
2259      program doesn't interfere with any following debugging session.  */
2260
2261   /* For cloned processes we must check both with __WCLONE and
2262      without, since the exit status of a cloned process isn't reported
2263      with __WCLONE.  */
2264   if (lp->cloned)
2265     {
2266       do
2267         {
2268           pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
2269           if (pid != (pid_t) -1 && debug_linux_nat)
2270             {
2271               fprintf_unfiltered (gdb_stdlog,
2272                                   "KWC: wait %s received unknown.\n",
2273                                   target_pid_to_str (lp->ptid));
2274             }
2275         }
2276       while (pid == GET_LWP (lp->ptid));
2277
2278       gdb_assert (pid == -1 && errno == ECHILD);
2279     }
2280
2281   do
2282     {
2283       pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
2284       if (pid != (pid_t) -1 && debug_linux_nat)
2285         {
2286           fprintf_unfiltered (gdb_stdlog,
2287                               "KWC: wait %s received unk.\n",
2288                               target_pid_to_str (lp->ptid));
2289         }
2290     }
2291   while (pid == GET_LWP (lp->ptid));
2292
2293   gdb_assert (pid == -1 && errno == ECHILD);
2294   return 0;
2295 }
2296
2297 static void
2298 linux_nat_kill (void)
2299 {
2300   /* Kill all LWP's ...  */
2301   iterate_over_lwps (kill_callback, NULL);
2302
2303   /* ... and wait until we've flushed all events.  */
2304   iterate_over_lwps (kill_wait_callback, NULL);
2305
2306   target_mourn_inferior ();
2307 }
2308
2309 static void
2310 linux_nat_create_inferior (char *exec_file, char *allargs, char **env,
2311                          int from_tty)
2312 {
2313   deprecated_child_ops.to_create_inferior (exec_file, allargs, env, from_tty);
2314 }
2315
2316 static void
2317 linux_nat_mourn_inferior (void)
2318 {
2319   trap_ptid = null_ptid;
2320
2321   /* Destroy LWP info; it's no longer valid.  */
2322   init_lwp_list ();
2323
2324   /* Restore the original signal mask.  */
2325   sigprocmask (SIG_SETMASK, &normal_mask, NULL);
2326   sigemptyset (&blocked_mask);
2327
2328   deprecated_child_ops.to_mourn_inferior ();
2329 }
2330
2331 static int
2332 linux_nat_xfer_memory (CORE_ADDR memaddr, gdb_byte *myaddr, int len,
2333                        int write, struct mem_attrib *attrib,
2334                        struct target_ops *target)
2335 {
2336   struct cleanup *old_chain = save_inferior_ptid ();
2337   int xfer;
2338
2339   if (is_lwp (inferior_ptid))
2340     inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
2341
2342   xfer = linux_proc_xfer_memory (memaddr, myaddr, len, write, attrib, target);
2343   if (xfer == 0)
2344     xfer = child_xfer_memory (memaddr, myaddr, len, write, attrib, target);
2345
2346   do_cleanups (old_chain);
2347   return xfer;
2348 }
2349
2350 static int
2351 linux_nat_thread_alive (ptid_t ptid)
2352 {
2353   gdb_assert (is_lwp (ptid));
2354
2355   errno = 0;
2356   ptrace (PTRACE_PEEKUSER, GET_LWP (ptid), 0, 0);
2357   if (debug_linux_nat)
2358     fprintf_unfiltered (gdb_stdlog,
2359                         "LLTA: PTRACE_PEEKUSER %s, 0, 0 (%s)\n",
2360                         target_pid_to_str (ptid),
2361                         errno ? safe_strerror (errno) : "OK");
2362   if (errno)
2363     return 0;
2364
2365   return 1;
2366 }
2367
2368 static char *
2369 linux_nat_pid_to_str (ptid_t ptid)
2370 {
2371   static char buf[64];
2372
2373   if (is_lwp (ptid))
2374     {
2375       snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
2376       return buf;
2377     }
2378
2379   return normal_pid_to_str (ptid);
2380 }
2381
2382 static void
2383 init_linux_nat_ops (void)
2384 {
2385 #if 0
2386   linux_nat_ops.to_open = linux_nat_open;
2387 #endif
2388   linux_nat_ops.to_shortname = "lwp-layer";
2389   linux_nat_ops.to_longname = "lwp-layer";
2390   linux_nat_ops.to_doc = "Low level threads support (LWP layer)";
2391   linux_nat_ops.to_attach = linux_nat_attach;
2392   linux_nat_ops.to_detach = linux_nat_detach;
2393   linux_nat_ops.to_resume = linux_nat_resume;
2394   linux_nat_ops.to_wait = linux_nat_wait;
2395   /* fetch_inferior_registers and store_inferior_registers will
2396      honor the LWP id, so we can use them directly.  */
2397   linux_nat_ops.to_fetch_registers = fetch_inferior_registers;
2398   linux_nat_ops.to_store_registers = store_inferior_registers;
2399   linux_nat_ops.deprecated_xfer_memory = linux_nat_xfer_memory;
2400   linux_nat_ops.to_kill = linux_nat_kill;
2401   linux_nat_ops.to_create_inferior = linux_nat_create_inferior;
2402   linux_nat_ops.to_mourn_inferior = linux_nat_mourn_inferior;
2403   linux_nat_ops.to_thread_alive = linux_nat_thread_alive;
2404   linux_nat_ops.to_pid_to_str = linux_nat_pid_to_str;
2405   linux_nat_ops.to_post_startup_inferior = child_post_startup_inferior;
2406   linux_nat_ops.to_post_attach = child_post_attach;
2407   linux_nat_ops.to_insert_fork_catchpoint = child_insert_fork_catchpoint;
2408   linux_nat_ops.to_insert_vfork_catchpoint = child_insert_vfork_catchpoint;
2409   linux_nat_ops.to_insert_exec_catchpoint = child_insert_exec_catchpoint;
2410
2411   linux_nat_ops.to_stratum = thread_stratum;
2412   linux_nat_ops.to_has_thread_control = tc_schedlock;
2413   linux_nat_ops.to_magic = OPS_MAGIC;
2414 }
2415
2416 static void
2417 sigchld_handler (int signo)
2418 {
2419   /* Do nothing.  The only reason for this handler is that it allows
2420      us to use sigsuspend in linux_nat_wait above to wait for the
2421      arrival of a SIGCHLD.  */
2422 }
2423
2424 /* Accepts an integer PID; Returns a string representing a file that
2425    can be opened to get the symbols for the child process.  */
2426
2427 char *
2428 child_pid_to_exec_file (int pid)
2429 {
2430   char *name1, *name2;
2431
2432   name1 = xmalloc (MAXPATHLEN);
2433   name2 = xmalloc (MAXPATHLEN);
2434   make_cleanup (xfree, name1);
2435   make_cleanup (xfree, name2);
2436   memset (name2, 0, MAXPATHLEN);
2437
2438   sprintf (name1, "/proc/%d/exe", pid);
2439   if (readlink (name1, name2, MAXPATHLEN) > 0)
2440     return name2;
2441   else
2442     return name1;
2443 }
2444
2445 /* Service function for corefiles and info proc.  */
2446
2447 static int
2448 read_mapping (FILE *mapfile,
2449               long long *addr,
2450               long long *endaddr,
2451               char *permissions,
2452               long long *offset,
2453               char *device, long long *inode, char *filename)
2454 {
2455   int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
2456                     addr, endaddr, permissions, offset, device, inode);
2457
2458   filename[0] = '\0';
2459   if (ret > 0 && ret != EOF)
2460     {
2461       /* Eat everything up to EOL for the filename.  This will prevent
2462          weird filenames (such as one with embedded whitespace) from
2463          confusing this code.  It also makes this code more robust in
2464          respect to annotations the kernel may add after the filename.
2465
2466          Note the filename is used for informational purposes
2467          only.  */
2468       ret += fscanf (mapfile, "%[^\n]\n", filename);
2469     }
2470
2471   return (ret != 0 && ret != EOF);
2472 }
2473
2474 /* Fills the "to_find_memory_regions" target vector.  Lists the memory
2475    regions in the inferior for a corefile.  */
2476
2477 static int
2478 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
2479                                             unsigned long,
2480                                             int, int, int, void *), void *obfd)
2481 {
2482   long long pid = PIDGET (inferior_ptid);
2483   char mapsfilename[MAXPATHLEN];
2484   FILE *mapsfile;
2485   long long addr, endaddr, size, offset, inode;
2486   char permissions[8], device[8], filename[MAXPATHLEN];
2487   int read, write, exec;
2488   int ret;
2489
2490   /* Compose the filename for the /proc memory map, and open it.  */
2491   sprintf (mapsfilename, "/proc/%lld/maps", pid);
2492   if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
2493     error (_("Could not open %s."), mapsfilename);
2494
2495   if (info_verbose)
2496     fprintf_filtered (gdb_stdout,
2497                       "Reading memory regions from %s\n", mapsfilename);
2498
2499   /* Now iterate until end-of-file.  */
2500   while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
2501                        &offset, &device[0], &inode, &filename[0]))
2502     {
2503       size = endaddr - addr;
2504
2505       /* Get the segment's permissions.  */
2506       read = (strchr (permissions, 'r') != 0);
2507       write = (strchr (permissions, 'w') != 0);
2508       exec = (strchr (permissions, 'x') != 0);
2509
2510       if (info_verbose)
2511         {
2512           fprintf_filtered (gdb_stdout,
2513                             "Save segment, %lld bytes at 0x%s (%c%c%c)",
2514                             size, paddr_nz (addr),
2515                             read ? 'r' : ' ',
2516                             write ? 'w' : ' ', exec ? 'x' : ' ');
2517           if (filename && filename[0])
2518             fprintf_filtered (gdb_stdout, " for %s", filename);
2519           fprintf_filtered (gdb_stdout, "\n");
2520         }
2521
2522       /* Invoke the callback function to create the corefile
2523          segment.  */
2524       func (addr, size, read, write, exec, obfd);
2525     }
2526   fclose (mapsfile);
2527   return 0;
2528 }
2529
2530 /* Records the thread's register state for the corefile note
2531    section.  */
2532
2533 static char *
2534 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
2535                                char *note_data, int *note_size)
2536 {
2537   gdb_gregset_t gregs;
2538   gdb_fpregset_t fpregs;
2539 #ifdef FILL_FPXREGSET
2540   gdb_fpxregset_t fpxregs;
2541 #endif
2542   unsigned long lwp = ptid_get_lwp (ptid);
2543
2544   fill_gregset (&gregs, -1);
2545   note_data = (char *) elfcore_write_prstatus (obfd,
2546                                                note_data,
2547                                                note_size,
2548                                                lwp,
2549                                                stop_signal, &gregs);
2550
2551   fill_fpregset (&fpregs, -1);
2552   note_data = (char *) elfcore_write_prfpreg (obfd,
2553                                               note_data,
2554                                               note_size,
2555                                               &fpregs, sizeof (fpregs));
2556 #ifdef FILL_FPXREGSET
2557   fill_fpxregset (&fpxregs, -1);
2558   note_data = (char *) elfcore_write_prxfpreg (obfd,
2559                                                note_data,
2560                                                note_size,
2561                                                &fpxregs, sizeof (fpxregs));
2562 #endif
2563   return note_data;
2564 }
2565
2566 struct linux_nat_corefile_thread_data
2567 {
2568   bfd *obfd;
2569   char *note_data;
2570   int *note_size;
2571   int num_notes;
2572 };
2573
2574 /* Called by gdbthread.c once per thread.  Records the thread's
2575    register state for the corefile note section.  */
2576
2577 static int
2578 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
2579 {
2580   struct linux_nat_corefile_thread_data *args = data;
2581   ptid_t saved_ptid = inferior_ptid;
2582
2583   inferior_ptid = ti->ptid;
2584   registers_changed ();
2585   target_fetch_registers (-1);  /* FIXME should not be necessary;
2586                                    fill_gregset should do it automatically. */
2587   args->note_data = linux_nat_do_thread_registers (args->obfd,
2588                                                    ti->ptid,
2589                                                    args->note_data,
2590                                                    args->note_size);
2591   args->num_notes++;
2592   inferior_ptid = saved_ptid;
2593   registers_changed ();
2594   target_fetch_registers (-1);  /* FIXME should not be necessary;
2595                                    fill_gregset should do it automatically. */
2596   return 0;
2597 }
2598
2599 /* Records the register state for the corefile note section.  */
2600
2601 static char *
2602 linux_nat_do_registers (bfd *obfd, ptid_t ptid,
2603                         char *note_data, int *note_size)
2604 {
2605   registers_changed ();
2606   target_fetch_registers (-1);  /* FIXME should not be necessary;
2607                                    fill_gregset should do it automatically. */
2608   return linux_nat_do_thread_registers (obfd,
2609                                         ptid_build (ptid_get_pid (inferior_ptid),
2610                                                     ptid_get_pid (inferior_ptid),
2611                                                     0),
2612                                         note_data, note_size);
2613   return note_data;
2614 }
2615
2616 /* Fills the "to_make_corefile_note" target vector.  Builds the note
2617    section for a corefile, and returns it in a malloc buffer.  */
2618
2619 static char *
2620 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
2621 {
2622   struct linux_nat_corefile_thread_data thread_args;
2623   struct cleanup *old_chain;
2624   char fname[16] = { '\0' };
2625   char psargs[80] = { '\0' };
2626   char *note_data = NULL;
2627   ptid_t current_ptid = inferior_ptid;
2628   gdb_byte *auxv;
2629   int auxv_len;
2630
2631   if (get_exec_file (0))
2632     {
2633       strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
2634       strncpy (psargs, get_exec_file (0), sizeof (psargs));
2635       if (get_inferior_args ())
2636         {
2637           strncat (psargs, " ", sizeof (psargs) - strlen (psargs));
2638           strncat (psargs, get_inferior_args (),
2639                    sizeof (psargs) - strlen (psargs));
2640         }
2641       note_data = (char *) elfcore_write_prpsinfo (obfd,
2642                                                    note_data,
2643                                                    note_size, fname, psargs);
2644     }
2645
2646   /* Dump information for threads.  */
2647   thread_args.obfd = obfd;
2648   thread_args.note_data = note_data;
2649   thread_args.note_size = note_size;
2650   thread_args.num_notes = 0;
2651   iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
2652   if (thread_args.num_notes == 0)
2653     {
2654       /* iterate_over_threads didn't come up with any threads; just
2655          use inferior_ptid.  */
2656       note_data = linux_nat_do_registers (obfd, inferior_ptid,
2657                                           note_data, note_size);
2658     }
2659   else
2660     {
2661       note_data = thread_args.note_data;
2662     }
2663
2664   auxv_len = target_auxv_read (&current_target, &auxv);
2665   if (auxv_len > 0)
2666     {
2667       note_data = elfcore_write_note (obfd, note_data, note_size,
2668                                       "CORE", NT_AUXV, auxv, auxv_len);
2669       xfree (auxv);
2670     }
2671
2672   make_cleanup (xfree, note_data);
2673   return note_data;
2674 }
2675
2676 /* Implement the "info proc" command.  */
2677
2678 static void
2679 linux_nat_info_proc_cmd (char *args, int from_tty)
2680 {
2681   long long pid = PIDGET (inferior_ptid);
2682   FILE *procfile;
2683   char **argv = NULL;
2684   char buffer[MAXPATHLEN];
2685   char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
2686   int cmdline_f = 1;
2687   int cwd_f = 1;
2688   int exe_f = 1;
2689   int mappings_f = 0;
2690   int environ_f = 0;
2691   int status_f = 0;
2692   int stat_f = 0;
2693   int all = 0;
2694   struct stat dummy;
2695
2696   if (args)
2697     {
2698       /* Break up 'args' into an argv array.  */
2699       if ((argv = buildargv (args)) == NULL)
2700         nomem (0);
2701       else
2702         make_cleanup_freeargv (argv);
2703     }
2704   while (argv != NULL && *argv != NULL)
2705     {
2706       if (isdigit (argv[0][0]))
2707         {
2708           pid = strtoul (argv[0], NULL, 10);
2709         }
2710       else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
2711         {
2712           mappings_f = 1;
2713         }
2714       else if (strcmp (argv[0], "status") == 0)
2715         {
2716           status_f = 1;
2717         }
2718       else if (strcmp (argv[0], "stat") == 0)
2719         {
2720           stat_f = 1;
2721         }
2722       else if (strcmp (argv[0], "cmd") == 0)
2723         {
2724           cmdline_f = 1;
2725         }
2726       else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
2727         {
2728           exe_f = 1;
2729         }
2730       else if (strcmp (argv[0], "cwd") == 0)
2731         {
2732           cwd_f = 1;
2733         }
2734       else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
2735         {
2736           all = 1;
2737         }
2738       else
2739         {
2740           /* [...] (future options here) */
2741         }
2742       argv++;
2743     }
2744   if (pid == 0)
2745     error (_("No current process: you must name one."));
2746
2747   sprintf (fname1, "/proc/%lld", pid);
2748   if (stat (fname1, &dummy) != 0)
2749     error (_("No /proc directory: '%s'"), fname1);
2750
2751   printf_filtered (_("process %lld\n"), pid);
2752   if (cmdline_f || all)
2753     {
2754       sprintf (fname1, "/proc/%lld/cmdline", pid);
2755       if ((procfile = fopen (fname1, "r")) > 0)
2756         {
2757           fgets (buffer, sizeof (buffer), procfile);
2758           printf_filtered ("cmdline = '%s'\n", buffer);
2759           fclose (procfile);
2760         }
2761       else
2762         warning (_("unable to open /proc file '%s'"), fname1);
2763     }
2764   if (cwd_f || all)
2765     {
2766       sprintf (fname1, "/proc/%lld/cwd", pid);
2767       memset (fname2, 0, sizeof (fname2));
2768       if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2769         printf_filtered ("cwd = '%s'\n", fname2);
2770       else
2771         warning (_("unable to read link '%s'"), fname1);
2772     }
2773   if (exe_f || all)
2774     {
2775       sprintf (fname1, "/proc/%lld/exe", pid);
2776       memset (fname2, 0, sizeof (fname2));
2777       if (readlink (fname1, fname2, sizeof (fname2)) > 0)
2778         printf_filtered ("exe = '%s'\n", fname2);
2779       else
2780         warning (_("unable to read link '%s'"), fname1);
2781     }
2782   if (mappings_f || all)
2783     {
2784       sprintf (fname1, "/proc/%lld/maps", pid);
2785       if ((procfile = fopen (fname1, "r")) > 0)
2786         {
2787           long long addr, endaddr, size, offset, inode;
2788           char permissions[8], device[8], filename[MAXPATHLEN];
2789
2790           printf_filtered (_("Mapped address spaces:\n\n"));
2791           if (TARGET_ADDR_BIT == 32)
2792             {
2793               printf_filtered ("\t%10s %10s %10s %10s %7s\n",
2794                            "Start Addr",
2795                            "  End Addr",
2796                            "      Size", "    Offset", "objfile");
2797             }
2798           else
2799             {
2800               printf_filtered ("  %18s %18s %10s %10s %7s\n",
2801                            "Start Addr",
2802                            "  End Addr",
2803                            "      Size", "    Offset", "objfile");
2804             }
2805
2806           while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
2807                                &offset, &device[0], &inode, &filename[0]))
2808             {
2809               size = endaddr - addr;
2810
2811               /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
2812                  calls here (and possibly above) should be abstracted
2813                  out into their own functions?  Andrew suggests using
2814                  a generic local_address_string instead to print out
2815                  the addresses; that makes sense to me, too.  */
2816
2817               if (TARGET_ADDR_BIT == 32)
2818                 {
2819                   printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
2820                                (unsigned long) addr,    /* FIXME: pr_addr */
2821                                (unsigned long) endaddr,
2822                                (int) size,
2823                                (unsigned int) offset,
2824                                filename[0] ? filename : "");
2825                 }
2826               else
2827                 {
2828                   printf_filtered ("  %#18lx %#18lx %#10x %#10x %7s\n",
2829                                (unsigned long) addr,    /* FIXME: pr_addr */
2830                                (unsigned long) endaddr,
2831                                (int) size,
2832                                (unsigned int) offset,
2833                                filename[0] ? filename : "");
2834                 }
2835             }
2836
2837           fclose (procfile);
2838         }
2839       else
2840         warning (_("unable to open /proc file '%s'"), fname1);
2841     }
2842   if (status_f || all)
2843     {
2844       sprintf (fname1, "/proc/%lld/status", pid);
2845       if ((procfile = fopen (fname1, "r")) > 0)
2846         {
2847           while (fgets (buffer, sizeof (buffer), procfile) != NULL)
2848             puts_filtered (buffer);
2849           fclose (procfile);
2850         }
2851       else
2852         warning (_("unable to open /proc file '%s'"), fname1);
2853     }
2854   if (stat_f || all)
2855     {
2856       sprintf (fname1, "/proc/%lld/stat", pid);
2857       if ((procfile = fopen (fname1, "r")) > 0)
2858         {
2859           int itmp;
2860           char ctmp;
2861
2862           if (fscanf (procfile, "%d ", &itmp) > 0)
2863             printf_filtered (_("Process: %d\n"), itmp);
2864           if (fscanf (procfile, "%s ", &buffer[0]) > 0)
2865             printf_filtered (_("Exec file: %s\n"), buffer);
2866           if (fscanf (procfile, "%c ", &ctmp) > 0)
2867             printf_filtered (_("State: %c\n"), ctmp);
2868           if (fscanf (procfile, "%d ", &itmp) > 0)
2869             printf_filtered (_("Parent process: %d\n"), itmp);
2870           if (fscanf (procfile, "%d ", &itmp) > 0)
2871             printf_filtered (_("Process group: %d\n"), itmp);
2872           if (fscanf (procfile, "%d ", &itmp) > 0)
2873             printf_filtered (_("Session id: %d\n"), itmp);
2874           if (fscanf (procfile, "%d ", &itmp) > 0)
2875             printf_filtered (_("TTY: %d\n"), itmp);
2876           if (fscanf (procfile, "%d ", &itmp) > 0)
2877             printf_filtered (_("TTY owner process group: %d\n"), itmp);
2878           if (fscanf (procfile, "%u ", &itmp) > 0)
2879             printf_filtered (_("Flags: 0x%x\n"), itmp);
2880           if (fscanf (procfile, "%u ", &itmp) > 0)
2881             printf_filtered (_("Minor faults (no memory page): %u\n"),
2882                              (unsigned int) itmp);
2883           if (fscanf (procfile, "%u ", &itmp) > 0)
2884             printf_filtered (_("Minor faults, children: %u\n"),
2885                              (unsigned int) itmp);
2886           if (fscanf (procfile, "%u ", &itmp) > 0)
2887             printf_filtered (_("Major faults (memory page faults): %u\n"),
2888                              (unsigned int) itmp);
2889           if (fscanf (procfile, "%u ", &itmp) > 0)
2890             printf_filtered (_("Major faults, children: %u\n"),
2891                              (unsigned int) itmp);
2892           if (fscanf (procfile, "%d ", &itmp) > 0)
2893             printf_filtered ("utime: %d\n", itmp);
2894           if (fscanf (procfile, "%d ", &itmp) > 0)
2895             printf_filtered ("stime: %d\n", itmp);
2896           if (fscanf (procfile, "%d ", &itmp) > 0)
2897             printf_filtered ("utime, children: %d\n", itmp);
2898           if (fscanf (procfile, "%d ", &itmp) > 0)
2899             printf_filtered ("stime, children: %d\n", itmp);
2900           if (fscanf (procfile, "%d ", &itmp) > 0)
2901             printf_filtered (_("jiffies remaining in current time slice: %d\n"),
2902                              itmp);
2903           if (fscanf (procfile, "%d ", &itmp) > 0)
2904             printf_filtered ("'nice' value: %d\n", itmp);
2905           if (fscanf (procfile, "%u ", &itmp) > 0)
2906             printf_filtered (_("jiffies until next timeout: %u\n"),
2907                              (unsigned int) itmp);
2908           if (fscanf (procfile, "%u ", &itmp) > 0)
2909             printf_filtered ("jiffies until next SIGALRM: %u\n",
2910                              (unsigned int) itmp);
2911           if (fscanf (procfile, "%d ", &itmp) > 0)
2912             printf_filtered (_("start time (jiffies since system boot): %d\n"),
2913                              itmp);
2914           if (fscanf (procfile, "%u ", &itmp) > 0)
2915             printf_filtered (_("Virtual memory size: %u\n"),
2916                              (unsigned int) itmp);
2917           if (fscanf (procfile, "%u ", &itmp) > 0)
2918             printf_filtered (_("Resident set size: %u\n"), (unsigned int) itmp);
2919           if (fscanf (procfile, "%u ", &itmp) > 0)
2920             printf_filtered ("rlim: %u\n", (unsigned int) itmp);
2921           if (fscanf (procfile, "%u ", &itmp) > 0)
2922             printf_filtered (_("Start of text: 0x%x\n"), itmp);
2923           if (fscanf (procfile, "%u ", &itmp) > 0)
2924             printf_filtered (_("End of text: 0x%x\n"), itmp);
2925           if (fscanf (procfile, "%u ", &itmp) > 0)
2926             printf_filtered (_("Start of stack: 0x%x\n"), itmp);
2927 #if 0                           /* Don't know how architecture-dependent the rest is...
2928                                    Anyway the signal bitmap info is available from "status".  */
2929           if (fscanf (procfile, "%u ", &itmp) > 0)      /* FIXME arch? */
2930             printf_filtered (_("Kernel stack pointer: 0x%x\n"), itmp);
2931           if (fscanf (procfile, "%u ", &itmp) > 0)      /* FIXME arch? */
2932             printf_filtered (_("Kernel instr pointer: 0x%x\n"), itmp);
2933           if (fscanf (procfile, "%d ", &itmp) > 0)
2934             printf_filtered (_("Pending signals bitmap: 0x%x\n"), itmp);
2935           if (fscanf (procfile, "%d ", &itmp) > 0)
2936             printf_filtered (_("Blocked signals bitmap: 0x%x\n"), itmp);
2937           if (fscanf (procfile, "%d ", &itmp) > 0)
2938             printf_filtered (_("Ignored signals bitmap: 0x%x\n"), itmp);
2939           if (fscanf (procfile, "%d ", &itmp) > 0)
2940             printf_filtered (_("Catched signals bitmap: 0x%x\n"), itmp);
2941           if (fscanf (procfile, "%u ", &itmp) > 0)      /* FIXME arch? */
2942             printf_filtered (_("wchan (system call): 0x%x\n"), itmp);
2943 #endif
2944           fclose (procfile);
2945         }
2946       else
2947         warning (_("unable to open /proc file '%s'"), fname1);
2948     }
2949 }
2950
2951 int
2952 linux_proc_xfer_memory (CORE_ADDR addr, gdb_byte *myaddr, int len, int write,
2953                         struct mem_attrib *attrib, struct target_ops *target)
2954 {
2955   int fd, ret;
2956   char filename[64];
2957
2958   if (write)
2959     return 0;
2960
2961   /* Don't bother for one word.  */
2962   if (len < 3 * sizeof (long))
2963     return 0;
2964
2965   /* We could keep this file open and cache it - possibly one per
2966      thread.  That requires some juggling, but is even faster.  */
2967   sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
2968   fd = open (filename, O_RDONLY | O_LARGEFILE);
2969   if (fd == -1)
2970     return 0;
2971
2972   /* If pread64 is available, use it.  It's faster if the kernel
2973      supports it (only one syscall), and it's 64-bit safe even on
2974      32-bit platforms (for instance, SPARC debugging a SPARC64
2975      application).  */
2976 #ifdef HAVE_PREAD64
2977   if (pread64 (fd, myaddr, len, addr) != len)
2978 #else
2979   if (lseek (fd, addr, SEEK_SET) == -1 || read (fd, myaddr, len) != len)
2980 #endif
2981     ret = 0;
2982   else
2983     ret = len;
2984
2985   close (fd);
2986   return ret;
2987 }
2988
2989 /* Parse LINE as a signal set and add its set bits to SIGS.  */
2990
2991 static void
2992 add_line_to_sigset (const char *line, sigset_t *sigs)
2993 {
2994   int len = strlen (line) - 1;
2995   const char *p;
2996   int signum;
2997
2998   if (line[len] != '\n')
2999     error (_("Could not parse signal set: %s"), line);
3000
3001   p = line;
3002   signum = len * 4;
3003   while (len-- > 0)
3004     {
3005       int digit;
3006
3007       if (*p >= '0' && *p <= '9')
3008         digit = *p - '0';
3009       else if (*p >= 'a' && *p <= 'f')
3010         digit = *p - 'a' + 10;
3011       else
3012         error (_("Could not parse signal set: %s"), line);
3013
3014       signum -= 4;
3015
3016       if (digit & 1)
3017         sigaddset (sigs, signum + 1);
3018       if (digit & 2)
3019         sigaddset (sigs, signum + 2);
3020       if (digit & 4)
3021         sigaddset (sigs, signum + 3);
3022       if (digit & 8)
3023         sigaddset (sigs, signum + 4);
3024
3025       p++;
3026     }
3027 }
3028
3029 /* Find process PID's pending signals from /proc/pid/status and set
3030    SIGS to match.  */
3031
3032 void
3033 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3034 {
3035   FILE *procfile;
3036   char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3037   int signum;
3038
3039   sigemptyset (pending);
3040   sigemptyset (blocked);
3041   sigemptyset (ignored);
3042   sprintf (fname, "/proc/%d/status", pid);
3043   procfile = fopen (fname, "r");
3044   if (procfile == NULL)
3045     error (_("Could not open %s"), fname);
3046
3047   while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3048     {
3049       /* Normal queued signals are on the SigPnd line in the status
3050          file.  However, 2.6 kernels also have a "shared" pending
3051          queue for delivering signals to a thread group, so check for
3052          a ShdPnd line also.
3053
3054          Unfortunately some Red Hat kernels include the shared pending
3055          queue but not the ShdPnd status field.  */
3056
3057       if (strncmp (buffer, "SigPnd:\t", 8) == 0)
3058         add_line_to_sigset (buffer + 8, pending);
3059       else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
3060         add_line_to_sigset (buffer + 8, pending);
3061       else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
3062         add_line_to_sigset (buffer + 8, blocked);
3063       else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
3064         add_line_to_sigset (buffer + 8, ignored);
3065     }
3066
3067   fclose (procfile);
3068 }
3069
3070 void
3071 _initialize_linux_nat (void)
3072 {
3073   struct sigaction action;
3074   extern void thread_db_init (struct target_ops *);
3075
3076   deprecated_child_ops.to_find_memory_regions = linux_nat_find_memory_regions;
3077   deprecated_child_ops.to_make_corefile_notes = linux_nat_make_corefile_notes;
3078
3079   add_info ("proc", linux_nat_info_proc_cmd, _("\
3080 Show /proc process information about any running process.\n\
3081 Specify any process id, or use the program being debugged by default.\n\
3082 Specify any of the following keywords for detailed info:\n\
3083   mappings -- list of mapped memory regions.\n\
3084   stat     -- list a bunch of random process info.\n\
3085   status   -- list a different bunch of random process info.\n\
3086   all      -- list all available /proc info."));
3087
3088   init_linux_nat_ops ();
3089   add_target (&linux_nat_ops);
3090   thread_db_init (&linux_nat_ops);
3091
3092   /* Save the original signal mask.  */
3093   sigprocmask (SIG_SETMASK, NULL, &normal_mask);
3094
3095   action.sa_handler = sigchld_handler;
3096   sigemptyset (&action.sa_mask);
3097   action.sa_flags = SA_RESTART;
3098   sigaction (SIGCHLD, &action, NULL);
3099
3100   /* Make sure we don't block SIGCHLD during a sigsuspend.  */
3101   sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
3102   sigdelset (&suspend_mask, SIGCHLD);
3103
3104   sigemptyset (&blocked_mask);
3105
3106   add_setshow_zinteger_cmd ("lin-lwp", no_class, &debug_linux_nat, _("\
3107 Set debugging of GNU/Linux lwp module."), _("\
3108 Show debugging of GNU/Linux lwp module."), _("\
3109 Enables printf debugging output."),
3110                             NULL,
3111                             show_debug_linux_nat,
3112                             &setdebuglist, &showdebuglist);
3113 }
3114 \f
3115
3116 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
3117    the GNU/Linux Threads library and therefore doesn't really belong
3118    here.  */
3119
3120 /* Read variable NAME in the target and return its value if found.
3121    Otherwise return zero.  It is assumed that the type of the variable
3122    is `int'.  */
3123
3124 static int
3125 get_signo (const char *name)
3126 {
3127   struct minimal_symbol *ms;
3128   int signo;
3129
3130   ms = lookup_minimal_symbol (name, NULL, NULL);
3131   if (ms == NULL)
3132     return 0;
3133
3134   if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
3135                           sizeof (signo)) != 0)
3136     return 0;
3137
3138   return signo;
3139 }
3140
3141 /* Return the set of signals used by the threads library in *SET.  */
3142
3143 void
3144 lin_thread_get_thread_signals (sigset_t *set)
3145 {
3146   struct sigaction action;
3147   int restart, cancel;
3148
3149   sigemptyset (set);
3150
3151   restart = get_signo ("__pthread_sig_restart");
3152   if (restart == 0)
3153     return;
3154
3155   cancel = get_signo ("__pthread_sig_cancel");
3156   if (cancel == 0)
3157     return;
3158
3159   sigaddset (set, restart);
3160   sigaddset (set, cancel);
3161
3162   /* The GNU/Linux Threads library makes terminating threads send a
3163      special "cancel" signal instead of SIGCHLD.  Make sure we catch
3164      those (to prevent them from terminating GDB itself, which is
3165      likely to be their default action) and treat them the same way as
3166      SIGCHLD.  */
3167
3168   action.sa_handler = sigchld_handler;
3169   sigemptyset (&action.sa_mask);
3170   action.sa_flags = SA_RESTART;
3171   sigaction (cancel, &action, NULL);
3172
3173   /* We block the "cancel" signal throughout this code ...  */
3174   sigaddset (&blocked_mask, cancel);
3175   sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
3176
3177   /* ... except during a sigsuspend.  */
3178   sigdelset (&suspend_mask, cancel);
3179 }