246712cb5a71e9789df713c9eeffc1847923bad8
[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
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
53 /* Note on this file's use of signals:
54
55 We stop threads by sending a SIGSTOP. The use of SIGSTOP instead
56 of another signal is not entirely significant; we just need for a
57 signal to be delivered, so that we can intercept it. SIGSTOP's
58 advantage is that it can not be blocked. A disadvantage is that it
59 is not a real-time signal, so it can only be queued once; we do not
60 keep track of other sources of SIGSTOP.
61
62 Two other signals that can't be blocked are SIGCONT and SIGKILL.
63 But we can't use them, because they have special behavior when the
64 signal is generated - not when it is delivered. SIGCONT resumes
65 the entire thread group and SIGKILL kills the entire thread group.
66
67 A delivered SIGSTOP would stop the entire thread group, not just the
68 thread we tkill'd. But we never let the SIGSTOP deliver; we always
69 intercept and cancel it (by PTRACE_CONT without passing SIGSTOP).
70
71 We could use a real-time signal instead. This would solve those
72 problems; we could use PTRACE_GETSIGINFO to locate the specific
73 stop signals sent by GDB. But we would still have to have some
74 support for SIGSTOP, since PTRACE_ATTACH generates it, and there
75 are races with trying to find a signal that is not blocked. */
76
77 #ifndef O_LARGEFILE
78 #define O_LARGEFILE 0
79 #endif
80
81 /* If the system headers did not provide the constants, hard-code the normal
82 values. */
83 #ifndef PTRACE_EVENT_FORK
84
85 #define PTRACE_SETOPTIONS 0x4200
86 #define PTRACE_GETEVENTMSG 0x4201
87
88 /* options set using PTRACE_SETOPTIONS */
89 #define PTRACE_O_TRACESYSGOOD 0x00000001
90 #define PTRACE_O_TRACEFORK 0x00000002
91 #define PTRACE_O_TRACEVFORK 0x00000004
92 #define PTRACE_O_TRACECLONE 0x00000008
93 #define PTRACE_O_TRACEEXEC 0x00000010
94 #define PTRACE_O_TRACEVFORKDONE 0x00000020
95 #define PTRACE_O_TRACEEXIT 0x00000040
96
97 /* Wait extended result codes for the above trace options. */
98 #define PTRACE_EVENT_FORK 1
99 #define PTRACE_EVENT_VFORK 2
100 #define PTRACE_EVENT_CLONE 3
101 #define PTRACE_EVENT_EXEC 4
102 #define PTRACE_EVENT_VFORK_DONE 5
103 #define PTRACE_EVENT_EXIT 6
104
105 #endif /* PTRACE_EVENT_FORK */
106
107 /* We can't always assume that this flag is available, but all systems
108 with the ptrace event handlers also have __WALL, so it's safe to use
109 here. */
110 #ifndef __WALL
111 #define __WALL 0x40000000 /* Wait for any child. */
112 #endif
113
114 #ifndef PTRACE_GETSIGINFO
115 #define PTRACE_GETSIGINFO 0x4202
116 #endif
117
118 /* The single-threaded native GNU/Linux target_ops. We save a pointer for
119 the use of the multi-threaded target. */
120 static struct target_ops *linux_ops;
121 static struct target_ops linux_ops_saved;
122
123 /* The method to call, if any, when a new thread is attached. */
124 static void (*linux_nat_new_thread) (ptid_t);
125
126 /* The saved to_xfer_partial method, inherited from inf-ptrace.c.
127 Called by our to_xfer_partial. */
128 static LONGEST (*super_xfer_partial) (struct target_ops *,
129 enum target_object,
130 const char *, gdb_byte *,
131 const gdb_byte *,
132 ULONGEST, LONGEST);
133
134 static int debug_linux_nat;
135 static void
136 show_debug_linux_nat (struct ui_file *file, int from_tty,
137 struct cmd_list_element *c, const char *value)
138 {
139 fprintf_filtered (file, _("Debugging of GNU/Linux lwp module is %s.\n"),
140 value);
141 }
142
143 static int debug_linux_nat_async = 0;
144 static void
145 show_debug_linux_nat_async (struct ui_file *file, int from_tty,
146 struct cmd_list_element *c, const char *value)
147 {
148 fprintf_filtered (file, _("Debugging of GNU/Linux async lwp module is %s.\n"),
149 value);
150 }
151
152 static int linux_parent_pid;
153
154 struct simple_pid_list
155 {
156 int pid;
157 int status;
158 struct simple_pid_list *next;
159 };
160 struct simple_pid_list *stopped_pids;
161
162 /* This variable is a tri-state flag: -1 for unknown, 0 if PTRACE_O_TRACEFORK
163 can not be used, 1 if it can. */
164
165 static int linux_supports_tracefork_flag = -1;
166
167 /* If we have PTRACE_O_TRACEFORK, this flag indicates whether we also have
168 PTRACE_O_TRACEVFORKDONE. */
169
170 static int linux_supports_tracevforkdone_flag = -1;
171
172 /* Async mode support */
173
174 /* To listen to target events asynchronously, we install a SIGCHLD
175 handler whose duty is to call waitpid (-1, ..., WNOHANG) to get all
176 the pending events into a pipe. Whenever we're ready to handle
177 events asynchronously, this pipe is registered as the waitable file
178 handle in the event loop. When we get to entry target points
179 coming out of the common code (target_wait, target_resume, ...),
180 that are going to call waitpid, we block SIGCHLD signals, and
181 remove all the events placed in the pipe into a local queue. All
182 the subsequent calls to my_waitpid (a waitpid wrapper) check this
183 local queue first. */
184
185 /* True if async mode is currently on. */
186 static int linux_nat_async_enabled;
187
188 /* Zero if the async mode, although enabled, is masked, which means
189 linux_nat_wait should behave as if async mode was off. */
190 static int linux_nat_async_mask_value = 1;
191
192 /* The read/write ends of the pipe registered as waitable file in the
193 event loop. */
194 static int linux_nat_event_pipe[2] = { -1, -1 };
195
196 /* Number of queued events in the pipe. */
197 static volatile int linux_nat_num_queued_events;
198
199 /* If async mode is on, true if we're listening for events; false if
200 target events are blocked. */
201 static int linux_nat_async_events_enabled;
202
203 static int linux_nat_async_events (int enable);
204 static void pipe_to_local_event_queue (void);
205 static void local_event_queue_to_pipe (void);
206 static void linux_nat_event_pipe_push (int pid, int status, int options);
207 static int linux_nat_event_pipe_pop (int* ptr_status, int* ptr_options);
208 static void linux_nat_set_async_mode (int on);
209 static void linux_nat_async (void (*callback)
210 (enum inferior_event_type event_type, void *context),
211 void *context);
212 static int linux_nat_async_mask (int mask);
213 static int kill_lwp (int lwpid, int signo);
214
215 /* Captures the result of a successful waitpid call, along with the
216 options used in that call. */
217 struct waitpid_result
218 {
219 int pid;
220 int status;
221 int options;
222 struct waitpid_result *next;
223 };
224
225 /* A singly-linked list of the results of the waitpid calls performed
226 in the async SIGCHLD handler. */
227 static struct waitpid_result *waitpid_queue = NULL;
228
229 static int
230 queued_waitpid (int pid, int *status, int flags)
231 {
232 struct waitpid_result *msg = waitpid_queue, *prev = NULL;
233
234 if (debug_linux_nat_async)
235 fprintf_unfiltered (gdb_stdlog,
236 "\
237 QWPID: linux_nat_async_events_enabled(%d), linux_nat_num_queued_events(%d)\n",
238 linux_nat_async_events_enabled,
239 linux_nat_num_queued_events);
240
241 if (flags & __WALL)
242 {
243 for (; msg; prev = msg, msg = msg->next)
244 if (pid == -1 || pid == msg->pid)
245 break;
246 }
247 else if (flags & __WCLONE)
248 {
249 for (; msg; prev = msg, msg = msg->next)
250 if (msg->options & __WCLONE
251 && (pid == -1 || pid == msg->pid))
252 break;
253 }
254 else
255 {
256 for (; msg; prev = msg, msg = msg->next)
257 if ((msg->options & __WCLONE) == 0
258 && (pid == -1 || pid == msg->pid))
259 break;
260 }
261
262 if (msg)
263 {
264 int pid;
265
266 if (prev)
267 prev->next = msg->next;
268 else
269 waitpid_queue = msg->next;
270
271 msg->next = NULL;
272 if (status)
273 *status = msg->status;
274 pid = msg->pid;
275
276 if (debug_linux_nat_async)
277 fprintf_unfiltered (gdb_stdlog, "QWPID: pid(%d), status(%x)\n",
278 pid, msg->status);
279 xfree (msg);
280
281 return pid;
282 }
283
284 if (debug_linux_nat_async)
285 fprintf_unfiltered (gdb_stdlog, "QWPID: miss\n");
286
287 if (status)
288 *status = 0;
289 return -1;
290 }
291
292 static void
293 push_waitpid (int pid, int status, int options)
294 {
295 struct waitpid_result *event, *new_event;
296
297 new_event = xmalloc (sizeof (*new_event));
298 new_event->pid = pid;
299 new_event->status = status;
300 new_event->options = options;
301 new_event->next = NULL;
302
303 if (waitpid_queue)
304 {
305 for (event = waitpid_queue;
306 event && event->next;
307 event = event->next)
308 ;
309
310 event->next = new_event;
311 }
312 else
313 waitpid_queue = new_event;
314 }
315
316 /* Drain all queued events of PID. If PID is -1, the effect is of
317 draining all events. */
318 static void
319 drain_queued_events (int pid)
320 {
321 while (queued_waitpid (pid, NULL, __WALL) != -1)
322 ;
323 }
324
325 \f
326 /* Trivial list manipulation functions to keep track of a list of
327 new stopped processes. */
328 static void
329 add_to_pid_list (struct simple_pid_list **listp, int pid, int status)
330 {
331 struct simple_pid_list *new_pid = xmalloc (sizeof (struct simple_pid_list));
332 new_pid->pid = pid;
333 new_pid->status = status;
334 new_pid->next = *listp;
335 *listp = new_pid;
336 }
337
338 static int
339 pull_pid_from_list (struct simple_pid_list **listp, int pid, int *status)
340 {
341 struct simple_pid_list **p;
342
343 for (p = listp; *p != NULL; p = &(*p)->next)
344 if ((*p)->pid == pid)
345 {
346 struct simple_pid_list *next = (*p)->next;
347 *status = (*p)->status;
348 xfree (*p);
349 *p = next;
350 return 1;
351 }
352 return 0;
353 }
354
355 static void
356 linux_record_stopped_pid (int pid, int status)
357 {
358 add_to_pid_list (&stopped_pids, pid, status);
359 }
360
361 \f
362 /* A helper function for linux_test_for_tracefork, called after fork (). */
363
364 static void
365 linux_tracefork_child (void)
366 {
367 int ret;
368
369 ptrace (PTRACE_TRACEME, 0, 0, 0);
370 kill (getpid (), SIGSTOP);
371 fork ();
372 _exit (0);
373 }
374
375 /* Wrapper function for waitpid which handles EINTR, and checks for
376 locally queued events. */
377
378 static int
379 my_waitpid (int pid, int *status, int flags)
380 {
381 int ret;
382
383 /* There should be no concurrent calls to waitpid. */
384 gdb_assert (!linux_nat_async_events_enabled);
385
386 ret = queued_waitpid (pid, status, flags);
387 if (ret != -1)
388 return ret;
389
390 do
391 {
392 ret = waitpid (pid, status, flags);
393 }
394 while (ret == -1 && errno == EINTR);
395
396 return ret;
397 }
398
399 /* Determine if PTRACE_O_TRACEFORK can be used to follow fork events.
400
401 First, we try to enable fork tracing on ORIGINAL_PID. If this fails,
402 we know that the feature is not available. This may change the tracing
403 options for ORIGINAL_PID, but we'll be setting them shortly anyway.
404
405 However, if it succeeds, we don't know for sure that the feature is
406 available; old versions of PTRACE_SETOPTIONS ignored unknown options. We
407 create a child process, attach to it, use PTRACE_SETOPTIONS to enable
408 fork tracing, and let it fork. If the process exits, we assume that we
409 can't use TRACEFORK; if we get the fork notification, and we can extract
410 the new child's PID, then we assume that we can. */
411
412 static void
413 linux_test_for_tracefork (int original_pid)
414 {
415 int child_pid, ret, status;
416 long second_pid;
417
418 linux_supports_tracefork_flag = 0;
419 linux_supports_tracevforkdone_flag = 0;
420
421 ret = ptrace (PTRACE_SETOPTIONS, original_pid, 0, PTRACE_O_TRACEFORK);
422 if (ret != 0)
423 return;
424
425 child_pid = fork ();
426 if (child_pid == -1)
427 perror_with_name (("fork"));
428
429 if (child_pid == 0)
430 linux_tracefork_child ();
431
432 ret = my_waitpid (child_pid, &status, 0);
433 if (ret == -1)
434 perror_with_name (("waitpid"));
435 else if (ret != child_pid)
436 error (_("linux_test_for_tracefork: waitpid: unexpected result %d."), ret);
437 if (! WIFSTOPPED (status))
438 error (_("linux_test_for_tracefork: waitpid: unexpected status %d."), status);
439
440 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0, PTRACE_O_TRACEFORK);
441 if (ret != 0)
442 {
443 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
444 if (ret != 0)
445 {
446 warning (_("linux_test_for_tracefork: failed to kill child"));
447 return;
448 }
449
450 ret = my_waitpid (child_pid, &status, 0);
451 if (ret != child_pid)
452 warning (_("linux_test_for_tracefork: failed to wait for killed child"));
453 else if (!WIFSIGNALED (status))
454 warning (_("linux_test_for_tracefork: unexpected wait status 0x%x from "
455 "killed child"), status);
456
457 return;
458 }
459
460 /* Check whether PTRACE_O_TRACEVFORKDONE is available. */
461 ret = ptrace (PTRACE_SETOPTIONS, child_pid, 0,
462 PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORKDONE);
463 linux_supports_tracevforkdone_flag = (ret == 0);
464
465 ret = ptrace (PTRACE_CONT, child_pid, 0, 0);
466 if (ret != 0)
467 warning (_("linux_test_for_tracefork: failed to resume child"));
468
469 ret = my_waitpid (child_pid, &status, 0);
470
471 if (ret == child_pid && WIFSTOPPED (status)
472 && status >> 16 == PTRACE_EVENT_FORK)
473 {
474 second_pid = 0;
475 ret = ptrace (PTRACE_GETEVENTMSG, child_pid, 0, &second_pid);
476 if (ret == 0 && second_pid != 0)
477 {
478 int second_status;
479
480 linux_supports_tracefork_flag = 1;
481 my_waitpid (second_pid, &second_status, 0);
482 ret = ptrace (PTRACE_KILL, second_pid, 0, 0);
483 if (ret != 0)
484 warning (_("linux_test_for_tracefork: failed to kill second child"));
485 my_waitpid (second_pid, &status, 0);
486 }
487 }
488 else
489 warning (_("linux_test_for_tracefork: unexpected result from waitpid "
490 "(%d, status 0x%x)"), ret, status);
491
492 ret = ptrace (PTRACE_KILL, child_pid, 0, 0);
493 if (ret != 0)
494 warning (_("linux_test_for_tracefork: failed to kill child"));
495 my_waitpid (child_pid, &status, 0);
496 }
497
498 /* Return non-zero iff we have tracefork functionality available.
499 This function also sets linux_supports_tracefork_flag. */
500
501 static int
502 linux_supports_tracefork (int pid)
503 {
504 if (linux_supports_tracefork_flag == -1)
505 linux_test_for_tracefork (pid);
506 return linux_supports_tracefork_flag;
507 }
508
509 static int
510 linux_supports_tracevforkdone (int pid)
511 {
512 if (linux_supports_tracefork_flag == -1)
513 linux_test_for_tracefork (pid);
514 return linux_supports_tracevforkdone_flag;
515 }
516
517 \f
518 void
519 linux_enable_event_reporting (ptid_t ptid)
520 {
521 int pid = ptid_get_lwp (ptid);
522 int options;
523
524 if (pid == 0)
525 pid = ptid_get_pid (ptid);
526
527 if (! linux_supports_tracefork (pid))
528 return;
529
530 options = PTRACE_O_TRACEFORK | PTRACE_O_TRACEVFORK | PTRACE_O_TRACEEXEC
531 | PTRACE_O_TRACECLONE;
532 if (linux_supports_tracevforkdone (pid))
533 options |= PTRACE_O_TRACEVFORKDONE;
534
535 /* Do not enable PTRACE_O_TRACEEXIT until GDB is more prepared to support
536 read-only process state. */
537
538 ptrace (PTRACE_SETOPTIONS, pid, 0, options);
539 }
540
541 static void
542 linux_child_post_attach (int pid)
543 {
544 linux_enable_event_reporting (pid_to_ptid (pid));
545 check_for_thread_db ();
546 }
547
548 static void
549 linux_child_post_startup_inferior (ptid_t ptid)
550 {
551 linux_enable_event_reporting (ptid);
552 check_for_thread_db ();
553 }
554
555 static int
556 linux_child_follow_fork (struct target_ops *ops, int follow_child)
557 {
558 ptid_t last_ptid;
559 struct target_waitstatus last_status;
560 int has_vforked;
561 int parent_pid, child_pid;
562
563 if (target_can_async_p ())
564 target_async (NULL, 0);
565
566 get_last_target_status (&last_ptid, &last_status);
567 has_vforked = (last_status.kind == TARGET_WAITKIND_VFORKED);
568 parent_pid = ptid_get_lwp (last_ptid);
569 if (parent_pid == 0)
570 parent_pid = ptid_get_pid (last_ptid);
571 child_pid = last_status.value.related_pid;
572
573 if (! follow_child)
574 {
575 /* We're already attached to the parent, by default. */
576
577 /* Before detaching from the child, remove all breakpoints from
578 it. (This won't actually modify the breakpoint list, but will
579 physically remove the breakpoints from the child.) */
580 /* If we vforked this will remove the breakpoints from the parent
581 also, but they'll be reinserted below. */
582 detach_breakpoints (child_pid);
583
584 /* Detach new forked process? */
585 if (detach_fork)
586 {
587 if (info_verbose || debug_linux_nat)
588 {
589 target_terminal_ours ();
590 fprintf_filtered (gdb_stdlog,
591 "Detaching after fork from child process %d.\n",
592 child_pid);
593 }
594
595 ptrace (PTRACE_DETACH, child_pid, 0, 0);
596 }
597 else
598 {
599 struct fork_info *fp;
600 /* Retain child fork in ptrace (stopped) state. */
601 fp = find_fork_pid (child_pid);
602 if (!fp)
603 fp = add_fork (child_pid);
604 fork_save_infrun_state (fp, 0);
605 }
606
607 if (has_vforked)
608 {
609 gdb_assert (linux_supports_tracefork_flag >= 0);
610 if (linux_supports_tracevforkdone (0))
611 {
612 int status;
613
614 ptrace (PTRACE_CONT, parent_pid, 0, 0);
615 my_waitpid (parent_pid, &status, __WALL);
616 if ((status >> 16) != PTRACE_EVENT_VFORK_DONE)
617 warning (_("Unexpected waitpid result %06x when waiting for "
618 "vfork-done"), status);
619 }
620 else
621 {
622 /* We can't insert breakpoints until the child has
623 finished with the shared memory region. We need to
624 wait until that happens. Ideal would be to just
625 call:
626 - ptrace (PTRACE_SYSCALL, parent_pid, 0, 0);
627 - waitpid (parent_pid, &status, __WALL);
628 However, most architectures can't handle a syscall
629 being traced on the way out if it wasn't traced on
630 the way in.
631
632 We might also think to loop, continuing the child
633 until it exits or gets a SIGTRAP. One problem is
634 that the child might call ptrace with PTRACE_TRACEME.
635
636 There's no simple and reliable way to figure out when
637 the vforked child will be done with its copy of the
638 shared memory. We could step it out of the syscall,
639 two instructions, let it go, and then single-step the
640 parent once. When we have hardware single-step, this
641 would work; with software single-step it could still
642 be made to work but we'd have to be able to insert
643 single-step breakpoints in the child, and we'd have
644 to insert -just- the single-step breakpoint in the
645 parent. Very awkward.
646
647 In the end, the best we can do is to make sure it
648 runs for a little while. Hopefully it will be out of
649 range of any breakpoints we reinsert. Usually this
650 is only the single-step breakpoint at vfork's return
651 point. */
652
653 usleep (10000);
654 }
655
656 /* Since we vforked, breakpoints were removed in the parent
657 too. Put them back. */
658 reattach_breakpoints (parent_pid);
659 }
660 }
661 else
662 {
663 char child_pid_spelling[40];
664
665 /* Needed to keep the breakpoint lists in sync. */
666 if (! has_vforked)
667 detach_breakpoints (child_pid);
668
669 /* Before detaching from the parent, remove all breakpoints from it. */
670 remove_breakpoints ();
671
672 if (info_verbose || debug_linux_nat)
673 {
674 target_terminal_ours ();
675 fprintf_filtered (gdb_stdlog,
676 "Attaching after fork to child process %d.\n",
677 child_pid);
678 }
679
680 /* If we're vforking, we may want to hold on to the parent until
681 the child exits or execs. At exec time we can remove the old
682 breakpoints from the parent and detach it; at exit time we
683 could do the same (or even, sneakily, resume debugging it - the
684 child's exec has failed, or something similar).
685
686 This doesn't clean up "properly", because we can't call
687 target_detach, but that's OK; if the current target is "child",
688 then it doesn't need any further cleanups, and lin_lwp will
689 generally not encounter vfork (vfork is defined to fork
690 in libpthread.so).
691
692 The holding part is very easy if we have VFORKDONE events;
693 but keeping track of both processes is beyond GDB at the
694 moment. So we don't expose the parent to the rest of GDB.
695 Instead we quietly hold onto it until such time as we can
696 safely resume it. */
697
698 if (has_vforked)
699 linux_parent_pid = parent_pid;
700 else if (!detach_fork)
701 {
702 struct fork_info *fp;
703 /* Retain parent fork in ptrace (stopped) state. */
704 fp = find_fork_pid (parent_pid);
705 if (!fp)
706 fp = add_fork (parent_pid);
707 fork_save_infrun_state (fp, 0);
708 }
709 else
710 target_detach (NULL, 0);
711
712 inferior_ptid = ptid_build (child_pid, child_pid, 0);
713
714 /* Reinstall ourselves, since we might have been removed in
715 target_detach (which does other necessary cleanup). */
716
717 push_target (ops);
718 linux_nat_switch_fork (inferior_ptid);
719 check_for_thread_db ();
720
721 /* Reset breakpoints in the child as appropriate. */
722 follow_inferior_reset_breakpoints ();
723 }
724
725 if (target_can_async_p ())
726 target_async (inferior_event_handler, 0);
727
728 return 0;
729 }
730
731 \f
732 static void
733 linux_child_insert_fork_catchpoint (int pid)
734 {
735 if (! linux_supports_tracefork (pid))
736 error (_("Your system does not support fork catchpoints."));
737 }
738
739 static void
740 linux_child_insert_vfork_catchpoint (int pid)
741 {
742 if (!linux_supports_tracefork (pid))
743 error (_("Your system does not support vfork catchpoints."));
744 }
745
746 static void
747 linux_child_insert_exec_catchpoint (int pid)
748 {
749 if (!linux_supports_tracefork (pid))
750 error (_("Your system does not support exec catchpoints."));
751 }
752
753 /* On GNU/Linux there are no real LWP's. The closest thing to LWP's
754 are processes sharing the same VM space. A multi-threaded process
755 is basically a group of such processes. However, such a grouping
756 is almost entirely a user-space issue; the kernel doesn't enforce
757 such a grouping at all (this might change in the future). In
758 general, we'll rely on the threads library (i.e. the GNU/Linux
759 Threads library) to provide such a grouping.
760
761 It is perfectly well possible to write a multi-threaded application
762 without the assistance of a threads library, by using the clone
763 system call directly. This module should be able to give some
764 rudimentary support for debugging such applications if developers
765 specify the CLONE_PTRACE flag in the clone system call, and are
766 using the Linux kernel 2.4 or above.
767
768 Note that there are some peculiarities in GNU/Linux that affect
769 this code:
770
771 - In general one should specify the __WCLONE flag to waitpid in
772 order to make it report events for any of the cloned processes
773 (and leave it out for the initial process). However, if a cloned
774 process has exited the exit status is only reported if the
775 __WCLONE flag is absent. Linux kernel 2.4 has a __WALL flag, but
776 we cannot use it since GDB must work on older systems too.
777
778 - When a traced, cloned process exits and is waited for by the
779 debugger, the kernel reassigns it to the original parent and
780 keeps it around as a "zombie". Somehow, the GNU/Linux Threads
781 library doesn't notice this, which leads to the "zombie problem":
782 When debugged a multi-threaded process that spawns a lot of
783 threads will run out of processes, even if the threads exit,
784 because the "zombies" stay around. */
785
786 /* List of known LWPs. */
787 struct lwp_info *lwp_list;
788
789 /* Number of LWPs in the list. */
790 static int num_lwps;
791 \f
792
793 /* If the last reported event was a SIGTRAP, this variable is set to
794 the process id of the LWP/thread that got it. */
795 ptid_t trap_ptid;
796 \f
797
798 /* Since we cannot wait (in linux_nat_wait) for the initial process and
799 any cloned processes with a single call to waitpid, we have to use
800 the WNOHANG flag and call waitpid in a loop. To optimize
801 things a bit we use `sigsuspend' to wake us up when a process has
802 something to report (it will send us a SIGCHLD if it has). To make
803 this work we have to juggle with the signal mask. We save the
804 original signal mask such that we can restore it before creating a
805 new process in order to avoid blocking certain signals in the
806 inferior. We then block SIGCHLD during the waitpid/sigsuspend
807 loop. */
808
809 /* Original signal mask. */
810 static sigset_t normal_mask;
811
812 /* Signal mask for use with sigsuspend in linux_nat_wait, initialized in
813 _initialize_linux_nat. */
814 static sigset_t suspend_mask;
815
816 /* SIGCHLD action for synchronous mode. */
817 struct sigaction sync_sigchld_action;
818
819 /* SIGCHLD action for asynchronous mode. */
820 static struct sigaction async_sigchld_action;
821 \f
822
823 /* Prototypes for local functions. */
824 static int stop_wait_callback (struct lwp_info *lp, void *data);
825 static int linux_nat_thread_alive (ptid_t ptid);
826 static char *linux_child_pid_to_exec_file (int pid);
827 static int cancel_breakpoint (struct lwp_info *lp);
828
829 \f
830 /* Convert wait status STATUS to a string. Used for printing debug
831 messages only. */
832
833 static char *
834 status_to_str (int status)
835 {
836 static char buf[64];
837
838 if (WIFSTOPPED (status))
839 snprintf (buf, sizeof (buf), "%s (stopped)",
840 strsignal (WSTOPSIG (status)));
841 else if (WIFSIGNALED (status))
842 snprintf (buf, sizeof (buf), "%s (terminated)",
843 strsignal (WSTOPSIG (status)));
844 else
845 snprintf (buf, sizeof (buf), "%d (exited)", WEXITSTATUS (status));
846
847 return buf;
848 }
849
850 /* Initialize the list of LWPs. Note that this module, contrary to
851 what GDB's generic threads layer does for its thread list,
852 re-initializes the LWP lists whenever we mourn or detach (which
853 doesn't involve mourning) the inferior. */
854
855 static void
856 init_lwp_list (void)
857 {
858 struct lwp_info *lp, *lpnext;
859
860 for (lp = lwp_list; lp; lp = lpnext)
861 {
862 lpnext = lp->next;
863 xfree (lp);
864 }
865
866 lwp_list = NULL;
867 num_lwps = 0;
868 }
869
870 /* Add the LWP specified by PID to the list. Return a pointer to the
871 structure describing the new LWP. The LWP should already be stopped
872 (with an exception for the very first LWP). */
873
874 static struct lwp_info *
875 add_lwp (ptid_t ptid)
876 {
877 struct lwp_info *lp;
878
879 gdb_assert (is_lwp (ptid));
880
881 lp = (struct lwp_info *) xmalloc (sizeof (struct lwp_info));
882
883 memset (lp, 0, sizeof (struct lwp_info));
884
885 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
886
887 lp->ptid = ptid;
888
889 lp->next = lwp_list;
890 lwp_list = lp;
891 ++num_lwps;
892
893 if (num_lwps > 1 && linux_nat_new_thread != NULL)
894 linux_nat_new_thread (ptid);
895
896 return lp;
897 }
898
899 /* Remove the LWP specified by PID from the list. */
900
901 static void
902 delete_lwp (ptid_t ptid)
903 {
904 struct lwp_info *lp, *lpprev;
905
906 lpprev = NULL;
907
908 for (lp = lwp_list; lp; lpprev = lp, lp = lp->next)
909 if (ptid_equal (lp->ptid, ptid))
910 break;
911
912 if (!lp)
913 return;
914
915 num_lwps--;
916
917 if (lpprev)
918 lpprev->next = lp->next;
919 else
920 lwp_list = lp->next;
921
922 xfree (lp);
923 }
924
925 /* Return a pointer to the structure describing the LWP corresponding
926 to PID. If no corresponding LWP could be found, return NULL. */
927
928 static struct lwp_info *
929 find_lwp_pid (ptid_t ptid)
930 {
931 struct lwp_info *lp;
932 int lwp;
933
934 if (is_lwp (ptid))
935 lwp = GET_LWP (ptid);
936 else
937 lwp = GET_PID (ptid);
938
939 for (lp = lwp_list; lp; lp = lp->next)
940 if (lwp == GET_LWP (lp->ptid))
941 return lp;
942
943 return NULL;
944 }
945
946 /* Call CALLBACK with its second argument set to DATA for every LWP in
947 the list. If CALLBACK returns 1 for a particular LWP, return a
948 pointer to the structure describing that LWP immediately.
949 Otherwise return NULL. */
950
951 struct lwp_info *
952 iterate_over_lwps (int (*callback) (struct lwp_info *, void *), void *data)
953 {
954 struct lwp_info *lp, *lpnext;
955
956 for (lp = lwp_list; lp; lp = lpnext)
957 {
958 lpnext = lp->next;
959 if ((*callback) (lp, data))
960 return lp;
961 }
962
963 return NULL;
964 }
965
966 /* Update our internal state when changing from one fork (checkpoint,
967 et cetera) to another indicated by NEW_PTID. We can only switch
968 single-threaded applications, so we only create one new LWP, and
969 the previous list is discarded. */
970
971 void
972 linux_nat_switch_fork (ptid_t new_ptid)
973 {
974 struct lwp_info *lp;
975
976 init_thread_list ();
977 init_lwp_list ();
978 lp = add_lwp (new_ptid);
979 add_thread_silent (new_ptid);
980 lp->stopped = 1;
981 }
982
983 /* Record a PTID for later deletion. */
984
985 struct saved_ptids
986 {
987 ptid_t ptid;
988 struct saved_ptids *next;
989 };
990 static struct saved_ptids *threads_to_delete;
991
992 static void
993 record_dead_thread (ptid_t ptid)
994 {
995 struct saved_ptids *p = xmalloc (sizeof (struct saved_ptids));
996 p->ptid = ptid;
997 p->next = threads_to_delete;
998 threads_to_delete = p;
999 }
1000
1001 /* Delete any dead threads which are not the current thread. */
1002
1003 static void
1004 prune_lwps (void)
1005 {
1006 struct saved_ptids **p = &threads_to_delete;
1007
1008 while (*p)
1009 if (! ptid_equal ((*p)->ptid, inferior_ptid))
1010 {
1011 struct saved_ptids *tmp = *p;
1012 delete_thread (tmp->ptid);
1013 *p = tmp->next;
1014 xfree (tmp);
1015 }
1016 else
1017 p = &(*p)->next;
1018 }
1019
1020 /* Handle the exit of a single thread LP. */
1021
1022 static void
1023 exit_lwp (struct lwp_info *lp)
1024 {
1025 if (in_thread_list (lp->ptid))
1026 {
1027 if (print_thread_events)
1028 printf_unfiltered (_("[%s exited]\n"), target_pid_to_str (lp->ptid));
1029
1030 /* Core GDB cannot deal with us deleting the current thread. */
1031 if (!ptid_equal (lp->ptid, inferior_ptid))
1032 delete_thread (lp->ptid);
1033 else
1034 record_dead_thread (lp->ptid);
1035 }
1036
1037 delete_lwp (lp->ptid);
1038 }
1039
1040 /* Detect `T (stopped)' in `/proc/PID/status'.
1041 Other states including `T (tracing stop)' are reported as false. */
1042
1043 static int
1044 pid_is_stopped (pid_t pid)
1045 {
1046 FILE *status_file;
1047 char buf[100];
1048 int retval = 0;
1049
1050 snprintf (buf, sizeof (buf), "/proc/%d/status", (int) pid);
1051 status_file = fopen (buf, "r");
1052 if (status_file != NULL)
1053 {
1054 int have_state = 0;
1055
1056 while (fgets (buf, sizeof (buf), status_file))
1057 {
1058 if (strncmp (buf, "State:", 6) == 0)
1059 {
1060 have_state = 1;
1061 break;
1062 }
1063 }
1064 if (have_state && strstr (buf, "T (stopped)") != NULL)
1065 retval = 1;
1066 fclose (status_file);
1067 }
1068 return retval;
1069 }
1070
1071 /* Wait for the LWP specified by LP, which we have just attached to.
1072 Returns a wait status for that LWP, to cache. */
1073
1074 static int
1075 linux_nat_post_attach_wait (ptid_t ptid, int first, int *cloned,
1076 int *signalled)
1077 {
1078 pid_t new_pid, pid = GET_LWP (ptid);
1079 int status;
1080
1081 if (pid_is_stopped (pid))
1082 {
1083 if (debug_linux_nat)
1084 fprintf_unfiltered (gdb_stdlog,
1085 "LNPAW: Attaching to a stopped process\n");
1086
1087 /* The process is definitely stopped. It is in a job control
1088 stop, unless the kernel predates the TASK_STOPPED /
1089 TASK_TRACED distinction, in which case it might be in a
1090 ptrace stop. Make sure it is in a ptrace stop; from there we
1091 can kill it, signal it, et cetera.
1092
1093 First make sure there is a pending SIGSTOP. Since we are
1094 already attached, the process can not transition from stopped
1095 to running without a PTRACE_CONT; so we know this signal will
1096 go into the queue. The SIGSTOP generated by PTRACE_ATTACH is
1097 probably already in the queue (unless this kernel is old
1098 enough to use TASK_STOPPED for ptrace stops); but since SIGSTOP
1099 is not an RT signal, it can only be queued once. */
1100 kill_lwp (pid, SIGSTOP);
1101
1102 /* Finally, resume the stopped process. This will deliver the SIGSTOP
1103 (or a higher priority signal, just like normal PTRACE_ATTACH). */
1104 ptrace (PTRACE_CONT, pid, 0, 0);
1105 }
1106
1107 /* Make sure the initial process is stopped. The user-level threads
1108 layer might want to poke around in the inferior, and that won't
1109 work if things haven't stabilized yet. */
1110 new_pid = my_waitpid (pid, &status, 0);
1111 if (new_pid == -1 && errno == ECHILD)
1112 {
1113 if (first)
1114 warning (_("%s is a cloned process"), target_pid_to_str (ptid));
1115
1116 /* Try again with __WCLONE to check cloned processes. */
1117 new_pid = my_waitpid (pid, &status, __WCLONE);
1118 *cloned = 1;
1119 }
1120
1121 gdb_assert (pid == new_pid && WIFSTOPPED (status));
1122
1123 if (WSTOPSIG (status) != SIGSTOP)
1124 {
1125 *signalled = 1;
1126 if (debug_linux_nat)
1127 fprintf_unfiltered (gdb_stdlog,
1128 "LNPAW: Received %s after attaching\n",
1129 status_to_str (status));
1130 }
1131
1132 return status;
1133 }
1134
1135 /* Attach to the LWP specified by PID. Return 0 if successful or -1
1136 if the new LWP could not be attached. */
1137
1138 int
1139 lin_lwp_attach_lwp (ptid_t ptid)
1140 {
1141 struct lwp_info *lp;
1142 int async_events_were_enabled = 0;
1143
1144 gdb_assert (is_lwp (ptid));
1145
1146 if (target_can_async_p ())
1147 async_events_were_enabled = linux_nat_async_events (0);
1148
1149 lp = find_lwp_pid (ptid);
1150
1151 /* We assume that we're already attached to any LWP that has an id
1152 equal to the overall process id, and to any LWP that is already
1153 in our list of LWPs. If we're not seeing exit events from threads
1154 and we've had PID wraparound since we last tried to stop all threads,
1155 this assumption might be wrong; fortunately, this is very unlikely
1156 to happen. */
1157 if (GET_LWP (ptid) != GET_PID (ptid) && lp == NULL)
1158 {
1159 int status, cloned = 0, signalled = 0;
1160
1161 if (ptrace (PTRACE_ATTACH, GET_LWP (ptid), 0, 0) < 0)
1162 {
1163 /* If we fail to attach to the thread, issue a warning,
1164 but continue. One way this can happen is if thread
1165 creation is interrupted; as of Linux kernel 2.6.19, a
1166 bug may place threads in the thread list and then fail
1167 to create them. */
1168 warning (_("Can't attach %s: %s"), target_pid_to_str (ptid),
1169 safe_strerror (errno));
1170 return -1;
1171 }
1172
1173 if (debug_linux_nat)
1174 fprintf_unfiltered (gdb_stdlog,
1175 "LLAL: PTRACE_ATTACH %s, 0, 0 (OK)\n",
1176 target_pid_to_str (ptid));
1177
1178 status = linux_nat_post_attach_wait (ptid, 0, &cloned, &signalled);
1179 lp = add_lwp (ptid);
1180 lp->stopped = 1;
1181 lp->cloned = cloned;
1182 lp->signalled = signalled;
1183 if (WSTOPSIG (status) != SIGSTOP)
1184 {
1185 lp->resumed = 1;
1186 lp->status = status;
1187 }
1188
1189 target_post_attach (GET_LWP (lp->ptid));
1190
1191 if (debug_linux_nat)
1192 {
1193 fprintf_unfiltered (gdb_stdlog,
1194 "LLAL: waitpid %s received %s\n",
1195 target_pid_to_str (ptid),
1196 status_to_str (status));
1197 }
1198 }
1199 else
1200 {
1201 /* We assume that the LWP representing the original process is
1202 already stopped. Mark it as stopped in the data structure
1203 that the GNU/linux ptrace layer uses to keep track of
1204 threads. Note that this won't have already been done since
1205 the main thread will have, we assume, been stopped by an
1206 attach from a different layer. */
1207 if (lp == NULL)
1208 lp = add_lwp (ptid);
1209 lp->stopped = 1;
1210 }
1211
1212 if (async_events_were_enabled)
1213 linux_nat_async_events (1);
1214
1215 return 0;
1216 }
1217
1218 static void
1219 linux_nat_create_inferior (char *exec_file, char *allargs, char **env,
1220 int from_tty)
1221 {
1222 int saved_async = 0;
1223
1224 /* The fork_child mechanism is synchronous and calls target_wait, so
1225 we have to mask the async mode. */
1226
1227 if (target_can_async_p ())
1228 saved_async = linux_nat_async_mask (0);
1229 else
1230 {
1231 /* Restore the original signal mask. */
1232 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1233 /* Make sure we don't block SIGCHLD during a sigsuspend. */
1234 suspend_mask = normal_mask;
1235 sigdelset (&suspend_mask, SIGCHLD);
1236 }
1237
1238 linux_ops->to_create_inferior (exec_file, allargs, env, from_tty);
1239
1240 if (saved_async)
1241 linux_nat_async_mask (saved_async);
1242 }
1243
1244 static void
1245 linux_nat_attach (char *args, int from_tty)
1246 {
1247 struct lwp_info *lp;
1248 int status;
1249
1250 /* FIXME: We should probably accept a list of process id's, and
1251 attach all of them. */
1252 linux_ops->to_attach (args, from_tty);
1253
1254 if (!target_can_async_p ())
1255 {
1256 /* Restore the original signal mask. */
1257 sigprocmask (SIG_SETMASK, &normal_mask, NULL);
1258 /* Make sure we don't block SIGCHLD during a sigsuspend. */
1259 suspend_mask = normal_mask;
1260 sigdelset (&suspend_mask, SIGCHLD);
1261 }
1262
1263 /* Add the initial process as the first LWP to the list. */
1264 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid), GET_PID (inferior_ptid));
1265 lp = add_lwp (inferior_ptid);
1266
1267 status = linux_nat_post_attach_wait (lp->ptid, 1, &lp->cloned,
1268 &lp->signalled);
1269 lp->stopped = 1;
1270
1271 /* If this process is not using thread_db, then we still don't
1272 detect any other threads, but add at least this one. */
1273 add_thread_silent (lp->ptid);
1274
1275 /* Save the wait status to report later. */
1276 lp->resumed = 1;
1277 if (debug_linux_nat)
1278 fprintf_unfiltered (gdb_stdlog,
1279 "LNA: waitpid %ld, saving status %s\n",
1280 (long) GET_PID (lp->ptid), status_to_str (status));
1281
1282 if (!target_can_async_p ())
1283 lp->status = status;
1284 else
1285 {
1286 /* We already waited for this LWP, so put the wait result on the
1287 pipe. The event loop will wake up and gets us to handling
1288 this event. */
1289 linux_nat_event_pipe_push (GET_PID (lp->ptid), status,
1290 lp->cloned ? __WCLONE : 0);
1291 /* Register in the event loop. */
1292 target_async (inferior_event_handler, 0);
1293 }
1294 }
1295
1296 /* Get pending status of LP. */
1297 static int
1298 get_pending_status (struct lwp_info *lp, int *status)
1299 {
1300 struct target_waitstatus last;
1301 ptid_t last_ptid;
1302
1303 get_last_target_status (&last_ptid, &last);
1304
1305 /* If this lwp is the ptid that GDB is processing an event from, the
1306 signal will be in stop_signal. Otherwise, in all-stop + sync
1307 mode, we may cache pending events in lp->status while trying to
1308 stop all threads (see stop_wait_callback). In async mode, the
1309 events are always cached in waitpid_queue. */
1310
1311 *status = 0;
1312 if (GET_LWP (lp->ptid) == GET_LWP (last_ptid))
1313 {
1314 if (stop_signal != TARGET_SIGNAL_0
1315 && signal_pass_state (stop_signal))
1316 *status = W_STOPCODE (target_signal_to_host (stop_signal));
1317 }
1318 else if (target_can_async_p ())
1319 queued_waitpid (GET_LWP (lp->ptid), status, __WALL);
1320 else
1321 *status = lp->status;
1322
1323 return 0;
1324 }
1325
1326 static int
1327 detach_callback (struct lwp_info *lp, void *data)
1328 {
1329 gdb_assert (lp->status == 0 || WIFSTOPPED (lp->status));
1330
1331 if (debug_linux_nat && lp->status)
1332 fprintf_unfiltered (gdb_stdlog, "DC: Pending %s for %s on detach.\n",
1333 strsignal (WSTOPSIG (lp->status)),
1334 target_pid_to_str (lp->ptid));
1335
1336 /* If there is a pending SIGSTOP, get rid of it. */
1337 if (lp->signalled)
1338 {
1339 if (debug_linux_nat)
1340 fprintf_unfiltered (gdb_stdlog,
1341 "DC: Sending SIGCONT to %s\n",
1342 target_pid_to_str (lp->ptid));
1343
1344 kill_lwp (GET_LWP (lp->ptid), SIGCONT);
1345 lp->signalled = 0;
1346 }
1347
1348 /* We don't actually detach from the LWP that has an id equal to the
1349 overall process id just yet. */
1350 if (GET_LWP (lp->ptid) != GET_PID (lp->ptid))
1351 {
1352 int status = 0;
1353
1354 /* Pass on any pending signal for this LWP. */
1355 get_pending_status (lp, &status);
1356
1357 errno = 0;
1358 if (ptrace (PTRACE_DETACH, GET_LWP (lp->ptid), 0,
1359 WSTOPSIG (status)) < 0)
1360 error (_("Can't detach %s: %s"), target_pid_to_str (lp->ptid),
1361 safe_strerror (errno));
1362
1363 if (debug_linux_nat)
1364 fprintf_unfiltered (gdb_stdlog,
1365 "PTRACE_DETACH (%s, %s, 0) (OK)\n",
1366 target_pid_to_str (lp->ptid),
1367 strsignal (WSTOPSIG (lp->status)));
1368
1369 delete_lwp (lp->ptid);
1370 }
1371
1372 return 0;
1373 }
1374
1375 static void
1376 linux_nat_detach (char *args, int from_tty)
1377 {
1378 int pid;
1379 int status;
1380 enum target_signal sig;
1381
1382 if (target_can_async_p ())
1383 linux_nat_async (NULL, 0);
1384
1385 iterate_over_lwps (detach_callback, NULL);
1386
1387 /* Only the initial process should be left right now. */
1388 gdb_assert (num_lwps == 1);
1389
1390 /* Pass on any pending signal for the last LWP. */
1391 if ((args == NULL || *args == '\0')
1392 && get_pending_status (lwp_list, &status) != -1
1393 && WIFSTOPPED (status))
1394 {
1395 /* Put the signal number in ARGS so that inf_ptrace_detach will
1396 pass it along with PTRACE_DETACH. */
1397 args = alloca (8);
1398 sprintf (args, "%d", (int) WSTOPSIG (status));
1399 fprintf_unfiltered (gdb_stdlog,
1400 "LND: Sending signal %s to %s\n",
1401 args,
1402 target_pid_to_str (lwp_list->ptid));
1403 }
1404
1405 trap_ptid = null_ptid;
1406
1407 /* Destroy LWP info; it's no longer valid. */
1408 init_lwp_list ();
1409
1410 pid = GET_PID (inferior_ptid);
1411 inferior_ptid = pid_to_ptid (pid);
1412 linux_ops->to_detach (args, from_tty);
1413
1414 if (target_can_async_p ())
1415 drain_queued_events (pid);
1416 }
1417
1418 /* Resume LP. */
1419
1420 static int
1421 resume_callback (struct lwp_info *lp, void *data)
1422 {
1423 if (lp->stopped && lp->status == 0)
1424 {
1425 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
1426 0, TARGET_SIGNAL_0);
1427 if (debug_linux_nat)
1428 fprintf_unfiltered (gdb_stdlog,
1429 "RC: PTRACE_CONT %s, 0, 0 (resume sibling)\n",
1430 target_pid_to_str (lp->ptid));
1431 lp->stopped = 0;
1432 lp->step = 0;
1433 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1434 }
1435
1436 return 0;
1437 }
1438
1439 static int
1440 resume_clear_callback (struct lwp_info *lp, void *data)
1441 {
1442 lp->resumed = 0;
1443 return 0;
1444 }
1445
1446 static int
1447 resume_set_callback (struct lwp_info *lp, void *data)
1448 {
1449 lp->resumed = 1;
1450 return 0;
1451 }
1452
1453 static void
1454 linux_nat_resume (ptid_t ptid, int step, enum target_signal signo)
1455 {
1456 struct lwp_info *lp;
1457 int resume_all;
1458
1459 if (debug_linux_nat)
1460 fprintf_unfiltered (gdb_stdlog,
1461 "LLR: Preparing to %s %s, %s, inferior_ptid %s\n",
1462 step ? "step" : "resume",
1463 target_pid_to_str (ptid),
1464 signo ? strsignal (signo) : "0",
1465 target_pid_to_str (inferior_ptid));
1466
1467 prune_lwps ();
1468
1469 if (target_can_async_p ())
1470 /* Block events while we're here. */
1471 linux_nat_async_events (0);
1472
1473 /* A specific PTID means `step only this process id'. */
1474 resume_all = (PIDGET (ptid) == -1);
1475
1476 if (resume_all)
1477 iterate_over_lwps (resume_set_callback, NULL);
1478 else
1479 iterate_over_lwps (resume_clear_callback, NULL);
1480
1481 /* If PID is -1, it's the current inferior that should be
1482 handled specially. */
1483 if (PIDGET (ptid) == -1)
1484 ptid = inferior_ptid;
1485
1486 lp = find_lwp_pid (ptid);
1487 gdb_assert (lp != NULL);
1488
1489 ptid = pid_to_ptid (GET_LWP (lp->ptid));
1490
1491 /* Remember if we're stepping. */
1492 lp->step = step;
1493
1494 /* Mark this LWP as resumed. */
1495 lp->resumed = 1;
1496
1497 /* If we have a pending wait status for this thread, there is no
1498 point in resuming the process. But first make sure that
1499 linux_nat_wait won't preemptively handle the event - we
1500 should never take this short-circuit if we are going to
1501 leave LP running, since we have skipped resuming all the
1502 other threads. This bit of code needs to be synchronized
1503 with linux_nat_wait. */
1504
1505 /* In async mode, we never have pending wait status. */
1506 if (target_can_async_p () && lp->status)
1507 internal_error (__FILE__, __LINE__, "Pending status in async mode");
1508
1509 if (lp->status && WIFSTOPPED (lp->status))
1510 {
1511 int saved_signo = target_signal_from_host (WSTOPSIG (lp->status));
1512
1513 if (signal_stop_state (saved_signo) == 0
1514 && signal_print_state (saved_signo) == 0
1515 && signal_pass_state (saved_signo) == 1)
1516 {
1517 if (debug_linux_nat)
1518 fprintf_unfiltered (gdb_stdlog,
1519 "LLR: Not short circuiting for ignored "
1520 "status 0x%x\n", lp->status);
1521
1522 /* FIXME: What should we do if we are supposed to continue
1523 this thread with a signal? */
1524 gdb_assert (signo == TARGET_SIGNAL_0);
1525 signo = saved_signo;
1526 lp->status = 0;
1527 }
1528 }
1529
1530 if (lp->status)
1531 {
1532 /* FIXME: What should we do if we are supposed to continue
1533 this thread with a signal? */
1534 gdb_assert (signo == TARGET_SIGNAL_0);
1535
1536 if (debug_linux_nat)
1537 fprintf_unfiltered (gdb_stdlog,
1538 "LLR: Short circuiting for status 0x%x\n",
1539 lp->status);
1540
1541 return;
1542 }
1543
1544 /* Mark LWP as not stopped to prevent it from being continued by
1545 resume_callback. */
1546 lp->stopped = 0;
1547
1548 if (resume_all)
1549 iterate_over_lwps (resume_callback, NULL);
1550
1551 linux_ops->to_resume (ptid, step, signo);
1552 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1553
1554 if (debug_linux_nat)
1555 fprintf_unfiltered (gdb_stdlog,
1556 "LLR: %s %s, %s (resume event thread)\n",
1557 step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
1558 target_pid_to_str (ptid),
1559 signo ? strsignal (signo) : "0");
1560
1561 if (target_can_async_p ())
1562 {
1563 target_executing = 1;
1564 target_async (inferior_event_handler, 0);
1565 }
1566 }
1567
1568 /* Issue kill to specified lwp. */
1569
1570 static int tkill_failed;
1571
1572 static int
1573 kill_lwp (int lwpid, int signo)
1574 {
1575 errno = 0;
1576
1577 /* Use tkill, if possible, in case we are using nptl threads. If tkill
1578 fails, then we are not using nptl threads and we should be using kill. */
1579
1580 #ifdef HAVE_TKILL_SYSCALL
1581 if (!tkill_failed)
1582 {
1583 int ret = syscall (__NR_tkill, lwpid, signo);
1584 if (errno != ENOSYS)
1585 return ret;
1586 errno = 0;
1587 tkill_failed = 1;
1588 }
1589 #endif
1590
1591 return kill (lwpid, signo);
1592 }
1593
1594 /* Handle a GNU/Linux extended wait response. If we see a clone
1595 event, we need to add the new LWP to our list (and not report the
1596 trap to higher layers). This function returns non-zero if the
1597 event should be ignored and we should wait again. If STOPPING is
1598 true, the new LWP remains stopped, otherwise it is continued. */
1599
1600 static int
1601 linux_handle_extended_wait (struct lwp_info *lp, int status,
1602 int stopping)
1603 {
1604 int pid = GET_LWP (lp->ptid);
1605 struct target_waitstatus *ourstatus = &lp->waitstatus;
1606 struct lwp_info *new_lp = NULL;
1607 int event = status >> 16;
1608
1609 if (event == PTRACE_EVENT_FORK || event == PTRACE_EVENT_VFORK
1610 || event == PTRACE_EVENT_CLONE)
1611 {
1612 unsigned long new_pid;
1613 int ret;
1614
1615 ptrace (PTRACE_GETEVENTMSG, pid, 0, &new_pid);
1616
1617 /* If we haven't already seen the new PID stop, wait for it now. */
1618 if (! pull_pid_from_list (&stopped_pids, new_pid, &status))
1619 {
1620 /* The new child has a pending SIGSTOP. We can't affect it until it
1621 hits the SIGSTOP, but we're already attached. */
1622 ret = my_waitpid (new_pid, &status,
1623 (event == PTRACE_EVENT_CLONE) ? __WCLONE : 0);
1624 if (ret == -1)
1625 perror_with_name (_("waiting for new child"));
1626 else if (ret != new_pid)
1627 internal_error (__FILE__, __LINE__,
1628 _("wait returned unexpected PID %d"), ret);
1629 else if (!WIFSTOPPED (status))
1630 internal_error (__FILE__, __LINE__,
1631 _("wait returned unexpected status 0x%x"), status);
1632 }
1633
1634 ourstatus->value.related_pid = new_pid;
1635
1636 if (event == PTRACE_EVENT_FORK)
1637 ourstatus->kind = TARGET_WAITKIND_FORKED;
1638 else if (event == PTRACE_EVENT_VFORK)
1639 ourstatus->kind = TARGET_WAITKIND_VFORKED;
1640 else
1641 {
1642 ourstatus->kind = TARGET_WAITKIND_IGNORE;
1643 new_lp = add_lwp (BUILD_LWP (new_pid, GET_PID (inferior_ptid)));
1644 new_lp->cloned = 1;
1645
1646 if (WSTOPSIG (status) != SIGSTOP)
1647 {
1648 /* This can happen if someone starts sending signals to
1649 the new thread before it gets a chance to run, which
1650 have a lower number than SIGSTOP (e.g. SIGUSR1).
1651 This is an unlikely case, and harder to handle for
1652 fork / vfork than for clone, so we do not try - but
1653 we handle it for clone events here. We'll send
1654 the other signal on to the thread below. */
1655
1656 new_lp->signalled = 1;
1657 }
1658 else
1659 status = 0;
1660
1661 if (stopping)
1662 new_lp->stopped = 1;
1663 else
1664 {
1665 new_lp->resumed = 1;
1666 ptrace (PTRACE_CONT, lp->waitstatus.value.related_pid, 0,
1667 status ? WSTOPSIG (status) : 0);
1668 }
1669
1670 if (debug_linux_nat)
1671 fprintf_unfiltered (gdb_stdlog,
1672 "LHEW: Got clone event from LWP %ld, resuming\n",
1673 GET_LWP (lp->ptid));
1674 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1675
1676 return 1;
1677 }
1678
1679 return 0;
1680 }
1681
1682 if (event == PTRACE_EVENT_EXEC)
1683 {
1684 ourstatus->kind = TARGET_WAITKIND_EXECD;
1685 ourstatus->value.execd_pathname
1686 = xstrdup (linux_child_pid_to_exec_file (pid));
1687
1688 if (linux_parent_pid)
1689 {
1690 detach_breakpoints (linux_parent_pid);
1691 ptrace (PTRACE_DETACH, linux_parent_pid, 0, 0);
1692
1693 linux_parent_pid = 0;
1694 }
1695
1696 return 0;
1697 }
1698
1699 internal_error (__FILE__, __LINE__,
1700 _("unknown ptrace event %d"), event);
1701 }
1702
1703 /* Wait for LP to stop. Returns the wait status, or 0 if the LWP has
1704 exited. */
1705
1706 static int
1707 wait_lwp (struct lwp_info *lp)
1708 {
1709 pid_t pid;
1710 int status;
1711 int thread_dead = 0;
1712
1713 gdb_assert (!lp->stopped);
1714 gdb_assert (lp->status == 0);
1715
1716 pid = my_waitpid (GET_LWP (lp->ptid), &status, 0);
1717 if (pid == -1 && errno == ECHILD)
1718 {
1719 pid = my_waitpid (GET_LWP (lp->ptid), &status, __WCLONE);
1720 if (pid == -1 && errno == ECHILD)
1721 {
1722 /* The thread has previously exited. We need to delete it
1723 now because, for some vendor 2.4 kernels with NPTL
1724 support backported, there won't be an exit event unless
1725 it is the main thread. 2.6 kernels will report an exit
1726 event for each thread that exits, as expected. */
1727 thread_dead = 1;
1728 if (debug_linux_nat)
1729 fprintf_unfiltered (gdb_stdlog, "WL: %s vanished.\n",
1730 target_pid_to_str (lp->ptid));
1731 }
1732 }
1733
1734 if (!thread_dead)
1735 {
1736 gdb_assert (pid == GET_LWP (lp->ptid));
1737
1738 if (debug_linux_nat)
1739 {
1740 fprintf_unfiltered (gdb_stdlog,
1741 "WL: waitpid %s received %s\n",
1742 target_pid_to_str (lp->ptid),
1743 status_to_str (status));
1744 }
1745 }
1746
1747 /* Check if the thread has exited. */
1748 if (WIFEXITED (status) || WIFSIGNALED (status))
1749 {
1750 thread_dead = 1;
1751 if (debug_linux_nat)
1752 fprintf_unfiltered (gdb_stdlog, "WL: %s exited.\n",
1753 target_pid_to_str (lp->ptid));
1754 }
1755
1756 if (thread_dead)
1757 {
1758 exit_lwp (lp);
1759 return 0;
1760 }
1761
1762 gdb_assert (WIFSTOPPED (status));
1763
1764 /* Handle GNU/Linux's extended waitstatus for trace events. */
1765 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
1766 {
1767 if (debug_linux_nat)
1768 fprintf_unfiltered (gdb_stdlog,
1769 "WL: Handling extended status 0x%06x\n",
1770 status);
1771 if (linux_handle_extended_wait (lp, status, 1))
1772 return wait_lwp (lp);
1773 }
1774
1775 return status;
1776 }
1777
1778 /* Save the most recent siginfo for LP. This is currently only called
1779 for SIGTRAP; some ports use the si_addr field for
1780 target_stopped_data_address. In the future, it may also be used to
1781 restore the siginfo of requeued signals. */
1782
1783 static void
1784 save_siginfo (struct lwp_info *lp)
1785 {
1786 errno = 0;
1787 ptrace (PTRACE_GETSIGINFO, GET_LWP (lp->ptid),
1788 (PTRACE_TYPE_ARG3) 0, &lp->siginfo);
1789
1790 if (errno != 0)
1791 memset (&lp->siginfo, 0, sizeof (lp->siginfo));
1792 }
1793
1794 /* Send a SIGSTOP to LP. */
1795
1796 static int
1797 stop_callback (struct lwp_info *lp, void *data)
1798 {
1799 if (!lp->stopped && !lp->signalled)
1800 {
1801 int ret;
1802
1803 if (debug_linux_nat)
1804 {
1805 fprintf_unfiltered (gdb_stdlog,
1806 "SC: kill %s **<SIGSTOP>**\n",
1807 target_pid_to_str (lp->ptid));
1808 }
1809 errno = 0;
1810 ret = kill_lwp (GET_LWP (lp->ptid), SIGSTOP);
1811 if (debug_linux_nat)
1812 {
1813 fprintf_unfiltered (gdb_stdlog,
1814 "SC: lwp kill %d %s\n",
1815 ret,
1816 errno ? safe_strerror (errno) : "ERRNO-OK");
1817 }
1818
1819 lp->signalled = 1;
1820 gdb_assert (lp->status == 0);
1821 }
1822
1823 return 0;
1824 }
1825
1826 /* Wait until LP is stopped. If DATA is non-null it is interpreted as
1827 a pointer to a set of signals to be flushed immediately. */
1828
1829 static int
1830 stop_wait_callback (struct lwp_info *lp, void *data)
1831 {
1832 sigset_t *flush_mask = data;
1833
1834 if (!lp->stopped)
1835 {
1836 int status;
1837
1838 status = wait_lwp (lp);
1839 if (status == 0)
1840 return 0;
1841
1842 /* Ignore any signals in FLUSH_MASK. */
1843 if (flush_mask && sigismember (flush_mask, WSTOPSIG (status)))
1844 {
1845 if (!lp->signalled)
1846 {
1847 lp->stopped = 1;
1848 return 0;
1849 }
1850
1851 errno = 0;
1852 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1853 if (debug_linux_nat)
1854 fprintf_unfiltered (gdb_stdlog,
1855 "PTRACE_CONT %s, 0, 0 (%s)\n",
1856 target_pid_to_str (lp->ptid),
1857 errno ? safe_strerror (errno) : "OK");
1858
1859 return stop_wait_callback (lp, flush_mask);
1860 }
1861
1862 if (WSTOPSIG (status) != SIGSTOP)
1863 {
1864 if (WSTOPSIG (status) == SIGTRAP)
1865 {
1866 /* If a LWP other than the LWP that we're reporting an
1867 event for has hit a GDB breakpoint (as opposed to
1868 some random trap signal), then just arrange for it to
1869 hit it again later. We don't keep the SIGTRAP status
1870 and don't forward the SIGTRAP signal to the LWP. We
1871 will handle the current event, eventually we will
1872 resume all LWPs, and this one will get its breakpoint
1873 trap again.
1874
1875 If we do not do this, then we run the risk that the
1876 user will delete or disable the breakpoint, but the
1877 thread will have already tripped on it. */
1878
1879 /* Save the trap's siginfo in case we need it later. */
1880 save_siginfo (lp);
1881
1882 /* Now resume this LWP and get the SIGSTOP event. */
1883 errno = 0;
1884 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1885 if (debug_linux_nat)
1886 {
1887 fprintf_unfiltered (gdb_stdlog,
1888 "PTRACE_CONT %s, 0, 0 (%s)\n",
1889 target_pid_to_str (lp->ptid),
1890 errno ? safe_strerror (errno) : "OK");
1891
1892 fprintf_unfiltered (gdb_stdlog,
1893 "SWC: Candidate SIGTRAP event in %s\n",
1894 target_pid_to_str (lp->ptid));
1895 }
1896 /* Hold this event/waitstatus while we check to see if
1897 there are any more (we still want to get that SIGSTOP). */
1898 stop_wait_callback (lp, data);
1899
1900 if (target_can_async_p ())
1901 {
1902 /* Don't leave a pending wait status in async mode.
1903 Retrigger the breakpoint. */
1904 if (!cancel_breakpoint (lp))
1905 {
1906 /* There was no gdb breakpoint set at pc. Put
1907 the event back in the queue. */
1908 if (debug_linux_nat)
1909 fprintf_unfiltered (gdb_stdlog,
1910 "SWC: kill %s, %s\n",
1911 target_pid_to_str (lp->ptid),
1912 status_to_str ((int) status));
1913 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
1914 }
1915 }
1916 else
1917 {
1918 /* Hold the SIGTRAP for handling by
1919 linux_nat_wait. */
1920 /* If there's another event, throw it back into the
1921 queue. */
1922 if (lp->status)
1923 {
1924 if (debug_linux_nat)
1925 fprintf_unfiltered (gdb_stdlog,
1926 "SWC: kill %s, %s\n",
1927 target_pid_to_str (lp->ptid),
1928 status_to_str ((int) status));
1929 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (lp->status));
1930 }
1931 /* Save the sigtrap event. */
1932 lp->status = status;
1933 }
1934 return 0;
1935 }
1936 else
1937 {
1938 /* The thread was stopped with a signal other than
1939 SIGSTOP, and didn't accidentally trip a breakpoint. */
1940
1941 if (debug_linux_nat)
1942 {
1943 fprintf_unfiltered (gdb_stdlog,
1944 "SWC: Pending event %s in %s\n",
1945 status_to_str ((int) status),
1946 target_pid_to_str (lp->ptid));
1947 }
1948 /* Now resume this LWP and get the SIGSTOP event. */
1949 errno = 0;
1950 ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
1951 if (debug_linux_nat)
1952 fprintf_unfiltered (gdb_stdlog,
1953 "SWC: PTRACE_CONT %s, 0, 0 (%s)\n",
1954 target_pid_to_str (lp->ptid),
1955 errno ? safe_strerror (errno) : "OK");
1956
1957 /* Hold this event/waitstatus while we check to see if
1958 there are any more (we still want to get that SIGSTOP). */
1959 stop_wait_callback (lp, data);
1960
1961 /* If the lp->status field is still empty, use it to
1962 hold this event. If not, then this event must be
1963 returned to the event queue of the LWP. */
1964 if (lp->status || target_can_async_p ())
1965 {
1966 if (debug_linux_nat)
1967 {
1968 fprintf_unfiltered (gdb_stdlog,
1969 "SWC: kill %s, %s\n",
1970 target_pid_to_str (lp->ptid),
1971 status_to_str ((int) status));
1972 }
1973 kill_lwp (GET_LWP (lp->ptid), WSTOPSIG (status));
1974 }
1975 else
1976 lp->status = status;
1977 return 0;
1978 }
1979 }
1980 else
1981 {
1982 /* We caught the SIGSTOP that we intended to catch, so
1983 there's no SIGSTOP pending. */
1984 lp->stopped = 1;
1985 lp->signalled = 0;
1986 }
1987 }
1988
1989 return 0;
1990 }
1991
1992 /* Check whether PID has any pending signals in FLUSH_MASK. If so set
1993 the appropriate bits in PENDING, and return 1 - otherwise return 0. */
1994
1995 static int
1996 linux_nat_has_pending (int pid, sigset_t *pending, sigset_t *flush_mask)
1997 {
1998 sigset_t blocked, ignored;
1999 int i;
2000
2001 linux_proc_pending_signals (pid, pending, &blocked, &ignored);
2002
2003 if (!flush_mask)
2004 return 0;
2005
2006 for (i = 1; i < NSIG; i++)
2007 if (sigismember (pending, i))
2008 if (!sigismember (flush_mask, i)
2009 || sigismember (&blocked, i)
2010 || sigismember (&ignored, i))
2011 sigdelset (pending, i);
2012
2013 if (sigisemptyset (pending))
2014 return 0;
2015
2016 return 1;
2017 }
2018
2019 /* DATA is interpreted as a mask of signals to flush. If LP has
2020 signals pending, and they are all in the flush mask, then arrange
2021 to flush them. LP should be stopped, as should all other threads
2022 it might share a signal queue with. */
2023
2024 static int
2025 flush_callback (struct lwp_info *lp, void *data)
2026 {
2027 sigset_t *flush_mask = data;
2028 sigset_t pending, intersection, blocked, ignored;
2029 int pid, status;
2030
2031 /* Normally, when an LWP exits, it is removed from the LWP list. The
2032 last LWP isn't removed till later, however. So if there is only
2033 one LWP on the list, make sure it's alive. */
2034 if (lwp_list == lp && lp->next == NULL)
2035 if (!linux_nat_thread_alive (lp->ptid))
2036 return 0;
2037
2038 /* Just because the LWP is stopped doesn't mean that new signals
2039 can't arrive from outside, so this function must be careful of
2040 race conditions. However, because all threads are stopped, we
2041 can assume that the pending mask will not shrink unless we resume
2042 the LWP, and that it will then get another signal. We can't
2043 control which one, however. */
2044
2045 if (lp->status)
2046 {
2047 if (debug_linux_nat)
2048 printf_unfiltered (_("FC: LP has pending status %06x\n"), lp->status);
2049 if (WIFSTOPPED (lp->status) && sigismember (flush_mask, WSTOPSIG (lp->status)))
2050 lp->status = 0;
2051 }
2052
2053 /* While there is a pending signal we would like to flush, continue
2054 the inferior and collect another signal. But if there's already
2055 a saved status that we don't want to flush, we can't resume the
2056 inferior - if it stopped for some other reason we wouldn't have
2057 anywhere to save the new status. In that case, we must leave the
2058 signal unflushed (and possibly generate an extra SIGINT stop).
2059 That's much less bad than losing a signal. */
2060 while (lp->status == 0
2061 && linux_nat_has_pending (GET_LWP (lp->ptid), &pending, flush_mask))
2062 {
2063 int ret;
2064
2065 errno = 0;
2066 ret = ptrace (PTRACE_CONT, GET_LWP (lp->ptid), 0, 0);
2067 if (debug_linux_nat)
2068 fprintf_unfiltered (gdb_stderr,
2069 "FC: Sent PTRACE_CONT, ret %d %d\n", ret, errno);
2070
2071 lp->stopped = 0;
2072 stop_wait_callback (lp, flush_mask);
2073 if (debug_linux_nat)
2074 fprintf_unfiltered (gdb_stderr,
2075 "FC: Wait finished; saved status is %d\n",
2076 lp->status);
2077 }
2078
2079 return 0;
2080 }
2081
2082 /* Return non-zero if LP has a wait status pending. */
2083
2084 static int
2085 status_callback (struct lwp_info *lp, void *data)
2086 {
2087 /* Only report a pending wait status if we pretend that this has
2088 indeed been resumed. */
2089 return (lp->status != 0 && lp->resumed);
2090 }
2091
2092 /* Return non-zero if LP isn't stopped. */
2093
2094 static int
2095 running_callback (struct lwp_info *lp, void *data)
2096 {
2097 return (lp->stopped == 0 || (lp->status != 0 && lp->resumed));
2098 }
2099
2100 /* Count the LWP's that have had events. */
2101
2102 static int
2103 count_events_callback (struct lwp_info *lp, void *data)
2104 {
2105 int *count = data;
2106
2107 gdb_assert (count != NULL);
2108
2109 /* Count only LWPs that have a SIGTRAP event pending. */
2110 if (lp->status != 0
2111 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2112 (*count)++;
2113
2114 return 0;
2115 }
2116
2117 /* Select the LWP (if any) that is currently being single-stepped. */
2118
2119 static int
2120 select_singlestep_lwp_callback (struct lwp_info *lp, void *data)
2121 {
2122 if (lp->step && lp->status != 0)
2123 return 1;
2124 else
2125 return 0;
2126 }
2127
2128 /* Select the Nth LWP that has had a SIGTRAP event. */
2129
2130 static int
2131 select_event_lwp_callback (struct lwp_info *lp, void *data)
2132 {
2133 int *selector = data;
2134
2135 gdb_assert (selector != NULL);
2136
2137 /* Select only LWPs that have a SIGTRAP event pending. */
2138 if (lp->status != 0
2139 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP)
2140 if ((*selector)-- == 0)
2141 return 1;
2142
2143 return 0;
2144 }
2145
2146 static int
2147 cancel_breakpoint (struct lwp_info *lp)
2148 {
2149 /* Arrange for a breakpoint to be hit again later. We don't keep
2150 the SIGTRAP status and don't forward the SIGTRAP signal to the
2151 LWP. We will handle the current event, eventually we will resume
2152 this LWP, and this breakpoint will trap again.
2153
2154 If we do not do this, then we run the risk that the user will
2155 delete or disable the breakpoint, but the LWP will have already
2156 tripped on it. */
2157
2158 if (breakpoint_inserted_here_p (read_pc_pid (lp->ptid) -
2159 gdbarch_decr_pc_after_break
2160 (current_gdbarch)))
2161 {
2162 if (debug_linux_nat)
2163 fprintf_unfiltered (gdb_stdlog,
2164 "CB: Push back breakpoint for %s\n",
2165 target_pid_to_str (lp->ptid));
2166
2167 /* Back up the PC if necessary. */
2168 if (gdbarch_decr_pc_after_break (current_gdbarch))
2169 write_pc_pid (read_pc_pid (lp->ptid) - gdbarch_decr_pc_after_break
2170 (current_gdbarch),
2171 lp->ptid);
2172 return 1;
2173 }
2174 return 0;
2175 }
2176
2177 static int
2178 cancel_breakpoints_callback (struct lwp_info *lp, void *data)
2179 {
2180 struct lwp_info *event_lp = data;
2181
2182 /* Leave the LWP that has been elected to receive a SIGTRAP alone. */
2183 if (lp == event_lp)
2184 return 0;
2185
2186 /* If a LWP other than the LWP that we're reporting an event for has
2187 hit a GDB breakpoint (as opposed to some random trap signal),
2188 then just arrange for it to hit it again later. We don't keep
2189 the SIGTRAP status and don't forward the SIGTRAP signal to the
2190 LWP. We will handle the current event, eventually we will resume
2191 all LWPs, and this one will get its breakpoint trap again.
2192
2193 If we do not do this, then we run the risk that the user will
2194 delete or disable the breakpoint, but the LWP will have already
2195 tripped on it. */
2196
2197 if (lp->status != 0
2198 && WIFSTOPPED (lp->status) && WSTOPSIG (lp->status) == SIGTRAP
2199 && cancel_breakpoint (lp))
2200 /* Throw away the SIGTRAP. */
2201 lp->status = 0;
2202
2203 return 0;
2204 }
2205
2206 /* Select one LWP out of those that have events pending. */
2207
2208 static void
2209 select_event_lwp (struct lwp_info **orig_lp, int *status)
2210 {
2211 int num_events = 0;
2212 int random_selector;
2213 struct lwp_info *event_lp;
2214
2215 /* Record the wait status for the original LWP. */
2216 (*orig_lp)->status = *status;
2217
2218 /* Give preference to any LWP that is being single-stepped. */
2219 event_lp = iterate_over_lwps (select_singlestep_lwp_callback, NULL);
2220 if (event_lp != NULL)
2221 {
2222 if (debug_linux_nat)
2223 fprintf_unfiltered (gdb_stdlog,
2224 "SEL: Select single-step %s\n",
2225 target_pid_to_str (event_lp->ptid));
2226 }
2227 else
2228 {
2229 /* No single-stepping LWP. Select one at random, out of those
2230 which have had SIGTRAP events. */
2231
2232 /* First see how many SIGTRAP events we have. */
2233 iterate_over_lwps (count_events_callback, &num_events);
2234
2235 /* Now randomly pick a LWP out of those that have had a SIGTRAP. */
2236 random_selector = (int)
2237 ((num_events * (double) rand ()) / (RAND_MAX + 1.0));
2238
2239 if (debug_linux_nat && num_events > 1)
2240 fprintf_unfiltered (gdb_stdlog,
2241 "SEL: Found %d SIGTRAP events, selecting #%d\n",
2242 num_events, random_selector);
2243
2244 event_lp = iterate_over_lwps (select_event_lwp_callback,
2245 &random_selector);
2246 }
2247
2248 if (event_lp != NULL)
2249 {
2250 /* Switch the event LWP. */
2251 *orig_lp = event_lp;
2252 *status = event_lp->status;
2253 }
2254
2255 /* Flush the wait status for the event LWP. */
2256 (*orig_lp)->status = 0;
2257 }
2258
2259 /* Return non-zero if LP has been resumed. */
2260
2261 static int
2262 resumed_callback (struct lwp_info *lp, void *data)
2263 {
2264 return lp->resumed;
2265 }
2266
2267 /* Stop an active thread, verify it still exists, then resume it. */
2268
2269 static int
2270 stop_and_resume_callback (struct lwp_info *lp, void *data)
2271 {
2272 struct lwp_info *ptr;
2273
2274 if (!lp->stopped && !lp->signalled)
2275 {
2276 stop_callback (lp, NULL);
2277 stop_wait_callback (lp, NULL);
2278 /* Resume if the lwp still exists. */
2279 for (ptr = lwp_list; ptr; ptr = ptr->next)
2280 if (lp == ptr)
2281 {
2282 resume_callback (lp, NULL);
2283 resume_set_callback (lp, NULL);
2284 }
2285 }
2286 return 0;
2287 }
2288
2289 /* Check if we should go on and pass this event to common code.
2290 Return the affected lwp if we are, or NULL otherwise. */
2291 static struct lwp_info *
2292 linux_nat_filter_event (int lwpid, int status, int options)
2293 {
2294 struct lwp_info *lp;
2295
2296 lp = find_lwp_pid (pid_to_ptid (lwpid));
2297
2298 /* Check for stop events reported by a process we didn't already
2299 know about - anything not already in our LWP list.
2300
2301 If we're expecting to receive stopped processes after
2302 fork, vfork, and clone events, then we'll just add the
2303 new one to our list and go back to waiting for the event
2304 to be reported - the stopped process might be returned
2305 from waitpid before or after the event is. */
2306 if (WIFSTOPPED (status) && !lp)
2307 {
2308 linux_record_stopped_pid (lwpid, status);
2309 return NULL;
2310 }
2311
2312 /* Make sure we don't report an event for the exit of an LWP not in
2313 our list, i.e. not part of the current process. This can happen
2314 if we detach from a program we original forked and then it
2315 exits. */
2316 if (!WIFSTOPPED (status) && !lp)
2317 return NULL;
2318
2319 /* NOTE drow/2003-06-17: This code seems to be meant for debugging
2320 CLONE_PTRACE processes which do not use the thread library -
2321 otherwise we wouldn't find the new LWP this way. That doesn't
2322 currently work, and the following code is currently unreachable
2323 due to the two blocks above. If it's fixed some day, this code
2324 should be broken out into a function so that we can also pick up
2325 LWPs from the new interface. */
2326 if (!lp)
2327 {
2328 lp = add_lwp (BUILD_LWP (lwpid, GET_PID (inferior_ptid)));
2329 if (options & __WCLONE)
2330 lp->cloned = 1;
2331
2332 gdb_assert (WIFSTOPPED (status)
2333 && WSTOPSIG (status) == SIGSTOP);
2334 lp->signalled = 1;
2335
2336 if (!in_thread_list (inferior_ptid))
2337 {
2338 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2339 GET_PID (inferior_ptid));
2340 add_thread (inferior_ptid);
2341 }
2342
2343 add_thread (lp->ptid);
2344 }
2345
2346 /* Save the trap's siginfo in case we need it later. */
2347 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2348 save_siginfo (lp);
2349
2350 /* Handle GNU/Linux's extended waitstatus for trace events. */
2351 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP && status >> 16 != 0)
2352 {
2353 if (debug_linux_nat)
2354 fprintf_unfiltered (gdb_stdlog,
2355 "LLW: Handling extended status 0x%06x\n",
2356 status);
2357 if (linux_handle_extended_wait (lp, status, 0))
2358 return NULL;
2359 }
2360
2361 /* Check if the thread has exited. */
2362 if ((WIFEXITED (status) || WIFSIGNALED (status)) && num_lwps > 1)
2363 {
2364 /* If this is the main thread, we must stop all threads and
2365 verify if they are still alive. This is because in the nptl
2366 thread model, there is no signal issued for exiting LWPs
2367 other than the main thread. We only get the main thread exit
2368 signal once all child threads have already exited. If we
2369 stop all the threads and use the stop_wait_callback to check
2370 if they have exited we can determine whether this signal
2371 should be ignored or whether it means the end of the debugged
2372 application, regardless of which threading model is being
2373 used. */
2374 if (GET_PID (lp->ptid) == GET_LWP (lp->ptid))
2375 {
2376 lp->stopped = 1;
2377 iterate_over_lwps (stop_and_resume_callback, NULL);
2378 }
2379
2380 if (debug_linux_nat)
2381 fprintf_unfiltered (gdb_stdlog,
2382 "LLW: %s exited.\n",
2383 target_pid_to_str (lp->ptid));
2384
2385 exit_lwp (lp);
2386
2387 /* If there is at least one more LWP, then the exit signal was
2388 not the end of the debugged application and should be
2389 ignored. */
2390 if (num_lwps > 0)
2391 {
2392 /* Make sure there is at least one thread running. */
2393 gdb_assert (iterate_over_lwps (running_callback, NULL));
2394
2395 /* Discard the event. */
2396 return NULL;
2397 }
2398 }
2399
2400 /* Check if the current LWP has previously exited. In the nptl
2401 thread model, LWPs other than the main thread do not issue
2402 signals when they exit so we must check whenever the thread has
2403 stopped. A similar check is made in stop_wait_callback(). */
2404 if (num_lwps > 1 && !linux_nat_thread_alive (lp->ptid))
2405 {
2406 if (debug_linux_nat)
2407 fprintf_unfiltered (gdb_stdlog,
2408 "LLW: %s exited.\n",
2409 target_pid_to_str (lp->ptid));
2410
2411 exit_lwp (lp);
2412
2413 /* Make sure there is at least one thread running. */
2414 gdb_assert (iterate_over_lwps (running_callback, NULL));
2415
2416 /* Discard the event. */
2417 return NULL;
2418 }
2419
2420 /* Make sure we don't report a SIGSTOP that we sent ourselves in
2421 an attempt to stop an LWP. */
2422 if (lp->signalled
2423 && WIFSTOPPED (status) && WSTOPSIG (status) == SIGSTOP)
2424 {
2425 if (debug_linux_nat)
2426 fprintf_unfiltered (gdb_stdlog,
2427 "LLW: Delayed SIGSTOP caught for %s.\n",
2428 target_pid_to_str (lp->ptid));
2429
2430 /* This is a delayed SIGSTOP. */
2431 lp->signalled = 0;
2432
2433 registers_changed ();
2434
2435 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2436 lp->step, TARGET_SIGNAL_0);
2437 if (debug_linux_nat)
2438 fprintf_unfiltered (gdb_stdlog,
2439 "LLW: %s %s, 0, 0 (discard SIGSTOP)\n",
2440 lp->step ?
2441 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2442 target_pid_to_str (lp->ptid));
2443
2444 lp->stopped = 0;
2445 gdb_assert (lp->resumed);
2446
2447 /* Discard the event. */
2448 return NULL;
2449 }
2450
2451 /* An interesting event. */
2452 gdb_assert (lp);
2453 return lp;
2454 }
2455
2456 /* Get the events stored in the pipe into the local queue, so they are
2457 accessible to queued_waitpid. We need to do this, since it is not
2458 always the case that the event at the head of the pipe is the event
2459 we want. */
2460
2461 static void
2462 pipe_to_local_event_queue (void)
2463 {
2464 if (debug_linux_nat_async)
2465 fprintf_unfiltered (gdb_stdlog,
2466 "PTLEQ: linux_nat_num_queued_events(%d)\n",
2467 linux_nat_num_queued_events);
2468 while (linux_nat_num_queued_events)
2469 {
2470 int lwpid, status, options;
2471 lwpid = linux_nat_event_pipe_pop (&status, &options);
2472 gdb_assert (lwpid > 0);
2473 push_waitpid (lwpid, status, options);
2474 }
2475 }
2476
2477 /* Get the unprocessed events stored in the local queue back into the
2478 pipe, so the event loop realizes there's something else to
2479 process. */
2480
2481 static void
2482 local_event_queue_to_pipe (void)
2483 {
2484 struct waitpid_result *w = waitpid_queue;
2485 while (w)
2486 {
2487 struct waitpid_result *next = w->next;
2488 linux_nat_event_pipe_push (w->pid,
2489 w->status,
2490 w->options);
2491 xfree (w);
2492 w = next;
2493 }
2494 waitpid_queue = NULL;
2495
2496 if (debug_linux_nat_async)
2497 fprintf_unfiltered (gdb_stdlog,
2498 "LEQTP: linux_nat_num_queued_events(%d)\n",
2499 linux_nat_num_queued_events);
2500 }
2501
2502 static ptid_t
2503 linux_nat_wait (ptid_t ptid, struct target_waitstatus *ourstatus)
2504 {
2505 struct lwp_info *lp = NULL;
2506 int options = 0;
2507 int status = 0;
2508 pid_t pid = PIDGET (ptid);
2509 sigset_t flush_mask;
2510
2511 if (debug_linux_nat_async)
2512 fprintf_unfiltered (gdb_stdlog, "LLW: enter\n");
2513
2514 /* The first time we get here after starting a new inferior, we may
2515 not have added it to the LWP list yet - this is the earliest
2516 moment at which we know its PID. */
2517 if (num_lwps == 0)
2518 {
2519 gdb_assert (!is_lwp (inferior_ptid));
2520
2521 inferior_ptid = BUILD_LWP (GET_PID (inferior_ptid),
2522 GET_PID (inferior_ptid));
2523 lp = add_lwp (inferior_ptid);
2524 lp->resumed = 1;
2525 /* Add the main thread to GDB's thread list. */
2526 add_thread_silent (lp->ptid);
2527 }
2528
2529 sigemptyset (&flush_mask);
2530
2531 if (target_can_async_p ())
2532 /* Block events while we're here. */
2533 target_async (NULL, 0);
2534
2535 retry:
2536
2537 /* Make sure there is at least one LWP that has been resumed. */
2538 gdb_assert (iterate_over_lwps (resumed_callback, NULL));
2539
2540 /* First check if there is a LWP with a wait status pending. */
2541 if (pid == -1)
2542 {
2543 /* Any LWP that's been resumed will do. */
2544 lp = iterate_over_lwps (status_callback, NULL);
2545 if (lp)
2546 {
2547 if (target_can_async_p ())
2548 internal_error (__FILE__, __LINE__,
2549 "Found an LWP with a pending status in async mode.");
2550
2551 status = lp->status;
2552 lp->status = 0;
2553
2554 if (debug_linux_nat && status)
2555 fprintf_unfiltered (gdb_stdlog,
2556 "LLW: Using pending wait status %s for %s.\n",
2557 status_to_str (status),
2558 target_pid_to_str (lp->ptid));
2559 }
2560
2561 /* But if we don't find one, we'll have to wait, and check both
2562 cloned and uncloned processes. We start with the cloned
2563 processes. */
2564 options = __WCLONE | WNOHANG;
2565 }
2566 else if (is_lwp (ptid))
2567 {
2568 if (debug_linux_nat)
2569 fprintf_unfiltered (gdb_stdlog,
2570 "LLW: Waiting for specific LWP %s.\n",
2571 target_pid_to_str (ptid));
2572
2573 /* We have a specific LWP to check. */
2574 lp = find_lwp_pid (ptid);
2575 gdb_assert (lp);
2576 status = lp->status;
2577 lp->status = 0;
2578
2579 if (debug_linux_nat && status)
2580 fprintf_unfiltered (gdb_stdlog,
2581 "LLW: Using pending wait status %s for %s.\n",
2582 status_to_str (status),
2583 target_pid_to_str (lp->ptid));
2584
2585 /* If we have to wait, take into account whether PID is a cloned
2586 process or not. And we have to convert it to something that
2587 the layer beneath us can understand. */
2588 options = lp->cloned ? __WCLONE : 0;
2589 pid = GET_LWP (ptid);
2590 }
2591
2592 if (status && lp->signalled)
2593 {
2594 /* A pending SIGSTOP may interfere with the normal stream of
2595 events. In a typical case where interference is a problem,
2596 we have a SIGSTOP signal pending for LWP A while
2597 single-stepping it, encounter an event in LWP B, and take the
2598 pending SIGSTOP while trying to stop LWP A. After processing
2599 the event in LWP B, LWP A is continued, and we'll never see
2600 the SIGTRAP associated with the last time we were
2601 single-stepping LWP A. */
2602
2603 /* Resume the thread. It should halt immediately returning the
2604 pending SIGSTOP. */
2605 registers_changed ();
2606 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2607 lp->step, TARGET_SIGNAL_0);
2608 if (debug_linux_nat)
2609 fprintf_unfiltered (gdb_stdlog,
2610 "LLW: %s %s, 0, 0 (expect SIGSTOP)\n",
2611 lp->step ? "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2612 target_pid_to_str (lp->ptid));
2613 lp->stopped = 0;
2614 gdb_assert (lp->resumed);
2615
2616 /* This should catch the pending SIGSTOP. */
2617 stop_wait_callback (lp, NULL);
2618 }
2619
2620 if (!target_can_async_p ())
2621 {
2622 /* Causes SIGINT to be passed on to the attached process. */
2623 set_sigint_trap ();
2624 set_sigio_trap ();
2625 }
2626
2627 while (status == 0)
2628 {
2629 pid_t lwpid;
2630
2631 if (target_can_async_p ())
2632 /* In async mode, don't ever block. Only look at the locally
2633 queued events. */
2634 lwpid = queued_waitpid (pid, &status, options);
2635 else
2636 lwpid = my_waitpid (pid, &status, options);
2637
2638 if (lwpid > 0)
2639 {
2640 gdb_assert (pid == -1 || lwpid == pid);
2641
2642 if (debug_linux_nat)
2643 {
2644 fprintf_unfiltered (gdb_stdlog,
2645 "LLW: waitpid %ld received %s\n",
2646 (long) lwpid, status_to_str (status));
2647 }
2648
2649 lp = linux_nat_filter_event (lwpid, status, options);
2650 if (!lp)
2651 {
2652 /* A discarded event. */
2653 status = 0;
2654 continue;
2655 }
2656
2657 break;
2658 }
2659
2660 if (pid == -1)
2661 {
2662 /* Alternate between checking cloned and uncloned processes. */
2663 options ^= __WCLONE;
2664
2665 /* And every time we have checked both:
2666 In async mode, return to event loop;
2667 In sync mode, suspend waiting for a SIGCHLD signal. */
2668 if (options & __WCLONE)
2669 {
2670 if (target_can_async_p ())
2671 {
2672 /* No interesting event. */
2673 ourstatus->kind = TARGET_WAITKIND_IGNORE;
2674
2675 /* Get ready for the next event. */
2676 target_async (inferior_event_handler, 0);
2677
2678 if (debug_linux_nat_async)
2679 fprintf_unfiltered (gdb_stdlog, "LLW: exit (ignore)\n");
2680
2681 return minus_one_ptid;
2682 }
2683
2684 sigsuspend (&suspend_mask);
2685 }
2686 }
2687
2688 /* We shouldn't end up here unless we want to try again. */
2689 gdb_assert (status == 0);
2690 }
2691
2692 if (!target_can_async_p ())
2693 {
2694 clear_sigio_trap ();
2695 clear_sigint_trap ();
2696 }
2697
2698 gdb_assert (lp);
2699
2700 /* Don't report signals that GDB isn't interested in, such as
2701 signals that are neither printed nor stopped upon. Stopping all
2702 threads can be a bit time-consuming so if we want decent
2703 performance with heavily multi-threaded programs, especially when
2704 they're using a high frequency timer, we'd better avoid it if we
2705 can. */
2706
2707 if (WIFSTOPPED (status))
2708 {
2709 int signo = target_signal_from_host (WSTOPSIG (status));
2710
2711 /* If we get a signal while single-stepping, we may need special
2712 care, e.g. to skip the signal handler. Defer to common code. */
2713 if (!lp->step
2714 && signal_stop_state (signo) == 0
2715 && signal_print_state (signo) == 0
2716 && signal_pass_state (signo) == 1)
2717 {
2718 /* FIMXE: kettenis/2001-06-06: Should we resume all threads
2719 here? It is not clear we should. GDB may not expect
2720 other threads to run. On the other hand, not resuming
2721 newly attached threads may cause an unwanted delay in
2722 getting them running. */
2723 registers_changed ();
2724 linux_ops->to_resume (pid_to_ptid (GET_LWP (lp->ptid)),
2725 lp->step, signo);
2726 if (debug_linux_nat)
2727 fprintf_unfiltered (gdb_stdlog,
2728 "LLW: %s %s, %s (preempt 'handle')\n",
2729 lp->step ?
2730 "PTRACE_SINGLESTEP" : "PTRACE_CONT",
2731 target_pid_to_str (lp->ptid),
2732 signo ? strsignal (signo) : "0");
2733 lp->stopped = 0;
2734 status = 0;
2735 goto retry;
2736 }
2737
2738 if (signo == TARGET_SIGNAL_INT && signal_pass_state (signo) == 0)
2739 {
2740 /* If ^C/BREAK is typed at the tty/console, SIGINT gets
2741 forwarded to the entire process group, that is, all LWP's
2742 will receive it. Since we only want to report it once,
2743 we try to flush it from all LWPs except this one. */
2744 sigaddset (&flush_mask, SIGINT);
2745 }
2746 }
2747
2748 /* This LWP is stopped now. */
2749 lp->stopped = 1;
2750
2751 if (debug_linux_nat)
2752 fprintf_unfiltered (gdb_stdlog, "LLW: Candidate event %s in %s.\n",
2753 status_to_str (status), target_pid_to_str (lp->ptid));
2754
2755 /* Now stop all other LWP's ... */
2756 iterate_over_lwps (stop_callback, NULL);
2757
2758 /* ... and wait until all of them have reported back that they're no
2759 longer running. */
2760 iterate_over_lwps (stop_wait_callback, &flush_mask);
2761 iterate_over_lwps (flush_callback, &flush_mask);
2762
2763 /* If we're not waiting for a specific LWP, choose an event LWP from
2764 among those that have had events. Giving equal priority to all
2765 LWPs that have had events helps prevent starvation. */
2766 if (pid == -1)
2767 select_event_lwp (&lp, &status);
2768
2769 /* Now that we've selected our final event LWP, cancel any
2770 breakpoints in other LWPs that have hit a GDB breakpoint. See
2771 the comment in cancel_breakpoints_callback to find out why. */
2772 iterate_over_lwps (cancel_breakpoints_callback, lp);
2773
2774 if (WIFSTOPPED (status) && WSTOPSIG (status) == SIGTRAP)
2775 {
2776 trap_ptid = lp->ptid;
2777 if (debug_linux_nat)
2778 fprintf_unfiltered (gdb_stdlog,
2779 "LLW: trap_ptid is %s.\n",
2780 target_pid_to_str (trap_ptid));
2781 }
2782 else
2783 trap_ptid = null_ptid;
2784
2785 if (lp->waitstatus.kind != TARGET_WAITKIND_IGNORE)
2786 {
2787 *ourstatus = lp->waitstatus;
2788 lp->waitstatus.kind = TARGET_WAITKIND_IGNORE;
2789 }
2790 else
2791 store_waitstatus (ourstatus, status);
2792
2793 /* Get ready for the next event. */
2794 if (target_can_async_p ())
2795 target_async (inferior_event_handler, 0);
2796
2797 if (debug_linux_nat_async)
2798 fprintf_unfiltered (gdb_stdlog, "LLW: exit\n");
2799
2800 return lp->ptid;
2801 }
2802
2803 static int
2804 kill_callback (struct lwp_info *lp, void *data)
2805 {
2806 errno = 0;
2807 ptrace (PTRACE_KILL, GET_LWP (lp->ptid), 0, 0);
2808 if (debug_linux_nat)
2809 fprintf_unfiltered (gdb_stdlog,
2810 "KC: PTRACE_KILL %s, 0, 0 (%s)\n",
2811 target_pid_to_str (lp->ptid),
2812 errno ? safe_strerror (errno) : "OK");
2813
2814 return 0;
2815 }
2816
2817 static int
2818 kill_wait_callback (struct lwp_info *lp, void *data)
2819 {
2820 pid_t pid;
2821
2822 /* We must make sure that there are no pending events (delayed
2823 SIGSTOPs, pending SIGTRAPs, etc.) to make sure the current
2824 program doesn't interfere with any following debugging session. */
2825
2826 /* For cloned processes we must check both with __WCLONE and
2827 without, since the exit status of a cloned process isn't reported
2828 with __WCLONE. */
2829 if (lp->cloned)
2830 {
2831 do
2832 {
2833 pid = my_waitpid (GET_LWP (lp->ptid), NULL, __WCLONE);
2834 if (pid != (pid_t) -1)
2835 {
2836 if (debug_linux_nat)
2837 fprintf_unfiltered (gdb_stdlog,
2838 "KWC: wait %s received unknown.\n",
2839 target_pid_to_str (lp->ptid));
2840 /* The Linux kernel sometimes fails to kill a thread
2841 completely after PTRACE_KILL; that goes from the stop
2842 point in do_fork out to the one in
2843 get_signal_to_deliever and waits again. So kill it
2844 again. */
2845 kill_callback (lp, NULL);
2846 }
2847 }
2848 while (pid == GET_LWP (lp->ptid));
2849
2850 gdb_assert (pid == -1 && errno == ECHILD);
2851 }
2852
2853 do
2854 {
2855 pid = my_waitpid (GET_LWP (lp->ptid), NULL, 0);
2856 if (pid != (pid_t) -1)
2857 {
2858 if (debug_linux_nat)
2859 fprintf_unfiltered (gdb_stdlog,
2860 "KWC: wait %s received unk.\n",
2861 target_pid_to_str (lp->ptid));
2862 /* See the call to kill_callback above. */
2863 kill_callback (lp, NULL);
2864 }
2865 }
2866 while (pid == GET_LWP (lp->ptid));
2867
2868 gdb_assert (pid == -1 && errno == ECHILD);
2869 return 0;
2870 }
2871
2872 static void
2873 linux_nat_kill (void)
2874 {
2875 struct target_waitstatus last;
2876 ptid_t last_ptid;
2877 int status;
2878
2879 if (target_can_async_p ())
2880 target_async (NULL, 0);
2881
2882 /* If we're stopped while forking and we haven't followed yet,
2883 kill the other task. We need to do this first because the
2884 parent will be sleeping if this is a vfork. */
2885
2886 get_last_target_status (&last_ptid, &last);
2887
2888 if (last.kind == TARGET_WAITKIND_FORKED
2889 || last.kind == TARGET_WAITKIND_VFORKED)
2890 {
2891 ptrace (PT_KILL, last.value.related_pid, 0, 0);
2892 wait (&status);
2893 }
2894
2895 if (forks_exist_p ())
2896 {
2897 linux_fork_killall ();
2898 drain_queued_events (-1);
2899 }
2900 else
2901 {
2902 /* Kill all LWP's ... */
2903 iterate_over_lwps (kill_callback, NULL);
2904
2905 /* ... and wait until we've flushed all events. */
2906 iterate_over_lwps (kill_wait_callback, NULL);
2907 }
2908
2909 target_mourn_inferior ();
2910 }
2911
2912 static void
2913 linux_nat_mourn_inferior (void)
2914 {
2915 trap_ptid = null_ptid;
2916
2917 /* Destroy LWP info; it's no longer valid. */
2918 init_lwp_list ();
2919
2920 if (! forks_exist_p ())
2921 {
2922 /* Normal case, no other forks available. */
2923 if (target_can_async_p ())
2924 linux_nat_async (NULL, 0);
2925 linux_ops->to_mourn_inferior ();
2926 }
2927 else
2928 /* Multi-fork case. The current inferior_ptid has exited, but
2929 there are other viable forks to debug. Delete the exiting
2930 one and context-switch to the first available. */
2931 linux_fork_mourn_inferior ();
2932 }
2933
2934 static LONGEST
2935 linux_nat_xfer_partial (struct target_ops *ops, enum target_object object,
2936 const char *annex, gdb_byte *readbuf,
2937 const gdb_byte *writebuf,
2938 ULONGEST offset, LONGEST len)
2939 {
2940 struct cleanup *old_chain = save_inferior_ptid ();
2941 LONGEST xfer;
2942
2943 if (is_lwp (inferior_ptid))
2944 inferior_ptid = pid_to_ptid (GET_LWP (inferior_ptid));
2945
2946 xfer = linux_ops->to_xfer_partial (ops, object, annex, readbuf, writebuf,
2947 offset, len);
2948
2949 do_cleanups (old_chain);
2950 return xfer;
2951 }
2952
2953 static int
2954 linux_nat_thread_alive (ptid_t ptid)
2955 {
2956 gdb_assert (is_lwp (ptid));
2957
2958 errno = 0;
2959 ptrace (PTRACE_PEEKUSER, GET_LWP (ptid), 0, 0);
2960 if (debug_linux_nat)
2961 fprintf_unfiltered (gdb_stdlog,
2962 "LLTA: PTRACE_PEEKUSER %s, 0, 0 (%s)\n",
2963 target_pid_to_str (ptid),
2964 errno ? safe_strerror (errno) : "OK");
2965
2966 /* Not every Linux kernel implements PTRACE_PEEKUSER. But we can
2967 handle that case gracefully since ptrace will first do a lookup
2968 for the process based upon the passed-in pid. If that fails we
2969 will get either -ESRCH or -EPERM, otherwise the child exists and
2970 is alive. */
2971 if (errno == ESRCH || errno == EPERM)
2972 return 0;
2973
2974 return 1;
2975 }
2976
2977 static char *
2978 linux_nat_pid_to_str (ptid_t ptid)
2979 {
2980 static char buf[64];
2981
2982 if (is_lwp (ptid)
2983 && ((lwp_list && lwp_list->next)
2984 || GET_PID (ptid) != GET_LWP (ptid)))
2985 {
2986 snprintf (buf, sizeof (buf), "LWP %ld", GET_LWP (ptid));
2987 return buf;
2988 }
2989
2990 return normal_pid_to_str (ptid);
2991 }
2992
2993 static void
2994 sigchld_handler (int signo)
2995 {
2996 if (linux_nat_async_enabled
2997 && linux_nat_async_events_enabled
2998 && signo == SIGCHLD)
2999 /* It is *always* a bug to hit this. */
3000 internal_error (__FILE__, __LINE__,
3001 "sigchld_handler called when async events are enabled");
3002
3003 /* Do nothing. The only reason for this handler is that it allows
3004 us to use sigsuspend in linux_nat_wait above to wait for the
3005 arrival of a SIGCHLD. */
3006 }
3007
3008 /* Accepts an integer PID; Returns a string representing a file that
3009 can be opened to get the symbols for the child process. */
3010
3011 static char *
3012 linux_child_pid_to_exec_file (int pid)
3013 {
3014 char *name1, *name2;
3015
3016 name1 = xmalloc (MAXPATHLEN);
3017 name2 = xmalloc (MAXPATHLEN);
3018 make_cleanup (xfree, name1);
3019 make_cleanup (xfree, name2);
3020 memset (name2, 0, MAXPATHLEN);
3021
3022 sprintf (name1, "/proc/%d/exe", pid);
3023 if (readlink (name1, name2, MAXPATHLEN) > 0)
3024 return name2;
3025 else
3026 return name1;
3027 }
3028
3029 /* Service function for corefiles and info proc. */
3030
3031 static int
3032 read_mapping (FILE *mapfile,
3033 long long *addr,
3034 long long *endaddr,
3035 char *permissions,
3036 long long *offset,
3037 char *device, long long *inode, char *filename)
3038 {
3039 int ret = fscanf (mapfile, "%llx-%llx %s %llx %s %llx",
3040 addr, endaddr, permissions, offset, device, inode);
3041
3042 filename[0] = '\0';
3043 if (ret > 0 && ret != EOF)
3044 {
3045 /* Eat everything up to EOL for the filename. This will prevent
3046 weird filenames (such as one with embedded whitespace) from
3047 confusing this code. It also makes this code more robust in
3048 respect to annotations the kernel may add after the filename.
3049
3050 Note the filename is used for informational purposes
3051 only. */
3052 ret += fscanf (mapfile, "%[^\n]\n", filename);
3053 }
3054
3055 return (ret != 0 && ret != EOF);
3056 }
3057
3058 /* Fills the "to_find_memory_regions" target vector. Lists the memory
3059 regions in the inferior for a corefile. */
3060
3061 static int
3062 linux_nat_find_memory_regions (int (*func) (CORE_ADDR,
3063 unsigned long,
3064 int, int, int, void *), void *obfd)
3065 {
3066 long long pid = PIDGET (inferior_ptid);
3067 char mapsfilename[MAXPATHLEN];
3068 FILE *mapsfile;
3069 long long addr, endaddr, size, offset, inode;
3070 char permissions[8], device[8], filename[MAXPATHLEN];
3071 int read, write, exec;
3072 int ret;
3073
3074 /* Compose the filename for the /proc memory map, and open it. */
3075 sprintf (mapsfilename, "/proc/%lld/maps", pid);
3076 if ((mapsfile = fopen (mapsfilename, "r")) == NULL)
3077 error (_("Could not open %s."), mapsfilename);
3078
3079 if (info_verbose)
3080 fprintf_filtered (gdb_stdout,
3081 "Reading memory regions from %s\n", mapsfilename);
3082
3083 /* Now iterate until end-of-file. */
3084 while (read_mapping (mapsfile, &addr, &endaddr, &permissions[0],
3085 &offset, &device[0], &inode, &filename[0]))
3086 {
3087 size = endaddr - addr;
3088
3089 /* Get the segment's permissions. */
3090 read = (strchr (permissions, 'r') != 0);
3091 write = (strchr (permissions, 'w') != 0);
3092 exec = (strchr (permissions, 'x') != 0);
3093
3094 if (info_verbose)
3095 {
3096 fprintf_filtered (gdb_stdout,
3097 "Save segment, %lld bytes at 0x%s (%c%c%c)",
3098 size, paddr_nz (addr),
3099 read ? 'r' : ' ',
3100 write ? 'w' : ' ', exec ? 'x' : ' ');
3101 if (filename[0])
3102 fprintf_filtered (gdb_stdout, " for %s", filename);
3103 fprintf_filtered (gdb_stdout, "\n");
3104 }
3105
3106 /* Invoke the callback function to create the corefile
3107 segment. */
3108 func (addr, size, read, write, exec, obfd);
3109 }
3110 fclose (mapsfile);
3111 return 0;
3112 }
3113
3114 /* Records the thread's register state for the corefile note
3115 section. */
3116
3117 static char *
3118 linux_nat_do_thread_registers (bfd *obfd, ptid_t ptid,
3119 char *note_data, int *note_size)
3120 {
3121 gdb_gregset_t gregs;
3122 gdb_fpregset_t fpregs;
3123 #ifdef FILL_FPXREGSET
3124 gdb_fpxregset_t fpxregs;
3125 #endif
3126 unsigned long lwp = ptid_get_lwp (ptid);
3127 struct regcache *regcache = get_thread_regcache (ptid);
3128 struct gdbarch *gdbarch = get_regcache_arch (regcache);
3129 const struct regset *regset;
3130 int core_regset_p;
3131 struct cleanup *old_chain;
3132
3133 old_chain = save_inferior_ptid ();
3134 inferior_ptid = ptid;
3135 target_fetch_registers (regcache, -1);
3136 do_cleanups (old_chain);
3137
3138 core_regset_p = gdbarch_regset_from_core_section_p (gdbarch);
3139 if (core_regset_p
3140 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg",
3141 sizeof (gregs))) != NULL
3142 && regset->collect_regset != NULL)
3143 regset->collect_regset (regset, regcache, -1,
3144 &gregs, sizeof (gregs));
3145 else
3146 fill_gregset (regcache, &gregs, -1);
3147
3148 note_data = (char *) elfcore_write_prstatus (obfd,
3149 note_data,
3150 note_size,
3151 lwp,
3152 stop_signal, &gregs);
3153
3154 if (core_regset_p
3155 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg2",
3156 sizeof (fpregs))) != NULL
3157 && regset->collect_regset != NULL)
3158 regset->collect_regset (regset, regcache, -1,
3159 &fpregs, sizeof (fpregs));
3160 else
3161 fill_fpregset (regcache, &fpregs, -1);
3162
3163 note_data = (char *) elfcore_write_prfpreg (obfd,
3164 note_data,
3165 note_size,
3166 &fpregs, sizeof (fpregs));
3167
3168 #ifdef FILL_FPXREGSET
3169 if (core_regset_p
3170 && (regset = gdbarch_regset_from_core_section (gdbarch, ".reg-xfp",
3171 sizeof (fpxregs))) != NULL
3172 && regset->collect_regset != NULL)
3173 regset->collect_regset (regset, regcache, -1,
3174 &fpxregs, sizeof (fpxregs));
3175 else
3176 fill_fpxregset (regcache, &fpxregs, -1);
3177
3178 note_data = (char *) elfcore_write_prxfpreg (obfd,
3179 note_data,
3180 note_size,
3181 &fpxregs, sizeof (fpxregs));
3182 #endif
3183 return note_data;
3184 }
3185
3186 struct linux_nat_corefile_thread_data
3187 {
3188 bfd *obfd;
3189 char *note_data;
3190 int *note_size;
3191 int num_notes;
3192 };
3193
3194 /* Called by gdbthread.c once per thread. Records the thread's
3195 register state for the corefile note section. */
3196
3197 static int
3198 linux_nat_corefile_thread_callback (struct lwp_info *ti, void *data)
3199 {
3200 struct linux_nat_corefile_thread_data *args = data;
3201
3202 args->note_data = linux_nat_do_thread_registers (args->obfd,
3203 ti->ptid,
3204 args->note_data,
3205 args->note_size);
3206 args->num_notes++;
3207
3208 return 0;
3209 }
3210
3211 /* Records the register state for the corefile note section. */
3212
3213 static char *
3214 linux_nat_do_registers (bfd *obfd, ptid_t ptid,
3215 char *note_data, int *note_size)
3216 {
3217 return linux_nat_do_thread_registers (obfd,
3218 ptid_build (ptid_get_pid (inferior_ptid),
3219 ptid_get_pid (inferior_ptid),
3220 0),
3221 note_data, note_size);
3222 }
3223
3224 /* Fills the "to_make_corefile_note" target vector. Builds the note
3225 section for a corefile, and returns it in a malloc buffer. */
3226
3227 static char *
3228 linux_nat_make_corefile_notes (bfd *obfd, int *note_size)
3229 {
3230 struct linux_nat_corefile_thread_data thread_args;
3231 struct cleanup *old_chain;
3232 /* The variable size must be >= sizeof (prpsinfo_t.pr_fname). */
3233 char fname[16] = { '\0' };
3234 /* The variable size must be >= sizeof (prpsinfo_t.pr_psargs). */
3235 char psargs[80] = { '\0' };
3236 char *note_data = NULL;
3237 ptid_t current_ptid = inferior_ptid;
3238 gdb_byte *auxv;
3239 int auxv_len;
3240
3241 if (get_exec_file (0))
3242 {
3243 strncpy (fname, strrchr (get_exec_file (0), '/') + 1, sizeof (fname));
3244 strncpy (psargs, get_exec_file (0), sizeof (psargs));
3245 if (get_inferior_args ())
3246 {
3247 char *string_end;
3248 char *psargs_end = psargs + sizeof (psargs);
3249
3250 /* linux_elfcore_write_prpsinfo () handles zero unterminated
3251 strings fine. */
3252 string_end = memchr (psargs, 0, sizeof (psargs));
3253 if (string_end != NULL)
3254 {
3255 *string_end++ = ' ';
3256 strncpy (string_end, get_inferior_args (),
3257 psargs_end - string_end);
3258 }
3259 }
3260 note_data = (char *) elfcore_write_prpsinfo (obfd,
3261 note_data,
3262 note_size, fname, psargs);
3263 }
3264
3265 /* Dump information for threads. */
3266 thread_args.obfd = obfd;
3267 thread_args.note_data = note_data;
3268 thread_args.note_size = note_size;
3269 thread_args.num_notes = 0;
3270 iterate_over_lwps (linux_nat_corefile_thread_callback, &thread_args);
3271 if (thread_args.num_notes == 0)
3272 {
3273 /* iterate_over_threads didn't come up with any threads; just
3274 use inferior_ptid. */
3275 note_data = linux_nat_do_registers (obfd, inferior_ptid,
3276 note_data, note_size);
3277 }
3278 else
3279 {
3280 note_data = thread_args.note_data;
3281 }
3282
3283 auxv_len = target_read_alloc (&current_target, TARGET_OBJECT_AUXV,
3284 NULL, &auxv);
3285 if (auxv_len > 0)
3286 {
3287 note_data = elfcore_write_note (obfd, note_data, note_size,
3288 "CORE", NT_AUXV, auxv, auxv_len);
3289 xfree (auxv);
3290 }
3291
3292 make_cleanup (xfree, note_data);
3293 return note_data;
3294 }
3295
3296 /* Implement the "info proc" command. */
3297
3298 static void
3299 linux_nat_info_proc_cmd (char *args, int from_tty)
3300 {
3301 long long pid = PIDGET (inferior_ptid);
3302 FILE *procfile;
3303 char **argv = NULL;
3304 char buffer[MAXPATHLEN];
3305 char fname1[MAXPATHLEN], fname2[MAXPATHLEN];
3306 int cmdline_f = 1;
3307 int cwd_f = 1;
3308 int exe_f = 1;
3309 int mappings_f = 0;
3310 int environ_f = 0;
3311 int status_f = 0;
3312 int stat_f = 0;
3313 int all = 0;
3314 struct stat dummy;
3315
3316 if (args)
3317 {
3318 /* Break up 'args' into an argv array. */
3319 if ((argv = buildargv (args)) == NULL)
3320 nomem (0);
3321 else
3322 make_cleanup_freeargv (argv);
3323 }
3324 while (argv != NULL && *argv != NULL)
3325 {
3326 if (isdigit (argv[0][0]))
3327 {
3328 pid = strtoul (argv[0], NULL, 10);
3329 }
3330 else if (strncmp (argv[0], "mappings", strlen (argv[0])) == 0)
3331 {
3332 mappings_f = 1;
3333 }
3334 else if (strcmp (argv[0], "status") == 0)
3335 {
3336 status_f = 1;
3337 }
3338 else if (strcmp (argv[0], "stat") == 0)
3339 {
3340 stat_f = 1;
3341 }
3342 else if (strcmp (argv[0], "cmd") == 0)
3343 {
3344 cmdline_f = 1;
3345 }
3346 else if (strncmp (argv[0], "exe", strlen (argv[0])) == 0)
3347 {
3348 exe_f = 1;
3349 }
3350 else if (strcmp (argv[0], "cwd") == 0)
3351 {
3352 cwd_f = 1;
3353 }
3354 else if (strncmp (argv[0], "all", strlen (argv[0])) == 0)
3355 {
3356 all = 1;
3357 }
3358 else
3359 {
3360 /* [...] (future options here) */
3361 }
3362 argv++;
3363 }
3364 if (pid == 0)
3365 error (_("No current process: you must name one."));
3366
3367 sprintf (fname1, "/proc/%lld", pid);
3368 if (stat (fname1, &dummy) != 0)
3369 error (_("No /proc directory: '%s'"), fname1);
3370
3371 printf_filtered (_("process %lld\n"), pid);
3372 if (cmdline_f || all)
3373 {
3374 sprintf (fname1, "/proc/%lld/cmdline", pid);
3375 if ((procfile = fopen (fname1, "r")) != NULL)
3376 {
3377 fgets (buffer, sizeof (buffer), procfile);
3378 printf_filtered ("cmdline = '%s'\n", buffer);
3379 fclose (procfile);
3380 }
3381 else
3382 warning (_("unable to open /proc file '%s'"), fname1);
3383 }
3384 if (cwd_f || all)
3385 {
3386 sprintf (fname1, "/proc/%lld/cwd", pid);
3387 memset (fname2, 0, sizeof (fname2));
3388 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3389 printf_filtered ("cwd = '%s'\n", fname2);
3390 else
3391 warning (_("unable to read link '%s'"), fname1);
3392 }
3393 if (exe_f || all)
3394 {
3395 sprintf (fname1, "/proc/%lld/exe", pid);
3396 memset (fname2, 0, sizeof (fname2));
3397 if (readlink (fname1, fname2, sizeof (fname2)) > 0)
3398 printf_filtered ("exe = '%s'\n", fname2);
3399 else
3400 warning (_("unable to read link '%s'"), fname1);
3401 }
3402 if (mappings_f || all)
3403 {
3404 sprintf (fname1, "/proc/%lld/maps", pid);
3405 if ((procfile = fopen (fname1, "r")) != NULL)
3406 {
3407 long long addr, endaddr, size, offset, inode;
3408 char permissions[8], device[8], filename[MAXPATHLEN];
3409
3410 printf_filtered (_("Mapped address spaces:\n\n"));
3411 if (gdbarch_addr_bit (current_gdbarch) == 32)
3412 {
3413 printf_filtered ("\t%10s %10s %10s %10s %7s\n",
3414 "Start Addr",
3415 " End Addr",
3416 " Size", " Offset", "objfile");
3417 }
3418 else
3419 {
3420 printf_filtered (" %18s %18s %10s %10s %7s\n",
3421 "Start Addr",
3422 " End Addr",
3423 " Size", " Offset", "objfile");
3424 }
3425
3426 while (read_mapping (procfile, &addr, &endaddr, &permissions[0],
3427 &offset, &device[0], &inode, &filename[0]))
3428 {
3429 size = endaddr - addr;
3430
3431 /* FIXME: carlton/2003-08-27: Maybe the printf_filtered
3432 calls here (and possibly above) should be abstracted
3433 out into their own functions? Andrew suggests using
3434 a generic local_address_string instead to print out
3435 the addresses; that makes sense to me, too. */
3436
3437 if (gdbarch_addr_bit (current_gdbarch) == 32)
3438 {
3439 printf_filtered ("\t%#10lx %#10lx %#10x %#10x %7s\n",
3440 (unsigned long) addr, /* FIXME: pr_addr */
3441 (unsigned long) endaddr,
3442 (int) size,
3443 (unsigned int) offset,
3444 filename[0] ? filename : "");
3445 }
3446 else
3447 {
3448 printf_filtered (" %#18lx %#18lx %#10x %#10x %7s\n",
3449 (unsigned long) addr, /* FIXME: pr_addr */
3450 (unsigned long) endaddr,
3451 (int) size,
3452 (unsigned int) offset,
3453 filename[0] ? filename : "");
3454 }
3455 }
3456
3457 fclose (procfile);
3458 }
3459 else
3460 warning (_("unable to open /proc file '%s'"), fname1);
3461 }
3462 if (status_f || all)
3463 {
3464 sprintf (fname1, "/proc/%lld/status", pid);
3465 if ((procfile = fopen (fname1, "r")) != NULL)
3466 {
3467 while (fgets (buffer, sizeof (buffer), procfile) != NULL)
3468 puts_filtered (buffer);
3469 fclose (procfile);
3470 }
3471 else
3472 warning (_("unable to open /proc file '%s'"), fname1);
3473 }
3474 if (stat_f || all)
3475 {
3476 sprintf (fname1, "/proc/%lld/stat", pid);
3477 if ((procfile = fopen (fname1, "r")) != NULL)
3478 {
3479 int itmp;
3480 char ctmp;
3481 long ltmp;
3482
3483 if (fscanf (procfile, "%d ", &itmp) > 0)
3484 printf_filtered (_("Process: %d\n"), itmp);
3485 if (fscanf (procfile, "(%[^)]) ", &buffer[0]) > 0)
3486 printf_filtered (_("Exec file: %s\n"), buffer);
3487 if (fscanf (procfile, "%c ", &ctmp) > 0)
3488 printf_filtered (_("State: %c\n"), ctmp);
3489 if (fscanf (procfile, "%d ", &itmp) > 0)
3490 printf_filtered (_("Parent process: %d\n"), itmp);
3491 if (fscanf (procfile, "%d ", &itmp) > 0)
3492 printf_filtered (_("Process group: %d\n"), itmp);
3493 if (fscanf (procfile, "%d ", &itmp) > 0)
3494 printf_filtered (_("Session id: %d\n"), itmp);
3495 if (fscanf (procfile, "%d ", &itmp) > 0)
3496 printf_filtered (_("TTY: %d\n"), itmp);
3497 if (fscanf (procfile, "%d ", &itmp) > 0)
3498 printf_filtered (_("TTY owner process group: %d\n"), itmp);
3499 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3500 printf_filtered (_("Flags: 0x%lx\n"), ltmp);
3501 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3502 printf_filtered (_("Minor faults (no memory page): %lu\n"),
3503 (unsigned long) ltmp);
3504 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3505 printf_filtered (_("Minor faults, children: %lu\n"),
3506 (unsigned long) ltmp);
3507 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3508 printf_filtered (_("Major faults (memory page faults): %lu\n"),
3509 (unsigned long) ltmp);
3510 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3511 printf_filtered (_("Major faults, children: %lu\n"),
3512 (unsigned long) ltmp);
3513 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3514 printf_filtered (_("utime: %ld\n"), ltmp);
3515 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3516 printf_filtered (_("stime: %ld\n"), ltmp);
3517 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3518 printf_filtered (_("utime, children: %ld\n"), ltmp);
3519 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3520 printf_filtered (_("stime, children: %ld\n"), ltmp);
3521 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3522 printf_filtered (_("jiffies remaining in current time slice: %ld\n"),
3523 ltmp);
3524 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3525 printf_filtered (_("'nice' value: %ld\n"), ltmp);
3526 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3527 printf_filtered (_("jiffies until next timeout: %lu\n"),
3528 (unsigned long) ltmp);
3529 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3530 printf_filtered (_("jiffies until next SIGALRM: %lu\n"),
3531 (unsigned long) ltmp);
3532 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3533 printf_filtered (_("start time (jiffies since system boot): %ld\n"),
3534 ltmp);
3535 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3536 printf_filtered (_("Virtual memory size: %lu\n"),
3537 (unsigned long) ltmp);
3538 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3539 printf_filtered (_("Resident set size: %lu\n"), (unsigned long) ltmp);
3540 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3541 printf_filtered (_("rlim: %lu\n"), (unsigned long) ltmp);
3542 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3543 printf_filtered (_("Start of text: 0x%lx\n"), ltmp);
3544 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3545 printf_filtered (_("End of text: 0x%lx\n"), ltmp);
3546 if (fscanf (procfile, "%lu ", &ltmp) > 0)
3547 printf_filtered (_("Start of stack: 0x%lx\n"), ltmp);
3548 #if 0 /* Don't know how architecture-dependent the rest is...
3549 Anyway the signal bitmap info is available from "status". */
3550 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3551 printf_filtered (_("Kernel stack pointer: 0x%lx\n"), ltmp);
3552 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3553 printf_filtered (_("Kernel instr pointer: 0x%lx\n"), ltmp);
3554 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3555 printf_filtered (_("Pending signals bitmap: 0x%lx\n"), ltmp);
3556 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3557 printf_filtered (_("Blocked signals bitmap: 0x%lx\n"), ltmp);
3558 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3559 printf_filtered (_("Ignored signals bitmap: 0x%lx\n"), ltmp);
3560 if (fscanf (procfile, "%ld ", &ltmp) > 0)
3561 printf_filtered (_("Catched signals bitmap: 0x%lx\n"), ltmp);
3562 if (fscanf (procfile, "%lu ", &ltmp) > 0) /* FIXME arch? */
3563 printf_filtered (_("wchan (system call): 0x%lx\n"), ltmp);
3564 #endif
3565 fclose (procfile);
3566 }
3567 else
3568 warning (_("unable to open /proc file '%s'"), fname1);
3569 }
3570 }
3571
3572 /* Implement the to_xfer_partial interface for memory reads using the /proc
3573 filesystem. Because we can use a single read() call for /proc, this
3574 can be much more efficient than banging away at PTRACE_PEEKTEXT,
3575 but it doesn't support writes. */
3576
3577 static LONGEST
3578 linux_proc_xfer_partial (struct target_ops *ops, enum target_object object,
3579 const char *annex, gdb_byte *readbuf,
3580 const gdb_byte *writebuf,
3581 ULONGEST offset, LONGEST len)
3582 {
3583 LONGEST ret;
3584 int fd;
3585 char filename[64];
3586
3587 if (object != TARGET_OBJECT_MEMORY || !readbuf)
3588 return 0;
3589
3590 /* Don't bother for one word. */
3591 if (len < 3 * sizeof (long))
3592 return 0;
3593
3594 /* We could keep this file open and cache it - possibly one per
3595 thread. That requires some juggling, but is even faster. */
3596 sprintf (filename, "/proc/%d/mem", PIDGET (inferior_ptid));
3597 fd = open (filename, O_RDONLY | O_LARGEFILE);
3598 if (fd == -1)
3599 return 0;
3600
3601 /* If pread64 is available, use it. It's faster if the kernel
3602 supports it (only one syscall), and it's 64-bit safe even on
3603 32-bit platforms (for instance, SPARC debugging a SPARC64
3604 application). */
3605 #ifdef HAVE_PREAD64
3606 if (pread64 (fd, readbuf, len, offset) != len)
3607 #else
3608 if (lseek (fd, offset, SEEK_SET) == -1 || read (fd, readbuf, len) != len)
3609 #endif
3610 ret = 0;
3611 else
3612 ret = len;
3613
3614 close (fd);
3615 return ret;
3616 }
3617
3618 /* Parse LINE as a signal set and add its set bits to SIGS. */
3619
3620 static void
3621 add_line_to_sigset (const char *line, sigset_t *sigs)
3622 {
3623 int len = strlen (line) - 1;
3624 const char *p;
3625 int signum;
3626
3627 if (line[len] != '\n')
3628 error (_("Could not parse signal set: %s"), line);
3629
3630 p = line;
3631 signum = len * 4;
3632 while (len-- > 0)
3633 {
3634 int digit;
3635
3636 if (*p >= '0' && *p <= '9')
3637 digit = *p - '0';
3638 else if (*p >= 'a' && *p <= 'f')
3639 digit = *p - 'a' + 10;
3640 else
3641 error (_("Could not parse signal set: %s"), line);
3642
3643 signum -= 4;
3644
3645 if (digit & 1)
3646 sigaddset (sigs, signum + 1);
3647 if (digit & 2)
3648 sigaddset (sigs, signum + 2);
3649 if (digit & 4)
3650 sigaddset (sigs, signum + 3);
3651 if (digit & 8)
3652 sigaddset (sigs, signum + 4);
3653
3654 p++;
3655 }
3656 }
3657
3658 /* Find process PID's pending signals from /proc/pid/status and set
3659 SIGS to match. */
3660
3661 void
3662 linux_proc_pending_signals (int pid, sigset_t *pending, sigset_t *blocked, sigset_t *ignored)
3663 {
3664 FILE *procfile;
3665 char buffer[MAXPATHLEN], fname[MAXPATHLEN];
3666 int signum;
3667
3668 sigemptyset (pending);
3669 sigemptyset (blocked);
3670 sigemptyset (ignored);
3671 sprintf (fname, "/proc/%d/status", pid);
3672 procfile = fopen (fname, "r");
3673 if (procfile == NULL)
3674 error (_("Could not open %s"), fname);
3675
3676 while (fgets (buffer, MAXPATHLEN, procfile) != NULL)
3677 {
3678 /* Normal queued signals are on the SigPnd line in the status
3679 file. However, 2.6 kernels also have a "shared" pending
3680 queue for delivering signals to a thread group, so check for
3681 a ShdPnd line also.
3682
3683 Unfortunately some Red Hat kernels include the shared pending
3684 queue but not the ShdPnd status field. */
3685
3686 if (strncmp (buffer, "SigPnd:\t", 8) == 0)
3687 add_line_to_sigset (buffer + 8, pending);
3688 else if (strncmp (buffer, "ShdPnd:\t", 8) == 0)
3689 add_line_to_sigset (buffer + 8, pending);
3690 else if (strncmp (buffer, "SigBlk:\t", 8) == 0)
3691 add_line_to_sigset (buffer + 8, blocked);
3692 else if (strncmp (buffer, "SigIgn:\t", 8) == 0)
3693 add_line_to_sigset (buffer + 8, ignored);
3694 }
3695
3696 fclose (procfile);
3697 }
3698
3699 static LONGEST
3700 linux_xfer_partial (struct target_ops *ops, enum target_object object,
3701 const char *annex, gdb_byte *readbuf,
3702 const gdb_byte *writebuf, ULONGEST offset, LONGEST len)
3703 {
3704 LONGEST xfer;
3705
3706 if (object == TARGET_OBJECT_AUXV)
3707 return procfs_xfer_auxv (ops, object, annex, readbuf, writebuf,
3708 offset, len);
3709
3710 xfer = linux_proc_xfer_partial (ops, object, annex, readbuf, writebuf,
3711 offset, len);
3712 if (xfer != 0)
3713 return xfer;
3714
3715 return super_xfer_partial (ops, object, annex, readbuf, writebuf,
3716 offset, len);
3717 }
3718
3719 /* Create a prototype generic GNU/Linux target. The client can override
3720 it with local methods. */
3721
3722 static void
3723 linux_target_install_ops (struct target_ops *t)
3724 {
3725 t->to_insert_fork_catchpoint = linux_child_insert_fork_catchpoint;
3726 t->to_insert_vfork_catchpoint = linux_child_insert_vfork_catchpoint;
3727 t->to_insert_exec_catchpoint = linux_child_insert_exec_catchpoint;
3728 t->to_pid_to_exec_file = linux_child_pid_to_exec_file;
3729 t->to_post_startup_inferior = linux_child_post_startup_inferior;
3730 t->to_post_attach = linux_child_post_attach;
3731 t->to_follow_fork = linux_child_follow_fork;
3732 t->to_find_memory_regions = linux_nat_find_memory_regions;
3733 t->to_make_corefile_notes = linux_nat_make_corefile_notes;
3734
3735 super_xfer_partial = t->to_xfer_partial;
3736 t->to_xfer_partial = linux_xfer_partial;
3737 }
3738
3739 struct target_ops *
3740 linux_target (void)
3741 {
3742 struct target_ops *t;
3743
3744 t = inf_ptrace_target ();
3745 linux_target_install_ops (t);
3746
3747 return t;
3748 }
3749
3750 struct target_ops *
3751 linux_trad_target (CORE_ADDR (*register_u_offset)(struct gdbarch *, int, int))
3752 {
3753 struct target_ops *t;
3754
3755 t = inf_ptrace_trad_target (register_u_offset);
3756 linux_target_install_ops (t);
3757
3758 return t;
3759 }
3760
3761 /* Controls if async mode is permitted. */
3762 static int linux_async_permitted = 0;
3763
3764 /* The set command writes to this variable. If the inferior is
3765 executing, linux_nat_async_permitted is *not* updated. */
3766 static int linux_async_permitted_1 = 0;
3767
3768 static void
3769 set_maintenance_linux_async_permitted (char *args, int from_tty,
3770 struct cmd_list_element *c)
3771 {
3772 if (target_has_execution)
3773 {
3774 linux_async_permitted_1 = linux_async_permitted;
3775 error (_("Cannot change this setting while the inferior is running."));
3776 }
3777
3778 linux_async_permitted = linux_async_permitted_1;
3779 linux_nat_set_async_mode (linux_async_permitted);
3780 }
3781
3782 static void
3783 show_maintenance_linux_async_permitted (struct ui_file *file, int from_tty,
3784 struct cmd_list_element *c, const char *value)
3785 {
3786 fprintf_filtered (file, _("\
3787 Controlling the GNU/Linux inferior in asynchronous mode is %s.\n"),
3788 value);
3789 }
3790
3791 /* target_is_async_p implementation. */
3792
3793 static int
3794 linux_nat_is_async_p (void)
3795 {
3796 /* NOTE: palves 2008-03-21: We're only async when the user requests
3797 it explicitly with the "maintenance set linux-async" command.
3798 Someday, linux will always be async. */
3799 if (!linux_async_permitted)
3800 return 0;
3801
3802 return 1;
3803 }
3804
3805 /* target_can_async_p implementation. */
3806
3807 static int
3808 linux_nat_can_async_p (void)
3809 {
3810 /* NOTE: palves 2008-03-21: We're only async when the user requests
3811 it explicitly with the "maintenance set linux-async" command.
3812 Someday, linux will always be async. */
3813 if (!linux_async_permitted)
3814 return 0;
3815
3816 /* See target.h/target_async_mask. */
3817 return linux_nat_async_mask_value;
3818 }
3819
3820 /* target_async_mask implementation. */
3821
3822 static int
3823 linux_nat_async_mask (int mask)
3824 {
3825 int current_state;
3826 current_state = linux_nat_async_mask_value;
3827
3828 if (current_state != mask)
3829 {
3830 if (mask == 0)
3831 {
3832 linux_nat_async (NULL, 0);
3833 linux_nat_async_mask_value = mask;
3834 /* We're in sync mode. Make sure SIGCHLD isn't handled by
3835 async_sigchld_handler when we come out of sigsuspend in
3836 linux_nat_wait. */
3837 sigaction (SIGCHLD, &sync_sigchld_action, NULL);
3838 }
3839 else
3840 {
3841 /* Restore the async handler. */
3842 sigaction (SIGCHLD, &async_sigchld_action, NULL);
3843 linux_nat_async_mask_value = mask;
3844 linux_nat_async (inferior_event_handler, 0);
3845 }
3846 }
3847
3848 return current_state;
3849 }
3850
3851 /* Pop an event from the event pipe. */
3852
3853 static int
3854 linux_nat_event_pipe_pop (int* ptr_status, int* ptr_options)
3855 {
3856 struct waitpid_result event = {0};
3857 int ret;
3858
3859 do
3860 {
3861 ret = read (linux_nat_event_pipe[0], &event, sizeof (event));
3862 }
3863 while (ret == -1 && errno == EINTR);
3864
3865 gdb_assert (ret == sizeof (event));
3866
3867 *ptr_status = event.status;
3868 *ptr_options = event.options;
3869
3870 linux_nat_num_queued_events--;
3871
3872 return event.pid;
3873 }
3874
3875 /* Push an event into the event pipe. */
3876
3877 static void
3878 linux_nat_event_pipe_push (int pid, int status, int options)
3879 {
3880 int ret;
3881 struct waitpid_result event = {0};
3882 event.pid = pid;
3883 event.status = status;
3884 event.options = options;
3885
3886 do
3887 {
3888 ret = write (linux_nat_event_pipe[1], &event, sizeof (event));
3889 gdb_assert ((ret == -1 && errno == EINTR) || ret == sizeof (event));
3890 } while (ret == -1 && errno == EINTR);
3891
3892 linux_nat_num_queued_events++;
3893 }
3894
3895 static void
3896 get_pending_events (void)
3897 {
3898 int status, options, pid;
3899
3900 if (!linux_nat_async_enabled || !linux_nat_async_events_enabled)
3901 internal_error (__FILE__, __LINE__,
3902 "get_pending_events called with async masked");
3903
3904 while (1)
3905 {
3906 status = 0;
3907 options = __WCLONE | WNOHANG;
3908
3909 do
3910 {
3911 pid = waitpid (-1, &status, options);
3912 }
3913 while (pid == -1 && errno == EINTR);
3914
3915 if (pid <= 0)
3916 {
3917 options = WNOHANG;
3918 do
3919 {
3920 pid = waitpid (-1, &status, options);
3921 }
3922 while (pid == -1 && errno == EINTR);
3923 }
3924
3925 if (pid <= 0)
3926 /* No more children reporting events. */
3927 break;
3928
3929 if (debug_linux_nat_async)
3930 fprintf_unfiltered (gdb_stdlog, "\
3931 get_pending_events: pid(%d), status(%x), options (%x)\n",
3932 pid, status, options);
3933
3934 linux_nat_event_pipe_push (pid, status, options);
3935 }
3936
3937 if (debug_linux_nat_async)
3938 fprintf_unfiltered (gdb_stdlog, "\
3939 get_pending_events: linux_nat_num_queued_events(%d)\n",
3940 linux_nat_num_queued_events);
3941 }
3942
3943 /* SIGCHLD handler for async mode. */
3944
3945 static void
3946 async_sigchld_handler (int signo)
3947 {
3948 if (debug_linux_nat_async)
3949 fprintf_unfiltered (gdb_stdlog, "async_sigchld_handler\n");
3950
3951 get_pending_events ();
3952 }
3953
3954 /* Enable or disable async SIGCHLD handling. */
3955
3956 static int
3957 linux_nat_async_events (int enable)
3958 {
3959 int current_state = linux_nat_async_events_enabled;
3960
3961 if (debug_linux_nat_async)
3962 fprintf_unfiltered (gdb_stdlog,
3963 "LNAE: enable(%d): linux_nat_async_events_enabled(%d), "
3964 "linux_nat_num_queued_events(%d)\n",
3965 enable, linux_nat_async_events_enabled,
3966 linux_nat_num_queued_events);
3967
3968 if (current_state != enable)
3969 {
3970 sigset_t mask;
3971 sigemptyset (&mask);
3972 sigaddset (&mask, SIGCHLD);
3973 if (enable)
3974 {
3975 /* Unblock target events. */
3976 linux_nat_async_events_enabled = 1;
3977
3978 local_event_queue_to_pipe ();
3979 /* While in masked async, we may have not collected all the
3980 pending events. Get them out now. */
3981 get_pending_events ();
3982 sigprocmask (SIG_UNBLOCK, &mask, NULL);
3983 }
3984 else
3985 {
3986 /* Block target events. */
3987 sigprocmask (SIG_BLOCK, &mask, NULL);
3988 linux_nat_async_events_enabled = 0;
3989 /* Get events out of queue, and make them available to
3990 queued_waitpid / my_waitpid. */
3991 pipe_to_local_event_queue ();
3992 }
3993 }
3994
3995 return current_state;
3996 }
3997
3998 static int async_terminal_is_ours = 1;
3999
4000 /* target_terminal_inferior implementation. */
4001
4002 static void
4003 linux_nat_terminal_inferior (void)
4004 {
4005 if (!target_is_async_p ())
4006 {
4007 /* Async mode is disabled. */
4008 terminal_inferior ();
4009 return;
4010 }
4011
4012 /* GDB should never give the terminal to the inferior, if the
4013 inferior is running in the background (run&, continue&, etc.).
4014 This check can be removed when the common code is fixed. */
4015 if (!sync_execution)
4016 return;
4017
4018 terminal_inferior ();
4019
4020 if (!async_terminal_is_ours)
4021 return;
4022
4023 delete_file_handler (input_fd);
4024 async_terminal_is_ours = 0;
4025 set_sigint_trap ();
4026 }
4027
4028 /* target_terminal_ours implementation. */
4029
4030 void
4031 linux_nat_terminal_ours (void)
4032 {
4033 if (!target_is_async_p ())
4034 {
4035 /* Async mode is disabled. */
4036 terminal_ours ();
4037 return;
4038 }
4039
4040 /* GDB should never give the terminal to the inferior if the
4041 inferior is running in the background (run&, continue&, etc.),
4042 but claiming it sure should. */
4043 terminal_ours ();
4044
4045 if (!sync_execution)
4046 return;
4047
4048 if (async_terminal_is_ours)
4049 return;
4050
4051 clear_sigint_trap ();
4052 add_file_handler (input_fd, stdin_event_handler, 0);
4053 async_terminal_is_ours = 1;
4054 }
4055
4056 static void (*async_client_callback) (enum inferior_event_type event_type,
4057 void *context);
4058 static void *async_client_context;
4059
4060 static void
4061 linux_nat_async_file_handler (int error, gdb_client_data client_data)
4062 {
4063 async_client_callback (INF_REG_EVENT, async_client_context);
4064 }
4065
4066 /* target_async implementation. */
4067
4068 static void
4069 linux_nat_async (void (*callback) (enum inferior_event_type event_type,
4070 void *context), void *context)
4071 {
4072 if (linux_nat_async_mask_value == 0 || !linux_nat_async_enabled)
4073 internal_error (__FILE__, __LINE__,
4074 "Calling target_async when async is masked");
4075
4076 if (callback != NULL)
4077 {
4078 async_client_callback = callback;
4079 async_client_context = context;
4080 add_file_handler (linux_nat_event_pipe[0],
4081 linux_nat_async_file_handler, NULL);
4082
4083 linux_nat_async_events (1);
4084 }
4085 else
4086 {
4087 async_client_callback = callback;
4088 async_client_context = context;
4089
4090 linux_nat_async_events (0);
4091 delete_file_handler (linux_nat_event_pipe[0]);
4092 }
4093 return;
4094 }
4095
4096 /* Enable/Disable async mode. */
4097
4098 static void
4099 linux_nat_set_async_mode (int on)
4100 {
4101 if (linux_nat_async_enabled != on)
4102 {
4103 if (on)
4104 {
4105 gdb_assert (waitpid_queue == NULL);
4106 sigaction (SIGCHLD, &async_sigchld_action, NULL);
4107
4108 if (pipe (linux_nat_event_pipe) == -1)
4109 internal_error (__FILE__, __LINE__,
4110 "creating event pipe failed.");
4111
4112 fcntl (linux_nat_event_pipe[0], F_SETFL, O_NONBLOCK);
4113 fcntl (linux_nat_event_pipe[1], F_SETFL, O_NONBLOCK);
4114 }
4115 else
4116 {
4117 sigaction (SIGCHLD, &sync_sigchld_action, NULL);
4118
4119 drain_queued_events (-1);
4120
4121 linux_nat_num_queued_events = 0;
4122 close (linux_nat_event_pipe[0]);
4123 close (linux_nat_event_pipe[1]);
4124 linux_nat_event_pipe[0] = linux_nat_event_pipe[1] = -1;
4125
4126 }
4127 }
4128 linux_nat_async_enabled = on;
4129 }
4130
4131 void
4132 linux_nat_add_target (struct target_ops *t)
4133 {
4134 /* Save the provided single-threaded target. We save this in a separate
4135 variable because another target we've inherited from (e.g. inf-ptrace)
4136 may have saved a pointer to T; we want to use it for the final
4137 process stratum target. */
4138 linux_ops_saved = *t;
4139 linux_ops = &linux_ops_saved;
4140
4141 /* Override some methods for multithreading. */
4142 t->to_create_inferior = linux_nat_create_inferior;
4143 t->to_attach = linux_nat_attach;
4144 t->to_detach = linux_nat_detach;
4145 t->to_resume = linux_nat_resume;
4146 t->to_wait = linux_nat_wait;
4147 t->to_xfer_partial = linux_nat_xfer_partial;
4148 t->to_kill = linux_nat_kill;
4149 t->to_mourn_inferior = linux_nat_mourn_inferior;
4150 t->to_thread_alive = linux_nat_thread_alive;
4151 t->to_pid_to_str = linux_nat_pid_to_str;
4152 t->to_has_thread_control = tc_schedlock;
4153
4154 t->to_can_async_p = linux_nat_can_async_p;
4155 t->to_is_async_p = linux_nat_is_async_p;
4156 t->to_async = linux_nat_async;
4157 t->to_async_mask = linux_nat_async_mask;
4158 t->to_terminal_inferior = linux_nat_terminal_inferior;
4159 t->to_terminal_ours = linux_nat_terminal_ours;
4160
4161 /* We don't change the stratum; this target will sit at
4162 process_stratum and thread_db will set at thread_stratum. This
4163 is a little strange, since this is a multi-threaded-capable
4164 target, but we want to be on the stack below thread_db, and we
4165 also want to be used for single-threaded processes. */
4166
4167 add_target (t);
4168
4169 /* TODO: Eliminate this and have libthread_db use
4170 find_target_beneath. */
4171 thread_db_init (t);
4172 }
4173
4174 /* Register a method to call whenever a new thread is attached. */
4175 void
4176 linux_nat_set_new_thread (struct target_ops *t, void (*new_thread) (ptid_t))
4177 {
4178 /* Save the pointer. We only support a single registered instance
4179 of the GNU/Linux native target, so we do not need to map this to
4180 T. */
4181 linux_nat_new_thread = new_thread;
4182 }
4183
4184 /* Return the saved siginfo associated with PTID. */
4185 struct siginfo *
4186 linux_nat_get_siginfo (ptid_t ptid)
4187 {
4188 struct lwp_info *lp = find_lwp_pid (ptid);
4189
4190 gdb_assert (lp != NULL);
4191
4192 return &lp->siginfo;
4193 }
4194
4195 void
4196 _initialize_linux_nat (void)
4197 {
4198 sigset_t mask;
4199
4200 add_info ("proc", linux_nat_info_proc_cmd, _("\
4201 Show /proc process information about any running process.\n\
4202 Specify any process id, or use the program being debugged by default.\n\
4203 Specify any of the following keywords for detailed info:\n\
4204 mappings -- list of mapped memory regions.\n\
4205 stat -- list a bunch of random process info.\n\
4206 status -- list a different bunch of random process info.\n\
4207 all -- list all available /proc info."));
4208
4209 add_setshow_zinteger_cmd ("lin-lwp", class_maintenance,
4210 &debug_linux_nat, _("\
4211 Set debugging of GNU/Linux lwp module."), _("\
4212 Show debugging of GNU/Linux lwp module."), _("\
4213 Enables printf debugging output."),
4214 NULL,
4215 show_debug_linux_nat,
4216 &setdebuglist, &showdebuglist);
4217
4218 add_setshow_zinteger_cmd ("lin-lwp-async", class_maintenance,
4219 &debug_linux_nat_async, _("\
4220 Set debugging of GNU/Linux async lwp module."), _("\
4221 Show debugging of GNU/Linux async lwp module."), _("\
4222 Enables printf debugging output."),
4223 NULL,
4224 show_debug_linux_nat_async,
4225 &setdebuglist, &showdebuglist);
4226
4227 add_setshow_boolean_cmd ("linux-async", class_maintenance,
4228 &linux_async_permitted_1, _("\
4229 Set whether gdb controls the GNU/Linux inferior in asynchronous mode."), _("\
4230 Show whether gdb controls the GNU/Linux inferior in asynchronous mode."), _("\
4231 Tells gdb whether to control the GNU/Linux inferior in asynchronous mode."),
4232 set_maintenance_linux_async_permitted,
4233 show_maintenance_linux_async_permitted,
4234 &maintenance_set_cmdlist,
4235 &maintenance_show_cmdlist);
4236
4237 /* Block SIGCHLD by default. Doing this early prevents it getting
4238 unblocked if an exception is thrown due to an error while the
4239 inferior is starting (sigsetjmp/siglongjmp). */
4240 sigemptyset (&mask);
4241 sigaddset (&mask, SIGCHLD);
4242 sigprocmask (SIG_BLOCK, &mask, NULL);
4243
4244 /* Save this mask as the default. */
4245 sigprocmask (SIG_SETMASK, NULL, &normal_mask);
4246
4247 /* The synchronous SIGCHLD handler. */
4248 sync_sigchld_action.sa_handler = sigchld_handler;
4249 sigemptyset (&sync_sigchld_action.sa_mask);
4250 sync_sigchld_action.sa_flags = SA_RESTART;
4251
4252 /* Make it the default. */
4253 sigaction (SIGCHLD, &sync_sigchld_action, NULL);
4254
4255 /* Make sure we don't block SIGCHLD during a sigsuspend. */
4256 sigprocmask (SIG_SETMASK, NULL, &suspend_mask);
4257 sigdelset (&suspend_mask, SIGCHLD);
4258
4259 /* SIGCHLD handler for async mode. */
4260 async_sigchld_action.sa_handler = async_sigchld_handler;
4261 sigemptyset (&async_sigchld_action.sa_mask);
4262 async_sigchld_action.sa_flags = SA_RESTART;
4263
4264 /* Install the default mode. */
4265 linux_nat_set_async_mode (linux_async_permitted);
4266 }
4267 \f
4268
4269 /* FIXME: kettenis/2000-08-26: The stuff on this page is specific to
4270 the GNU/Linux Threads library and therefore doesn't really belong
4271 here. */
4272
4273 /* Read variable NAME in the target and return its value if found.
4274 Otherwise return zero. It is assumed that the type of the variable
4275 is `int'. */
4276
4277 static int
4278 get_signo (const char *name)
4279 {
4280 struct minimal_symbol *ms;
4281 int signo;
4282
4283 ms = lookup_minimal_symbol (name, NULL, NULL);
4284 if (ms == NULL)
4285 return 0;
4286
4287 if (target_read_memory (SYMBOL_VALUE_ADDRESS (ms), (gdb_byte *) &signo,
4288 sizeof (signo)) != 0)
4289 return 0;
4290
4291 return signo;
4292 }
4293
4294 /* Return the set of signals used by the threads library in *SET. */
4295
4296 void
4297 lin_thread_get_thread_signals (sigset_t *set)
4298 {
4299 struct sigaction action;
4300 int restart, cancel;
4301 sigset_t blocked_mask;
4302
4303 sigemptyset (&blocked_mask);
4304 sigemptyset (set);
4305
4306 restart = get_signo ("__pthread_sig_restart");
4307 cancel = get_signo ("__pthread_sig_cancel");
4308
4309 /* LinuxThreads normally uses the first two RT signals, but in some legacy
4310 cases may use SIGUSR1/SIGUSR2. NPTL always uses RT signals, but does
4311 not provide any way for the debugger to query the signal numbers -
4312 fortunately they don't change! */
4313
4314 if (restart == 0)
4315 restart = __SIGRTMIN;
4316
4317 if (cancel == 0)
4318 cancel = __SIGRTMIN + 1;
4319
4320 sigaddset (set, restart);
4321 sigaddset (set, cancel);
4322
4323 /* The GNU/Linux Threads library makes terminating threads send a
4324 special "cancel" signal instead of SIGCHLD. Make sure we catch
4325 those (to prevent them from terminating GDB itself, which is
4326 likely to be their default action) and treat them the same way as
4327 SIGCHLD. */
4328
4329 action.sa_handler = sigchld_handler;
4330 sigemptyset (&action.sa_mask);
4331 action.sa_flags = SA_RESTART;
4332 sigaction (cancel, &action, NULL);
4333
4334 /* We block the "cancel" signal throughout this code ... */
4335 sigaddset (&blocked_mask, cancel);
4336 sigprocmask (SIG_BLOCK, &blocked_mask, NULL);
4337
4338 /* ... except during a sigsuspend. */
4339 sigdelset (&suspend_mask, cancel);
4340 }
This page took 0.117327 seconds and 4 git commands to generate.