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