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