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