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