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