2 * Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
3 * Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
4 * Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
5 * Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
6 * Copyright (c) 1999-2018 The strace developers.
9 * Redistribution and use in source and binary forms, with or without
10 * modification, are permitted provided that the following conditions
12 * 1. Redistributions of source code must retain the above copyright
13 * notice, this list of conditions and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in the
16 * documentation and/or other materials provided with the distribution.
17 * 3. The name of the author may not be used to endorse or promote products
18 * derived from this software without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
21 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
22 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
23 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
24 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
25 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
26 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
27 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
28 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
29 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 #include <sys/resource.h>
48 #include <sys/utsname.h>
50 # include <sys/prctl.h>
52 #include <asm/unistd.h>
54 #include "largefile_wrappers.h"
55 #include "mmap_cache.h"
56 #include "number_set.h"
58 #include "printsiginfo.h"
59 #include "trace_event.h"
63 /* In some libc, these aren't declared. Do it ourself: */
64 extern char **environ;
69 /* if this is true do the stack trace for every system call */
70 bool stack_trace_enabled;
73 #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
75 /* Glue for systems without a MMU that cannot provide fork() */
76 #if !defined(HAVE_FORK)
78 # define NOMMU_SYSTEM 1
81 # define fork() vfork()
84 const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
86 cflag_t cflag = CFLAG_NONE;
87 unsigned int followfork;
88 unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
96 static unsigned int tflag;
98 static bool print_pid_pfx;
103 INTR_ANYWHERE = 1, /* don't block/ignore any signals */
104 INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
105 INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
106 INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
110 /* We play with signal mask only if this mode is active: */
111 #define interactive (opt_intr == INTR_WHILE_WAIT)
114 * daemonized_tracer supports -D option.
115 * With this option, strace forks twice.
116 * Unlike normal case, with -D *grandparent* process exec's,
117 * becoming a traced process. Child exits (this prevents traced process
118 * from having children it doesn't expect to have), and grandchild
119 * attaches to grandparent similarly to strace -p PID.
120 * This allows for more transparent interaction in cases
121 * when process and its parent are communicating via signals,
122 * wait() etc. Without -D, strace process gets lodged in between,
123 * disrupting parent<->child link.
125 static bool daemonized_tracer;
127 static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
128 #define use_seize (post_attach_sigstop == 0)
130 /* Sometimes we want to print only succeeding syscalls. */
131 bool not_failing_only;
133 /* Show path associated with fd arguments */
134 unsigned int show_fd_path;
136 static bool detach_on_execve;
138 static int exit_code;
139 static int strace_child;
140 static int strace_tracer_pid;
142 static const char *username;
143 static uid_t run_uid;
144 static gid_t run_gid;
146 unsigned int max_strlen = DEFAULT_STRLEN;
147 static int acolumn = DEFAULT_ACOLUMN;
148 static char *acolumn_spaces;
150 static const char *outfname;
151 /* If -ff, points to stderr. Else, it's our common output log */
152 static FILE *shared_log;
154 struct tcb *printing_tcp;
155 static struct tcb *current_tcp;
157 static struct tcb **tcbtab;
158 static unsigned int nprocs;
159 static size_t tcbtabsize;
161 #ifndef HAVE_PROGRAM_INVOCATION_NAME
162 char *program_invocation_name;
165 unsigned os_release; /* generated from uname()'s u.release */
167 static void detach(struct tcb *tcp);
168 static void cleanup(void);
169 static void interrupt(int sig);
171 #ifdef HAVE_SIG_ATOMIC_T
172 static volatile sig_atomic_t interrupted, restart_failed;
174 static volatile int interrupted, restart_failed;
177 static sigset_t timer_set;
178 static void timer_sighandler(int);
180 #ifndef HAVE_STRERROR
182 #if !HAVE_DECL_SYS_ERRLIST
184 extern char *sys_errlist[];
190 static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
192 if (err_no < 1 || err_no >= sys_nerr) {
193 xsprintf(buf, "Unknown error %d", err_no);
196 return sys_errlist[err_no];
199 #endif /* HAVE_STERRROR */
204 static const char features[] =
207 #endif /* USE_LIBUNWIND */
210 #endif /* USE_DEMANGLE */
211 #if SUPPORTED_PERSONALITIES > 1
212 # if defined HAVE_M32_MPERS
217 #endif /* SUPPORTED_PERSONALITIES > 1 */
218 #if SUPPORTED_PERSONALITIES > 2
219 # if defined HAVE_MX32_MPERS
224 #endif /* SUPPORTED_PERSONALITIES > 2 */
227 printf("%s -- version %s\n"
228 "Copyright (c) 1991-%s The strace developers <%s>.\n"
229 "This is free software; see the source for copying conditions. There is NO\n"
230 "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
231 PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
232 printf("\nOptional features enabled:%s\n",
233 features[0] ? features : " (none)");
240 usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
241 [-a column] [-o file] [-s strsize] [-P path]...\n\
242 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
243 or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
244 -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
247 -a column alignment COLUMN for printing syscall results (default %d)\n\
248 -i print instruction pointer at time of syscall\n\
252 -k obtain stack trace between each syscall (experimental)\n\
256 -o file send trace output to FILE instead of stderr\n\
257 -q suppress messages about attaching, detaching, etc.\n\
258 -r print relative timestamp\n\
259 -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
260 -t print absolute timestamp\n\
261 -tt print absolute timestamp with usecs\n\
262 -T print time spent in each syscall\n\
263 -x print non-ascii strings in hex\n\
264 -xx print all strings in hex\n\
265 -y print paths associated with file descriptor arguments\n\
266 -yy print protocol specific information associated with socket file descriptors\n\
269 -c count time, calls, and errors for each syscall and report summary\n\
270 -C like -c but also print regular output\n\
271 -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
272 -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
273 -w summarise syscall latency (default is system time)\n\
276 -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
277 options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
278 -P path trace accesses to path\n\
281 -b execve detach on execve syscall\n\
282 -D run tracer process as a detached grandchild, not as parent\n\
284 -ff follow forks with output into separate files\n\
286 1: no signals are blocked\n\
287 2: fatal signals are blocked while decoding syscall (default)\n\
288 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
289 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
290 (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
293 -E var remove var from the environment for command\n\
294 -E var=val put var=val in the environment for command\n\
295 -p pid trace process with process id PID, may be repeated\n\
296 -u username run command as username handling setuid and/or setgid\n\
299 -d enable debug output to stderr\n\
300 -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
301 -h print help message\n\
304 /* ancient, no one should use it
305 -F -- attempt to follow vforks (deprecated, use -f)\n\
307 /* this is broken, so don't document it
308 -z -- print only succeeding syscalls\n\
310 , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
314 void ATTRIBUTE_NORETURN
317 if (strace_tracer_pid == getpid()) {
327 error_opt_arg(int opt, const char *arg)
329 error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
332 static const char *ptrace_attach_cmd;
335 ptrace_attach_or_seize(int pid)
339 return ptrace_attach_cmd = "PTRACE_ATTACH",
340 ptrace(PTRACE_ATTACH, pid, 0L, 0L);
341 r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
343 return ptrace_attach_cmd = "PTRACE_SEIZE", r;
344 r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
345 return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
349 * Used when we want to unblock stopped traced process.
350 * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
351 * Returns 0 on success or if error was ESRCH
352 * (presumably process was killed while we talk to it).
353 * Otherwise prints error message and returns -1.
356 ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
362 ptrace(op, tcp->pid, 0L, (unsigned long) sig);
382 * Why curcol != 0? Otherwise sometimes we get this:
384 * 10252 kill(10253, SIGKILL) = 0
385 * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
387 * 10252 died after we retrieved syscall exit data,
388 * but before we tried to restart it. Log looks ugly.
390 if (current_tcp && current_tcp->curcol != 0) {
391 tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
397 perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
402 set_cloexec_flag(int fd)
406 flags = fcntl(fd, F_GETFD);
408 /* Can happen only if fd is bad.
409 * Should never happen: if it does, we have a bug
410 * in the caller. Therefore we just abort
411 * instead of propagating the error.
413 perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
416 newflags = flags | FD_CLOEXEC;
417 if (flags == newflags)
420 fcntl(fd, F_SETFD, newflags); /* never fails */
424 kill_save_errno(pid_t pid, int sig)
426 int saved_errno = errno;
428 (void) kill(pid, sig);
433 * When strace is setuid executable, we have to swap uids
434 * before and after filesystem and process management operations.
439 int euid = geteuid(), uid = getuid();
441 if (euid != uid && setreuid(euid, uid) < 0) {
442 perror_msg_and_die("setreuid");
447 strace_fopen(const char *path)
452 fp = fopen_stream(path, "w");
454 perror_msg_and_die("Can't fopen '%s'", path);
456 set_cloexec_flag(fileno(fp));
460 static int popen_pid;
463 # define _PATH_BSHELL "/bin/sh"
467 * We cannot use standard popen(3) here because we have to distinguish
468 * popen child process from other processes we trace, and standard popen(3)
469 * does not export its child's pid.
472 strace_popen(const char *command)
480 perror_msg_and_die("pipe");
482 set_cloexec_flag(fds[1]); /* never fails */
486 perror_msg_and_die("vfork");
493 perror_msg_and_die("dup2");
496 execl(_PATH_BSHELL, "sh", "-c", command, NULL);
497 perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
504 fp = fdopen(fds[1], "w");
506 perror_msg_and_die("fdopen");
511 outf_perror(const struct tcb * const tcp)
513 if (tcp->outf == stderr)
516 /* This is ugly, but we don't store separate file names */
518 perror_msg("%s.%u", outfname, tcp->pid);
520 perror_msg("%s", outfname);
523 ATTRIBUTE_FORMAT((printf, 1, 0))
525 tvprintf(const char *const fmt, va_list args)
528 int n = vfprintf(current_tcp->outf, fmt, args);
530 /* very unlikely due to vfprintf buffering */
531 outf_perror(current_tcp);
533 current_tcp->curcol += n;
538 tprintf(const char *fmt, ...)
546 #ifndef HAVE_FPUTS_UNLOCKED
547 # define fputs_unlocked fputs
551 tprints(const char *str)
554 int n = fputs_unlocked(str, current_tcp->outf);
556 current_tcp->curcol += strlen(str);
559 /* very unlikely due to fputs_unlocked buffering */
560 outf_perror(current_tcp);
565 tprints_comment(const char *const str)
568 tprintf(" /* %s */", str);
572 tprintf_comment(const char *fmt, ...)
586 flush_tcp_output(const struct tcb *const tcp)
588 if (fflush(tcp->outf))
596 current_tcp->curcol = 0;
597 flush_tcp_output(current_tcp);
600 printing_tcp->curcol = 0;
606 set_current_tcp(const struct tcb *tcp)
608 current_tcp = (struct tcb *) tcp;
610 /* Sync current_personality and stuff */
612 set_personality(current_tcp->currpers);
616 printleader(struct tcb *tcp)
618 /* If -ff, "previous tcb we printed" is always the same as current,
619 * because we have per-tcb output files.
625 set_current_tcp(printing_tcp);
626 if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
628 * case 1: we have a shared log (i.e. not -ff), and last line
629 * wasn't finished (same or different tcb, doesn't matter).
630 * case 2: split log, we are the same tcb, but our last line
631 * didn't finish ("SIGKILL nuked us after syscall entry" etc).
633 tprints(" <unfinished ...>\n");
634 printing_tcp->curcol = 0;
639 set_current_tcp(tcp);
640 current_tcp->curcol = 0;
643 tprintf("%-5d ", tcp->pid);
644 else if (nprocs > 1 && !outfname)
645 tprintf("[pid %5u] ", tcp->pid);
649 clock_gettime(rflag ? CLOCK_MONOTONIC : CLOCK_REALTIME, &ts);
652 static struct timespec ots;
657 ts_sub(&dts, &ts, &ots);
660 tprintf("%6ld.%06ld ",
661 (long) dts.tv_sec, (long) dts.tv_nsec / 1000);
662 } else if (tflag > 2) {
663 tprintf("%lld.%06ld ",
664 (long long) ts.tv_sec, (long) ts.tv_nsec / 1000);
666 time_t local = ts.tv_sec;
667 char str[sizeof("HH:MM:SS")];
669 strftime(str, sizeof(str), "%T", localtime(&local));
672 str, (long) ts.tv_nsec / 1000);
684 if (current_tcp->curcol < acolumn)
685 tprints(acolumn_spaces + current_tcp->curcol);
688 /* Should be only called directly *after successful attach* to a tracee.
689 * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
690 * may create bogus empty FILE.<nonexistant_pid>, and then die.
693 newoutf(struct tcb *tcp)
695 tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
696 if (followfork >= 2) {
698 xsprintf(name, "%s.%u", outfname, tcp->pid);
699 tcp->outf = strace_fopen(name);
706 /* Allocate some (more) TCBs (and expand the table).
707 We don't want to relocate the TCBs because our
708 callers have pointers and it would be a pain.
709 So tcbtab is a table of pointers. Since we never
710 free the TCBs, we allocate a single chunk of many. */
711 size_t old_tcbtabsize;
713 struct tcb **tcb_ptr;
715 old_tcbtabsize = tcbtabsize;
717 tcbtab = xgrowarray(tcbtab, &tcbtabsize, sizeof(tcbtab[0]));
718 newtcbs = xcalloc(tcbtabsize - old_tcbtabsize, sizeof(newtcbs[0]));
720 for (tcb_ptr = tcbtab + old_tcbtabsize;
721 tcb_ptr < tcbtab + tcbtabsize; tcb_ptr++, newtcbs++)
731 if (nprocs == tcbtabsize)
734 for (i = 0; i < tcbtabsize; i++) {
737 memset(tcp, 0, sizeof(*tcp));
739 #if SUPPORTED_PERSONALITIES > 1
740 tcp->currpers = current_personality;
744 if (stack_trace_enabled)
745 unwind_tcb_init(tcp);
749 debug_msg("new tcb for pid %d, active tcbs:%d",
754 error_msg_and_die("bug in alloctcb");
758 get_tcb_priv_data(const struct tcb *tcp)
760 return tcp->_priv_data;
764 set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
765 void (*const free_priv_data)(void *))
770 tcp->_free_priv_data = free_priv_data;
771 tcp->_priv_data = priv_data;
777 free_tcb_priv_data(struct tcb *tcp)
779 if (tcp->_priv_data) {
780 if (tcp->_free_priv_data) {
781 tcp->_free_priv_data(tcp->_priv_data);
782 tcp->_free_priv_data = NULL;
784 tcp->_priv_data = NULL;
789 droptcb(struct tcb *tcp)
795 for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
796 free(tcp->inject_vec[p]);
798 free_tcb_priv_data(tcp);
801 if (stack_trace_enabled) {
806 mmap_cache_delete(tcp, __func__);
809 debug_msg("dropped tcb for pid %d, %d remain", tcp->pid, nprocs);
812 if (followfork >= 2) {
813 if (tcp->curcol != 0)
814 fprintf(tcp->outf, " <detached ...>\n");
817 if (printing_tcp == tcp && tcp->curcol != 0)
818 fprintf(tcp->outf, " <detached ...>\n");
819 flush_tcp_output(tcp);
823 if (current_tcp == tcp)
824 set_current_tcp(NULL);
825 if (printing_tcp == tcp)
828 memset(tcp, 0, sizeof(*tcp));
831 /* Detach traced process.
832 * Never call DETACH twice on the same process as both unattached and
833 * attached-unstopped processes give the same ESRCH. For unattached process we
834 * would SIGSTOP it and wait for its SIGSTOP notification forever.
837 detach(struct tcb *tcp)
843 * Linux wrongly insists the child be stopped
844 * before detaching. Arghh. We go through hoops
845 * to make a clean break of things.
848 if (!(tcp->flags & TCB_ATTACHED))
851 /* We attached but possibly didn't see the expected SIGSTOP.
852 * We must catch exactly one as otherwise the detached process
853 * would be left stopped (process state T).
855 if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
858 error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
860 /* On a clear day, you can see forever. */
863 if (errno != ESRCH) {
864 /* Shouldn't happen. */
865 perror_func_msg("ptrace(PTRACE_DETACH,%u)", tcp->pid);
868 /* ESRCH: process is either not stopped or doesn't exist. */
869 if (my_tkill(tcp->pid, 0) < 0) {
871 /* Shouldn't happen. */
872 perror_func_msg("tkill(%u,0)", tcp->pid);
873 /* else: process doesn't exist. */
876 /* Process is not stopped, need to stop it. */
879 * With SEIZE, tracee can be in group-stop already.
880 * In this state sending it another SIGSTOP does nothing.
881 * Need to use INTERRUPT.
882 * Testcase: trying to ^C a "strace -p <stopped_process>".
884 error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
888 perror_func_msg("ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
890 error = my_tkill(tcp->pid, SIGSTOP);
894 perror_func_msg("tkill(%u,SIGSTOP)", tcp->pid);
896 /* Either process doesn't exist, or some weird error. */
900 /* We end up here in three cases:
901 * 1. We sent PTRACE_INTERRUPT (use_seize case)
902 * 2. We sent SIGSTOP (!use_seize)
903 * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
907 if (waitpid(tcp->pid, &status, __WALL) < 0) {
911 * if (errno == ECHILD) break;
912 * ^^^ WRONG! We expect this PID to exist,
913 * and want to emit a message otherwise:
915 perror_func_msg("waitpid(%u)", tcp->pid);
918 if (!WIFSTOPPED(status)) {
920 * Tracee exited or was killed by signal.
921 * We shouldn't normally reach this place:
922 * we don't want to consume exit status.
923 * Consider "strace -p PID" being ^C-ed:
924 * we want merely to detach from PID.
926 * However, we _can_ end up here if tracee
931 sig = WSTOPSIG(status);
932 debug_msg("detach wait: event:%d sig:%d",
933 (unsigned) status >> 16, sig);
935 unsigned event = (unsigned)status >> 16;
936 if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
938 * sig == SIGTRAP: PTRACE_INTERRUPT stop.
939 * sig == other: process was already stopped
940 * with this stopping sig (see tests/detach-stopped).
941 * Looks like re-injecting this sig is not necessary
942 * in DETACH for the tracee to remain stopped.
947 * PTRACE_INTERRUPT is not guaranteed to produce
948 * the above event if other ptrace-stop is pending.
949 * See tests/detach-sleeping testcase:
950 * strace got SIGINT while tracee is sleeping.
951 * We sent PTRACE_INTERRUPT.
952 * We see syscall exit, not PTRACE_INTERRUPT stop.
953 * We won't get PTRACE_INTERRUPT stop
954 * if we would CONT now. Need to DETACH.
956 if (sig == syscall_trap_sig)
958 /* else: not sure in which case we can be here.
959 * Signal stop? Inject it while detaching.
961 ptrace_restart(PTRACE_DETACH, tcp, sig);
964 /* Note: this check has to be after use_seize check */
965 /* (else, in use_seize case SIGSTOP will be mistreated) */
966 if (sig == SIGSTOP) {
967 /* Detach, suppressing SIGSTOP */
968 ptrace_restart(PTRACE_DETACH, tcp, 0);
971 if (sig == syscall_trap_sig)
973 /* Can't detach just yet, may need to wait for SIGSTOP */
974 error = ptrace_restart(PTRACE_CONT, tcp, sig);
976 /* Should not happen.
977 * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
978 * ptrace_restart already emitted error message.
985 if (!qflag && (tcp->flags & TCB_ATTACHED))
986 error_msg("Process %u detached", tcp->pid);
992 process_opt_p_list(char *opt)
996 * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
997 * pidof uses space as delim, pgrep uses newline. :(
1000 char *delim = opt + strcspn(opt, "\n\t ,");
1004 pid = string_to_uint(opt);
1006 error_msg_and_die("Invalid process id: '%s'", opt);
1008 if (pid == strace_tracer_pid) {
1009 error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
1020 attach_tcb(struct tcb *const tcp)
1022 if (ptrace_attach_or_seize(tcp->pid) < 0) {
1023 perror_msg("attach: ptrace(%s, %d)",
1024 ptrace_attach_cmd, tcp->pid);
1029 tcp->flags |= TCB_ATTACHED | TCB_GRABBED | TCB_STARTUP |
1030 post_attach_sigstop;
1032 debug_msg("attach to pid %d (main) succeeded", tcp->pid);
1034 static const char task_path[] = "/proc/%d/task";
1035 char procdir[sizeof(task_path) + sizeof(int) * 3];
1037 unsigned int ntid = 0, nerr = 0;
1039 if (followfork && tcp->pid != strace_child &&
1040 xsprintf(procdir, task_path, tcp->pid) > 0 &&
1041 (dir = opendir(procdir)) != NULL) {
1044 while ((de = read_dir(dir)) != NULL) {
1045 if (de->d_fileno == 0)
1048 int tid = string_to_uint(de->d_name);
1049 if (tid <= 0 || tid == tcp->pid)
1053 if (ptrace_attach_or_seize(tid) < 0) {
1055 debug_perror_msg("attach: ptrace(%s, %d)",
1056 ptrace_attach_cmd, tid);
1059 debug_msg("attach to pid %d succeeded", tid);
1061 struct tcb *tid_tcp = alloctcb(tid);
1062 tid_tcp->flags |= TCB_ATTACHED | TCB_GRABBED |
1063 TCB_STARTUP | post_attach_sigstop;
1072 error_msg("Process %u attached"
1074 tcp->pid, ntid - nerr + 1);
1076 error_msg("Process %u attached",
1082 startup_attach(void)
1084 pid_t parent_pid = strace_tracer_pid;
1088 if (daemonized_tracer) {
1091 perror_func_msg_and_die("fork");
1093 if (pid) { /* parent */
1095 * Wait for grandchild to attach to straced process
1096 * (grandparent). Grandchild SIGKILLs us after it attached.
1097 * Grandparent's wait() is unblocked by our death,
1098 * it proceeds to exec the straced program.
1101 _exit(0); /* paranoia */
1104 /* We will be the tracer process. Remember our new pid: */
1105 strace_tracer_pid = getpid();
1108 for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1114 /* Is this a process we should attach to, but not yet attached? */
1115 if (tcp->flags & TCB_ATTACHED)
1116 continue; /* no, we already attached it */
1118 if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1120 perror_msg("attach: pid %d", tcp->pid);
1129 } /* for each tcbtab[] */
1131 if (daemonized_tracer) {
1133 * Make parent go away.
1134 * Also makes grandparent's wait() unblock.
1136 kill(parent_pid, SIGKILL);
1141 /* Stack-o-phobic exec helper, in the hope to work around
1142 * NOMMU + "daemonized tracer" difficulty.
1144 struct exec_params {
1150 struct sigaction child_sa;
1152 static struct exec_params params_for_tracee;
1154 static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1157 struct exec_params *params = ¶ms_for_tracee;
1159 if (params->fd_to_close >= 0)
1160 close(params->fd_to_close);
1161 if (!daemonized_tracer && !use_seize) {
1162 if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1163 perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1167 if (username != NULL) {
1169 * It is important to set groups before we
1170 * lose privileges on setuid.
1172 if (initgroups(username, run_gid) < 0) {
1173 perror_msg_and_die("initgroups");
1175 if (setregid(run_gid, params->run_egid) < 0) {
1176 perror_msg_and_die("setregid");
1178 if (setreuid(run_uid, params->run_euid) < 0) {
1179 perror_msg_and_die("setreuid");
1181 } else if (geteuid() != 0)
1182 if (setreuid(run_uid, run_uid) < 0) {
1183 perror_msg_and_die("setreuid");
1186 if (!daemonized_tracer) {
1188 * Induce a ptrace stop. Tracer (our parent)
1189 * will resume us with PTRACE_SYSCALL and display
1190 * the immediately following execve syscall.
1191 * Can't do this on NOMMU systems, we are after
1192 * vfork: parent is blocked, stopping would deadlock.
1195 kill(getpid(), SIGSTOP);
1198 /* we depend on SIGCHLD set to SIG_DFL by init code */
1199 /* if it happens to be SIG_IGN'ed, wait won't block */
1204 if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1205 sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1207 execv(params->pathname, params->argv);
1208 perror_msg_and_die("exec");
1212 * Open a dummy descriptor for use as a placeholder.
1213 * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1214 * A read attempt from such descriptor ends with EOF,
1215 * a write attempt is rejected with EBADF.
1218 open_dummy_desc(void)
1223 perror_func_msg_and_die("pipe");
1225 set_cloexec_flag(fds[0]);
1229 /* placeholder fds status for stdin and stdout */
1230 static bool fd_is_placeholder[2];
1233 * Ensure that all standard file descriptors are open by opening placeholder
1234 * file descriptors for those standard file descriptors that are not open.
1236 * The information which descriptors have been made open is saved
1237 * in fd_is_placeholder for later use.
1240 ensure_standard_fds_opened(void)
1244 while ((fd = open_dummy_desc()) <= 2) {
1247 fd_is_placeholder[fd] = true;
1255 * Redirect stdin and stdout unless they have been opened earlier
1256 * by ensure_standard_fds_opened as placeholders.
1259 redirect_standard_fds(void)
1264 * It might be a good idea to redirect stderr as well,
1265 * but we sometimes need to print error messages.
1267 for (i = 0; i <= 1; ++i) {
1268 if (!fd_is_placeholder[i]) {
1276 startup_child(char **argv)
1278 struct_stat statbuf;
1279 const char *filename;
1280 size_t filename_len;
1281 char pathname[PATH_MAX];
1286 filename_len = strlen(filename);
1288 if (filename_len > sizeof(pathname) - 1) {
1289 errno = ENAMETOOLONG;
1290 perror_msg_and_die("exec");
1292 if (strchr(filename, '/')) {
1293 strcpy(pathname, filename);
1295 #ifdef USE_DEBUGGING_EXEC
1297 * Debuggers customarily check the current directory
1298 * first regardless of the path but doing that gives
1299 * security geeks a panic attack.
1301 else if (stat_file(filename, &statbuf) == 0)
1302 strcpy(pathname, filename);
1303 #endif /* USE_DEBUGGING_EXEC */
1308 for (path = getenv("PATH"); path && *path; path += m) {
1309 const char *colon = strchr(path, ':');
1314 m = n = strlen(path);
1316 if (!getcwd(pathname, PATH_MAX))
1318 len = strlen(pathname);
1319 } else if (n > sizeof(pathname) - 1)
1322 strncpy(pathname, path, n);
1325 if (len && pathname[len - 1] != '/')
1326 pathname[len++] = '/';
1327 if (filename_len + len > sizeof(pathname) - 1)
1329 strcpy(pathname + len, filename);
1330 if (stat_file(pathname, &statbuf) == 0 &&
1331 /* Accept only regular files
1332 with some execute bits set.
1333 XXX not perfect, might still fail */
1334 S_ISREG(statbuf.st_mode) &&
1335 (statbuf.st_mode & 0111))
1338 if (!path || !*path)
1341 if (stat_file(pathname, &statbuf) < 0) {
1342 perror_msg_and_die("Can't stat '%s'", filename);
1345 params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1346 params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1347 params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1348 params_for_tracee.argv = argv;
1350 * On NOMMU, can be safely freed only after execve in tracee.
1351 * It's hard to know when that happens, so we just leak it.
1353 params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1355 #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1356 if (daemonized_tracer)
1357 prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1362 perror_func_msg_and_die("fork");
1364 if ((pid != 0 && daemonized_tracer)
1365 || (pid == 0 && !daemonized_tracer)
1367 /* We are to become the tracee. Two cases:
1369 * not -D: we are child
1374 /* We are the tracer */
1376 if (!daemonized_tracer) {
1379 /* child did PTRACE_TRACEME, nothing to do in parent */
1381 if (!NOMMU_SYSTEM) {
1382 /* Wait until child stopped itself */
1384 while (waitpid(pid, &status, WSTOPPED) < 0) {
1387 perror_msg_and_die("waitpid");
1389 if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1390 kill_save_errno(pid, SIGKILL);
1391 perror_msg_and_die("Unexpected wait status %#x",
1395 /* Else: NOMMU case, we have no way to sync.
1396 * Just attach to it as soon as possible.
1397 * This means that we may miss a few first syscalls...
1400 if (ptrace_attach_or_seize(pid)) {
1401 kill_save_errno(pid, SIGKILL);
1402 perror_msg_and_die("attach: ptrace(%s, %d)",
1403 ptrace_attach_cmd, pid);
1408 tcp = alloctcb(pid);
1409 tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1410 | TCB_SKIP_DETACH_ON_FIRST_EXEC
1411 | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1414 /* With -D, we are *child* here, the tracee is our parent. */
1415 strace_child = strace_tracer_pid;
1416 strace_tracer_pid = getpid();
1417 tcp = alloctcb(strace_child);
1418 tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1419 /* attaching will be done later, by startup_attach */
1420 /* note: we don't do newoutf(tcp) here either! */
1422 /* NOMMU BUG! -D mode is active, we (child) return,
1423 * and we will scribble over parent's stack!
1424 * When parent later unpauses, it segfaults.
1427 * (1) by declaring exec_or_die() NORETURN,
1428 * hopefully compiler will just jump to it
1429 * instead of call (won't push anything to stack),
1430 * (2) by trying very hard in exec_or_die()
1431 * to not use any stack,
1432 * (3) having a really big (PATH_MAX) stack object
1433 * in this function, which creates a "buffer" between
1434 * child's and parent's stack pointers.
1435 * This may save us if (1) and (2) failed
1436 * and compiler decided to use stack in exec_or_die() anyway
1437 * (happens on i386 because of stack parameter passing).
1439 * A cleaner solution is to use makecontext + setcontext
1440 * to create a genuine separate stack and execute on it.
1444 * A case where straced process is part of a pipe:
1445 * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1446 * If strace won't close its fd#0, closing it in tracee is not enough:
1447 * the pipe is still open, it has a reader. Thus, "head" will not get its
1448 * SIGPIPE at once, on the first write.
1450 * Preventing it by redirecting strace's stdin/out.
1451 * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1452 * will reuse them, unexpectedly making a newly opened object "stdin").
1454 redirect_standard_fds();
1458 test_ptrace_seize(void)
1462 /* Need fork for test. NOMMU has no forks */
1464 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1470 perror_func_msg_and_die("fork");
1477 /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1478 * attaching tracee continues to run unless a trap condition occurs.
1479 * PTRACE_SEIZE doesn't affect signal or group stop state.
1481 if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1482 post_attach_sigstop = 0; /* this sets use_seize to 1 */
1484 debug_msg("PTRACE_SEIZE doesn't work");
1490 int status, tracee_pid;
1493 tracee_pid = waitpid(pid, &status, 0);
1494 if (tracee_pid <= 0) {
1497 perror_func_msg_and_die("unexpected wait result %d",
1500 if (WIFSIGNALED(status))
1503 error_func_msg_and_die("unexpected wait status %#x", status);
1508 get_os_release(void)
1514 perror_msg_and_die("uname");
1515 /* u.release has this form: "3.2.9[-some-garbage]" */
1519 if (!(*p >= '0' && *p <= '9'))
1520 error_msg_and_die("Bad OS release string: '%s'", u.release);
1521 /* Note: this open-codes KERNEL_VERSION(): */
1522 rel = (rel << 8) | atoi(p);
1523 if (rel >= KERNEL_VERSION(1, 0, 0))
1525 while (*p >= '0' && *p <= '9')
1528 if (rel >= KERNEL_VERSION(0, 1, 0)) {
1529 /* "X.Y-something" means "X.Y.0" */
1533 error_msg_and_die("Bad OS release string: '%s'", u.release);
1541 set_sighandler(int signo, void (*sighandler)(int), struct sigaction *oldact)
1543 const struct sigaction sa = { .sa_handler = sighandler };
1544 sigaction(signo, &sa, oldact);
1548 * Initialization part of main() was eating much stack (~0.5k),
1549 * which was unused after init.
1550 * We can reuse it if we move init code into a separate function.
1552 * Don't want main() to inline us and defeat the reason
1553 * we have a separate function.
1555 static void ATTRIBUTE_NOINLINE
1556 init(int argc, char *argv[])
1561 if (!program_invocation_name || !*program_invocation_name) {
1562 static char name[] = "strace";
1563 program_invocation_name =
1564 (argc > 0 && argv[0] && *argv[0]) ? argv[0] : name;
1567 strace_tracer_pid = getpid();
1569 os_release = get_os_release();
1571 shared_log = stderr;
1572 set_sortby(DEFAULT_SORTBY);
1573 set_personality(DEFAULT_PERSONALITY);
1574 qualify("trace=all");
1575 qualify("abbrev=all");
1576 qualify("verbose=all");
1577 #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1578 # error Bug in DEFAULT_QUAL_FLAGS
1580 qualify("signal=all");
1581 while ((c = getopt(argc, argv, "+"
1582 #ifdef USE_LIBUNWIND
1585 "a:b:cCdDe:E:fFhiI:o:O:p:P:qrs:S:tTu:vVwxyz")) != EOF) {
1588 acolumn = string_to_uint(optarg);
1590 error_opt_arg(c, optarg);
1593 if (strcmp(optarg, "execve") != 0)
1594 error_msg_and_die("Syscall '%s' for -b isn't supported",
1596 detach_on_execve = 1;
1599 if (cflag == CFLAG_BOTH) {
1600 error_msg_and_help("-c and -C are mutually exclusive");
1602 cflag = CFLAG_ONLY_STATS;
1605 if (cflag == CFLAG_ONLY_STATS) {
1606 error_msg_and_help("-c and -C are mutually exclusive");
1614 daemonized_tracer = 1;
1620 if (putenv(optarg) < 0)
1621 perror_msg_and_die("putenv");
1636 opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1638 error_opt_arg(c, optarg);
1640 #ifdef USE_LIBUNWIND
1642 stack_trace_enabled = true;
1649 i = string_to_uint(optarg);
1651 error_opt_arg(c, optarg);
1655 process_opt_p_list(optarg);
1658 pathtrace_select(optarg);
1667 i = string_to_uint(optarg);
1668 if (i < 0 || (unsigned int) i > -1U / 4)
1669 error_opt_arg(c, optarg);
1685 qualify("abbrev=none");
1692 count_wallclock = 1;
1701 not_failing_only = 1;
1704 error_msg_and_help(NULL);
1712 if (argc < 0 || (!nprocs && !argc)) {
1713 error_msg_and_help("must have PROG [ARGS] or -p PID");
1716 if (!argc && daemonized_tracer) {
1717 error_msg_and_help("PROG [ARGS] must be specified with -D");
1722 error_msg("deprecated option -F ignored");
1724 error_msg("option -F is deprecated, "
1725 "please use -f instead");
1730 if (followfork >= 2 && cflag) {
1731 error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1734 if (count_wallclock && !cflag) {
1735 error_msg_and_help("-w must be given with (-c or -C)");
1738 if (cflag == CFLAG_ONLY_STATS) {
1740 error_msg("-%c has no effect with -c", 'i');
1741 #ifdef USE_LIBUNWIND
1742 if (stack_trace_enabled)
1743 error_msg("-%c has no effect with -c", 'k');
1746 error_msg("-%c has no effect with -c", 'r');
1748 error_msg("-%c has no effect with -c", 't');
1750 error_msg("-%c has no effect with -c", 'T');
1752 error_msg("-%c has no effect with -c", 'y');
1757 error_msg("-tt has no effect with -r");
1761 acolumn_spaces = xmalloc(acolumn + 1);
1762 memset(acolumn_spaces, ' ', acolumn);
1763 acolumn_spaces[acolumn] = '\0';
1765 set_sighandler(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1767 #ifdef USE_LIBUNWIND
1768 if (stack_trace_enabled) {
1772 for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1773 unwind_tcb_init(tcbtab[tcbi]);
1778 /* See if they want to run as another user. */
1779 if (username != NULL) {
1780 struct passwd *pent;
1782 if (getuid() != 0 || geteuid() != 0) {
1783 error_msg_and_die("You must be root to use the -u option");
1785 pent = getpwnam(username);
1787 error_msg_and_die("Cannot find user '%s'", username);
1789 run_uid = pent->pw_uid;
1790 run_gid = pent->pw_gid;
1797 ptrace_setoptions |= PTRACE_O_TRACECLONE |
1798 PTRACE_O_TRACEFORK |
1799 PTRACE_O_TRACEVFORK;
1800 debug_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1801 test_ptrace_seize();
1804 * Is something weird with our stdin and/or stdout -
1805 * for example, may they be not open? In this case,
1806 * ensure that none of the future opens uses them.
1808 * This was seen in the wild when /proc/sys/kernel/core_pattern
1809 * was set to "|/bin/strace -o/tmp/LOG PROG":
1810 * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1811 * therefore LOG gets opened to fd#1, and fd#1 is closed by
1812 * "don't hold up stdin/out open" code soon after.
1814 ensure_standard_fds_opened();
1816 /* Check if they want to redirect the output. */
1818 /* See if they want to pipe the output. */
1819 if (outfname[0] == '|' || outfname[0] == '!') {
1821 * We can't do the <outfname>.PID funny business
1822 * when using popen, so prohibit it.
1824 if (followfork >= 2)
1825 error_msg_and_help("piping the output and -ff "
1826 "are mutually exclusive");
1827 shared_log = strace_popen(outfname + 1);
1828 } else if (followfork < 2) {
1829 shared_log = strace_fopen(outfname);
1830 } else if (strlen(outfname) >= PATH_MAX - sizeof(int) * 3) {
1831 errno = ENAMETOOLONG;
1832 perror_msg_and_die("%s", outfname);
1835 /* -ff without -o FILE is the same as single -f */
1836 if (followfork >= 2)
1840 if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
1841 setvbuf(shared_log, NULL, _IOLBF, 0);
1845 * argv[0] -pPID -oFILE Default interactive setting
1846 * yes * 0 INTR_WHILE_WAIT
1847 * no 1 0 INTR_WHILE_WAIT
1848 * yes * 1 INTR_NEVER
1849 * no 1 1 INTR_WHILE_WAIT
1852 if (outfname && argc) {
1854 opt_intr = INTR_NEVER;
1859 opt_intr = INTR_WHILE_WAIT;
1862 * startup_child() must be called before the signal handlers get
1863 * installed below as they are inherited into the spawned process.
1864 * Also we do not need to be protected by them as during interruption
1865 * in the startup_child() mode we kill the spawned process anyway.
1868 startup_child(argv);
1871 set_sighandler(SIGTTOU, SIG_IGN, NULL);
1872 set_sighandler(SIGTTIN, SIG_IGN, NULL);
1873 if (opt_intr != INTR_ANYWHERE) {
1874 if (opt_intr == INTR_BLOCK_TSTP_TOO)
1875 set_sighandler(SIGTSTP, SIG_IGN, NULL);
1877 * In interactive mode (if no -o OUTFILE, or -p PID is used),
1878 * fatal signals are handled asynchronously and acted
1879 * when waiting for process state changes.
1880 * In non-interactive mode these signals are ignored.
1882 set_sighandler(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1883 set_sighandler(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1884 set_sighandler(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1885 set_sighandler(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1886 set_sighandler(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1889 sigemptyset(&timer_set);
1890 sigaddset(&timer_set, SIGALRM);
1891 sigprocmask(SIG_BLOCK, &timer_set, NULL);
1892 set_sighandler(SIGALRM, timer_sighandler, NULL);
1894 if (nprocs != 0 || daemonized_tracer)
1897 /* Do we want pids printed in our -o OUTFILE?
1898 * -ff: no (every pid has its own file); or
1899 * -f: yes (there can be more pids in the future); or
1900 * -p PID1,PID2: yes (there are already more than one pid)
1902 print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
1906 pid2tcb(const int pid)
1911 #define PID2TCB_CACHE_SIZE 1024U
1912 #define PID2TCB_CACHE_MASK (PID2TCB_CACHE_SIZE - 1)
1914 static struct tcb *pid2tcb_cache[PID2TCB_CACHE_SIZE];
1915 struct tcb **const ptcp = &pid2tcb_cache[pid & PID2TCB_CACHE_MASK];
1916 struct tcb *tcp = *ptcp;
1918 if (tcp && tcp->pid == pid)
1921 for (unsigned int i = 0; i < tcbtabsize; ++i) {
1923 if (tcp->pid == pid)
1937 /* 'interrupted' is a volatile object, fetch it only once */
1938 fatal_sig = interrupted;
1940 fatal_sig = SIGTERM;
1942 for (i = 0; i < tcbtabsize; i++) {
1946 debug_func_msg("looking at pid %u", tcp->pid);
1947 if (tcp->pid == strace_child) {
1948 kill(tcp->pid, SIGCONT);
1949 kill(tcp->pid, fatal_sig);
1954 call_summary(shared_log);
1964 print_debug_info(const int pid, int status)
1966 const unsigned int event = (unsigned int) status >> 16;
1967 char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1968 char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1971 if (WIFSIGNALED(status))
1973 xsprintf(buf, "WIFSIGNALED,%ssig=%s",
1974 WCOREDUMP(status) ? "core," : "",
1975 signame(WTERMSIG(status)));
1977 xsprintf(buf, "WIFSIGNALED,sig=%s",
1978 signame(WTERMSIG(status)));
1980 if (WIFEXITED(status))
1981 xsprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1982 if (WIFSTOPPED(status))
1983 xsprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1986 static const char *const event_names[] = {
1987 [PTRACE_EVENT_CLONE] = "CLONE",
1988 [PTRACE_EVENT_FORK] = "FORK",
1989 [PTRACE_EVENT_VFORK] = "VFORK",
1990 [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1991 [PTRACE_EVENT_EXEC] = "EXEC",
1992 [PTRACE_EVENT_EXIT] = "EXIT",
1993 /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
1995 const char *e = "??";
1996 if (event < ARRAY_SIZE(event_names))
1997 e = event_names[event];
1998 else if (event == PTRACE_EVENT_STOP)
2000 xsprintf(evbuf, ",EVENT_%s (%u)", e, event);
2002 error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
2006 maybe_allocate_tcb(const int pid, int status)
2008 if (!WIFSTOPPED(status)) {
2009 if (detach_on_execve && pid == strace_child) {
2010 /* example: strace -bexecve sh -c 'exec true' */
2015 * This can happen if we inherited an unknown child.
2016 * Example: (sleep 1 & exec strace true)
2018 error_msg("Exit of unknown pid %u ignored", pid);
2022 /* We assume it's a fork/vfork/clone child */
2023 struct tcb *tcp = alloctcb(pid);
2024 tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2027 error_msg("Process %d attached", pid);
2031 * This can happen if a clone call misused CLONE_PTRACE itself.
2033 * There used to be a dance around possible re-injection of
2034 * WSTOPSIG(status), but it was later removed as the only
2035 * observable stop here is the initial ptrace-stop.
2037 ptrace(PTRACE_DETACH, pid, NULL, 0L);
2038 error_msg("Detached unknown pid %d", pid);
2044 maybe_switch_tcbs(struct tcb *tcp, const int pid)
2047 struct tcb *execve_thread;
2050 if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2052 /* Avoid truncation in pid2tcb() param passing */
2053 if (old_pid <= 0 || old_pid == pid)
2055 if ((unsigned long) old_pid > UINT_MAX)
2057 execve_thread = pid2tcb(old_pid);
2058 /* It should be !NULL, but I feel paranoid */
2062 if (execve_thread->curcol != 0) {
2064 * One case we are here is -ff:
2065 * try "strace -oLOG -ff test/threaded_execve"
2067 fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2068 /*execve_thread->curcol = 0; - no need, see code below */
2070 /* Swap output FILEs (needed for -ff) */
2071 fp = execve_thread->outf;
2072 execve_thread->outf = tcp->outf;
2074 /* And their column positions */
2075 execve_thread->curcol = tcp->curcol;
2077 /* Drop leader, but close execve'd thread outfile (if -ff) */
2079 /* Switch to the thread, reusing leader's outfile and pid */
2080 tcp = execve_thread;
2082 if (cflag != CFLAG_ONLY_STATS) {
2084 tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2086 tcp->flags |= TCB_REPRINT;
2093 print_signalled(struct tcb *tcp, const int pid, int status)
2095 if (pid == strace_child) {
2096 exit_code = 0x100 | WTERMSIG(status);
2100 if (cflag != CFLAG_ONLY_STATS
2101 && is_number_in_set(WTERMSIG(status), signal_set)) {
2104 tprintf("+++ killed by %s %s+++\n",
2105 signame(WTERMSIG(status)),
2106 WCOREDUMP(status) ? "(core dumped) " : "");
2108 tprintf("+++ killed by %s +++\n",
2109 signame(WTERMSIG(status)));
2116 print_exited(struct tcb *tcp, const int pid, int status)
2118 if (pid == strace_child) {
2119 exit_code = WEXITSTATUS(status);
2123 if (cflag != CFLAG_ONLY_STATS &&
2126 tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2132 print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2134 if (cflag != CFLAG_ONLY_STATS
2136 && is_number_in_set(sig, signal_set)) {
2139 tprintf("--- %s ", signame(sig));
2143 tprintf("--- stopped by %s ---\n", signame(sig));
2149 startup_tcb(struct tcb *tcp)
2151 debug_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2153 tcp->flags &= ~TCB_STARTUP;
2156 debug_msg("setting opts 0x%x on pid %d",
2157 ptrace_setoptions, tcp->pid);
2158 if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2159 if (errno != ESRCH) {
2160 /* Should never happen, really */
2161 perror_msg_and_die("PTRACE_SETOPTIONS");
2166 if ((tcp->flags & TCB_GRABBED) && (get_scno(tcp) == 1))
2167 tcp->s_prev_ent = tcp->s_ent;
2171 print_event_exit(struct tcb *tcp)
2173 if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2174 || cflag == CFLAG_ONLY_STATS) {
2178 if (followfork < 2 && printing_tcp && printing_tcp != tcp
2179 && printing_tcp->curcol != 0) {
2180 set_current_tcp(printing_tcp);
2181 tprints(" <unfinished ...>\n");
2182 flush_tcp_output(printing_tcp);
2183 printing_tcp->curcol = 0;
2184 set_current_tcp(tcp);
2187 if ((followfork < 2 && printing_tcp != tcp)
2188 || (tcp->flags & TCB_REPRINT)) {
2189 tcp->flags &= ~TCB_REPRINT;
2191 tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2194 if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2196 * The decoder has probably decided to print something
2197 * on exiting syscall which is not going to happen.
2199 tprints(" <unfinished ...>");
2209 static enum trace_event
2210 next_event(int *pstatus, siginfo_t *si)
2221 * Used to exit simply when nprocs hits zero, but in this testcase:
2222 * int main(void) { _exit(!!fork()); }
2223 * under strace -f, parent sometimes (rarely) manages
2224 * to exit before we see the first stop of the child,
2225 * and we are losing track of it:
2226 * 19923 clone(...) = 19924
2227 * 19923 exit_group(1) = ?
2228 * 19923 +++ exited with 1 +++
2229 * Exiting only when wait() returns ECHILD works better.
2231 if (popen_pid != 0) {
2232 /* However, if -o|logger is in use, we can't do that.
2233 * Can work around that by double-forking the logger,
2234 * but that loses the ability to wait for its completion
2235 * on exit. Oh well...
2241 const bool unblock_delay_timer = is_delay_timer_armed();
2244 * The window of opportunity to handle expirations
2245 * of the delay timer opens here.
2247 * Unblock the signal handler for the delay timer
2248 * iff the delay timer is already created.
2250 if (unblock_delay_timer)
2251 sigprocmask(SIG_UNBLOCK, &timer_set, NULL);
2254 * If the delay timer has expired, then its expiration
2255 * has been handled already by the signal handler.
2257 * If the delay timer expires during wait4(),
2258 * then the system call will be interrupted and
2259 * the expiration will be handled by the signal handler.
2261 pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2262 const int wait_errno = errno;
2265 * The window of opportunity to handle expirations
2266 * of the delay timer closes here.
2268 * Block the signal handler for the delay timer
2269 * iff it was unblocked earlier.
2271 if (unblock_delay_timer) {
2272 sigprocmask(SIG_BLOCK, &timer_set, NULL);
2279 if (wait_errno == EINTR)
2281 if (nprocs == 0 && wait_errno == ECHILD)
2284 * If nprocs > 0, ECHILD is not expected,
2285 * treat it as any other error here:
2288 perror_msg_and_die("wait4(__WALL)");
2293 if (pid == popen_pid) {
2294 if (!WIFSTOPPED(status))
2300 print_debug_info(pid, status);
2302 /* Look up 'pid' in our table. */
2306 tcp = maybe_allocate_tcb(pid, status);
2313 /* Set current output file */
2314 set_current_tcp(tcp);
2317 struct timespec stime = {
2318 .tv_sec = ru.ru_stime.tv_sec,
2319 .tv_nsec = ru.ru_stime.tv_usec * 1000
2321 ts_sub(&tcp->dtime, &stime, &tcp->stime);
2325 if (WIFSIGNALED(status))
2326 return TE_SIGNALLED;
2328 if (WIFEXITED(status))
2332 * As WCONTINUED flag has not been specified to wait4,
2333 * it cannot be WIFCONTINUED(status), so the only case
2334 * that remains is WIFSTOPPED(status).
2337 /* Is this the very first time we see this tracee stopped? */
2338 if (tcp->flags & TCB_STARTUP)
2341 const unsigned int sig = WSTOPSIG(status);
2342 const unsigned int event = (unsigned int) status >> 16;
2347 * Is this post-attach SIGSTOP?
2348 * Interestingly, the process may stop
2349 * with STOPSIG equal to some other signal
2350 * than SIGSTOP if we happened to attach
2351 * just before the process takes a signal.
2353 if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2354 debug_func_msg("ignored SIGSTOP on pid %d", tcp->pid);
2355 tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2357 } else if (sig == syscall_trap_sig) {
2358 return TE_SYSCALL_STOP;
2360 *si = (siginfo_t) {};
2362 * True if tracee is stopped by signal
2363 * (as opposed to "tracee received signal").
2364 * TODO: shouldn't we check for errno == EINVAL too?
2365 * We can get ESRCH instead, you know...
2367 bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2368 return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2371 case PTRACE_EVENT_STOP:
2373 * PTRACE_INTERRUPT-stop or group-stop.
2374 * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2381 return TE_GROUP_STOP;
2384 case PTRACE_EVENT_EXEC:
2385 return TE_STOP_BEFORE_EXECVE;
2386 case PTRACE_EVENT_EXIT:
2387 return TE_STOP_BEFORE_EXIT;
2394 trace_syscall(struct tcb *tcp, unsigned int *sig)
2396 if (entering(tcp)) {
2397 int res = syscall_entering_decode(tcp);
2402 res = syscall_entering_trace(tcp, sig);
2404 syscall_entering_finish(tcp, res);
2407 struct timespec ts = {};
2408 int res = syscall_exiting_decode(tcp, &ts);
2410 res = syscall_exiting_trace(tcp, &ts, res);
2412 syscall_exiting_finish(tcp);
2417 /* Returns true iff the main trace loop has to continue. */
2419 dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2421 unsigned int restart_op = PTRACE_SYSCALL;
2422 unsigned int restart_sig = 0;
2434 case TE_SYSCALL_STOP:
2435 if (trace_syscall(current_tcp, &restart_sig) < 0) {
2437 * ptrace() failed in trace_syscall().
2438 * Likely a result of process disappearing mid-flight.
2439 * Observed case: exit_group() or SIGKILL terminating
2440 * all processes in thread group.
2441 * We assume that ptrace error was caused by process death.
2442 * We used to detach(current_tcp) here, but since we no
2443 * longer implement "detach before death" policy/hack,
2444 * we can let this process to report its death to us
2445 * normally, via WIFEXITED or WIFSIGNALED wait status.
2451 case TE_SIGNAL_DELIVERY_STOP:
2452 restart_sig = WSTOPSIG(*pstatus);
2453 print_stopped(current_tcp, si, restart_sig);
2457 print_signalled(current_tcp, current_tcp->pid, *pstatus);
2458 droptcb(current_tcp);
2462 restart_sig = WSTOPSIG(*pstatus);
2463 print_stopped(current_tcp, NULL, restart_sig);
2466 * This ends ptrace-stop, but does *not* end group-stop.
2467 * This makes stopping signals work properly on straced
2468 * process (that is, process really stops. It used to
2471 restart_op = PTRACE_LISTEN;
2477 print_exited(current_tcp, current_tcp->pid, *pstatus);
2478 droptcb(current_tcp);
2481 case TE_STOP_BEFORE_EXECVE:
2483 * Check that we are inside syscall now (next event after
2484 * PTRACE_EVENT_EXEC should be for syscall exiting). If it is
2485 * not the case, we might have a situation when we attach to a
2486 * process and the first thing we see is a PTRACE_EVENT_EXEC
2487 * and all the following syscall state tracking is screwed up
2490 if (entering(current_tcp)) {
2493 error_msg("Stray PTRACE_EVENT_EXEC from pid %d"
2494 ", trying to recover...",
2497 current_tcp->flags |= TCB_RECOVERING;
2498 ret = trace_syscall(current_tcp, &restart_sig);
2499 current_tcp->flags &= ~TCB_RECOVERING;
2502 /* The reason is described in TE_SYSCALL_STOP */
2508 * Under Linux, execve changes pid to thread leader's pid,
2509 * and we see this changed pid on EVENT_EXEC and later,
2510 * execve sysexit. Leader "disappears" without exit
2511 * notification. Let user know that, drop leader's tcb,
2512 * and fix up pid in execve thread's tcb.
2513 * Effectively, execve thread's tcb replaces leader's tcb.
2515 * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2516 * on exit syscall) in multithreaded programs exactly
2517 * in order to handle this case.
2519 * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2520 * On 2.6 and earlier, it can return garbage.
2522 if (os_release >= KERNEL_VERSION(3, 0, 0))
2523 set_current_tcp(maybe_switch_tcbs(current_tcp,
2526 if (detach_on_execve) {
2527 if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2528 current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2530 detach(current_tcp); /* do "-b execve" thingy */
2536 case TE_STOP_BEFORE_EXIT:
2537 print_event_exit(current_tcp);
2541 /* We handled quick cases, we are permitted to interrupt now. */
2545 /* If the process is being delayed, do not ptrace_restart just yet */
2546 if (syscall_delayed(current_tcp))
2549 if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2550 /* Note: ptrace_restart emitted error message */
2558 restart_delayed_tcb(struct tcb *const tcp)
2560 debug_func_msg("pid %d", tcp->pid);
2562 tcp->flags &= ~TCB_DELAYED;
2564 struct tcb *const prev_tcp = current_tcp;
2566 bool ret = dispatch_event(TE_RESTART, NULL, NULL);
2567 current_tcp = prev_tcp;
2573 restart_delayed_tcbs(void)
2575 struct tcb *tcp_next = NULL;
2576 struct timespec ts_now;
2578 clock_gettime(CLOCK_MONOTONIC, &ts_now);
2580 for (size_t i = 0; i < tcbtabsize; i++) {
2581 struct tcb *tcp = tcbtab[i];
2583 if (tcp->pid && syscall_delayed(tcp)) {
2584 if (ts_cmp(&ts_now, &tcp->delay_expiration_time) > 0) {
2585 if (!restart_delayed_tcb(tcp))
2588 /* Check whether this tcb is the next. */
2590 ts_cmp(&tcp_next->delay_expiration_time,
2591 &tcp->delay_expiration_time) > 0) {
2599 arm_delay_timer(tcp_next);
2605 * As this signal handler does a lot of work that is not suitable
2606 * for signal handlers, extra care must be taken to ensure that
2607 * it is enabled only in those places where it's safe.
2610 timer_sighandler(int sig)
2612 delay_timer_expired();
2617 int saved_errno = errno;
2619 if (!restart_delayed_tcbs())
2622 errno = saved_errno;
2625 #ifdef ENABLE_COVERAGE_GCOV
2626 extern void __gcov_flush(void);
2629 static void ATTRIBUTE_NORETURN
2634 if (shared_log != stderr)
2637 while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2640 if (exit_code > 0xff) {
2641 /* Avoid potential core file clobbering. */
2642 struct_rlimit rlim = {0, 0};
2643 set_rlimit(RLIMIT_CORE, &rlim);
2645 /* Child was killed by a signal, mimic that. */
2647 signal(exit_code, SIG_DFL);
2648 #ifdef ENABLE_COVERAGE_GCOV
2653 /* Unblock the signal. */
2656 sigaddset(&mask, exit_code);
2657 #ifdef ENABLE_COVERAGE_GCOV
2660 sigprocmask(SIG_UNBLOCK, &mask, NULL);
2662 /* Paranoia - what if this signal is not fatal?
2663 Exit with 128 + signo then. */
2670 main(int argc, char *argv[])
2672 setlocale(LC_ALL, "");
2675 exit_code = !nprocs;
2679 while (dispatch_event(next_event(&status, &si), &status, &si))