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