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