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