Branch data Line data Source code
1 : : /*
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-2017 The strace developers.
7 : : * All rights reserved.
8 : : *
9 : : * Redistribution and use in source and binary forms, with or without
10 : : * modification, are permitted provided that the following conditions
11 : : * are met:
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.
19 : : *
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.
30 : : */
31 : :
32 : : #include "defs.h"
33 : : #include <stdarg.h>
34 : : #include <sys/param.h>
35 : : #include <fcntl.h>
36 : : #include <signal.h>
37 : : #include <sys/resource.h>
38 : : #include <sys/wait.h>
39 : : #include <sys/stat.h>
40 : : #include <pwd.h>
41 : : #include <grp.h>
42 : : #include <dirent.h>
43 : : #include <sys/utsname.h>
44 : : #ifdef HAVE_PRCTL
45 : : # include <sys/prctl.h>
46 : : #endif
47 : : #include <asm/unistd.h>
48 : : #ifdef USE_LUAJIT
49 : : # include <lua.h>
50 : : #endif
51 : :
52 : : #include "scno.h"
53 : : #include "ptrace.h"
54 : : #include "printsiginfo.h"
55 : :
56 : : /* In some libc, these aren't declared. Do it ourself: */
57 : : extern char **environ;
58 : : extern int optind;
59 : : extern char *optarg;
60 : :
61 : : #ifdef USE_LIBUNWIND
62 : : /* if this is true do the stack trace for every system call */
63 : : bool stack_trace_enabled;
64 : : #endif
65 : :
66 : : #define my_tkill(tid, sig) syscall(__NR_tkill, (tid), (sig))
67 : :
68 : : /* Glue for systems without a MMU that cannot provide fork() */
69 : : #if !defined(HAVE_FORK)
70 : : # undef NOMMU_SYSTEM
71 : : # define NOMMU_SYSTEM 1
72 : : #endif
73 : : #if NOMMU_SYSTEM
74 : : # define fork() vfork()
75 : : #endif
76 : :
77 : : const unsigned int syscall_trap_sig = SIGTRAP | 0x80;
78 : :
79 : : cflag_t cflag = CFLAG_NONE;
80 : : unsigned int followfork;
81 : : unsigned int ptrace_setoptions = PTRACE_O_TRACESYSGOOD | PTRACE_O_TRACEEXEC
82 : : | PTRACE_O_TRACEEXIT;
83 : : unsigned int xflag;
84 : : bool debug_flag;
85 : : bool Tflag;
86 : : bool iflag;
87 : : bool count_wallclock;
88 : : unsigned int qflag;
89 : : static unsigned int tflag;
90 : : static bool rflag;
91 : : static bool print_pid_pfx;
92 : :
93 : : /* -I n */
94 : : enum {
95 : : INTR_NOT_SET = 0,
96 : : INTR_ANYWHERE = 1, /* don't block/ignore any signals */
97 : : INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
98 : : INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
99 : : INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
100 : : NUM_INTR_OPTS
101 : : };
102 : : static int opt_intr;
103 : : /* We play with signal mask only if this mode is active: */
104 : : #define interactive (opt_intr == INTR_WHILE_WAIT)
105 : :
106 : : /*
107 : : * daemonized_tracer supports -D option.
108 : : * With this option, strace forks twice.
109 : : * Unlike normal case, with -D *grandparent* process exec's,
110 : : * becoming a traced process. Child exits (this prevents traced process
111 : : * from having children it doesn't expect to have), and grandchild
112 : : * attaches to grandparent similarly to strace -p PID.
113 : : * This allows for more transparent interaction in cases
114 : : * when process and its parent are communicating via signals,
115 : : * wait() etc. Without -D, strace process gets lodged in between,
116 : : * disrupting parent<->child link.
117 : : */
118 : : static bool daemonized_tracer;
119 : :
120 : : #if USE_SEIZE
121 : : static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
122 : : # define use_seize (post_attach_sigstop == 0)
123 : : #else
124 : : # define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
125 : : # define use_seize 0
126 : : #endif
127 : :
128 : : /* Sometimes we want to print only succeeding syscalls. */
129 : : bool not_failing_only;
130 : :
131 : : /* Show path associated with fd arguments */
132 : : unsigned int show_fd_path;
133 : :
134 : : static bool detach_on_execve;
135 : :
136 : : static int exit_code;
137 : : static int strace_child;
138 : : static int strace_tracer_pid;
139 : :
140 : : static const char *username;
141 : : static uid_t run_uid;
142 : : static gid_t run_gid;
143 : :
144 : : unsigned int max_strlen = DEFAULT_STRLEN;
145 : : static int acolumn = DEFAULT_ACOLUMN;
146 : : static char *acolumn_spaces;
147 : :
148 : : static const char *outfname;
149 : : /* If -ff, points to stderr. Else, it's our common output log */
150 : : static FILE *shared_log;
151 : :
152 : : struct tcb *printing_tcp;
153 : : static struct tcb *current_tcp;
154 : :
155 : : static struct tcb **tcbtab;
156 : : static unsigned int nprocs, tcbtabsize;
157 : :
158 : : #ifndef HAVE_PROGRAM_INVOCATION_NAME
159 : : char *program_invocation_name;
160 : : #endif
161 : :
162 : : unsigned os_release; /* generated from uname()'s u.release */
163 : :
164 : : static void detach(struct tcb *tcp);
165 : : static void cleanup(void);
166 : : static void interrupt(int sig);
167 : : static sigset_t start_set, blocked_set;
168 : :
169 : : #ifdef HAVE_SIG_ATOMIC_T
170 : : static volatile sig_atomic_t interrupted;
171 : : #else
172 : : static volatile int interrupted;
173 : : #endif
174 : :
175 : : #ifdef USE_LUAJIT
176 : : static lua_State *script_L = NULL;
177 : : static void init_luajit(const char *scriptfile);
178 : : #endif
179 : :
180 : : #ifndef HAVE_STRERROR
181 : :
182 : : #if !HAVE_DECL_SYS_ERRLIST
183 : : extern int sys_nerr;
184 : : extern char *sys_errlist[];
185 : : #endif
186 : :
187 : : const char *
188 : : strerror(int err_no)
189 : : {
190 : : static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
191 : :
192 : : if (err_no < 1 || err_no >= sys_nerr) {
193 : : sprintf(buf, "Unknown error %d", err_no);
194 : : return buf;
195 : : }
196 : : return sys_errlist[err_no];
197 : : }
198 : :
199 : : #endif /* HAVE_STERRROR */
200 : :
201 : : static void
202 : : print_version(void)
203 : : {
204 : 892 : printf("%s -- version %s\n"
205 : : "Copyright (c) 1991-%s The strace developers <%s>.\n"
206 : : "This is free software; see the source for copying conditions. There is NO\n"
207 : : "warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n",
208 : : PACKAGE_NAME, PACKAGE_VERSION, COPYRIGHT_YEAR, PACKAGE_URL);
209 : : }
210 : :
211 : : static void
212 : 8 : usage(void)
213 : : {
214 : 8 : printf("\
215 : : usage: strace [-CdffhiqrtttTvVwxxy] [-I n] [-e expr]...\n\
216 : : [-a column] [-o file] [-s strsize] [-P path]...\n\
217 : : -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
218 : : or: strace -c[dfw] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
219 : : -p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
220 : : \n\
221 : : Output format:\n\
222 : : -a column alignment COLUMN for printing syscall results (default %d)\n\
223 : : -i print instruction pointer at time of syscall\n\
224 : : "
225 : : #ifdef USE_LIBUNWIND
226 : : "\
227 : : -k obtain stack trace between each syscall (experimental)\n\
228 : : "
229 : : #endif
230 : : #ifdef USE_LUAJIT
231 : : "\
232 : : -l file run a Lua script from FILE\n\
233 : : "
234 : : #endif
235 : : "\
236 : : -o file send trace output to FILE instead of stderr\n\
237 : : -q suppress messages about attaching, detaching, etc.\n\
238 : : -r print relative timestamp\n\
239 : : -s strsize limit length of print strings to STRSIZE chars (default %d)\n\
240 : : -t print absolute timestamp\n\
241 : : -tt print absolute timestamp with usecs\n\
242 : : -T print time spent in each syscall\n\
243 : : -x print non-ascii strings in hex\n\
244 : : -xx print all strings in hex\n\
245 : : -y print paths associated with file descriptor arguments\n\
246 : : -yy print protocol specific information associated with socket file descriptors\n\
247 : : \n\
248 : : Statistics:\n\
249 : : -c count time, calls, and errors for each syscall and report summary\n\
250 : : -C like -c but also print regular output\n\
251 : : -O overhead set overhead for tracing syscalls to OVERHEAD usecs\n\
252 : : -S sortby sort syscall counts by: time, calls, name, nothing (default %s)\n\
253 : : -w summarise syscall latency (default is system time)\n\
254 : : \n\
255 : : Filtering:\n\
256 : : -e expr a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
257 : : options: trace, abbrev, verbose, raw, signal, read, write, fault\n\
258 : : -P path trace accesses to path\n\
259 : : \n\
260 : : Tracing:\n\
261 : : -b execve detach on execve syscall\n\
262 : : -D run tracer process as a detached grandchild, not as parent\n\
263 : : -f follow forks\n\
264 : : -ff follow forks with output into separate files\n\
265 : : -I interruptible\n\
266 : : 1: no signals are blocked\n\
267 : : 2: fatal signals are blocked while decoding syscall (default)\n\
268 : : 3: fatal signals are always blocked (default if '-o FILE PROG')\n\
269 : : 4: fatal signals and SIGTSTP (^Z) are always blocked\n\
270 : : (useful to make 'strace -o FILE PROG' not stop on ^Z)\n\
271 : : \n\
272 : : Startup:\n\
273 : : -E var remove var from the environment for command\n\
274 : : -E var=val put var=val in the environment for command\n\
275 : : -p pid trace process with process id PID, may be repeated\n\
276 : : -u username run command as username handling setuid and/or setgid\n\
277 : : \n\
278 : : Miscellaneous:\n\
279 : : -d enable debug output to stderr\n\
280 : : -v verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
281 : : -h print help message\n\
282 : : -V print version\n\
283 : : "
284 : : /* ancient, no one should use it
285 : : -F -- attempt to follow vforks (deprecated, use -f)\n\
286 : : */
287 : : /* this is broken, so don't document it
288 : : -z -- print only succeeding syscalls\n\
289 : : */
290 : : , DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
291 : 8 : exit(0);
292 : : }
293 : :
294 : : void ATTRIBUTE_NORETURN
295 : 419 : die(void)
296 : : {
297 [ + + ]: 419 : if (strace_tracer_pid == getpid()) {
298 : 417 : cflag = 0;
299 : 417 : cleanup();
300 : : }
301 : 419 : exit(1);
302 : : }
303 : :
304 : : static void
305 : 10 : error_opt_arg(int opt, const char *arg)
306 : : {
307 : 10 : error_msg_and_help("invalid -%c argument: '%s'", opt, arg);
308 : : }
309 : :
310 : : static const char *ptrace_attach_cmd;
311 : :
312 : : static int
313 : 9500 : ptrace_attach_or_seize(int pid)
314 : : {
315 : : #if USE_SEIZE
316 : : int r;
317 [ - + ]: 9500 : if (!use_seize)
318 : 0 : return ptrace_attach_cmd = "PTRACE_ATTACH",
319 : 0 : ptrace(PTRACE_ATTACH, pid, 0L, 0L);
320 : 9500 : r = ptrace(PTRACE_SEIZE, pid, 0L, (unsigned long) ptrace_setoptions);
321 [ + + ]: 9500 : if (r)
322 : 2 : return ptrace_attach_cmd = "PTRACE_SEIZE", r;
323 : 9498 : r = ptrace(PTRACE_INTERRUPT, pid, 0L, 0L);
324 : 9498 : return ptrace_attach_cmd = "PTRACE_INTERRUPT", r;
325 : : #else
326 : : return ptrace_attach_cmd = "PTRACE_ATTACH",
327 : : ptrace(PTRACE_ATTACH, pid, 0L, 0L);
328 : : #endif
329 : : }
330 : :
331 : : /*
332 : : * Used when we want to unblock stopped traced process.
333 : : * Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
334 : : * Returns 0 on success or if error was ESRCH
335 : : * (presumably process was killed while we talk to it).
336 : : * Otherwise prints error message and returns -1.
337 : : */
338 : : static int
339 : 74223197 : ptrace_restart(const unsigned int op, struct tcb *const tcp, unsigned int sig)
340 : : {
341 : : int err;
342 : : const char *msg;
343 : :
344 : 74223197 : errno = 0;
345 : 74223197 : ptrace(op, tcp->pid, 0L, (unsigned long) sig);
346 : 74223197 : err = errno;
347 [ + + ]: 74223197 : if (!err)
348 : : return 0;
349 : :
350 [ - - + - ]: 5 : switch (op) {
351 : : case PTRACE_CONT:
352 : : msg = "CONT";
353 : : break;
354 : : case PTRACE_DETACH:
355 : 0 : msg = "DETACH";
356 : : break;
357 : : case PTRACE_LISTEN:
358 : 0 : msg = "LISTEN";
359 : : break;
360 : : default:
361 : 5 : msg = "SYSCALL";
362 : : }
363 : :
364 : : /*
365 : : * Why curcol != 0? Otherwise sometimes we get this:
366 : : *
367 : : * 10252 kill(10253, SIGKILL) = 0
368 : : * <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
369 : : *
370 : : * 10252 died after we retrieved syscall exit data,
371 : : * but before we tried to restart it. Log looks ugly.
372 : : */
373 [ + - ][ - + ]: 5 : if (current_tcp && current_tcp->curcol != 0) {
374 : 0 : tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
375 : 0 : line_ended();
376 : : }
377 [ - + ]: 5 : if (err == ESRCH)
378 : : return 0;
379 : 0 : errno = err;
380 : 0 : perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%u)", msg, tcp->pid, sig);
381 : : return -1;
382 : : }
383 : :
384 : : static void
385 : 41030 : set_cloexec_flag(int fd)
386 : : {
387 : : int flags, newflags;
388 : :
389 : 41030 : flags = fcntl(fd, F_GETFD);
390 [ - + ]: 41030 : if (flags < 0) {
391 : : /* Can happen only if fd is bad.
392 : : * Should never happen: if it does, we have a bug
393 : : * in the caller. Therefore we just abort
394 : : * instead of propagating the error.
395 : : */
396 : 0 : perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
397 : : }
398 : :
399 : 41030 : newflags = flags | FD_CLOEXEC;
400 [ + - ]: 41030 : if (flags == newflags)
401 : 41030 : return;
402 : :
403 : 41030 : fcntl(fd, F_SETFD, newflags); /* never fails */
404 : : }
405 : :
406 : : static void
407 : 0 : kill_save_errno(pid_t pid, int sig)
408 : : {
409 : 0 : int saved_errno = errno;
410 : :
411 : 0 : (void) kill(pid, sig);
412 : 0 : errno = saved_errno;
413 : 0 : }
414 : :
415 : : /*
416 : : * When strace is setuid executable, we have to swap uids
417 : : * before and after filesystem and process management operations.
418 : : */
419 : : static void
420 : 25152 : swap_uid(void)
421 : : {
422 : 25152 : int euid = geteuid(), uid = getuid();
423 : :
424 [ - + ][ # # ]: 25152 : if (euid != uid && setreuid(euid, uid) < 0) {
425 : 0 : perror_msg_and_die("setreuid");
426 : : }
427 : 25152 : }
428 : :
429 : : #ifdef _LARGEFILE64_SOURCE
430 : : # ifdef HAVE_FOPEN64
431 : : # define fopen_for_output fopen64
432 : : # else
433 : : # define fopen_for_output fopen
434 : : # endif
435 : : # define struct_stat struct stat64
436 : : # define stat_file stat64
437 : : # define struct_dirent struct dirent64
438 : : # define read_dir readdir64
439 : : # define struct_rlimit struct rlimit64
440 : : # define set_rlimit setrlimit64
441 : : #else
442 : : # define fopen_for_output fopen
443 : : # define struct_stat struct stat
444 : : # define stat_file stat
445 : : # define struct_dirent struct dirent
446 : : # define read_dir readdir
447 : : # define struct_rlimit struct rlimit
448 : : # define set_rlimit setrlimit
449 : : #endif
450 : :
451 : : static FILE *
452 : 12570 : strace_fopen(const char *path)
453 : : {
454 : : FILE *fp;
455 : :
456 : 12570 : swap_uid();
457 : 12570 : fp = fopen_for_output(path, "w");
458 [ - + ]: 12570 : if (!fp)
459 : 0 : perror_msg_and_die("Can't fopen '%s'", path);
460 : 12570 : swap_uid();
461 : 12570 : set_cloexec_flag(fileno(fp));
462 : 12570 : return fp;
463 : : }
464 : :
465 : : static int popen_pid;
466 : :
467 : : #ifndef _PATH_BSHELL
468 : : # define _PATH_BSHELL "/bin/sh"
469 : : #endif
470 : :
471 : : /*
472 : : * We cannot use standard popen(3) here because we have to distinguish
473 : : * popen child process from other processes we trace, and standard popen(3)
474 : : * does not export its child's pid.
475 : : */
476 : : static FILE *
477 : 12 : strace_popen(const char *command)
478 : : {
479 : : FILE *fp;
480 : : int pid;
481 : : int fds[2];
482 : :
483 : 6 : swap_uid();
484 [ - + ]: 6 : if (pipe(fds) < 0)
485 : 0 : perror_msg_and_die("pipe");
486 : :
487 : 6 : set_cloexec_flag(fds[1]); /* never fails */
488 : :
489 : 12 : pid = vfork();
490 [ - + ]: 12 : if (pid < 0)
491 : 0 : perror_msg_and_die("vfork");
492 : :
493 [ + + ]: 12 : if (pid == 0) {
494 : : /* child */
495 : 6 : close(fds[1]);
496 [ + - ]: 6 : if (fds[0] != 0) {
497 [ - + ]: 6 : if (dup2(fds[0], 0))
498 : 0 : perror_msg_and_die("dup2");
499 : 6 : close(fds[0]);
500 : : }
501 : 6 : execl(_PATH_BSHELL, "sh", "-c", command, NULL);
502 : 6 : perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
503 : : }
504 : :
505 : : /* parent */
506 : 6 : popen_pid = pid;
507 : 6 : close(fds[0]);
508 : 6 : swap_uid();
509 : 6 : fp = fdopen(fds[1], "w");
510 [ - + ]: 6 : if (!fp)
511 : 0 : perror_msg_and_die("fdopen");
512 : 6 : return fp;
513 : : }
514 : :
515 : : ATTRIBUTE_FORMAT((printf, 1, 0))
516 : : static void
517 : 2809151 : tvprintf(const char *const fmt, va_list args)
518 : : {
519 [ + - ]: 2809151 : if (current_tcp) {
520 : 2809151 : int n = vfprintf(current_tcp->outf, fmt, args);
521 [ - + ]: 2809151 : if (n < 0) {
522 [ # # ]: 0 : if (current_tcp->outf != stderr)
523 : 0 : perror_msg("%s", outfname);
524 : : } else
525 : 2809151 : current_tcp->curcol += n;
526 : : }
527 : 2809151 : }
528 : :
529 : : void
530 : 2809025 : tprintf(const char *fmt, ...)
531 : : {
532 : : va_list args;
533 : 2809025 : va_start(args, fmt);
534 : 2809025 : tvprintf(fmt, args);
535 : 2809025 : va_end(args);
536 : 2809025 : }
537 : :
538 : : #ifndef HAVE_FPUTS_UNLOCKED
539 : : # define fputs_unlocked fputs
540 : : #endif
541 : :
542 : : void
543 : 4172796 : tprints(const char *str)
544 : : {
545 [ + - ]: 4172796 : if (current_tcp) {
546 : 4172796 : int n = fputs_unlocked(str, current_tcp->outf);
547 [ + - ]: 4172796 : if (n >= 0) {
548 : 4172796 : current_tcp->curcol += strlen(str);
549 : 4172796 : return;
550 : : }
551 [ # # ]: 0 : if (current_tcp->outf != stderr)
552 : 0 : perror_msg("%s", outfname);
553 : : }
554 : : }
555 : :
556 : : void
557 : 5608 : tprints_comment(const char *const str)
558 : : {
559 [ + + ][ + - ]: 5608 : if (str && *str)
560 : 5133 : tprintf(" /* %s */", str);
561 : 5608 : }
562 : :
563 : : void
564 : 126 : tprintf_comment(const char *fmt, ...)
565 : : {
566 [ + - ][ + - ]: 126 : if (!fmt || !*fmt)
567 : 0 : return;
568 : :
569 : : va_list args;
570 : 126 : va_start(args, fmt);
571 : 126 : tprints(" /* ");
572 : 126 : tvprintf(fmt, args);
573 : 126 : tprints(" */");
574 : 126 : va_end(args);
575 : : }
576 : :
577 : : void
578 : 451558 : line_ended(void)
579 : : {
580 [ + - ]: 451558 : if (current_tcp) {
581 : 451558 : current_tcp->curcol = 0;
582 : 451558 : fflush(current_tcp->outf);
583 : : }
584 [ + - ]: 451558 : if (printing_tcp) {
585 : 451558 : printing_tcp->curcol = 0;
586 : 451558 : printing_tcp = NULL;
587 : : }
588 : 451558 : }
589 : :
590 : : void
591 : 451572 : printleader(struct tcb *tcp)
592 : : {
593 : : /* If -ff, "previous tcb we printed" is always the same as current,
594 : : * because we have per-tcb output files.
595 : : */
596 [ + + ]: 451572 : if (followfork >= 2)
597 : 317975 : printing_tcp = tcp;
598 : :
599 [ + + ]: 451572 : if (printing_tcp) {
600 : 317987 : current_tcp = printing_tcp;
601 [ + + ][ - + ]: 317987 : if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
[ # # ]
602 : : /*
603 : : * case 1: we have a shared log (i.e. not -ff), and last line
604 : : * wasn't finished (same or different tcb, doesn't matter).
605 : : * case 2: split log, we are the same tcb, but our last line
606 : : * didn't finish ("SIGKILL nuked us after syscall entry" etc).
607 : : */
608 : 6 : tprints(" <unfinished ...>\n");
609 : 6 : printing_tcp->curcol = 0;
610 : : }
611 : : }
612 : :
613 : 451572 : printing_tcp = tcp;
614 : 451572 : current_tcp = tcp;
615 : 451572 : current_tcp->curcol = 0;
616 : :
617 [ + + ]: 451572 : if (print_pid_pfx)
618 : 95 : tprintf("%-5d ", tcp->pid);
619 [ + + ][ + + ]: 451477 : else if (nprocs > 1 && !outfname)
620 : 8 : tprintf("[pid %5u] ", tcp->pid);
621 : :
622 [ + + ]: 451572 : if (tflag) {
623 : : char str[sizeof("HH:MM:SS")];
624 : : struct timeval tv, dtv;
625 : : static struct timeval otv;
626 : :
627 : 52 : gettimeofday(&tv, NULL);
628 [ + + ]: 52 : if (rflag) {
629 [ + + ]: 4 : if (otv.tv_sec == 0)
630 : 2 : otv = tv;
631 : 4 : tv_sub(&dtv, &tv, &otv);
632 : 4 : tprintf("%6ld.%06ld ",
633 : : (long) dtv.tv_sec, (long) dtv.tv_usec);
634 : 4 : otv = tv;
635 [ + + ]: 48 : } else if (tflag > 2) {
636 : 4 : tprintf("%ld.%06ld ",
637 : : (long) tv.tv_sec, (long) tv.tv_usec);
638 : : } else {
639 : 44 : time_t local = tv.tv_sec;
640 : 44 : strftime(str, sizeof(str), "%T", localtime(&local));
641 [ + + ]: 44 : if (tflag > 1)
642 : 40 : tprintf("%s.%06ld ", str, (long) tv.tv_usec);
643 : : else
644 : 52 : tprintf("%s ", str);
645 : : }
646 : : }
647 [ + + ]: 451572 : if (iflag)
648 : 93 : print_pc(tcp);
649 : 451572 : }
650 : :
651 : : void
652 : 442494 : tabto(void)
653 : : {
654 [ + + ]: 442494 : if (current_tcp->curcol < acolumn)
655 : 43294 : tprints(acolumn_spaces + current_tcp->curcol);
656 : 442494 : }
657 : :
658 : : /* Should be only called directly *after successful attach* to a tracee.
659 : : * Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
660 : : * may create bogus empty FILE.<nonexistant_pid>, and then die.
661 : : */
662 : : static void
663 : 25908 : newoutf(struct tcb *tcp)
664 : : {
665 : 12954 : tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
666 [ + + ]: 12954 : if (followfork >= 2) {
667 : : char name[520 + sizeof(int) * 3];
668 : 4490 : sprintf(name, "%.512s.%u", outfname, tcp->pid);
669 : 4490 : tcp->outf = strace_fopen(name);
670 : : }
671 : 12954 : }
672 : :
673 : : static void
674 : 12054 : expand_tcbtab(void)
675 : : {
676 : : /* Allocate some (more) TCBs (and expand the table).
677 : : We don't want to relocate the TCBs because our
678 : : callers have pointers and it would be a pain.
679 : : So tcbtab is a table of pointers. Since we never
680 : : free the TCBs, we allocate a single chunk of many. */
681 : : unsigned int new_tcbtabsize, alloc_tcbtabsize;
682 : : struct tcb *newtcbs;
683 : :
684 [ + + ]: 12054 : if (tcbtabsize) {
685 : 2560 : alloc_tcbtabsize = tcbtabsize;
686 : 2560 : new_tcbtabsize = tcbtabsize * 2;
687 : : } else {
688 : : new_tcbtabsize = alloc_tcbtabsize = 1;
689 : : }
690 : :
691 : 12054 : newtcbs = xcalloc(alloc_tcbtabsize, sizeof(newtcbs[0]));
692 : 12054 : tcbtab = xreallocarray(tcbtab, new_tcbtabsize, sizeof(tcbtab[0]));
693 [ + + ]: 26452 : while (tcbtabsize < new_tcbtabsize)
694 : 14398 : tcbtab[tcbtabsize++] = newtcbs++;
695 : 12054 : }
696 : :
697 : : static struct tcb *
698 : 12960 : alloctcb(int pid)
699 : : {
700 : : unsigned int i;
701 : : struct tcb *tcp;
702 : :
703 [ + + ]: 12960 : if (nprocs == tcbtabsize)
704 : 12054 : expand_tcbtab();
705 : :
706 [ + - ]: 21139 : for (i = 0; i < tcbtabsize; i++) {
707 : 21139 : tcp = tcbtab[i];
708 [ + + ]: 21139 : if (!tcp->pid) {
709 : 12960 : memset(tcp, 0, sizeof(*tcp));
710 : 12960 : tcp->pid = pid;
711 : : #if defined(USE_LUAJIT) || SUPPORTED_PERSONALITIES > 1
712 : 12960 : tcp->currpers = current_personality;
713 : : #endif
714 : :
715 : : #ifdef USE_LIBUNWIND
716 : : if (stack_trace_enabled)
717 : : unwind_tcb_init(tcp);
718 : : #endif
719 : :
720 : 12960 : nprocs++;
721 [ + + ]: 12960 : if (debug_flag)
722 : 2 : error_msg("new tcb for pid %d, active tcbs:%d",
723 : : tcp->pid, nprocs);
724 : 12960 : return tcp;
725 : : }
726 : : }
727 : 0 : error_msg_and_die("bug in alloctcb");
728 : : }
729 : :
730 : : void *
731 : 2456 : get_tcb_priv_data(const struct tcb *tcp)
732 : : {
733 : 2456 : return tcp->_priv_data;
734 : : }
735 : :
736 : : int
737 : 2480 : set_tcb_priv_data(struct tcb *tcp, void *const priv_data,
738 : : void (*const free_priv_data)(void *))
739 : : {
740 [ + - ]: 2480 : if (tcp->_priv_data)
741 : : return -1;
742 : :
743 : 2480 : tcp->_free_priv_data = free_priv_data;
744 : 2480 : tcp->_priv_data = priv_data;
745 : :
746 : 2480 : return 0;
747 : : }
748 : :
749 : : void
750 : 37059697 : free_tcb_priv_data(struct tcb *tcp)
751 : : {
752 [ + + ][ + + ]: 37072657 : if (tcp->_priv_data) {
753 [ + - ][ + + ]: 2274 : if (tcp->_free_priv_data) {
754 : 1466 : tcp->_free_priv_data(tcp->_priv_data);
755 : 1466 : tcp->_free_priv_data = NULL;
756 : : }
757 : 2274 : tcp->_priv_data = NULL;
758 : : }
759 : 37059697 : }
760 : :
761 : : static void
762 : 12960 : droptcb(struct tcb *tcp)
763 : : {
764 [ + - ]: 12960 : if (tcp->pid == 0)
765 : 12960 : return;
766 : :
767 : : #ifdef USE_LUAJIT
768 : 12960 : free(tcp->ad_hoc_inject_opts);
769 : : #endif
770 : :
771 : : int p;
772 [ + + ]: 51840 : for (p = 0; p < SUPPORTED_PERSONALITIES; ++p)
773 : 38880 : free(tcp->inject_vec[p]);
774 : :
775 : : free_tcb_priv_data(tcp);
776 : :
777 : : #ifdef USE_LIBUNWIND
778 : : if (stack_trace_enabled) {
779 : : unwind_tcb_fin(tcp);
780 : : }
781 : : #endif
782 : :
783 : 12960 : nprocs--;
784 [ + + ]: 12960 : if (debug_flag)
785 : 2 : error_msg("dropped tcb for pid %d, %d remain",
786 : : tcp->pid, nprocs);
787 : :
788 [ + + ]: 12960 : if (tcp->outf) {
789 [ + + ]: 12954 : if (followfork >= 2) {
790 [ - + ]: 4490 : if (tcp->curcol != 0)
791 : 0 : fprintf(tcp->outf, " <detached ...>\n");
792 : 4490 : fclose(tcp->outf);
793 : : } else {
794 [ + + ][ + - ]: 8464 : if (printing_tcp == tcp && tcp->curcol != 0)
795 : 2 : fprintf(tcp->outf, " <detached ...>\n");
796 : 8464 : fflush(tcp->outf);
797 : : }
798 : : }
799 : :
800 [ + + ]: 12960 : if (current_tcp == tcp)
801 : 12954 : current_tcp = NULL;
802 [ + + ]: 12960 : if (printing_tcp == tcp)
803 : 2 : printing_tcp = NULL;
804 : :
805 : 12960 : memset(tcp, 0, sizeof(*tcp));
806 : : }
807 : :
808 : : /* Detach traced process.
809 : : * Never call DETACH twice on the same process as both unattached and
810 : : * attached-unstopped processes give the same ESRCH. For unattached process we
811 : : * would SIGSTOP it and wait for its SIGSTOP notification forever.
812 : : */
813 : : static void
814 : 15 : detach(struct tcb *tcp)
815 : : {
816 : : int error;
817 : : int status;
818 : :
819 : : /*
820 : : * Linux wrongly insists the child be stopped
821 : : * before detaching. Arghh. We go through hoops
822 : : * to make a clean break of things.
823 : : */
824 : :
825 [ + + ]: 15 : if (!(tcp->flags & TCB_ATTACHED))
826 : : goto drop;
827 : :
828 : : /* We attached but possibly didn't see the expected SIGSTOP.
829 : : * We must catch exactly one as otherwise the detached process
830 : : * would be left stopped (process state T).
831 : : */
832 [ + - ]: 11 : if (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)
833 : : goto wait_loop;
834 : :
835 : 11 : error = ptrace(PTRACE_DETACH, tcp->pid, 0, 0);
836 [ + + ]: 11 : if (!error) {
837 : : /* On a clear day, you can see forever. */
838 : : goto drop;
839 : : }
840 [ - + ]: 6 : if (errno != ESRCH) {
841 : : /* Shouldn't happen. */
842 : 0 : perror_msg("detach: ptrace(PTRACE_DETACH,%u)", tcp->pid);
843 : 0 : goto drop;
844 : : }
845 : : /* ESRCH: process is either not stopped or doesn't exist. */
846 [ - + ]: 6 : if (my_tkill(tcp->pid, 0) < 0) {
847 [ # # ]: 0 : if (errno != ESRCH)
848 : : /* Shouldn't happen. */
849 : 0 : perror_msg("detach: tkill(%u,0)", tcp->pid);
850 : : /* else: process doesn't exist. */
851 : : goto drop;
852 : : }
853 : : /* Process is not stopped, need to stop it. */
854 [ + - ]: 6 : if (use_seize) {
855 : : /*
856 : : * With SEIZE, tracee can be in group-stop already.
857 : : * In this state sending it another SIGSTOP does nothing.
858 : : * Need to use INTERRUPT.
859 : : * Testcase: trying to ^C a "strace -p <stopped_process>".
860 : : */
861 : 6 : error = ptrace(PTRACE_INTERRUPT, tcp->pid, 0, 0);
862 [ - + ]: 6 : if (!error)
863 : : goto wait_loop;
864 [ # # ]: 0 : if (errno != ESRCH)
865 : 0 : perror_msg("detach: ptrace(PTRACE_INTERRUPT,%u)", tcp->pid);
866 : : } else {
867 : 0 : error = my_tkill(tcp->pid, SIGSTOP);
868 [ # # ]: 6 : if (!error)
869 : : goto wait_loop;
870 [ # # ]: 0 : if (errno != ESRCH)
871 : 0 : perror_msg("detach: tkill(%u,SIGSTOP)", tcp->pid);
872 : : }
873 : : /* Either process doesn't exist, or some weird error. */
874 : : goto drop;
875 : :
876 : : wait_loop:
877 : : /* We end up here in three cases:
878 : : * 1. We sent PTRACE_INTERRUPT (use_seize case)
879 : : * 2. We sent SIGSTOP (!use_seize)
880 : : * 3. Attach SIGSTOP was already pending (TCB_IGNORE_ONE_SIGSTOP set)
881 : : */
882 : : for (;;) {
883 : : unsigned int sig;
884 [ - + ]: 6 : if (waitpid(tcp->pid, &status, __WALL) < 0) {
885 [ # # ]: 0 : if (errno == EINTR)
886 : 0 : continue;
887 : : /*
888 : : * if (errno == ECHILD) break;
889 : : * ^^^ WRONG! We expect this PID to exist,
890 : : * and want to emit a message otherwise:
891 : : */
892 : 0 : perror_msg("detach: waitpid(%u)", tcp->pid);
893 : 0 : break;
894 : : }
895 [ + - ]: 6 : if (!WIFSTOPPED(status)) {
896 : : /*
897 : : * Tracee exited or was killed by signal.
898 : : * We shouldn't normally reach this place:
899 : : * we don't want to consume exit status.
900 : : * Consider "strace -p PID" being ^C-ed:
901 : : * we want merely to detach from PID.
902 : : *
903 : : * However, we _can_ end up here if tracee
904 : : * was SIGKILLed.
905 : : */
906 : : break;
907 : : }
908 : 6 : sig = WSTOPSIG(status);
909 [ - + ]: 6 : if (debug_flag)
910 : 0 : error_msg("detach wait: event:%d sig:%d",
911 : 0 : (unsigned)status >> 16, sig);
912 [ + - ]: 6 : if (use_seize) {
913 : 6 : unsigned event = (unsigned)status >> 16;
914 [ + + ]: 6 : if (event == PTRACE_EVENT_STOP /*&& sig == SIGTRAP*/) {
915 : : /*
916 : : * sig == SIGTRAP: PTRACE_INTERRUPT stop.
917 : : * sig == other: process was already stopped
918 : : * with this stopping sig (see tests/detach-stopped).
919 : : * Looks like re-injecting this sig is not necessary
920 : : * in DETACH for the tracee to remain stopped.
921 : : */
922 : 4 : sig = 0;
923 : : }
924 : : /*
925 : : * PTRACE_INTERRUPT is not guaranteed to produce
926 : : * the above event if other ptrace-stop is pending.
927 : : * See tests/detach-sleeping testcase:
928 : : * strace got SIGINT while tracee is sleeping.
929 : : * We sent PTRACE_INTERRUPT.
930 : : * We see syscall exit, not PTRACE_INTERRUPT stop.
931 : : * We won't get PTRACE_INTERRUPT stop
932 : : * if we would CONT now. Need to DETACH.
933 : : */
934 [ + + ]: 6 : if (sig == syscall_trap_sig)
935 : 2 : sig = 0;
936 : : /* else: not sure in which case we can be here.
937 : : * Signal stop? Inject it while detaching.
938 : : */
939 : 6 : ptrace_restart(PTRACE_DETACH, tcp, sig);
940 : 6 : break;
941 : : }
942 : : /* Note: this check has to be after use_seize check */
943 : : /* (else, in use_seize case SIGSTOP will be mistreated) */
944 [ # # ]: 0 : if (sig == SIGSTOP) {
945 : : /* Detach, suppressing SIGSTOP */
946 : 0 : ptrace_restart(PTRACE_DETACH, tcp, 0);
947 : 0 : break;
948 : : }
949 [ # # ]: 0 : if (sig == syscall_trap_sig)
950 : 0 : sig = 0;
951 : : /* Can't detach just yet, may need to wait for SIGSTOP */
952 : 0 : error = ptrace_restart(PTRACE_CONT, tcp, sig);
953 [ # # ]: 0 : if (error < 0) {
954 : : /* Should not happen.
955 : : * Note: ptrace_restart returns 0 on ESRCH, so it's not it.
956 : : * ptrace_restart already emitted error message.
957 : : */
958 : : break;
959 : : }
960 : : }
961 : :
962 : : drop:
963 [ + + ][ + + ]: 15 : if (!qflag && (tcp->flags & TCB_ATTACHED))
964 : 8 : error_msg("Process %u detached", tcp->pid);
965 : :
966 : 15 : droptcb(tcp);
967 : 15 : }
968 : :
969 : : static void
970 : 24 : process_opt_p_list(char *opt)
971 : : {
972 [ + - ]: 26 : while (*opt) {
973 : : /*
974 : : * We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
975 : : * pidof uses space as delim, pgrep uses newline. :(
976 : : */
977 : : int pid;
978 : 26 : char *delim = opt + strcspn(opt, "\n\t ,");
979 : 26 : char c = *delim;
980 : :
981 : 26 : *delim = '\0';
982 : 26 : pid = string_to_uint(opt);
983 [ + + ]: 26 : if (pid <= 0) {
984 : 8 : error_msg_and_die("Invalid process id: '%s'", opt);
985 : : }
986 [ - + ]: 18 : if (pid == strace_tracer_pid) {
987 : 0 : error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
988 : : }
989 : 18 : *delim = c;
990 : 18 : alloctcb(pid);
991 [ + + ]: 18 : if (c == '\0')
992 : : break;
993 : 2 : opt = delim + 1;
994 : : }
995 : 16 : }
996 : :
997 : : static void
998 : 14 : attach_tcb(struct tcb *const tcp)
999 : : {
1000 [ + + ]: 14 : if (ptrace_attach_or_seize(tcp->pid) < 0) {
1001 : 2 : perror_msg("attach: ptrace(%s, %d)",
1002 : : ptrace_attach_cmd, tcp->pid);
1003 : 2 : droptcb(tcp);
1004 : 2 : return;
1005 : : }
1006 : :
1007 : 12 : tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
1008 : 12 : newoutf(tcp);
1009 [ - + ]: 12 : if (debug_flag)
1010 : 0 : error_msg("attach to pid %d (main) succeeded", tcp->pid);
1011 : :
1012 : : char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
1013 : : DIR *dir;
1014 : 12 : unsigned int ntid = 0, nerr = 0;
1015 : :
1016 [ + + ][ + - ]: 12 : if (followfork && tcp->pid != strace_child &&
[ + - ]
1017 [ + - ]: 4 : sprintf(procdir, "/proc/%d/task", tcp->pid) > 0 &&
1018 : : (dir = opendir(procdir)) != NULL) {
1019 : : struct_dirent *de;
1020 : :
1021 [ + + ]: 22 : while ((de = read_dir(dir)) != NULL) {
1022 [ - + ]: 18 : if (de->d_fileno == 0)
1023 : 0 : continue;
1024 : :
1025 : 18 : int tid = string_to_uint(de->d_name);
1026 [ + + ][ + + ]: 18 : if (tid <= 0 || tid == tcp->pid)
1027 : 12 : continue;
1028 : :
1029 : 6 : ++ntid;
1030 [ - + ]: 6 : if (ptrace_attach_or_seize(tid) < 0) {
1031 : 0 : ++nerr;
1032 [ # # ]: 0 : if (debug_flag)
1033 : 0 : perror_msg("attach: ptrace(%s, %d)",
1034 : : ptrace_attach_cmd, tid);
1035 : 0 : continue;
1036 : : }
1037 [ - + ]: 6 : if (debug_flag)
1038 : 0 : error_msg("attach to pid %d succeeded", tid);
1039 : :
1040 : 6 : struct tcb *tid_tcp = alloctcb(tid);
1041 : 6 : tid_tcp->flags |= TCB_ATTACHED | TCB_STARTUP |
1042 : : post_attach_sigstop;
1043 : 18 : newoutf(tid_tcp);
1044 : : }
1045 : :
1046 : 4 : closedir(dir);
1047 : : }
1048 : :
1049 [ + + ]: 12 : if (!qflag) {
1050 [ - + ]: 8 : if (ntid > nerr)
1051 : 0 : error_msg("Process %u attached"
1052 : : " with %u threads",
1053 : 0 : tcp->pid, ntid - nerr + 1);
1054 : : else
1055 : 12 : error_msg("Process %u attached",
1056 : : tcp->pid);
1057 : : }
1058 : : }
1059 : :
1060 : : static void
1061 : 9490 : startup_attach(void)
1062 : : {
1063 : 9490 : pid_t parent_pid = strace_tracer_pid;
1064 : : unsigned int tcbi;
1065 : : struct tcb *tcp;
1066 : :
1067 : : /*
1068 : : * Block user interruptions as we would leave the traced
1069 : : * process stopped (process state T) if we would terminate in
1070 : : * between PTRACE_ATTACH and wait4() on SIGSTOP.
1071 : : * We rely on cleanup() from this point on.
1072 : : */
1073 [ + + ]: 9490 : if (interactive)
1074 : 38 : sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1075 : :
1076 [ - + ]: 9490 : if (daemonized_tracer) {
1077 : 0 : pid_t pid = fork();
1078 [ # # ]: 0 : if (pid < 0) {
1079 : 0 : perror_msg_and_die("fork");
1080 : : }
1081 [ # # ]: 0 : if (pid) { /* parent */
1082 : : /*
1083 : : * Wait for grandchild to attach to straced process
1084 : : * (grandparent). Grandchild SIGKILLs us after it attached.
1085 : : * Grandparent's wait() is unblocked by our death,
1086 : : * it proceeds to exec the straced program.
1087 : : */
1088 : 0 : pause();
1089 : 0 : _exit(0); /* paranoia */
1090 : : }
1091 : : /* grandchild */
1092 : : /* We will be the tracer process. Remember our new pid: */
1093 : 9490 : strace_tracer_pid = getpid();
1094 : : }
1095 : :
1096 [ + + ]: 18996 : for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
1097 : 9506 : tcp = tcbtab[tcbi];
1098 : :
1099 [ + + ]: 9506 : if (!tcp->pid)
1100 : 6 : continue;
1101 : :
1102 : : /* Is this a process we should attach to, but not yet attached? */
1103 [ + + ]: 9500 : if (tcp->flags & TCB_ATTACHED)
1104 : 9486 : continue; /* no, we already attached it */
1105 : :
1106 [ + - ][ - + ]: 14 : if (tcp->pid == parent_pid || tcp->pid == strace_tracer_pid) {
1107 : 0 : errno = EPERM;
1108 : 0 : perror_msg("attach: pid %d", tcp->pid);
1109 : 0 : droptcb(tcp);
1110 : 0 : continue;
1111 : : }
1112 : :
1113 : 14 : attach_tcb(tcp);
1114 : :
1115 [ + + ]: 14 : if (interactive) {
1116 : 10 : sigprocmask(SIG_SETMASK, &start_set, NULL);
1117 [ + - ]: 10 : if (interrupted)
1118 : : goto ret;
1119 : 10 : sigprocmask(SIG_SETMASK, &blocked_set, NULL);
1120 : : }
1121 : : } /* for each tcbtab[] */
1122 : :
1123 [ - + ]: 9490 : if (daemonized_tracer) {
1124 : : /*
1125 : : * Make parent go away.
1126 : : * Also makes grandparent's wait() unblock.
1127 : : */
1128 : 0 : kill(parent_pid, SIGKILL);
1129 : 0 : strace_child = 0;
1130 : : }
1131 : :
1132 : : ret:
1133 [ + + ]: 9490 : if (interactive)
1134 : 38 : sigprocmask(SIG_SETMASK, &start_set, NULL);
1135 : 9490 : }
1136 : :
1137 : : /* Stack-o-phobic exec helper, in the hope to work around
1138 : : * NOMMU + "daemonized tracer" difficulty.
1139 : : */
1140 : : struct exec_params {
1141 : : int fd_to_close;
1142 : : uid_t run_euid;
1143 : : gid_t run_egid;
1144 : : char **argv;
1145 : : char *pathname;
1146 : : struct sigaction child_sa;
1147 : : };
1148 : : static struct exec_params params_for_tracee;
1149 : :
1150 : : static void ATTRIBUTE_NOINLINE ATTRIBUTE_NORETURN
1151 : 9478 : exec_or_die(void)
1152 : : {
1153 : 9478 : struct exec_params *params = ¶ms_for_tracee;
1154 : :
1155 [ + + ]: 9478 : if (params->fd_to_close >= 0)
1156 : 8084 : close(params->fd_to_close);
1157 [ + - ][ - + ]: 9478 : if (!daemonized_tracer && !use_seize) {
1158 [ # # ]: 0 : if (ptrace(PTRACE_TRACEME, 0L, 0L, 0L) < 0) {
1159 : 0 : perror_msg_and_die("ptrace(PTRACE_TRACEME, ...)");
1160 : : }
1161 : : }
1162 : :
1163 [ - + ]: 9478 : if (username != NULL) {
1164 : : /*
1165 : : * It is important to set groups before we
1166 : : * lose privileges on setuid.
1167 : : */
1168 [ # # ]: 0 : if (initgroups(username, run_gid) < 0) {
1169 : 0 : perror_msg_and_die("initgroups");
1170 : : }
1171 [ # # ]: 0 : if (setregid(run_gid, params->run_egid) < 0) {
1172 : 0 : perror_msg_and_die("setregid");
1173 : : }
1174 [ # # ]: 0 : if (setreuid(run_uid, params->run_euid) < 0) {
1175 : 0 : perror_msg_and_die("setreuid");
1176 : : }
1177 [ + - ]: 9478 : } else if (geteuid() != 0)
1178 [ - + ]: 9478 : if (setreuid(run_uid, run_uid) < 0) {
1179 : 0 : perror_msg_and_die("setreuid");
1180 : : }
1181 : :
1182 [ + - ]: 9478 : if (!daemonized_tracer) {
1183 : : /*
1184 : : * Induce a ptrace stop. Tracer (our parent)
1185 : : * will resume us with PTRACE_SYSCALL and display
1186 : : * the immediately following execve syscall.
1187 : : * Can't do this on NOMMU systems, we are after
1188 : : * vfork: parent is blocked, stopping would deadlock.
1189 : : */
1190 : : if (!NOMMU_SYSTEM)
1191 : 9478 : kill(getpid(), SIGSTOP);
1192 : : } else {
1193 : 0 : alarm(3);
1194 : : /* we depend on SIGCHLD set to SIG_DFL by init code */
1195 : : /* if it happens to be SIG_IGN'ed, wait won't block */
1196 : 0 : wait(NULL);
1197 : 0 : alarm(0);
1198 : : }
1199 : :
1200 [ - + ]: 9478 : if (params_for_tracee.child_sa.sa_handler != SIG_DFL)
1201 : 0 : sigaction(SIGCHLD, ¶ms_for_tracee.child_sa, NULL);
1202 : :
1203 : 9478 : execv(params->pathname, params->argv);
1204 : 9478 : perror_msg_and_die("exec");
1205 : : }
1206 : :
1207 : : /*
1208 : : * Open a dummy descriptor for use as a placeholder.
1209 : : * The descriptor is O_RDONLY with FD_CLOEXEC flag set.
1210 : : * A read attempt from such descriptor ends with EOF,
1211 : : * a write attempt is rejected with EBADF.
1212 : : */
1213 : : static int
1214 : 28454 : open_dummy_desc(void)
1215 : : {
1216 : : int fds[2];
1217 : :
1218 [ - + ]: 28454 : if (pipe(fds))
1219 : 0 : perror_msg_and_die("pipe");
1220 : 28454 : close(fds[1]);
1221 : 28454 : set_cloexec_flag(fds[0]);
1222 : 28454 : return fds[0];
1223 : : }
1224 : :
1225 : : /* placeholder fds status for stdin and stdout */
1226 : : static bool fd_is_placeholder[2];
1227 : :
1228 : : /*
1229 : : * Ensure that all standard file descriptors are open by opening placeholder
1230 : : * file descriptors for those standard file descriptors that are not open.
1231 : : *
1232 : : * The information which descriptors have been made open is saved
1233 : : * in fd_is_placeholder for later use.
1234 : : */
1235 : : static void
1236 : 9494 : ensure_standard_fds_opened(void)
1237 : : {
1238 : : int fd;
1239 : :
1240 [ + + ]: 9510 : while ((fd = open_dummy_desc()) <= 2) {
1241 [ + + ]: 24 : if (fd == 2)
1242 : : break;
1243 : 16 : fd_is_placeholder[fd] = true;
1244 : : }
1245 : :
1246 [ + + ]: 9494 : if (fd > 2)
1247 : 9486 : close(fd);
1248 : 9494 : }
1249 : :
1250 : : /*
1251 : : * Redirect stdin and stdout unless they have been opened earlier
1252 : : * by ensure_standard_fds_opened as placeholders.
1253 : : */
1254 : : static void
1255 : 9480 : redirect_standard_fds(void)
1256 : : {
1257 : : int i;
1258 : :
1259 : : /*
1260 : : * It might be a good idea to redirect stderr as well,
1261 : : * but we sometimes need to print error messages.
1262 : : */
1263 [ + + ]: 28440 : for (i = 0; i <= 1; ++i) {
1264 [ + + ]: 18960 : if (!fd_is_placeholder[i]) {
1265 : 18944 : close(i);
1266 : 18944 : open_dummy_desc();
1267 : : }
1268 : : }
1269 : 9480 : }
1270 : :
1271 : : static void
1272 : 9480 : startup_child(char **argv)
1273 : : {
1274 : : struct_stat statbuf;
1275 : : const char *filename;
1276 : : size_t filename_len;
1277 : : char pathname[PATH_MAX];
1278 : : int pid;
1279 : : struct tcb *tcp;
1280 : :
1281 : 9480 : filename = argv[0];
1282 : 9480 : filename_len = strlen(filename);
1283 : :
1284 [ - + ]: 9480 : if (filename_len > sizeof(pathname) - 1) {
1285 : 0 : errno = ENAMETOOLONG;
1286 : 0 : perror_msg_and_die("exec");
1287 : : }
1288 [ + + ]: 9480 : if (strchr(filename, '/')) {
1289 : 9476 : strcpy(pathname, filename);
1290 : : }
1291 : : #ifdef USE_DEBUGGING_EXEC
1292 : : /*
1293 : : * Debuggers customarily check the current directory
1294 : : * first regardless of the path but doing that gives
1295 : : * security geeks a panic attack.
1296 : : */
1297 : : else if (stat_file(filename, &statbuf) == 0)
1298 : : strcpy(pathname, filename);
1299 : : #endif /* USE_DEBUGGING_EXEC */
1300 : : else {
1301 : : const char *path;
1302 : : size_t m, n, len;
1303 : :
1304 [ + - ][ + - ]: 36 : for (path = getenv("PATH"); path && *path; path += m) {
1305 : 36 : const char *colon = strchr(path, ':');
1306 [ + - ]: 36 : if (colon) {
1307 : 36 : n = colon - path;
1308 : 36 : m = n + 1;
1309 : : } else
1310 : 0 : m = n = strlen(path);
1311 [ - + ]: 36 : if (n == 0) {
1312 [ # # ]: 0 : if (!getcwd(pathname, PATH_MAX))
1313 : 0 : continue;
1314 : 0 : len = strlen(pathname);
1315 [ - + ]: 36 : } else if (n > sizeof(pathname) - 1)
1316 : 0 : continue;
1317 : : else {
1318 : 36 : strncpy(pathname, path, n);
1319 : 36 : len = n;
1320 : : }
1321 [ + - ][ + - ]: 36 : if (len && pathname[len - 1] != '/')
1322 : 36 : pathname[len++] = '/';
1323 [ - + ]: 36 : if (filename_len + len > sizeof(pathname) - 1)
1324 : 0 : continue;
1325 : 36 : strcpy(pathname + len, filename);
1326 [ + + ][ + - ]: 36 : if (stat_file(pathname, &statbuf) == 0 &&
1327 : : /* Accept only regular files
1328 : : with some execute bits set.
1329 : : XXX not perfect, might still fail */
1330 [ - + ]: 4 : S_ISREG(statbuf.st_mode) &&
1331 : 4 : (statbuf.st_mode & 0111))
1332 : : break;
1333 : : }
1334 [ + - ][ - + ]: 4 : if (!path || !*path)
1335 : 0 : pathname[0] = '\0';
1336 : : }
1337 [ - + ]: 9480 : if (stat_file(pathname, &statbuf) < 0) {
1338 : 0 : perror_msg_and_die("Can't stat '%s'", filename);
1339 : : }
1340 : :
1341 [ + + ]: 9480 : params_for_tracee.fd_to_close = (shared_log != stderr) ? fileno(shared_log) : -1;
1342 [ - + ]: 9480 : params_for_tracee.run_euid = (statbuf.st_mode & S_ISUID) ? statbuf.st_uid : run_uid;
1343 [ - + ]: 9480 : params_for_tracee.run_egid = (statbuf.st_mode & S_ISGID) ? statbuf.st_gid : run_gid;
1344 : 9480 : params_for_tracee.argv = argv;
1345 : : /*
1346 : : * On NOMMU, can be safely freed only after execve in tracee.
1347 : : * It's hard to know when that happens, so we just leak it.
1348 : : */
1349 : 9480 : params_for_tracee.pathname = NOMMU_SYSTEM ? xstrdup(pathname) : pathname;
1350 : :
1351 : : #if defined HAVE_PRCTL && defined PR_SET_PTRACER && defined PR_SET_PTRACER_ANY
1352 [ - + ]: 9480 : if (daemonized_tracer)
1353 : 0 : prctl(PR_SET_PTRACER, PR_SET_PTRACER_ANY);
1354 : : #endif
1355 : :
1356 : 9480 : pid = fork();
1357 [ - + ]: 18958 : if (pid < 0) {
1358 : 0 : perror_msg_and_die("fork");
1359 : : }
1360 [ + + ][ + - ]: 18958 : if ((pid != 0 && daemonized_tracer)
1361 [ + + ][ + - ]: 18958 : || (pid == 0 && !daemonized_tracer)
1362 : : ) {
1363 : : /* We are to become the tracee. Two cases:
1364 : : * -D: we are parent
1365 : : * not -D: we are child
1366 : : */
1367 : 9478 : exec_or_die();
1368 : : }
1369 : :
1370 : : /* We are the tracer */
1371 : :
1372 [ + - ]: 9480 : if (!daemonized_tracer) {
1373 : 9480 : strace_child = pid;
1374 [ + - ]: 9480 : if (!use_seize) {
1375 : : /* child did PTRACE_TRACEME, nothing to do in parent */
1376 : : } else {
1377 : : if (!NOMMU_SYSTEM) {
1378 : : /* Wait until child stopped itself */
1379 : : int status;
1380 [ - + ]: 9480 : while (waitpid(pid, &status, WSTOPPED) < 0) {
1381 [ # # ]: 0 : if (errno == EINTR)
1382 : 0 : continue;
1383 : 0 : perror_msg_and_die("waitpid");
1384 : : }
1385 [ + - ][ - + ]: 9480 : if (!WIFSTOPPED(status) || WSTOPSIG(status) != SIGSTOP) {
1386 : 0 : kill_save_errno(pid, SIGKILL);
1387 : 0 : perror_msg_and_die("Unexpected wait status %#x",
1388 : : status);
1389 : : }
1390 : : }
1391 : : /* Else: NOMMU case, we have no way to sync.
1392 : : * Just attach to it as soon as possible.
1393 : : * This means that we may miss a few first syscalls...
1394 : : */
1395 : :
1396 [ - + ]: 9480 : if (ptrace_attach_or_seize(pid)) {
1397 : 0 : kill_save_errno(pid, SIGKILL);
1398 : 0 : perror_msg_and_die("attach: ptrace(%s, %d)",
1399 : : ptrace_attach_cmd, pid);
1400 : : }
1401 : : if (!NOMMU_SYSTEM)
1402 : 9480 : kill(pid, SIGCONT);
1403 : : }
1404 : 9480 : tcp = alloctcb(pid);
1405 : 18960 : tcp->flags |= TCB_ATTACHED | TCB_STARTUP
1406 : : | TCB_SKIP_DETACH_ON_FIRST_EXEC
1407 : 9480 : | (NOMMU_SYSTEM ? 0 : (TCB_HIDE_LOG | post_attach_sigstop));
1408 : 9480 : newoutf(tcp);
1409 : : } else {
1410 : : /* With -D, we are *child* here, the tracee is our parent. */
1411 : 0 : strace_child = strace_tracer_pid;
1412 : 0 : strace_tracer_pid = getpid();
1413 : 0 : tcp = alloctcb(strace_child);
1414 : 0 : tcp->flags |= TCB_SKIP_DETACH_ON_FIRST_EXEC | TCB_HIDE_LOG;
1415 : : /* attaching will be done later, by startup_attach */
1416 : : /* note: we don't do newoutf(tcp) here either! */
1417 : :
1418 : : /* NOMMU BUG! -D mode is active, we (child) return,
1419 : : * and we will scribble over parent's stack!
1420 : : * When parent later unpauses, it segfaults.
1421 : : *
1422 : : * We work around it
1423 : : * (1) by declaring exec_or_die() NORETURN,
1424 : : * hopefully compiler will just jump to it
1425 : : * instead of call (won't push anything to stack),
1426 : : * (2) by trying very hard in exec_or_die()
1427 : : * to not use any stack,
1428 : : * (3) having a really big (PATH_MAX) stack object
1429 : : * in this function, which creates a "buffer" between
1430 : : * child's and parent's stack pointers.
1431 : : * This may save us if (1) and (2) failed
1432 : : * and compiler decided to use stack in exec_or_die() anyway
1433 : : * (happens on i386 because of stack parameter passing).
1434 : : *
1435 : : * A cleaner solution is to use makecontext + setcontext
1436 : : * to create a genuine separate stack and execute on it.
1437 : : */
1438 : : }
1439 : : /*
1440 : : * A case where straced process is part of a pipe:
1441 : : * { sleep 1; yes | head -n99999; } | strace -o/dev/null sh -c 'exec <&-; sleep 9'
1442 : : * If strace won't close its fd#0, closing it in tracee is not enough:
1443 : : * the pipe is still open, it has a reader. Thus, "head" will not get its
1444 : : * SIGPIPE at once, on the first write.
1445 : : *
1446 : : * Preventing it by redirecting strace's stdin/out.
1447 : : * (Don't leave fds 0 and 1 closed, this is bad practice: future opens
1448 : : * will reuse them, unexpectedly making a newly opened object "stdin").
1449 : : */
1450 : 9480 : redirect_standard_fds();
1451 : 9480 : }
1452 : :
1453 : : #if USE_SEIZE
1454 : : static void
1455 : 9494 : test_ptrace_seize(void)
1456 : : {
1457 : : int pid;
1458 : :
1459 : : /* Need fork for test. NOMMU has no forks */
1460 : : if (NOMMU_SYSTEM) {
1461 : : post_attach_sigstop = 0; /* this sets use_seize to 1 */
1462 : : return;
1463 : : }
1464 : :
1465 : 9494 : pid = fork();
1466 [ - + ]: 9494 : if (pid < 0)
1467 : 0 : perror_msg_and_die("fork");
1468 : :
1469 [ - + ]: 9494 : if (pid == 0) {
1470 : 0 : pause();
1471 : 0 : _exit(0);
1472 : : }
1473 : :
1474 : : /* PTRACE_SEIZE, unlike ATTACH, doesn't force tracee to trap. After
1475 : : * attaching tracee continues to run unless a trap condition occurs.
1476 : : * PTRACE_SEIZE doesn't affect signal or group stop state.
1477 : : */
1478 [ + - ]: 9494 : if (ptrace(PTRACE_SEIZE, pid, 0, 0) == 0) {
1479 : 9494 : post_attach_sigstop = 0; /* this sets use_seize to 1 */
1480 [ # # ]: 0 : } else if (debug_flag) {
1481 : 0 : error_msg("PTRACE_SEIZE doesn't work");
1482 : : }
1483 : :
1484 : 9494 : kill(pid, SIGKILL);
1485 : :
1486 : : while (1) {
1487 : : int status, tracee_pid;
1488 : :
1489 : 9494 : errno = 0;
1490 : 9494 : tracee_pid = waitpid(pid, &status, 0);
1491 [ - + ]: 9494 : if (tracee_pid <= 0) {
1492 [ # # ]: 0 : if (errno == EINTR)
1493 : 0 : continue;
1494 : 0 : perror_msg_and_die("%s: unexpected wait result %d",
1495 : : __func__, tracee_pid);
1496 : : }
1497 [ - + ]: 9494 : if (WIFSIGNALED(status)) {
1498 : 9494 : return;
1499 : : }
1500 : 0 : error_msg_and_die("%s: unexpected wait status %#x",
1501 : : __func__, status);
1502 : : }
1503 : : }
1504 : : #else /* !USE_SEIZE */
1505 : : # define test_ptrace_seize() ((void)0)
1506 : : #endif
1507 : :
1508 : : static unsigned
1509 : 10804 : get_os_release(void)
1510 : : {
1511 : : unsigned rel;
1512 : : const char *p;
1513 : : struct utsname u;
1514 [ + - ]: 10804 : if (uname(&u) < 0)
1515 : 0 : perror_msg_and_die("uname");
1516 : : /* u.release has this form: "3.2.9[-some-garbage]" */
1517 : : rel = 0;
1518 : : p = u.release;
1519 : : for (;;) {
1520 [ - + ]: 32412 : if (!(*p >= '0' && *p <= '9'))
1521 : 0 : error_msg_and_die("Bad OS release string: '%s'", u.release);
1522 : : /* Note: this open-codes KERNEL_VERSION(): */
1523 : 64824 : rel = (rel << 8) | atoi(p);
1524 [ + + ]: 32412 : if (rel >= KERNEL_VERSION(1, 0, 0))
1525 : : break;
1526 [ + + ]: 43216 : while (*p >= '0' && *p <= '9')
1527 : 21608 : p++;
1528 [ - + ]: 21608 : if (*p != '.') {
1529 [ # # ]: 0 : if (rel >= KERNEL_VERSION(0, 1, 0)) {
1530 : : /* "X.Y-something" means "X.Y.0" */
1531 : 0 : rel <<= 8;
1532 : 0 : break;
1533 : : }
1534 : 0 : error_msg_and_die("Bad OS release string: '%s'", u.release);
1535 : : }
1536 : 21608 : p++;
1537 : 21608 : }
1538 : 10804 : return rel;
1539 : : }
1540 : :
1541 : : static void
1542 : 75916 : set_sigaction(int signo, void (*sighandler)(int), struct sigaction *oldact)
1543 : : {
1544 : : /* if signal handler is a function, add the signal to blocked_set */
1545 [ + + ]: 75916 : if (sighandler != SIG_IGN && sighandler != SIG_DFL)
1546 : 190 : sigaddset(&blocked_set, signo);
1547 : :
1548 : 75916 : const struct sigaction sa = { .sa_handler = sighandler };
1549 : 75916 : sigaction(signo, &sa, oldact);
1550 : 75916 : }
1551 : :
1552 : : /*
1553 : : * Initialization part of main() was eating much stack (~0.5k),
1554 : : * which was unused after init.
1555 : : * We can reuse it if we move init code into a separate function.
1556 : : *
1557 : : * Don't want main() to inline us and defeat the reason
1558 : : * we have a separate function.
1559 : : */
1560 : : static void ATTRIBUTE_NOINLINE
1561 : 10804 : init(int argc, char *argv[])
1562 : : {
1563 : : int c, i;
1564 : 10804 : int optF = 0;
1565 : :
1566 [ + - ][ + + ]: 10804 : if (!program_invocation_name || !*program_invocation_name) {
1567 : : static char name[] = "strace";
1568 : 2 : program_invocation_name =
1569 [ - + ][ # # ]: 2 : (argv[0] && *argv[0]) ? argv[0] : name;
1570 : : }
1571 : :
1572 : 10804 : strace_tracer_pid = getpid();
1573 : :
1574 : 10804 : os_release = get_os_release();
1575 : :
1576 : 10804 : shared_log = stderr;
1577 : 10804 : set_sortby(DEFAULT_SORTBY);
1578 : 10804 : set_personality(DEFAULT_PERSONALITY);
1579 : 10804 : qualify("trace=all");
1580 : 10804 : qualify("abbrev=all");
1581 : 10804 : qualify("verbose=all");
1582 : : #if DEFAULT_QUAL_FLAGS != (QUAL_TRACE | QUAL_ABBREV | QUAL_VERBOSE)
1583 : : # error Bug in DEFAULT_QUAL_FLAGS
1584 : : #endif
1585 : 10804 : qualify("signal=all");
1586 [ + + ]: 76024 : while ((c = getopt(argc, argv,
1587 : : "+b:cCdfFhiqrtTvVwxyz"
1588 : : #ifdef USE_LIBUNWIND
1589 : : "k"
1590 : : #endif
1591 : : #ifdef USE_LUAJIT
1592 : : "l:"
1593 : : #endif
1594 : : "D"
1595 : : "a:e:o:O:p:s:S:u:E:P:I:")) != EOF) {
1596 [ + + + + : 55714 : switch (c) {
+ + + + +
+ + + + +
+ + + - +
+ + + + +
+ + - + +
+ - - ]
1597 : : case 'b':
1598 [ + + ]: 8 : if (strcmp(optarg, "execve") != 0)
1599 : 4 : error_msg_and_die("Syscall '%s' for -b isn't supported",
1600 : : optarg);
1601 : 4 : detach_on_execve = 1;
1602 : 4 : break;
1603 : : case 'c':
1604 [ + + ]: 20 : if (cflag == CFLAG_BOTH) {
1605 : 2 : error_msg_and_help("-c and -C are mutually exclusive");
1606 : : }
1607 : 18 : cflag = CFLAG_ONLY_STATS;
1608 : 18 : break;
1609 : : case 'C':
1610 [ + + ]: 8 : if (cflag == CFLAG_ONLY_STATS) {
1611 : 2 : error_msg_and_help("-c and -C are mutually exclusive");
1612 : : }
1613 : 6 : cflag = CFLAG_BOTH;
1614 : 6 : break;
1615 : : case 'd':
1616 : 2 : debug_flag = 1;
1617 : 2 : break;
1618 : : case 'D':
1619 : 2 : daemonized_tracer = 1;
1620 : 2 : break;
1621 : : case 'F':
1622 : : optF = 1;
1623 : : break;
1624 : : case 'f':
1625 : 2794 : followfork++;
1626 : 2794 : break;
1627 : : case 'h':
1628 : 8 : usage();
1629 : : break;
1630 : : case 'i':
1631 : 2 : iflag = 1;
1632 : 2 : break;
1633 : : case 'q':
1634 : 13702 : qflag++;
1635 : 13702 : break;
1636 : : case 'r':
1637 : 2 : rflag = 1;
1638 : 2 : break;
1639 : : case 't':
1640 : 20 : tflag++;
1641 : 20 : break;
1642 : : case 'T':
1643 : 2 : Tflag = 1;
1644 : 2 : break;
1645 : : case 'w':
1646 : 10 : count_wallclock = 1;
1647 : 10 : break;
1648 : : case 'x':
1649 : 10 : xflag++;
1650 : 10 : break;
1651 : : case 'y':
1652 : 16 : show_fd_path++;
1653 : 16 : break;
1654 : : case 'v':
1655 : 2573 : qualify("abbrev=none");
1656 : 65220 : break;
1657 : : case 'V':
1658 : : print_version();
1659 : 892 : exit(0);
1660 : : break;
1661 : : case 'z':
1662 : 0 : not_failing_only = 1;
1663 : 0 : break;
1664 : : case 'a':
1665 : 2020 : acolumn = string_to_uint(optarg);
1666 [ + + ]: 2020 : if (acolumn < 0)
1667 : 2 : error_opt_arg(c, optarg);
1668 : : break;
1669 : : case 'e':
1670 : 18936 : qualify(optarg);
1671 : 18564 : break;
1672 : : case 'o':
1673 : 9478 : outfname = optarg;
1674 : 9478 : break;
1675 : : case 'O':
1676 : 2 : i = string_to_uint(optarg);
1677 [ + - ]: 2 : if (i < 0)
1678 : 2 : error_opt_arg(c, optarg);
1679 : 0 : set_overhead(i);
1680 : 0 : break;
1681 : : case 'p':
1682 : 24 : process_opt_p_list(optarg);
1683 : 16 : break;
1684 : : case 'P':
1685 : 5054 : pathtrace_select(optarg);
1686 : 5054 : break;
1687 : : case 's':
1688 : 57 : i = string_to_uint(optarg);
1689 [ + + ]: 57 : if (i < 0 || (unsigned int) i > -1U / 4)
1690 : 4 : error_opt_arg(c, optarg);
1691 : 53 : max_strlen = i;
1692 : 53 : break;
1693 : : case 'S':
1694 : 4 : set_sortby(optarg);
1695 : 4 : break;
1696 : : case 'u':
1697 : 0 : username = optarg;
1698 : 0 : break;
1699 : : #ifdef USE_LIBUNWIND
1700 : : case 'k':
1701 : : stack_trace_enabled = true;
1702 : : break;
1703 : : #endif
1704 : : #ifdef USE_LUAJIT
1705 : : case 'l':
1706 : 44 : init_luajit(optarg);
1707 : 44 : break;
1708 : : #endif
1709 : : case 'E':
1710 [ - + ]: 2 : if (putenv(optarg) < 0)
1711 : 0 : perror_msg_and_die("putenv");
1712 : : break;
1713 : : case 'I':
1714 : 44 : opt_intr = string_to_uint_upto(optarg, NUM_INTR_OPTS - 1);
1715 [ + + ]: 22 : if (opt_intr <= 0)
1716 : 2 : error_opt_arg(c, optarg);
1717 : : break;
1718 : : default:
1719 : 0 : error_msg_and_help(NULL);
1720 : : break;
1721 : : }
1722 : : }
1723 : :
1724 : 9506 : argv += optind;
1725 : 9506 : argc -= optind;
1726 : :
1727 [ + + ][ + + ]: 9506 : if (argc < 0 || (!argv[0] && !nprocs)) {
[ + + ]
1728 : 4 : error_msg_and_help("must have PROG [ARGS] or -p PID");
1729 : : }
1730 : :
1731 [ + + ][ + + ]: 9502 : if (!argv[0] && daemonized_tracer) {
1732 : 2 : error_msg_and_help("PROG [ARGS] must be specified with -D");
1733 : : }
1734 : :
1735 [ + + ]: 9500 : if (!followfork)
1736 : 8096 : followfork = optF;
1737 : :
1738 [ + + ][ + + ]: 9500 : if (followfork >= 2 && cflag) {
1739 : 4 : error_msg_and_help("(-c or -C) and -ff are mutually exclusive");
1740 : : }
1741 : :
1742 [ + + ][ + + ]: 9496 : if (count_wallclock && !cflag) {
1743 : 2 : error_msg_and_help("-w must be given with (-c or -C)");
1744 : : }
1745 : :
1746 [ + + ]: 9494 : if (cflag == CFLAG_ONLY_STATS) {
1747 [ - + ]: 14 : if (iflag)
1748 : 0 : error_msg("-%c has no effect with -c", 'i');
1749 : : #ifdef USE_LIBUNWIND
1750 : : if (stack_trace_enabled)
1751 : : error_msg("-%c has no effect with -c", 'k');
1752 : : #endif
1753 [ - + ]: 14 : if (rflag)
1754 : 0 : error_msg("-%c has no effect with -c", 'r');
1755 [ - + ]: 14 : if (tflag)
1756 : 0 : error_msg("-%c has no effect with -c", 't');
1757 [ - + ]: 14 : if (Tflag)
1758 : 0 : error_msg("-%c has no effect with -c", 'T');
1759 [ - + ]: 14 : if (show_fd_path)
1760 : 0 : error_msg("-%c has no effect with -c", 'y');
1761 : : }
1762 : :
1763 [ + + ]: 9494 : if (rflag) {
1764 [ - + ]: 2 : if (tflag > 1)
1765 : 0 : error_msg("-tt has no effect with -r");
1766 : 2 : tflag = 1;
1767 : : }
1768 : :
1769 : 9494 : acolumn_spaces = xmalloc(acolumn + 1);
1770 : 9494 : memset(acolumn_spaces, ' ', acolumn);
1771 : 9494 : acolumn_spaces[acolumn] = '\0';
1772 : :
1773 : 9494 : sigprocmask(SIG_SETMASK, NULL, &start_set);
1774 : 9494 : memcpy(&blocked_set, &start_set, sizeof(blocked_set));
1775 : :
1776 : 9494 : set_sigaction(SIGCHLD, SIG_DFL, ¶ms_for_tracee.child_sa);
1777 : :
1778 : : #ifdef USE_LIBUNWIND
1779 : : if (stack_trace_enabled) {
1780 : : unsigned int tcbi;
1781 : :
1782 : : unwind_init();
1783 : : for (tcbi = 0; tcbi < tcbtabsize; ++tcbi) {
1784 : : unwind_tcb_init(tcbtab[tcbi]);
1785 : : }
1786 : : }
1787 : : #endif
1788 : :
1789 : : /* See if they want to run as another user. */
1790 [ - + ]: 9494 : if (username != NULL) {
1791 : : struct passwd *pent;
1792 : :
1793 [ # # ][ # # ]: 0 : if (getuid() != 0 || geteuid() != 0) {
1794 : 0 : error_msg_and_die("You must be root to use the -u option");
1795 : : }
1796 : 0 : pent = getpwnam(username);
1797 [ # # ]: 0 : if (pent == NULL) {
1798 : 0 : error_msg_and_die("Cannot find user '%s'", username);
1799 : : }
1800 : 0 : run_uid = pent->pw_uid;
1801 : 0 : run_gid = pent->pw_gid;
1802 : : } else {
1803 : 9494 : run_uid = getuid();
1804 : 9494 : run_gid = getgid();
1805 : : }
1806 : :
1807 [ + + ]: 9494 : if (followfork)
1808 : 1400 : ptrace_setoptions |= PTRACE_O_TRACECLONE |
1809 : : PTRACE_O_TRACEFORK |
1810 : : PTRACE_O_TRACEVFORK;
1811 [ + + ]: 9494 : if (debug_flag)
1812 : 2 : error_msg("ptrace_setoptions = %#x", ptrace_setoptions);
1813 : 9494 : test_ptrace_seize();
1814 : :
1815 : : /*
1816 : : * Is something weird with our stdin and/or stdout -
1817 : : * for example, may they be not open? In this case,
1818 : : * ensure that none of the future opens uses them.
1819 : : *
1820 : : * This was seen in the wild when /proc/sys/kernel/core_pattern
1821 : : * was set to "|/bin/strace -o/tmp/LOG PROG":
1822 : : * kernel runs coredump helper with fd#0 open but fd#1 closed (!),
1823 : : * therefore LOG gets opened to fd#1, and fd#1 is closed by
1824 : : * "don't hold up stdin/out open" code soon after.
1825 : : */
1826 : 9494 : ensure_standard_fds_opened();
1827 : :
1828 : : /* Check if they want to redirect the output. */
1829 [ + + ]: 9494 : if (outfname) {
1830 : : /* See if they want to pipe the output. */
1831 [ + + ]: 9472 : if (outfname[0] == '|' || outfname[0] == '!') {
1832 : : /*
1833 : : * We can't do the <outfname>.PID funny business
1834 : : * when using popen, so prohibit it.
1835 : : */
1836 [ + + ]: 10 : if (followfork >= 2)
1837 : 4 : error_msg_and_help("piping the output and -ff are mutually exclusive");
1838 : 6 : shared_log = strace_popen(outfname + 1);
1839 [ + + ]: 9462 : } else if (followfork < 2)
1840 : 8080 : shared_log = strace_fopen(outfname);
1841 : : } else {
1842 : : /* -ff without -o FILE is the same as single -f */
1843 [ - + ]: 22 : if (followfork >= 2)
1844 : 0 : followfork = 1;
1845 : : }
1846 : :
1847 [ + + ][ + + ]: 9490 : if (!outfname || outfname[0] == '|' || outfname[0] == '!') {
[ - + ]
1848 : 28 : setvbuf(shared_log, NULL, _IOLBF, 0);
1849 : : }
1850 : :
1851 : : /*
1852 : : * argv[0] -pPID -oFILE Default interactive setting
1853 : : * yes * 0 INTR_WHILE_WAIT
1854 : : * no 1 0 INTR_WHILE_WAIT
1855 : : * yes * 1 INTR_NEVER
1856 : : * no 1 1 INTR_WHILE_WAIT
1857 : : */
1858 : :
1859 [ + + ][ + + ]: 9490 : if (outfname && argv[0]) {
1860 [ + + ]: 9466 : if (!opt_intr)
1861 : 9446 : opt_intr = INTR_NEVER;
1862 [ + + ]: 9466 : if (!qflag)
1863 : 2618 : qflag = 1;
1864 : : }
1865 [ + + ]: 9490 : if (!opt_intr)
1866 : 24 : opt_intr = INTR_WHILE_WAIT;
1867 : :
1868 : : /*
1869 : : * startup_child() must be called before the signal handlers get
1870 : : * installed below as they are inherited into the spawned process.
1871 : : * Also we do not need to be protected by them as during interruption
1872 : : * in the startup_child() mode we kill the spawned process anyway.
1873 : : */
1874 [ + + ]: 9490 : if (argv[0]) {
1875 : 9480 : startup_child(argv);
1876 : : }
1877 : :
1878 : 9490 : set_sigaction(SIGTTOU, SIG_IGN, NULL);
1879 : 9490 : set_sigaction(SIGTTIN, SIG_IGN, NULL);
1880 [ + + ]: 9490 : if (opt_intr != INTR_ANYWHERE) {
1881 [ + + ]: 9488 : if (opt_intr == INTR_BLOCK_TSTP_TOO)
1882 : 2 : set_sigaction(SIGTSTP, SIG_IGN, NULL);
1883 : : /*
1884 : : * In interactive mode (if no -o OUTFILE, or -p PID is used),
1885 : : * fatal signals are blocked while syscall stop is processed,
1886 : : * and acted on in between, when waiting for new syscall stops.
1887 : : * In non-interactive mode, signals are ignored.
1888 : : */
1889 [ + + ]: 9488 : set_sigaction(SIGHUP, interactive ? interrupt : SIG_IGN, NULL);
1890 [ + + ]: 9488 : set_sigaction(SIGINT, interactive ? interrupt : SIG_IGN, NULL);
1891 [ + + ]: 9488 : set_sigaction(SIGQUIT, interactive ? interrupt : SIG_IGN, NULL);
1892 [ + + ]: 9488 : set_sigaction(SIGPIPE, interactive ? interrupt : SIG_IGN, NULL);
1893 [ + + ]: 9488 : set_sigaction(SIGTERM, interactive ? interrupt : SIG_IGN, NULL);
1894 : : }
1895 : :
1896 [ - + ][ # # ]: 9490 : if (nprocs != 0 || daemonized_tracer)
1897 : 9490 : startup_attach();
1898 : :
1899 : : /* Do we want pids printed in our -o OUTFILE?
1900 : : * -ff: no (every pid has its own file); or
1901 : : * -f: yes (there can be more pids in the future); or
1902 : : * -p PID1,PID2: yes (there are already more than one pid)
1903 : : */
1904 [ + + ][ + + ]: 9490 : print_pid_pfx = (outfname && followfork < 2 && (followfork == 1 || nprocs > 1));
[ + + ][ + + ]
1905 : 9490 : }
1906 : :
1907 : : static struct tcb *
1908 : : pid2tcb(int pid)
1909 : : {
1910 : : unsigned int i;
1911 : :
1912 [ + - ][ + - ]: 74236141 : if (pid <= 0)
1913 : : return NULL;
1914 : :
1915 [ + + ][ + - ]: 77906660 : for (i = 0; i < tcbtabsize; i++) {
1916 : 77903202 : struct tcb *tcp = tcbtab[i];
1917 [ + + ][ + + ]: 77903202 : if (tcp->pid == pid)
1918 : 74232683 : return tcp;
1919 : : }
1920 : :
1921 : : return NULL;
1922 : : }
1923 : :
1924 : : static void
1925 : 9904 : cleanup(void)
1926 : : {
1927 : : unsigned int i;
1928 : : struct tcb *tcp;
1929 : : int fatal_sig;
1930 : :
1931 : : /* 'interrupted' is a volatile object, fetch it only once */
1932 : 9904 : fatal_sig = interrupted;
1933 [ + + ]: 9904 : if (!fatal_sig)
1934 : 9898 : fatal_sig = SIGTERM;
1935 : :
1936 [ + + ]: 24302 : for (i = 0; i < tcbtabsize; i++) {
1937 : 14398 : tcp = tcbtab[i];
1938 [ + + ]: 14398 : if (!tcp->pid)
1939 : 14385 : continue;
1940 [ - + ]: 13 : if (debug_flag)
1941 : 0 : error_msg("cleanup: looking at pid %u", tcp->pid);
1942 [ + + ]: 13 : if (tcp->pid == strace_child) {
1943 : 3 : kill(tcp->pid, SIGCONT);
1944 : 3 : kill(tcp->pid, fatal_sig);
1945 : : }
1946 : 13 : detach(tcp);
1947 : : }
1948 [ + + ]: 9904 : if (cflag)
1949 : 16 : call_summary(shared_log);
1950 : 9904 : }
1951 : :
1952 : : static void
1953 : 6 : interrupt(int sig)
1954 : : {
1955 : 6 : interrupted = sig;
1956 : 6 : }
1957 : :
1958 : : static void
1959 : 28444 : print_debug_info(const int pid, int status)
1960 : : {
1961 : 28444 : const unsigned int event = (unsigned int) status >> 16;
1962 : : char buf[sizeof("WIFEXITED,exitcode=%u") + sizeof(int)*3 /*paranoia:*/ + 16];
1963 : : char evbuf[sizeof(",EVENT_VFORK_DONE (%u)") + sizeof(int)*3 /*paranoia:*/ + 16];
1964 : :
1965 : 28444 : strcpy(buf, "???");
1966 [ - + ]: 28444 : if (WIFSIGNALED(status))
1967 : : #ifdef WCOREDUMP
1968 [ # # ]: 0 : sprintf(buf, "WIFSIGNALED,%ssig=%s",
1969 : 0 : WCOREDUMP(status) ? "core," : "",
1970 : 0 : signame(WTERMSIG(status)));
1971 : : #else
1972 : : sprintf(buf, "WIFSIGNALED,sig=%s",
1973 : : signame(WTERMSIG(status)));
1974 : : #endif
1975 [ + + ]: 28444 : if (WIFEXITED(status))
1976 : 2 : sprintf(buf, "WIFEXITED,exitcode=%u", WEXITSTATUS(status));
1977 [ + + ]: 28444 : if (WIFSTOPPED(status))
1978 : 28442 : sprintf(buf, "WIFSTOPPED,sig=%s", signame(WSTOPSIG(status)));
1979 : 28444 : evbuf[0] = '\0';
1980 [ + + ]: 28444 : if (event != 0) {
1981 : : static const char *const event_names[] = {
1982 : : [PTRACE_EVENT_CLONE] = "CLONE",
1983 : : [PTRACE_EVENT_FORK] = "FORK",
1984 : : [PTRACE_EVENT_VFORK] = "VFORK",
1985 : : [PTRACE_EVENT_VFORK_DONE] = "VFORK_DONE",
1986 : : [PTRACE_EVENT_EXEC] = "EXEC",
1987 : : [PTRACE_EVENT_EXIT] = "EXIT",
1988 : : /* [PTRACE_EVENT_STOP (=128)] would make biggish array */
1989 : : };
1990 : 6 : const char *e = "??";
1991 [ + + ]: 6 : if (event < ARRAY_SIZE(event_names))
1992 : 2 : e = event_names[event];
1993 [ + - ]: 4 : else if (event == PTRACE_EVENT_STOP)
1994 : 4 : e = "STOP";
1995 : 6 : sprintf(evbuf, ",EVENT_%s (%u)", e, event);
1996 : : }
1997 : 28444 : error_msg("[wait(0x%06x) = %u] %s%s", status, pid, buf, evbuf);
1998 : 28444 : }
1999 : :
2000 : : static struct tcb *
2001 : 3458 : maybe_allocate_tcb(const int pid, int status)
2002 : : {
2003 [ + + ]: 3458 : if (!WIFSTOPPED(status)) {
2004 [ + - ][ + - ]: 2 : if (detach_on_execve && pid == strace_child) {
2005 : : /* example: strace -bexecve sh -c 'exec true' */
2006 : 2 : strace_child = 0;
2007 : 2 : return NULL;
2008 : : }
2009 : : /*
2010 : : * This can happen if we inherited an unknown child.
2011 : : * Example: (sleep 1 & exec strace true)
2012 : : */
2013 : 0 : error_msg("Exit of unknown pid %u ignored", pid);
2014 : 0 : return NULL;
2015 : : }
2016 [ + - ]: 3456 : if (followfork) {
2017 : : /* We assume it's a fork/vfork/clone child */
2018 : 3456 : struct tcb *tcp = alloctcb(pid);
2019 : 3456 : tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
2020 : 3456 : newoutf(tcp);
2021 [ + + ]: 3456 : if (!qflag)
2022 : 2 : error_msg("Process %d attached", pid);
2023 : 3456 : return tcp;
2024 : : } else {
2025 : : /* This can happen if a clone call used
2026 : : * CLONE_PTRACE itself.
2027 : : */
2028 : 0 : ptrace(PTRACE_CONT, pid, NULL, 0);
2029 : 0 : error_msg("Stop of unknown pid %u seen, PTRACE_CONTed it", pid);
2030 : 0 : return NULL;
2031 : : }
2032 : : }
2033 : :
2034 : : static struct tcb *
2035 : 9494 : maybe_switch_tcbs(struct tcb *tcp, const int pid)
2036 : : {
2037 : : FILE *fp;
2038 : : struct tcb *execve_thread;
2039 : 9494 : long old_pid = 0;
2040 : :
2041 [ + - ]: 9494 : if (ptrace(PTRACE_GETEVENTMSG, pid, NULL, &old_pid) < 0)
2042 : : return tcp;
2043 : : /* Avoid truncation in pid2tcb() param passing */
2044 [ + - ][ + + ]: 9494 : if (old_pid <= 0 || old_pid == pid)
2045 : : return tcp;
2046 [ + - ]: 6 : if ((unsigned long) old_pid > UINT_MAX)
2047 : : return tcp;
2048 : 12 : execve_thread = pid2tcb(old_pid);
2049 : : /* It should be !NULL, but I feel paranoid */
2050 [ + - ]: 6 : if (!execve_thread)
2051 : : return tcp;
2052 : :
2053 [ + + ]: 6 : if (execve_thread->curcol != 0) {
2054 : : /*
2055 : : * One case we are here is -ff:
2056 : : * try "strace -oLOG -ff test/threaded_execve"
2057 : : */
2058 : 2 : fprintf(execve_thread->outf, " <pid changed to %d ...>\n", pid);
2059 : : /*execve_thread->curcol = 0; - no need, see code below */
2060 : : }
2061 : : /* Swap output FILEs (needed for -ff) */
2062 : 6 : fp = execve_thread->outf;
2063 : 6 : execve_thread->outf = tcp->outf;
2064 : 6 : tcp->outf = fp;
2065 : : /* And their column positions */
2066 : 6 : execve_thread->curcol = tcp->curcol;
2067 : 6 : tcp->curcol = 0;
2068 : : /* Drop leader, but close execve'd thread outfile (if -ff) */
2069 : 6 : droptcb(tcp);
2070 : : /* Switch to the thread, reusing leader's outfile and pid */
2071 : 6 : tcp = execve_thread;
2072 : 6 : tcp->pid = pid;
2073 [ + - ]: 6 : if (cflag != CFLAG_ONLY_STATS) {
2074 : 6 : printleader(tcp);
2075 : 6 : tprintf("+++ superseded by execve in pid %lu +++\n", old_pid);
2076 : 6 : line_ended();
2077 : 6 : tcp->flags |= TCB_REPRINT;
2078 : : }
2079 : :
2080 : 6 : return tcp;
2081 : : }
2082 : :
2083 : : static void
2084 : 10 : print_signalled(struct tcb *tcp, const int pid, int status)
2085 : : {
2086 [ + + ]: 10 : if (pid == strace_child) {
2087 : 8 : exit_code = 0x100 | WTERMSIG(status);
2088 : 8 : strace_child = 0;
2089 : : }
2090 : :
2091 [ + - ]: 10 : if (cflag != CFLAG_ONLY_STATS
2092 [ + + ]: 10 : && is_number_in_set(WTERMSIG(status), &signal_set)) {
2093 : 2 : printleader(tcp);
2094 : : #ifdef WCOREDUMP
2095 [ - + ]: 2 : tprintf("+++ killed by %s %s+++\n",
2096 : 2 : signame(WTERMSIG(status)),
2097 : 2 : WCOREDUMP(status) ? "(core dumped) " : "");
2098 : : #else
2099 : : tprintf("+++ killed by %s +++\n",
2100 : : signame(WTERMSIG(status)));
2101 : : #endif
2102 : 2 : line_ended();
2103 : : }
2104 : 10 : }
2105 : :
2106 : : static void
2107 : 12927 : print_exited(struct tcb *tcp, const int pid, int status)
2108 : : {
2109 [ + + ]: 12927 : if (pid == strace_child) {
2110 : 9467 : exit_code = WEXITSTATUS(status);
2111 : 9467 : strace_child = 0;
2112 : : }
2113 : :
2114 [ + + ][ + + ]: 12927 : if (cflag != CFLAG_ONLY_STATS &&
2115 : 12833 : qflag < 2) {
2116 : 5723 : printleader(tcp);
2117 : 5723 : tprintf("+++ exited with %d +++\n", WEXITSTATUS(status));
2118 : 5723 : line_ended();
2119 : : }
2120 : 12927 : }
2121 : :
2122 : : static void
2123 : 52026 : print_stopped(struct tcb *tcp, const siginfo_t *si, const unsigned int sig)
2124 : : {
2125 [ + + ]: 52026 : if (cflag != CFLAG_ONLY_STATS
2126 [ + + ]: 51982 : && !hide_log(tcp)
2127 [ + + ]: 33050 : && is_number_in_set(sig, &signal_set)) {
2128 : 3333 : printleader(tcp);
2129 [ + + ]: 3333 : if (si) {
2130 : 3331 : tprintf("--- %s ", signame(sig));
2131 : 3331 : printsiginfo(si);
2132 : 3331 : tprints(" ---\n");
2133 : : } else
2134 : 2 : tprintf("--- stopped by %s ---\n", signame(sig));
2135 : 3333 : line_ended();
2136 : : }
2137 : 52026 : }
2138 : :
2139 : : static void
2140 : 12954 : startup_tcb(struct tcb *tcp)
2141 : : {
2142 [ + + ]: 12954 : if (debug_flag)
2143 : 2 : error_msg("pid %d has TCB_STARTUP, initializing it", tcp->pid);
2144 : :
2145 : 12954 : tcp->flags &= ~TCB_STARTUP;
2146 : :
2147 [ - + ]: 12954 : if (!use_seize) {
2148 [ # # ]: 0 : if (debug_flag)
2149 : 0 : error_msg("setting opts 0x%x on pid %d",
2150 : : ptrace_setoptions, tcp->pid);
2151 [ # # ]: 0 : if (ptrace(PTRACE_SETOPTIONS, tcp->pid, NULL, ptrace_setoptions) < 0) {
2152 [ # # ]: 0 : if (errno != ESRCH) {
2153 : : /* Should never happen, really */
2154 : 0 : perror_msg_and_die("PTRACE_SETOPTIONS");
2155 : : }
2156 : : }
2157 : : }
2158 : :
2159 [ + - ]: 12954 : if (get_scno(tcp) == 1)
2160 : 12954 : tcp->s_prev_ent = tcp->s_ent;
2161 : 12954 : }
2162 : :
2163 : : static void
2164 : 12940 : print_event_exit(struct tcb *tcp)
2165 : : {
2166 [ + + ]: 12940 : if (entering(tcp) || filtered(tcp) || hide_log(tcp)
2167 [ + + ]: 128 : || cflag == CFLAG_ONLY_STATS) {
2168 : 12940 : return;
2169 : : }
2170 : :
2171 [ + + ][ + - ]: 38 : if (followfork < 2 && printing_tcp && printing_tcp != tcp
[ + + ]
2172 [ + - ]: 4 : && printing_tcp->curcol != 0) {
2173 : 4 : current_tcp = printing_tcp;
2174 : 4 : tprints(" <unfinished ...>\n");
2175 : 4 : fflush(printing_tcp->outf);
2176 : 4 : printing_tcp->curcol = 0;
2177 : 4 : current_tcp = tcp;
2178 : : }
2179 : :
2180 [ + + ][ + + ]: 38 : if ((followfork < 2 && printing_tcp != tcp)
2181 [ - + ]: 34 : || (tcp->flags & TCB_REPRINT)) {
2182 : 4 : tcp->flags &= ~TCB_REPRINT;
2183 : 4 : printleader(tcp);
2184 : 4 : tprintf("<... %s resumed>", tcp->s_ent->sys_name);
2185 : : }
2186 : :
2187 [ + + ]: 38 : if (!(tcp->sys_func_rval & RVAL_DECODED)) {
2188 : : /*
2189 : : * The decoder has probably decided to print something
2190 : : * on exiting syscall which is not going to happen.
2191 : : */
2192 : 2 : tprints(" <unfinished ...>");
2193 : : }
2194 : 38 : tprints(") ");
2195 : 38 : tabto();
2196 : 38 : tprints("= ?\n");
2197 : 38 : line_ended();
2198 : : }
2199 : :
2200 : : enum trace_event {
2201 : : /* Break the main loop. */
2202 : : TE_BREAK,
2203 : :
2204 : : /* Call next_event() again. */
2205 : : TE_NEXT,
2206 : :
2207 : : /* Restart the tracee with signal 0 and call next_event() again. */
2208 : : TE_RESTART,
2209 : :
2210 : : /*
2211 : : * For all the events below, current_tcp is set to current tracee's
2212 : : * tcb. All the suggested actions imply that you want to continue
2213 : : * tracing of the current tracee; alternatively, you can detach it.
2214 : : */
2215 : :
2216 : : /*
2217 : : * Syscall entry or exit.
2218 : : * Restart the tracee with signal 0, or with an injected signal number.
2219 : : */
2220 : : TE_SYSCALL_STOP,
2221 : :
2222 : : /*
2223 : : * Tracee received signal with number WSTOPSIG(*pstatus); signal info
2224 : : * is written to *si. Restart the tracee (with that signal number
2225 : : * if you want to deliver it).
2226 : : */
2227 : : TE_SIGNAL_DELIVERY_STOP,
2228 : :
2229 : : /*
2230 : : * Tracee was killed by a signal with number WTERMSIG(*pstatus).
2231 : : */
2232 : : TE_SIGNALLED,
2233 : :
2234 : : /*
2235 : : * Tracee was stopped by a signal with number WSTOPSIG(*pstatus).
2236 : : * Restart the tracee with that signal number.
2237 : : */
2238 : : TE_GROUP_STOP,
2239 : :
2240 : : /*
2241 : : * Tracee exited with status WEXITSTATUS(*pstatus).
2242 : : */
2243 : : TE_EXITED,
2244 : :
2245 : : /*
2246 : : * Tracee is going to perform execve().
2247 : : * Restart the tracee with signal 0.
2248 : : */
2249 : : TE_STOP_BEFORE_EXECVE,
2250 : :
2251 : : /*
2252 : : * Tracee is going to terminate.
2253 : : * Restart the tracee with signal 0.
2254 : : */
2255 : : TE_STOP_BEFORE_EXIT,
2256 : : };
2257 : :
2258 : : static enum trace_event
2259 : 74245628 : next_event(int *pstatus, siginfo_t *si)
2260 : : {
2261 : : int pid;
2262 : : int wait_errno;
2263 : : int status;
2264 : : struct tcb *tcp;
2265 : : struct rusage ru;
2266 : :
2267 [ + + ]: 74245628 : if (interrupted)
2268 : : return TE_BREAK;
2269 : :
2270 : : /*
2271 : : * Used to exit simply when nprocs hits zero, but in this testcase:
2272 : : * int main(void) { _exit(!!fork()); }
2273 : : * under strace -f, parent sometimes (rarely) manages
2274 : : * to exit before we see the first stop of the child,
2275 : : * and we are losing track of it:
2276 : : * 19923 clone(...) = 19924
2277 : : * 19923 exit_group(1) = ?
2278 : : * 19923 +++ exited with 1 +++
2279 : : * Exiting only when wait() returns ECHILD works better.
2280 : : */
2281 [ + + ]: 74245622 : if (popen_pid != 0) {
2282 : : /* However, if -o|logger is in use, we can't do that.
2283 : : * Can work around that by double-forking the logger,
2284 : : * but that loses the ability to wait for its completion
2285 : : * on exit. Oh well...
2286 : : */
2287 [ + + ]: 300996 : if (nprocs == 0)
2288 : : return TE_BREAK;
2289 : : }
2290 : :
2291 [ + + ]: 74245616 : if (interactive)
2292 : 215418 : sigprocmask(SIG_SETMASK, &start_set, NULL);
2293 [ + + ]: 74245616 : pid = wait4(-1, pstatus, __WALL, (cflag ? &ru : NULL));
2294 : 74245616 : wait_errno = errno;
2295 [ + + ]: 74245616 : if (interactive)
2296 : 215418 : sigprocmask(SIG_SETMASK, &blocked_set, NULL);
2297 : :
2298 [ + + ]: 74245616 : if (pid < 0) {
2299 [ + + ]: 9481 : if (wait_errno == EINTR)
2300 : : return TE_NEXT;
2301 [ + - ][ - + ]: 9475 : if (nprocs == 0 && wait_errno == ECHILD)
2302 : : return TE_BREAK;
2303 : : /*
2304 : : * If nprocs > 0, ECHILD is not expected,
2305 : : * treat it as any other error here:
2306 : : */
2307 : 0 : errno = wait_errno;
2308 : 0 : perror_msg_and_die("wait4(__WALL)");
2309 : : }
2310 : :
2311 : 74236135 : status = *pstatus;
2312 : :
2313 [ - + ]: 74236135 : if (pid == popen_pid) {
2314 [ # # ]: 0 : if (!WIFSTOPPED(status))
2315 : 0 : popen_pid = 0;
2316 : : return TE_NEXT;
2317 : : }
2318 : :
2319 [ + + ]: 74236135 : if (debug_flag)
2320 : 28444 : print_debug_info(pid, status);
2321 : :
2322 : : /* Look up 'pid' in our table. */
2323 : 74236135 : tcp = pid2tcb(pid);
2324 : :
2325 [ + + ]: 74236135 : if (!tcp) {
2326 : 3458 : tcp = maybe_allocate_tcb(pid, status);
2327 [ + + ]: 3458 : if (!tcp)
2328 : : return TE_NEXT;
2329 : : }
2330 : :
2331 : 74236133 : clear_regs();
2332 : :
2333 : : /* Set current output file */
2334 : 74236133 : current_tcp = tcp;
2335 : :
2336 [ + + ]: 74236133 : if (cflag) {
2337 : 124696 : tv_sub(&tcp->dtime, &ru.ru_stime, &tcp->stime);
2338 : 124696 : tcp->stime = ru.ru_stime;
2339 : : }
2340 : :
2341 [ + + ]: 74236133 : if (WIFSIGNALED(status))
2342 : : return TE_SIGNALLED;
2343 : :
2344 [ + + ]: 74236123 : if (WIFEXITED(status))
2345 : : return TE_EXITED;
2346 : :
2347 : : /*
2348 : : * As WCONTINUED flag has not been specified to wait4,
2349 : : * it cannot be WIFCONTINUED(status), so the only case
2350 : : * that remains is WIFSTOPPED(status).
2351 : : */
2352 : :
2353 : : /* Is this the very first time we see this tracee stopped? */
2354 [ + + ]: 74223196 : if (tcp->flags & TCB_STARTUP)
2355 : 12954 : startup_tcb(tcp);
2356 : :
2357 : 74223196 : const unsigned int sig = WSTOPSIG(status);
2358 : 74223196 : const unsigned int event = (unsigned int) status >> 16;
2359 : :
2360 [ + + + + : 74223196 : switch (event) {
+ ]
2361 : : case 0:
2362 : : /*
2363 : : * Is this post-attach SIGSTOP?
2364 : : * Interestingly, the process may stop
2365 : : * with STOPSIG equal to some other signal
2366 : : * than SIGSTOP if we happened to attach
2367 : : * just before the process takes a signal.
2368 : : */
2369 [ - + ][ # # ]: 74174870 : if (sig == SIGSTOP && (tcp->flags & TCB_IGNORE_ONE_SIGSTOP)) {
2370 [ # # ]: 0 : if (debug_flag)
2371 : 0 : error_msg("ignored SIGSTOP on pid %d", tcp->pid);
2372 : 0 : tcp->flags &= ~TCB_IGNORE_ONE_SIGSTOP;
2373 : 0 : return TE_RESTART;
2374 [ + + ]: 74174870 : } else if (sig == syscall_trap_sig) {
2375 : : return TE_SYSCALL_STOP;
2376 : : } else {
2377 : 42544 : *si = (siginfo_t) {};
2378 : : /*
2379 : : * True if tracee is stopped by signal
2380 : : * (as opposed to "tracee received signal").
2381 : : * TODO: shouldn't we check for errno == EINVAL too?
2382 : : * We can get ESRCH instead, you know...
2383 : : */
2384 : 42544 : bool stopped = ptrace(PTRACE_GETSIGINFO, pid, 0, si) < 0;
2385 [ + - ]: 42544 : return stopped ? TE_GROUP_STOP : TE_SIGNAL_DELIVERY_STOP;
2386 : : }
2387 : : break;
2388 : : #if USE_SEIZE
2389 : : case PTRACE_EVENT_STOP:
2390 : : /*
2391 : : * PTRACE_INTERRUPT-stop or group-stop.
2392 : : * PTRACE_INTERRUPT-stop has sig == SIGTRAP here.
2393 : : */
2394 [ + + ]: 22436 : switch (sig) {
2395 : : case SIGSTOP:
2396 : : case SIGTSTP:
2397 : : case SIGTTIN:
2398 : : case SIGTTOU:
2399 : : return TE_GROUP_STOP;
2400 : : }
2401 : 12954 : return TE_RESTART;
2402 : : #endif
2403 : : case PTRACE_EVENT_EXEC:
2404 : : return TE_STOP_BEFORE_EXECVE;
2405 : : case PTRACE_EVENT_EXIT:
2406 : 12940 : return TE_STOP_BEFORE_EXIT;
2407 : : default:
2408 : 3456 : return TE_RESTART;
2409 : : }
2410 : : }
2411 : :
2412 : : static int
2413 : 73831154 : trace_syscall(struct tcb *tcp, unsigned int *sig)
2414 : : {
2415 [ + + ]: 73831154 : if (entering(tcp)) {
2416 : 36922021 : int res = syscall_entering_decode(tcp);
2417 [ + - - ]: 36922021 : switch (res) {
2418 : : case 0:
2419 : : return 0;
2420 : : case 1:
2421 : 36922021 : res = syscall_entering_trace(tcp, sig);
2422 : : }
2423 : 36922021 : syscall_entering_finish(tcp, res);
2424 : 36922021 : return res;
2425 : : } else {
2426 : 36909133 : struct timeval tv = {};
2427 : 36909133 : int res = syscall_exiting_decode(tcp, &tv);
2428 [ + + ]: 36909133 : if (res != 0) {
2429 : 447375 : res = syscall_exiting_trace(tcp, tv, res);
2430 : : }
2431 : 36909133 : syscall_exiting_finish(tcp);
2432 : : return res;
2433 : : }
2434 : : }
2435 : :
2436 : : /* Returns true iff the main trace loop has to continue. */
2437 : : static bool
2438 : 73944456 : dispatch_event(enum trace_event ret, int *pstatus, siginfo_t *si)
2439 : : {
2440 : 73944456 : unsigned int restart_op = PTRACE_SYSCALL;
2441 : 73944456 : unsigned int restart_sig = 0;
2442 : :
2443 [ + + + + : 73944456 : switch (ret) {
+ + + + +
+ ]
2444 : : case TE_BREAK:
2445 : : return false;
2446 : :
2447 : : case TE_NEXT:
2448 : 8 : return true;
2449 : :
2450 : : case TE_RESTART:
2451 : : break;
2452 : :
2453 : : case TE_SYSCALL_STOP:
2454 [ + - ]: 73831154 : if (trace_syscall(current_tcp, &restart_sig) < 0) {
2455 : : /*
2456 : : * ptrace() failed in trace_syscall().
2457 : : * Likely a result of process disappearing mid-flight.
2458 : : * Observed case: exit_group() or SIGKILL terminating
2459 : : * all processes in thread group.
2460 : : * We assume that ptrace error was caused by process death.
2461 : : * We used to detach(current_tcp) here, but since we no
2462 : : * longer implement "detach before death" policy/hack,
2463 : : * we can let this process to report its death to us
2464 : : * normally, via WIFEXITED or WIFSIGNALED wait status.
2465 : : */
2466 : : return true;
2467 : : }
2468 : : break;
2469 : :
2470 : : case TE_SIGNAL_DELIVERY_STOP:
2471 : 42544 : restart_sig = WSTOPSIG(*pstatus);
2472 : 42544 : print_stopped(current_tcp, si, restart_sig);
2473 : 42544 : break;
2474 : :
2475 : : case TE_SIGNALLED:
2476 : 10 : print_signalled(current_tcp, current_tcp->pid, *pstatus);
2477 : 10 : droptcb(current_tcp);
2478 : 10 : return true;
2479 : :
2480 : : case TE_GROUP_STOP:
2481 : 9482 : restart_sig = WSTOPSIG(*pstatus);
2482 : 9482 : print_stopped(current_tcp, NULL, restart_sig);
2483 [ + - ]: 9482 : if (use_seize) {
2484 : : /*
2485 : : * This ends ptrace-stop, but does *not* end group-stop.
2486 : : * This makes stopping signals work properly on straced
2487 : : * process (that is, process really stops. It used to
2488 : : * continue to run).
2489 : : */
2490 : 9482 : restart_op = PTRACE_LISTEN;
2491 : 9482 : restart_sig = 0;
2492 : : }
2493 : : break;
2494 : :
2495 : : case TE_EXITED:
2496 : 12927 : print_exited(current_tcp, current_tcp->pid, *pstatus);
2497 : 12927 : droptcb(current_tcp);
2498 : 12927 : return true;
2499 : :
2500 : : case TE_STOP_BEFORE_EXECVE:
2501 : : /*
2502 : : * Under Linux, execve changes pid to thread leader's pid,
2503 : : * and we see this changed pid on EVENT_EXEC and later,
2504 : : * execve sysexit. Leader "disappears" without exit
2505 : : * notification. Let user know that, drop leader's tcb,
2506 : : * and fix up pid in execve thread's tcb.
2507 : : * Effectively, execve thread's tcb replaces leader's tcb.
2508 : : *
2509 : : * BTW, leader is 'stuck undead' (doesn't report WIFEXITED
2510 : : * on exit syscall) in multithreaded programs exactly
2511 : : * in order to handle this case.
2512 : : *
2513 : : * PTRACE_GETEVENTMSG returns old pid starting from Linux 3.0.
2514 : : * On 2.6 and earlier, it can return garbage.
2515 : : */
2516 [ + - ]: 9494 : if (os_release >= KERNEL_VERSION(3, 0, 0))
2517 : 9494 : current_tcp = maybe_switch_tcbs(current_tcp, current_tcp->pid);
2518 : :
2519 [ + + ]: 9494 : if (detach_on_execve) {
2520 [ + + ]: 4 : if (current_tcp->flags & TCB_SKIP_DETACH_ON_FIRST_EXEC) {
2521 : 2 : current_tcp->flags &= ~TCB_SKIP_DETACH_ON_FIRST_EXEC;
2522 : : } else {
2523 : 2 : detach(current_tcp); /* do "-b execve" thingy */
2524 : 2 : return true;
2525 : : }
2526 : : }
2527 : : break;
2528 : :
2529 : : case TE_STOP_BEFORE_EXIT:
2530 : 12940 : print_event_exit(current_tcp);
2531 : 12940 : break;
2532 : : }
2533 : :
2534 : : /* We handled quick cases, we are permitted to interrupt now. */
2535 [ + - ]: 73922022 : if (interrupted)
2536 : : return false;
2537 : :
2538 [ - + ]: 73922022 : if (ptrace_restart(restart_op, current_tcp, restart_sig) < 0) {
2539 : : /* Note: ptrace_restart emitted error message */
2540 : 0 : exit_code = 1;
2541 : 0 : return false;
2542 : : }
2543 : : return true;
2544 : : }
2545 : :
2546 : : #ifdef ENABLE_COVERAGE_GCOV
2547 : : extern void __gcov_flush(void);
2548 : : #endif
2549 : :
2550 : : static void ATTRIBUTE_NORETURN
2551 : 9487 : terminate(void)
2552 : : {
2553 : 9487 : cleanup();
2554 : 9487 : fflush(NULL);
2555 [ + + ]: 9487 : if (shared_log != stderr)
2556 : 8083 : fclose(shared_log);
2557 [ + + ]: 9487 : if (popen_pid) {
2558 [ - + ][ # # ]: 6 : while (waitpid(popen_pid, NULL, 0) < 0 && errno == EINTR)
2559 : : ;
2560 : : }
2561 [ + + ]: 9487 : if (exit_code > 0xff) {
2562 : : /* Avoid potential core file clobbering. */
2563 : 8 : struct_rlimit rlim = {0, 0};
2564 : 8 : set_rlimit(RLIMIT_CORE, &rlim);
2565 : :
2566 : : /* Child was killed by a signal, mimic that. */
2567 : 8 : exit_code &= 0xff;
2568 : 8 : signal(exit_code, SIG_DFL);
2569 : : #ifdef ENABLE_COVERAGE_GCOV
2570 : 8 : __gcov_flush();
2571 : : #endif
2572 : 2 : raise(exit_code);
2573 : :
2574 : : /* Unblock the signal. */
2575 : : sigset_t mask;
2576 : 2 : sigemptyset(&mask);
2577 : 2 : sigaddset(&mask, exit_code);
2578 : : #ifdef ENABLE_COVERAGE_GCOV
2579 : 2 : __gcov_flush();
2580 : : #endif
2581 : 0 : sigprocmask(SIG_UNBLOCK, &mask, NULL);
2582 : :
2583 : : /* Paranoia - what if this signal is not fatal?
2584 : : Exit with 128 + signo then. */
2585 : 0 : exit_code += 128;
2586 : : }
2587 : 9479 : exit(exit_code);
2588 : : }
2589 : :
2590 : : #ifdef USE_LUAJIT
2591 : : # include "luajit.h"
2592 : : #endif
2593 : :
2594 : : int
2595 : 10804 : main(int argc, char *argv[])
2596 : : {
2597 : 10804 : init(argc, argv);
2598 : :
2599 : 9490 : exit_code = !nprocs;
2600 : :
2601 : : #ifdef USE_LUAJIT
2602 [ + + ]: 9490 : if (script_L)
2603 : 9490 : run_luajit();
2604 : : #endif
2605 : :
2606 : : int status;
2607 : : siginfo_t si;
2608 [ + + ]: 73944155 : while (dispatch_event(next_event(&status, &si), &status, &si))
2609 : : ;
2610 : 9446 : terminate();
2611 : : }
|