trace.c revision d3dc17b5e87068819a780af434afaf69e63d2b50
1#include "config.h"
2
3#include <asm/unistd.h>
4#include <sys/types.h>
5#include <sys/wait.h>
6#include <assert.h>
7#include <errno.h>
8#include <error.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <unistd.h>
13
14#ifdef HAVE_LIBSELINUX
15# include <selinux/selinux.h>
16#endif
17
18#include "ptrace.h"
19#include "common.h"
20#include "breakpoint.h"
21#include "proc.h"
22
23/* If the system headers did not provide the constants, hard-code the normal
24   values.  */
25#ifndef PTRACE_EVENT_FORK
26
27#define PTRACE_OLDSETOPTIONS    21
28#define PTRACE_SETOPTIONS       0x4200
29#define PTRACE_GETEVENTMSG      0x4201
30
31/* options set using PTRACE_SETOPTIONS */
32#define PTRACE_O_TRACESYSGOOD   0x00000001
33#define PTRACE_O_TRACEFORK      0x00000002
34#define PTRACE_O_TRACEVFORK     0x00000004
35#define PTRACE_O_TRACECLONE     0x00000008
36#define PTRACE_O_TRACEEXEC      0x00000010
37#define PTRACE_O_TRACEVFORKDONE 0x00000020
38#define PTRACE_O_TRACEEXIT      0x00000040
39
40/* Wait extended result codes for the above trace options.  */
41#define PTRACE_EVENT_FORK       1
42#define PTRACE_EVENT_VFORK      2
43#define PTRACE_EVENT_CLONE      3
44#define PTRACE_EVENT_EXEC       4
45#define PTRACE_EVENT_VFORK_DONE 5
46#define PTRACE_EVENT_EXIT       6
47
48#endif /* PTRACE_EVENT_FORK */
49
50#ifdef ARCH_HAVE_UMOVELONG
51extern int arch_umovelong (Process *, void *, long *, arg_type_info *);
52int
53umovelong (Process *proc, void *addr, long *result, arg_type_info *info) {
54	return arch_umovelong (proc, addr, result, info);
55}
56#else
57/* Read a single long from the process's memory address 'addr' */
58int
59umovelong (Process *proc, void *addr, long *result, arg_type_info *info) {
60	long pointed_to;
61
62	errno = 0;
63	pointed_to = ptrace (PTRACE_PEEKTEXT, proc->pid, addr, 0);
64	if (pointed_to == -1 && errno)
65		return -errno;
66
67	*result = pointed_to;
68	if (info) {
69		switch(info->type) {
70			case ARGTYPE_INT:
71				*result &= 0x00000000ffffffffUL;
72			default:
73				break;
74		};
75	}
76	return 0;
77}
78#endif
79
80void
81trace_fail_warning(pid_t pid)
82{
83	/* This was adapted from GDB.  */
84#ifdef HAVE_LIBSELINUX
85	static int checked = 0;
86	if (checked)
87		return;
88	checked = 1;
89
90	/* -1 is returned for errors, 0 if it has no effect, 1 if
91	 * PTRACE_ATTACH is forbidden.  */
92	if (security_get_boolean_active("deny_ptrace") == 1)
93		fprintf(stderr,
94"The SELinux boolean 'deny_ptrace' is enabled, which may prevent ltrace from\n"
95"tracing other processes.  You can disable this process attach protection by\n"
96"issuing 'setsebool deny_ptrace=0' in the superuser context.\n");
97#endif /* HAVE_LIBSELINUX */
98}
99
100void
101trace_me(void)
102{
103	debug(DEBUG_PROCESS, "trace_me: pid=%d", getpid());
104	if (ptrace(PTRACE_TRACEME, 0, 1, 0) < 0) {
105		perror("PTRACE_TRACEME");
106		trace_fail_warning(getpid());
107		exit(1);
108	}
109}
110
111/* There's a (hopefully) brief period of time after the child process
112 * forks when we can't trace it yet.  Here we wait for kernel to
113 * prepare the process.  */
114int
115wait_for_proc(pid_t pid)
116{
117	/* man ptrace: PTRACE_ATTACH attaches to the process specified
118	   in pid.  The child is sent a SIGSTOP, but will not
119	   necessarily have stopped by the completion of this call;
120	   use wait() to wait for the child to stop. */
121	if (waitpid(pid, NULL, __WALL) != pid) {
122		perror ("trace_pid: waitpid");
123		return -1;
124	}
125
126	return 0;
127}
128
129int
130trace_pid(pid_t pid)
131{
132	debug(DEBUG_PROCESS, "trace_pid: pid=%d", pid);
133	/* This shouldn't emit error messages, as there are legitimate
134	 * reasons that the PID can't be attached: like it may have
135	 * already ended.  */
136	if (ptrace(PTRACE_ATTACH, pid, 1, 0) < 0)
137		return -1;
138
139	return wait_for_proc(pid);
140}
141
142void
143trace_set_options(Process *proc, pid_t pid) {
144	if (proc->tracesysgood & 0x80)
145		return;
146
147	debug(DEBUG_PROCESS, "trace_set_options: pid=%d", pid);
148
149	long options = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEFORK |
150		PTRACE_O_TRACEVFORK | PTRACE_O_TRACECLONE |
151		PTRACE_O_TRACEEXEC;
152	if (ptrace(PTRACE_SETOPTIONS, pid, 0, options) < 0 &&
153	    ptrace(PTRACE_OLDSETOPTIONS, pid, 0, options) < 0) {
154		perror("PTRACE_SETOPTIONS");
155		return;
156	}
157	proc->tracesysgood |= 0x80;
158}
159
160void
161untrace_pid(pid_t pid) {
162	debug(DEBUG_PROCESS, "untrace_pid: pid=%d", pid);
163	ptrace(PTRACE_DETACH, pid, 1, 0);
164}
165
166void
167continue_after_signal(pid_t pid, int signum) {
168	debug(DEBUG_PROCESS, "continue_after_signal: pid=%d, signum=%d", pid, signum);
169	ptrace(PTRACE_SYSCALL, pid, 0, signum);
170}
171
172static enum ecb_status
173event_for_pid(Event * event, void * data)
174{
175	if (event->proc != NULL && event->proc->pid == (pid_t)(uintptr_t)data)
176		return ecb_yield;
177	return ecb_cont;
178}
179
180static int
181have_events_for(pid_t pid)
182{
183	return each_qd_event(event_for_pid, (void *)(uintptr_t)pid) != NULL;
184}
185
186void
187continue_process(pid_t pid)
188{
189	debug(DEBUG_PROCESS, "continue_process: pid=%d", pid);
190
191	/* Only really continue the process if there are no events in
192	   the queue for this process.  Otherwise just wait for the
193	   other events to arrive.  */
194	if (!have_events_for(pid))
195		/* We always trace syscalls to control fork(),
196		 * clone(), execve()... */
197		ptrace(PTRACE_SYSCALL, pid, 0, 0);
198	else
199		debug(DEBUG_PROCESS,
200		      "putting off the continue, events in que.");
201}
202
203/**
204 * This is used for bookkeeping related to PIDs that the event
205 * handlers work with.
206 */
207struct pid_task {
208	pid_t pid;	/* This may be 0 for tasks that exited
209			 * mid-handling.  */
210	int sigstopped : 1;
211	int got_event : 1;
212	int delivered : 1;
213	int vforked : 1;
214	int sysret : 1;
215} * pids;
216
217struct pid_set {
218	struct pid_task * tasks;
219	size_t count;
220	size_t alloc;
221};
222
223/**
224 * Breakpoint re-enablement.  When we hit a breakpoint, we must
225 * disable it, single-step, and re-enable it.  That single-step can be
226 * done only by one task in a task group, while others are stopped,
227 * otherwise the processes would race for who sees the breakpoint
228 * disabled and who doesn't.  The following is to keep track of it
229 * all.
230 */
231struct process_stopping_handler
232{
233	struct event_handler super;
234
235	/* The task that is doing the re-enablement.  */
236	Process * task_enabling_breakpoint;
237
238	/* The pointer being re-enabled.  */
239	struct breakpoint *breakpoint_being_enabled;
240
241	/* Artificial atomic skip breakpoint, if any needed.  */
242	void *atomic_skip_bp_addr;
243
244	enum {
245		/* We are waiting for everyone to land in t/T.  */
246		psh_stopping = 0,
247
248		/* We are doing the PTRACE_SINGLESTEP.  */
249		psh_singlestep,
250
251		/* We are waiting for all the SIGSTOPs to arrive so
252		 * that we can sink them.  */
253		psh_sinking,
254
255		/* This is for tracking the ugly workaround.  */
256		psh_ugly_workaround,
257	} state;
258
259	int exiting;
260
261	struct pid_set pids;
262};
263
264static struct pid_task *
265get_task_info(struct pid_set * pids, pid_t pid)
266{
267	assert(pid != 0);
268	size_t i;
269	for (i = 0; i < pids->count; ++i)
270		if (pids->tasks[i].pid == pid)
271			return &pids->tasks[i];
272
273	return NULL;
274}
275
276static struct pid_task *
277add_task_info(struct pid_set * pids, pid_t pid)
278{
279	if (pids->count == pids->alloc) {
280		size_t ns = (2 * pids->alloc) ?: 4;
281		struct pid_task * n = realloc(pids->tasks,
282					      sizeof(*pids->tasks) * ns);
283		if (n == NULL)
284			return NULL;
285		pids->tasks = n;
286		pids->alloc = ns;
287	}
288	struct pid_task * task_info = &pids->tasks[pids->count++];
289	memset(task_info, 0, sizeof(*task_info));
290	task_info->pid = pid;
291	return task_info;
292}
293
294static enum callback_status
295task_stopped(struct Process *task, void *data)
296{
297	enum process_status st = process_status(task->pid);
298	if (data != NULL)
299		*(enum process_status *)data = st;
300
301	/* If the task is already stopped, don't worry about it.
302	 * Likewise if it managed to become a zombie or terminate in
303	 * the meantime.  This can happen when the whole thread group
304	 * is terminating.  */
305	switch (st) {
306	case ps_invalid:
307	case ps_tracing_stop:
308	case ps_zombie:
309		return CBS_CONT;
310	case ps_sleeping:
311	case ps_stop:
312	case ps_other:
313		return CBS_STOP;
314	}
315
316	abort ();
317}
318
319/* Task is blocked if it's stopped, or if it's a vfork parent.  */
320static enum callback_status
321task_blocked(struct Process *task, void *data)
322{
323	struct pid_set * pids = data;
324	struct pid_task * task_info = get_task_info(pids, task->pid);
325	if (task_info != NULL
326	    && task_info->vforked)
327		return CBS_CONT;
328
329	return task_stopped(task, NULL);
330}
331
332static Event *process_vfork_on_event(struct event_handler *super, Event *event);
333
334static enum callback_status
335task_vforked(struct Process *task, void *data)
336{
337	if (task->event_handler != NULL
338	    && task->event_handler->on_event == &process_vfork_on_event)
339		return CBS_STOP;
340	return CBS_CONT;
341}
342
343static int
344is_vfork_parent(struct Process *task)
345{
346	return each_task(task->leader, NULL, &task_vforked, NULL) != NULL;
347}
348
349static enum callback_status
350send_sigstop(struct Process *task, void *data)
351{
352	Process * leader = task->leader;
353	struct pid_set * pids = data;
354
355	/* Look for pre-existing task record, or add new.  */
356	struct pid_task * task_info = get_task_info(pids, task->pid);
357	if (task_info == NULL)
358		task_info = add_task_info(pids, task->pid);
359	if (task_info == NULL) {
360		perror("send_sigstop: add_task_info");
361		destroy_event_handler(leader);
362		/* Signal failure upwards.  */
363		return CBS_STOP;
364	}
365
366	/* This task still has not been attached to.  It should be
367	   stopped by the kernel.  */
368	if (task->state == STATE_BEING_CREATED)
369		return CBS_CONT;
370
371	/* Don't bother sending SIGSTOP if we are already stopped, or
372	 * if we sent the SIGSTOP already, which happens when we are
373	 * handling "onexit" and inherited the handler from breakpoint
374	 * re-enablement.  */
375	enum process_status st;
376	if (task_stopped(task, &st) == CBS_CONT)
377		return CBS_CONT;
378	if (task_info->sigstopped) {
379		if (!task_info->delivered)
380			return CBS_CONT;
381		task_info->delivered = 0;
382	}
383
384	/* Also don't attempt to stop the process if it's a parent of
385	 * vforked process.  We set up event handler specially to hint
386	 * us.  In that case parent is in D state, which we use to
387	 * weed out unnecessary looping.  */
388	if (st == ps_sleeping
389	    && is_vfork_parent (task)) {
390		task_info->vforked = 1;
391		return CBS_CONT;
392	}
393
394	if (task_kill(task->pid, SIGSTOP) >= 0) {
395		debug(DEBUG_PROCESS, "send SIGSTOP to %d", task->pid);
396		task_info->sigstopped = 1;
397	} else
398		fprintf(stderr,
399			"Warning: couldn't send SIGSTOP to %d\n", task->pid);
400
401	return CBS_CONT;
402}
403
404/* On certain kernels, detaching right after a singlestep causes the
405   tracee to be killed with a SIGTRAP (that even though the singlestep
406   was properly caught by waitpid.  The ugly workaround is to put a
407   breakpoint where IP points and let the process continue.  After
408   this the breakpoint can be retracted and the process detached.  */
409static void
410ugly_workaround(Process * proc)
411{
412	void * ip = get_instruction_pointer(proc);
413	struct breakpoint *sbp = dict_find_entry(proc->leader->breakpoints, ip);
414	if (sbp != NULL)
415		enable_breakpoint(proc, sbp);
416	else
417		insert_breakpoint(proc, ip, NULL, 1);
418	ptrace(PTRACE_CONT, proc->pid, 0, 0);
419}
420
421static void
422process_stopping_done(struct process_stopping_handler * self, Process * leader)
423{
424	debug(DEBUG_PROCESS, "process stopping done %d",
425	      self->task_enabling_breakpoint->pid);
426	size_t i;
427	if (!self->exiting) {
428		for (i = 0; i < self->pids.count; ++i)
429			if (self->pids.tasks[i].pid != 0
430			    && (self->pids.tasks[i].delivered
431				|| self->pids.tasks[i].sysret))
432				continue_process(self->pids.tasks[i].pid);
433		continue_process(self->task_enabling_breakpoint->pid);
434		destroy_event_handler(leader);
435	} else {
436		self->state = psh_ugly_workaround;
437		ugly_workaround(self->task_enabling_breakpoint);
438	}
439}
440
441/* Before we detach, we need to make sure that task's IP is on the
442 * edge of an instruction.  So for tasks that have a breakpoint event
443 * in the queue, we adjust the instruction pointer, just like
444 * continue_after_breakpoint does.  */
445static enum ecb_status
446undo_breakpoint(Event * event, void * data)
447{
448	if (event != NULL
449	    && event->proc->leader == data
450	    && event->type == EVENT_BREAKPOINT)
451		set_instruction_pointer(event->proc, event->e_un.brk_addr);
452	return ecb_cont;
453}
454
455static enum callback_status
456untrace_task(struct Process *task, void *data)
457{
458	if (task != data)
459		untrace_pid(task->pid);
460	return CBS_CONT;
461}
462
463static enum callback_status
464remove_task(struct Process *task, void *data)
465{
466	/* Don't untrace leader just yet.  */
467	if (task != data)
468		remove_process(task);
469	return CBS_CONT;
470}
471
472static void
473detach_process(Process * leader)
474{
475	each_qd_event(&undo_breakpoint, leader);
476	disable_all_breakpoints(leader);
477
478	/* Now untrace the process, if it was attached to by -p.  */
479	struct opt_p_t * it;
480	for (it = opt_p; it != NULL; it = it->next) {
481		Process * proc = pid2proc(it->pid);
482		if (proc == NULL)
483			continue;
484		if (proc->leader == leader) {
485			each_task(leader, NULL, &untrace_task, NULL);
486			break;
487		}
488	}
489	each_task(leader, NULL, &remove_task, leader);
490	destroy_event_handler(leader);
491	remove_task(leader, NULL);
492}
493
494static void
495handle_stopping_event(struct pid_task * task_info, Event ** eventp)
496{
497	/* Mark all events, so that we know whom to SIGCONT later.  */
498	if (task_info != NULL)
499		task_info->got_event = 1;
500
501	Event * event = *eventp;
502
503	/* In every state, sink SIGSTOP events for tasks that it was
504	 * sent to.  */
505	if (task_info != NULL
506	    && event->type == EVENT_SIGNAL
507	    && event->e_un.signum == SIGSTOP) {
508		debug(DEBUG_PROCESS, "SIGSTOP delivered to %d", task_info->pid);
509		if (task_info->sigstopped
510		    && !task_info->delivered) {
511			task_info->delivered = 1;
512			*eventp = NULL; // sink the event
513		} else
514			fprintf(stderr, "suspicious: %d got SIGSTOP, but "
515				"sigstopped=%d and delivered=%d\n",
516				task_info->pid, task_info->sigstopped,
517				task_info->delivered);
518	}
519}
520
521/* Some SIGSTOPs may have not been delivered to their respective tasks
522 * yet.  They are still in the queue.  If we have seen an event for
523 * that process, continue it, so that the SIGSTOP can be delivered and
524 * caught by ltrace.  We don't mind that the process is after
525 * breakpoint (and therefore potentially doesn't have aligned IP),
526 * because the signal will be delivered without the process actually
527 * starting.  */
528static void
529continue_for_sigstop_delivery(struct pid_set * pids)
530{
531	size_t i;
532	for (i = 0; i < pids->count; ++i) {
533		if (pids->tasks[i].pid != 0
534		    && pids->tasks[i].sigstopped
535		    && !pids->tasks[i].delivered
536		    && pids->tasks[i].got_event) {
537			debug(DEBUG_PROCESS, "continue %d for SIGSTOP delivery",
538			      pids->tasks[i].pid);
539			ptrace(PTRACE_SYSCALL, pids->tasks[i].pid, 0, 0);
540		}
541	}
542}
543
544static int
545event_exit_p(Event * event)
546{
547	return event != NULL && (event->type == EVENT_EXIT
548				 || event->type == EVENT_EXIT_SIGNAL);
549}
550
551static int
552event_exit_or_none_p(Event * event)
553{
554	return event == NULL || event_exit_p(event)
555		|| event->type == EVENT_NONE;
556}
557
558static int
559await_sigstop_delivery(struct pid_set * pids, struct pid_task * task_info,
560		       Event * event)
561{
562	/* If we still didn't get our SIGSTOP, continue the process
563	 * and carry on.  */
564	if (event != NULL && !event_exit_or_none_p(event)
565	    && task_info != NULL && task_info->sigstopped) {
566		debug(DEBUG_PROCESS, "continue %d for SIGSTOP delivery",
567		      task_info->pid);
568		/* We should get the signal the first thing
569		 * after this, so it should be OK to continue
570		 * even if we are over a breakpoint.  */
571		ptrace(PTRACE_SYSCALL, task_info->pid, 0, 0);
572
573	} else {
574		/* If all SIGSTOPs were delivered, uninstall the
575		 * handler and continue everyone.  */
576		/* XXX I suspect that we should check tasks that are
577		 * still around.  Is things are now, there should be a
578		 * race between waiting for everyone to stop and one
579		 * of the tasks exiting.  */
580		int all_clear = 1;
581		size_t i;
582		for (i = 0; i < pids->count; ++i)
583			if (pids->tasks[i].pid != 0
584			    && pids->tasks[i].sigstopped
585			    && !pids->tasks[i].delivered) {
586				all_clear = 0;
587				break;
588			}
589		return all_clear;
590	}
591
592	return 0;
593}
594
595static int
596all_stops_accountable(struct pid_set * pids)
597{
598	size_t i;
599	for (i = 0; i < pids->count; ++i)
600		if (pids->tasks[i].pid != 0
601		    && !pids->tasks[i].got_event
602		    && !have_events_for(pids->tasks[i].pid))
603			return 0;
604	return 1;
605}
606
607/* The protocol is: 0 for success, negative for failure, positive if
608 * default singlestep is to be used.  */
609int arch_atomic_singlestep(struct Process *proc, Breakpoint *sbp,
610			   int (*add_cb)(void *addr, void *data),
611			   void *add_cb_data);
612
613#ifndef ARCH_HAVE_ATOMIC_SINGLESTEP
614int
615arch_atomic_singlestep(struct Process *proc, Breakpoint *sbp,
616		       int (*add_cb)(void *addr, void *data),
617		       void *add_cb_data)
618{
619	return 1;
620}
621#endif
622
623static int
624atomic_singlestep_add_bp(void *addr, void *data)
625{
626	struct process_stopping_handler *self = data;
627	struct Process *proc = self->task_enabling_breakpoint;
628
629	/* Only support single address as of now.  */
630	assert(self->atomic_skip_bp_addr == NULL);
631
632	self->atomic_skip_bp_addr = addr + 4;
633	insert_breakpoint(proc->leader, self->atomic_skip_bp_addr, NULL, 1);
634
635	return 0;
636}
637
638static int
639singlestep(struct process_stopping_handler *self)
640{
641	struct Process *proc = self->task_enabling_breakpoint;
642
643	int status = arch_atomic_singlestep(self->task_enabling_breakpoint,
644					    self->breakpoint_being_enabled,
645					    &atomic_singlestep_add_bp, self);
646
647	/* Propagate failure and success.  */
648	if (status <= 0)
649		return status;
650
651	/* Otherwise do the default action: singlestep.  */
652	debug(1, "PTRACE_SINGLESTEP");
653	if (ptrace(PTRACE_SINGLESTEP, proc->pid, 0, 0)) {
654		perror("PTRACE_SINGLESTEP");
655		return -1;
656	}
657	return 0;
658}
659
660static void
661post_singlestep(struct process_stopping_handler *self, Event **eventp)
662{
663	continue_for_sigstop_delivery(&self->pids);
664
665	if ((*eventp)->type == EVENT_BREAKPOINT)
666		*eventp = NULL; // handled
667
668	if (self->atomic_skip_bp_addr != 0)
669		delete_breakpoint(self->task_enabling_breakpoint->leader,
670				  self->atomic_skip_bp_addr);
671
672	self->breakpoint_being_enabled = NULL;
673}
674
675static void
676singlestep_error(struct process_stopping_handler *self, Event **eventp)
677{
678	struct Process *teb = self->task_enabling_breakpoint;
679	Breakpoint *sbp = self->breakpoint_being_enabled;
680	fprintf(stderr, "%d couldn't singlestep over %s (%p)\n",
681		teb->pid, sbp->libsym != NULL ? sbp->libsym->name : NULL,
682		sbp->addr);
683	delete_breakpoint(teb->leader, sbp->addr);
684	post_singlestep(self, eventp);
685}
686
687/* This event handler is installed when we are in the process of
688 * stopping the whole thread group to do the pointer re-enablement for
689 * one of the threads.  We pump all events to the queue for later
690 * processing while we wait for all the threads to stop.  When this
691 * happens, we let the re-enablement thread to PTRACE_SINGLESTEP,
692 * re-enable, and continue everyone.  */
693static Event *
694process_stopping_on_event(struct event_handler *super, Event *event)
695{
696	struct process_stopping_handler * self = (void *)super;
697	Process * task = event->proc;
698	Process * leader = task->leader;
699	struct breakpoint *sbp = self->breakpoint_being_enabled;
700	Process * teb = self->task_enabling_breakpoint;
701
702	debug(DEBUG_PROCESS,
703	      "pid %d; event type %d; state %d",
704	      task->pid, event->type, self->state);
705
706	struct pid_task * task_info = get_task_info(&self->pids, task->pid);
707	if (task_info == NULL)
708		fprintf(stderr, "new task??? %d\n", task->pid);
709	handle_stopping_event(task_info, &event);
710
711	int state = self->state;
712	int event_to_queue = !event_exit_or_none_p(event);
713
714	/* Deactivate the entry if the task exits.  */
715	if (event_exit_p(event) && task_info != NULL)
716		task_info->pid = 0;
717
718	/* Always handle sysrets.  Whether sysret occurred and what
719	 * sys it rets from may need to be determined based on process
720	 * stack, so we need to keep that in sync with reality.  Note
721	 * that we don't continue the process after the sysret is
722	 * handled.  See continue_after_syscall.  */
723	if (event != NULL && event->type == EVENT_SYSRET) {
724		debug(1, "%d LT_EV_SYSRET", event->proc->pid);
725		event_to_queue = 0;
726		task_info->sysret = 1;
727	}
728
729	switch (state) {
730	case psh_stopping:
731		/* If everyone is stopped, singlestep.  */
732		if (each_task(leader, NULL, &task_blocked,
733			      &self->pids) == NULL) {
734			debug(DEBUG_PROCESS, "all stopped, now SINGLESTEP %d",
735			      teb->pid);
736			if (sbp->enabled)
737				disable_breakpoint(teb, sbp);
738			if (singlestep(self) < 0) {
739				singlestep_error(self, &event);
740				goto psh_sinking;
741			}
742
743			self->state = state = psh_singlestep;
744		}
745		break;
746
747	case psh_singlestep:
748		/* In singlestep state, breakpoint signifies that we
749		 * have now stepped, and can re-enable the breakpoint.  */
750		if (event != NULL && task == teb) {
751
752			/* This is not the singlestep that we are waiting for.  */
753			if (event->type == EVENT_SIGNAL) {
754				if (singlestep(self) < 0) {
755					singlestep_error(self, &event);
756					goto psh_sinking;
757				}
758				break;
759			}
760
761			/* Essentially we don't care what event caused
762			 * the thread to stop.  We can do the
763			 * re-enablement now.  */
764			if (sbp->enabled)
765				enable_breakpoint(teb, sbp);
766
767			post_singlestep(self, &event);
768			goto psh_sinking;
769		}
770		break;
771
772	psh_sinking:
773		state = self->state = psh_sinking;
774	case psh_sinking:
775		if (await_sigstop_delivery(&self->pids, task_info, event))
776			process_stopping_done(self, leader);
777		break;
778
779	case psh_ugly_workaround:
780		if (event == NULL)
781			break;
782		if (event->type == EVENT_BREAKPOINT) {
783			undo_breakpoint(event, leader);
784			if (task == teb)
785				self->task_enabling_breakpoint = NULL;
786		}
787		if (self->task_enabling_breakpoint == NULL
788		    && all_stops_accountable(&self->pids)) {
789			undo_breakpoint(event, leader);
790			detach_process(leader);
791			event = NULL; // handled
792		}
793	}
794
795	if (event != NULL && event_to_queue) {
796		enque_event(event);
797		event = NULL; // sink the event
798	}
799
800	return event;
801}
802
803static void
804process_stopping_destroy(struct event_handler *super)
805{
806	struct process_stopping_handler * self = (void *)super;
807	free(self->pids.tasks);
808}
809
810void
811continue_after_breakpoint(Process *proc, struct breakpoint *sbp)
812{
813	set_instruction_pointer(proc, sbp->addr);
814	if (sbp->enabled == 0) {
815		continue_process(proc->pid);
816	} else {
817		debug(DEBUG_PROCESS,
818		      "continue_after_breakpoint: pid=%d, addr=%p",
819		      proc->pid, sbp->addr);
820#if defined __sparc__  || defined __ia64___ || defined __mips__
821		/* we don't want to singlestep here */
822		continue_process(proc->pid);
823#else
824		struct process_stopping_handler * handler
825			= calloc(sizeof(*handler), 1);
826		if (handler == NULL) {
827			perror("malloc breakpoint disable handler");
828		fatal:
829			/* Carry on not bothering to re-enable.  */
830			continue_process(proc->pid);
831			return;
832		}
833
834		handler->super.on_event = process_stopping_on_event;
835		handler->super.destroy = process_stopping_destroy;
836		handler->task_enabling_breakpoint = proc;
837		handler->breakpoint_being_enabled = sbp;
838		install_event_handler(proc->leader, &handler->super);
839
840		if (each_task(proc->leader, NULL, &send_sigstop,
841			      &handler->pids) != NULL)
842			goto fatal;
843
844		/* And deliver the first fake event, in case all the
845		 * conditions are already fulfilled.  */
846		Event ev;
847		ev.type = EVENT_NONE;
848		ev.proc = proc;
849		process_stopping_on_event(&handler->super, &ev);
850#endif
851	}
852}
853
854/**
855 * Ltrace exit.  When we are about to exit, we have to go through all
856 * the processes, stop them all, remove all the breakpoints, and then
857 * detach the processes that we attached to using -p.  If we left the
858 * other tasks running, they might hit stray return breakpoints and
859 * produce artifacts, so we better stop everyone, even if it's a bit
860 * of extra work.
861 */
862struct ltrace_exiting_handler
863{
864	struct event_handler super;
865	struct pid_set pids;
866};
867
868static Event *
869ltrace_exiting_on_event(struct event_handler *super, Event *event)
870{
871	struct ltrace_exiting_handler * self = (void *)super;
872	Process * task = event->proc;
873	Process * leader = task->leader;
874
875	debug(DEBUG_PROCESS, "pid %d; event type %d", task->pid, event->type);
876
877	struct pid_task * task_info = get_task_info(&self->pids, task->pid);
878	handle_stopping_event(task_info, &event);
879
880	if (event != NULL && event->type == EVENT_BREAKPOINT)
881		undo_breakpoint(event, leader);
882
883	if (await_sigstop_delivery(&self->pids, task_info, event)
884	    && all_stops_accountable(&self->pids))
885		detach_process(leader);
886
887	/* Sink all non-exit events.  We are about to exit, so we
888	 * don't bother with queuing them. */
889	if (event_exit_or_none_p(event))
890		return event;
891
892	return NULL;
893}
894
895static void
896ltrace_exiting_destroy(struct event_handler *super)
897{
898	struct ltrace_exiting_handler * self = (void *)super;
899	free(self->pids.tasks);
900}
901
902static int
903ltrace_exiting_install_handler(Process * proc)
904{
905	/* Only install to leader.  */
906	if (proc->leader != proc)
907		return 0;
908
909	/* Perhaps we are already installed, if the user passed
910	 * several -p options that are tasks of one process.  */
911	if (proc->event_handler != NULL
912	    && proc->event_handler->on_event == &ltrace_exiting_on_event)
913		return 0;
914
915	/* If stopping handler is already present, let it do the
916	 * work.  */
917	if (proc->event_handler != NULL) {
918		assert(proc->event_handler->on_event
919		       == &process_stopping_on_event);
920		struct process_stopping_handler * other
921			= (void *)proc->event_handler;
922		other->exiting = 1;
923		return 0;
924	}
925
926	struct ltrace_exiting_handler * handler
927		= calloc(sizeof(*handler), 1);
928	if (handler == NULL) {
929		perror("malloc exiting handler");
930	fatal:
931		/* XXXXXXXXXXXXXXXXXXX fixme */
932		return -1;
933	}
934
935	handler->super.on_event = ltrace_exiting_on_event;
936	handler->super.destroy = ltrace_exiting_destroy;
937	install_event_handler(proc->leader, &handler->super);
938
939	if (each_task(proc->leader, NULL, &send_sigstop,
940		      &handler->pids) != NULL)
941		goto fatal;
942
943	return 0;
944}
945
946/*
947 * When the traced process vforks, it's suspended until the child
948 * process calls _exit or exec*.  In the meantime, the two share the
949 * address space.
950 *
951 * The child process should only ever call _exit or exec*, but we
952 * can't count on that (it's not the role of ltrace to policy, but to
953 * observe).  In any case, we will _at least_ have to deal with
954 * removal of vfork return breakpoint (which we have to smuggle back
955 * in, so that the parent can see it, too), and introduction of exec*
956 * return breakpoint.  Since we already have both breakpoint actions
957 * to deal with, we might as well support it all.
958 *
959 * The gist is that we pretend that the child is in a thread group
960 * with its parent, and handle it as a multi-threaded case, with the
961 * exception that we know that the parent is blocked, and don't
962 * attempt to stop it.  When the child execs, we undo the setup.
963 */
964
965struct process_vfork_handler
966{
967	struct event_handler super;
968	void * bp_addr;
969};
970
971static Event *
972process_vfork_on_event(struct event_handler *super, Event *event)
973{
974	struct process_vfork_handler * self = (void *)super;
975	struct breakpoint *sbp;
976	assert(self != NULL);
977
978	switch (event->type) {
979	case EVENT_BREAKPOINT:
980		/* Remember the vfork return breakpoint.  */
981		if (self->bp_addr == NULL)
982			self->bp_addr = event->e_un.brk_addr;
983		break;
984
985	case EVENT_EXIT:
986	case EVENT_EXIT_SIGNAL:
987	case EVENT_EXEC:
988		/* Smuggle back in the vfork return breakpoint, so
989		 * that our parent can trip over it once again.  */
990		if (self->bp_addr != NULL) {
991			sbp = dict_find_entry(event->proc->leader->breakpoints,
992					      self->bp_addr);
993			if (sbp != NULL)
994				insert_breakpoint(event->proc->parent,
995						  self->bp_addr,
996						  sbp->libsym, 1);
997		}
998
999		continue_process(event->proc->parent->pid);
1000
1001		/* Remove the leader that we artificially set up
1002		 * earlier.  */
1003		change_process_leader(event->proc, event->proc);
1004		destroy_event_handler(event->proc);
1005
1006	default:
1007		;
1008	}
1009
1010	return event;
1011}
1012
1013void
1014continue_after_vfork(Process * proc)
1015{
1016	debug(DEBUG_PROCESS, "continue_after_vfork: pid=%d", proc->pid);
1017	struct process_vfork_handler * handler = calloc(sizeof(*handler), 1);
1018	if (handler == NULL) {
1019		perror("malloc vfork handler");
1020		/* Carry on not bothering to treat the process as
1021		 * necessary.  */
1022		continue_process(proc->parent->pid);
1023		return;
1024	}
1025
1026	/* We must set up custom event handler, so that we see
1027	 * exec/exit events for the task itself.  */
1028	handler->super.on_event = process_vfork_on_event;
1029	install_event_handler(proc, &handler->super);
1030
1031	/* Make sure that the child is sole thread.  */
1032	assert(proc->leader == proc);
1033	assert(proc->next == NULL || proc->next->leader != proc);
1034
1035	/* Make sure that the child's parent is properly set up.  */
1036	assert(proc->parent != NULL);
1037	assert(proc->parent->leader != NULL);
1038
1039	change_process_leader(proc, proc->parent->leader);
1040}
1041
1042static int
1043is_mid_stopping(Process *proc)
1044{
1045	return proc != NULL
1046		&& proc->event_handler != NULL
1047		&& proc->event_handler->on_event == &process_stopping_on_event;
1048}
1049
1050void
1051continue_after_syscall(Process * proc, int sysnum, int ret_p)
1052{
1053	/* Don't continue if we are mid-stopping.  */
1054	if (ret_p && (is_mid_stopping(proc) || is_mid_stopping(proc->leader))) {
1055		debug(DEBUG_PROCESS,
1056		      "continue_after_syscall: don't continue %d",
1057		      proc->pid);
1058		return;
1059	}
1060	continue_process(proc->pid);
1061}
1062
1063/* If ltrace gets SIGINT, the processes directly or indirectly run by
1064 * ltrace get it too.  We just have to wait long enough for the signal
1065 * to be delivered and the process terminated, which we notice and
1066 * exit ltrace, too.  So there's not much we need to do there.  We
1067 * want to keep tracing those processes as usual, in case they just
1068 * SIG_IGN the SIGINT to do their shutdown etc.
1069 *
1070 * For processes ran on the background, we want to install an exit
1071 * handler that stops all the threads, removes all breakpoints, and
1072 * detaches.
1073 */
1074void
1075os_ltrace_exiting(void)
1076{
1077	struct opt_p_t * it;
1078	for (it = opt_p; it != NULL; it = it->next) {
1079		Process * proc = pid2proc(it->pid);
1080		if (proc == NULL || proc->leader == NULL)
1081			continue;
1082		if (ltrace_exiting_install_handler(proc->leader) < 0)
1083			fprintf(stderr,
1084				"Couldn't install exiting handler for %d.\n",
1085				proc->pid);
1086	}
1087}
1088
1089int
1090os_ltrace_exiting_sighandler(void)
1091{
1092	extern int linux_in_waitpid;
1093	if (linux_in_waitpid) {
1094		os_ltrace_exiting();
1095		return 1;
1096	}
1097	return 0;
1098}
1099
1100size_t
1101umovebytes(Process *proc, void *addr, void *laddr, size_t len) {
1102
1103	union {
1104		long a;
1105		char c[sizeof(long)];
1106	} a;
1107	int started = 0;
1108	size_t offset = 0, bytes_read = 0;
1109
1110	while (offset < len) {
1111		a.a = ptrace(PTRACE_PEEKTEXT, proc->pid, addr + offset, 0);
1112		if (a.a == -1 && errno) {
1113			if (started && errno == EIO)
1114				return bytes_read;
1115			else
1116				return -1;
1117		}
1118		started = 1;
1119
1120		if (len - offset >= sizeof(long)) {
1121			memcpy(laddr + offset, &a.c[0], sizeof(long));
1122			bytes_read += sizeof(long);
1123		}
1124		else {
1125			memcpy(laddr + offset, &a.c[0], len - offset);
1126			bytes_read += (len - offset);
1127		}
1128		offset += sizeof(long);
1129	}
1130
1131	return bytes_read;
1132}
1133
1134/* Read a series of bytes starting at the process's memory address
1135   'addr' and continuing until a NUL ('\0') is seen or 'len' bytes
1136   have been read.
1137*/
1138int
1139umovestr(Process *proc, void *addr, int len, void *laddr) {
1140	union {
1141		long a;
1142		char c[sizeof(long)];
1143	} a;
1144	unsigned i;
1145	int offset = 0;
1146
1147	while (offset < len) {
1148		a.a = ptrace(PTRACE_PEEKTEXT, proc->pid, addr + offset, 0);
1149		for (i = 0; i < sizeof(long); i++) {
1150			if (a.c[i] && offset + (signed)i < len) {
1151				*(char *)(laddr + offset + i) = a.c[i];
1152			} else {
1153				*(char *)(laddr + offset + i) = '\0';
1154				return 0;
1155			}
1156		}
1157		offset += sizeof(long);
1158	}
1159	*(char *)(laddr + offset) = '\0';
1160	return 0;
1161}
1162