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