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