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