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