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