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