forked from aosp-mirror/platform_external_strace
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstrace.c
2857 lines (2643 loc) · 65.2 KB
/
strace.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 1991, 1992 Paul Kranenburg <pk@cs.few.eur.nl>
* Copyright (c) 1993 Branko Lankester <branko@hacktic.nl>
* Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <jrs@world.std.com>
* Copyright (c) 1996-1999 Wichert Akkerman <wichert@cistron.nl>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* $Id$
*/
#include "defs.h"
#include <sys/types.h>
#include <signal.h>
#include <errno.h>
#include <sys/param.h>
#include <fcntl.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <pwd.h>
#include <grp.h>
#include <string.h>
#include <limits.h>
#include <dirent.h>
#ifdef LINUX
# include <asm/unistd.h>
# if defined __NR_tgkill
# define my_tgkill(pid, tid, sig) syscall (__NR_tgkill, (pid), (tid), (sig))
# elif defined __NR_tkill
# define my_tgkill(pid, tid, sig) syscall (__NR_tkill, (tid), (sig))
# else
/* kill() may choose arbitrarily the target task of the process group
while we later wait on a that specific TID. PID process waits become
TID task specific waits for a process under ptrace(2). */
# warning "Neither tkill(2) nor tgkill(2) available, risk of strace hangs!"
# define my_tgkill(pid, tid, sig) kill ((tid), (sig))
# endif
#endif
#if defined(IA64) && defined(LINUX)
# include <asm/ptrace_offsets.h>
#endif
#ifdef USE_PROCFS
#include <poll.h>
#endif
#ifdef SVR4
#include <sys/stropts.h>
#ifdef HAVE_MP_PROCFS
#ifdef HAVE_SYS_UIO_H
#include <sys/uio.h>
#endif
#endif
#endif
extern char **environ;
extern int optind;
extern char *optarg;
int debug = 0, followfork = 0;
unsigned int ptrace_setoptions = 0;
int dtime = 0, xflag = 0, qflag = 0;
cflag_t cflag = CFLAG_NONE;
static int iflag = 0, interactive = 0, pflag_seen = 0, rflag = 0, tflag = 0;
/*
* daemonized_tracer supports -D option.
* With this option, strace forks twice.
* Unlike normal case, with -D *grandparent* process exec's,
* becoming a traced process. Child exits (this prevents traced process
* from having children it doesn't expect to have), and grandchild
* attaches to grandparent similarly to strace -p PID.
* This allows for more transparent interaction in cases
* when process and its parent are communicating via signals,
* wait() etc. Without -D, strace process gets lodged in between,
* disrupting parent<->child link.
*/
static bool daemonized_tracer = 0;
/* Sometimes we want to print only succeeding syscalls. */
int not_failing_only = 0;
static int exit_code = 0;
static int strace_child = 0;
static char *username = NULL;
uid_t run_uid;
gid_t run_gid;
int acolumn = DEFAULT_ACOLUMN;
int max_strlen = DEFAULT_STRLEN;
static char *outfname = NULL;
FILE *outf;
static int curcol;
struct tcb **tcbtab;
unsigned int nprocs, tcbtabsize;
const char *progname;
extern char **environ;
static int detach(struct tcb *tcp, int sig);
static int trace(void);
static void cleanup(void);
static void interrupt(int sig);
static sigset_t empty_set, blocked_set;
#ifdef HAVE_SIG_ATOMIC_T
static volatile sig_atomic_t interrupted;
#else /* !HAVE_SIG_ATOMIC_T */
static volatile int interrupted;
#endif /* !HAVE_SIG_ATOMIC_T */
#ifdef USE_PROCFS
static struct tcb *pfd2tcb(int pfd);
static void reaper(int sig);
static void rebuild_pollv(void);
static struct pollfd *pollv;
#ifndef HAVE_POLLABLE_PROCFS
static void proc_poll_open(void);
static void proc_poller(int pfd);
struct proc_pollfd {
int fd;
int revents;
int pid;
};
static int poller_pid;
static int proc_poll_pipe[2] = { -1, -1 };
#endif /* !HAVE_POLLABLE_PROCFS */
#ifdef HAVE_MP_PROCFS
#define POLLWANT POLLWRNORM
#else
#define POLLWANT POLLPRI
#endif
#endif /* USE_PROCFS */
static void
usage(ofp, exitval)
FILE *ofp;
int exitval;
{
fprintf(ofp, "\
usage: strace [-CdDffhiqrtttTvVxx] [-a column] [-e expr] ... [-o file]\n\
[-p pid] ... [-s strsize] [-u username] [-E var=val] ...\n\
[command [arg ...]]\n\
or: strace -c [-D] [-e expr] ... [-O overhead] [-S sortby] [-E var=val] ...\n\
[command [arg ...]]\n\
-c -- count time, calls, and errors for each syscall and report summary\n\
-C -- like -c but also print regular output while processes are running\n\
-f -- follow forks, -ff -- with output into separate files\n\
-F -- attempt to follow vforks, -h -- print help message\n\
-i -- print instruction pointer at time of syscall\n\
-q -- suppress messages about attaching, detaching, etc.\n\
-r -- print relative timestamp, -t -- absolute timestamp, -tt -- with usecs\n\
-T -- print time spent in each syscall, -V -- print version\n\
-v -- verbose mode: print unabbreviated argv, stat, termio[s], etc. args\n\
-x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
-a column -- alignment COLUMN for printing syscall results (default %d)\n\
-e expr -- a qualifying expression: option=[!]all or option=[!]val1[,val2]...\n\
options: trace, abbrev, verbose, raw, signal, read, or write\n\
-o file -- send trace output to FILE instead of stderr\n\
-O overhead -- set overhead for tracing syscalls to OVERHEAD usecs\n\
-p pid -- trace process with process id PID, may be repeated\n\
-D -- run tracer process as a detached grandchild, not as parent\n\
-s strsize -- limit length of print strings to STRSIZE chars (default %d)\n\
-S sortby -- sort syscall counts by: time, calls, name, nothing (default %s)\n\
-u username -- run command as username handling setuid and/or setgid\n\
-E var=val -- put var=val in the environment for command\n\
-E var -- remove var from the environment for command\n\
" /* this is broken, so don't document it
-z -- print only succeeding syscalls\n\
*/
, DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
exit(exitval);
}
#ifdef SVR4
#ifdef MIPS
void
foobar()
{
}
#endif /* MIPS */
#endif /* SVR4 */
/* Glue for systems without a MMU that cannot provide fork() */
#ifdef HAVE_FORK
# define strace_vforked 0
#else
# define strace_vforked 1
# define fork() vfork()
#endif
static int
set_cloexec_flag(int fd)
{
int flags, newflags;
if ((flags = fcntl(fd, F_GETFD, 0)) < 0)
{
fprintf(stderr, "%s: fcntl F_GETFD: %s\n",
progname, strerror(errno));
return -1;
}
newflags = flags | FD_CLOEXEC;
if (flags == newflags)
return 0;
if (fcntl(fd, F_SETFD, newflags) < 0)
{
fprintf(stderr, "%s: fcntl F_SETFD: %s\n",
progname, strerror(errno));
return -1;
}
return 0;
}
/*
* When strace is setuid executable, we have to swap uids
* before and after filesystem and process management operations.
*/
static void
swap_uid(void)
{
#ifndef SVR4
int euid = geteuid(), uid = getuid();
if (euid != uid && setreuid(euid, uid) < 0)
{
fprintf(stderr, "%s: setreuid: %s\n",
progname, strerror(errno));
exit(1);
}
#endif
}
#if _LFS64_LARGEFILE
# define fopen_for_output fopen64
#else
# define fopen_for_output fopen
#endif
static FILE *
strace_fopen(const char *path, const char *mode)
{
FILE *fp;
swap_uid();
if ((fp = fopen_for_output(path, mode)) == NULL)
fprintf(stderr, "%s: can't fopen '%s': %s\n",
progname, path, strerror(errno));
swap_uid();
if (fp && set_cloexec_flag(fileno(fp)) < 0)
{
fclose(fp);
fp = NULL;
}
return fp;
}
static int popen_pid = -1;
#ifndef _PATH_BSHELL
# define _PATH_BSHELL "/bin/sh"
#endif
/*
* We cannot use standard popen(3) here because we have to distinguish
* popen child process from other processes we trace, and standard popen(3)
* does not export its child's pid.
*/
static FILE *
strace_popen(const char *command)
{
int fds[2];
swap_uid();
if (pipe(fds) < 0)
{
fprintf(stderr, "%s: pipe: %s\n",
progname, strerror(errno));
swap_uid();
return NULL;
}
if (set_cloexec_flag(fds[1]) < 0)
{
close(fds[0]);
close(fds[1]);
swap_uid();
return NULL;
}
if ((popen_pid = fork()) == -1)
{
fprintf(stderr, "%s: fork: %s\n",
progname, strerror(errno));
close(fds[0]);
close(fds[1]);
swap_uid();
return NULL;
}
if (popen_pid)
{
/* parent */
close(fds[0]);
swap_uid();
return fdopen(fds[1], "w");
} else
{
/* child */
close(fds[1]);
if (fds[0] && (dup2(fds[0], 0) || close(fds[0])))
{
fprintf(stderr, "%s: dup2: %s\n",
progname, strerror(errno));
_exit(1);
}
execl(_PATH_BSHELL, "sh", "-c", command, NULL);
fprintf(stderr, "%s: execl: %s: %s\n",
progname, _PATH_BSHELL, strerror(errno));
_exit(1);
}
}
static int
newoutf(struct tcb *tcp)
{
if (outfname && followfork > 1) {
char name[520 + sizeof(int) * 3];
FILE *fp;
sprintf(name, "%.512s.%u", outfname, tcp->pid);
if ((fp = strace_fopen(name, "w")) == NULL)
return -1;
tcp->outf = fp;
}
return 0;
}
static void
startup_attach(void)
{
int tcbi;
struct tcb *tcp;
/*
* Block user interruptions as we would leave the traced
* process stopped (process state T) if we would terminate in
* between PTRACE_ATTACH and wait4 () on SIGSTOP.
* We rely on cleanup () from this point on.
*/
if (interactive)
sigprocmask(SIG_BLOCK, &blocked_set, NULL);
if (daemonized_tracer) {
pid_t pid = fork();
if (pid < 0) {
_exit(1);
}
if (pid) { /* parent */
/*
* Wait for child to attach to straced process
* (our parent). Child SIGKILLs us after it attached.
* Parent's wait() is unblocked by our death,
* it proceeds to exec the straced program.
*/
pause();
_exit(0); /* paranoia */
}
}
for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
tcp = tcbtab[tcbi];
if (!(tcp->flags & TCB_INUSE) || !(tcp->flags & TCB_ATTACHED))
continue;
#ifdef LINUX
if (tcp->flags & TCB_CLONE_THREAD)
continue;
#endif
/* Reinitialize the output since it may have changed. */
tcp->outf = outf;
if (newoutf(tcp) < 0)
exit(1);
#ifdef USE_PROCFS
if (proc_open(tcp, 1) < 0) {
fprintf(stderr, "trouble opening proc file\n");
droptcb(tcp);
continue;
}
#else /* !USE_PROCFS */
# ifdef LINUX
if (followfork && !daemonized_tracer) {
char procdir[sizeof("/proc/%d/task") + sizeof(int) * 3];
DIR *dir;
sprintf(procdir, "/proc/%d/task", tcp->pid);
dir = opendir(procdir);
if (dir != NULL) {
unsigned int ntid = 0, nerr = 0;
struct dirent *de;
int tid;
while ((de = readdir(dir)) != NULL) {
if (de->d_fileno == 0)
continue;
tid = atoi(de->d_name);
if (tid <= 0)
continue;
++ntid;
if (ptrace(PTRACE_ATTACH, tid, (char *) 1, 0) < 0)
++nerr;
else if (tid != tcbtab[tcbi]->pid) {
tcp = alloctcb(tid);
tcp->flags |= TCB_ATTACHED|TCB_CLONE_THREAD|TCB_FOLLOWFORK;
tcbtab[tcbi]->nchildren++;
tcbtab[tcbi]->nclone_threads++;
tcp->parent = tcbtab[tcbi];
}
if (interactive) {
sigprocmask(SIG_SETMASK, &empty_set, NULL);
if (interrupted)
return;
sigprocmask(SIG_BLOCK, &blocked_set, NULL);
}
}
closedir(dir);
ntid -= nerr;
if (ntid == 0) {
perror("attach: ptrace(PTRACE_ATTACH, ...)");
droptcb(tcp);
continue;
}
if (!qflag) {
fprintf(stderr, ntid > 1
? "Process %u attached with %u threads - interrupt to quit\n"
: "Process %u attached - interrupt to quit\n",
tcbtab[tcbi]->pid, ntid);
}
continue;
} /* if (opendir worked) */
} /* if (-f) */
# endif
if (ptrace(PTRACE_ATTACH, tcp->pid, (char *) 1, 0) < 0) {
perror("attach: ptrace(PTRACE_ATTACH, ...)");
droptcb(tcp);
continue;
}
/* INTERRUPTED is going to be checked at the top of TRACE. */
if (daemonized_tracer) {
/*
* It is our grandparent we trace, not a -p PID.
* Don't want to just detach on exit, so...
*/
tcp->flags &= ~TCB_ATTACHED;
/*
* Make parent go away.
* Also makes grandparent's wait() unblock.
*/
kill(getppid(), SIGKILL);
}
#endif /* !USE_PROCFS */
if (!qflag)
fprintf(stderr,
"Process %u attached - interrupt to quit\n",
tcp->pid);
}
if (interactive)
sigprocmask(SIG_SETMASK, &empty_set, NULL);
}
static void
startup_child (char **argv)
{
struct stat statbuf;
const char *filename;
char pathname[MAXPATHLEN];
int pid = 0;
struct tcb *tcp;
filename = argv[0];
if (strchr(filename, '/')) {
if (strlen(filename) > sizeof pathname - 1) {
errno = ENAMETOOLONG;
perror("strace: exec");
exit(1);
}
strcpy(pathname, filename);
}
#ifdef USE_DEBUGGING_EXEC
/*
* Debuggers customarily check the current directory
* first regardless of the path but doing that gives
* security geeks a panic attack.
*/
else if (stat(filename, &statbuf) == 0)
strcpy(pathname, filename);
#endif /* USE_DEBUGGING_EXEC */
else {
const char *path;
int m, n, len;
for (path = getenv("PATH"); path && *path; path += m) {
if (strchr(path, ':')) {
n = strchr(path, ':') - path;
m = n + 1;
}
else
m = n = strlen(path);
if (n == 0) {
if (!getcwd(pathname, MAXPATHLEN))
continue;
len = strlen(pathname);
}
else if (n > sizeof pathname - 1)
continue;
else {
strncpy(pathname, path, n);
len = n;
}
if (len && pathname[len - 1] != '/')
pathname[len++] = '/';
strcpy(pathname + len, filename);
if (stat(pathname, &statbuf) == 0 &&
/* Accept only regular files
with some execute bits set.
XXX not perfect, might still fail */
S_ISREG(statbuf.st_mode) &&
(statbuf.st_mode & 0111))
break;
}
}
if (stat(pathname, &statbuf) < 0) {
fprintf(stderr, "%s: %s: command not found\n",
progname, filename);
exit(1);
}
strace_child = pid = fork();
if (pid < 0) {
perror("strace: fork");
cleanup();
exit(1);
}
if ((pid != 0 && daemonized_tracer) /* parent: to become a traced process */
|| (pid == 0 && !daemonized_tracer) /* child: to become a traced process */
) {
pid = getpid();
#ifdef USE_PROCFS
if (outf != stderr) close (fileno (outf));
#ifdef MIPS
/* Kludge for SGI, see proc_open for details. */
sa.sa_handler = foobar;
sa.sa_flags = 0;
sigemptyset(&sa.sa_mask);
sigaction(SIGINT, &sa, NULL);
#endif /* MIPS */
#ifndef FREEBSD
pause();
#else /* FREEBSD */
kill(pid, SIGSTOP); /* stop HERE */
#endif /* FREEBSD */
#else /* !USE_PROCFS */
if (outf!=stderr)
close(fileno (outf));
if (!daemonized_tracer) {
if (ptrace(PTRACE_TRACEME, 0, (char *) 1, 0) < 0) {
perror("strace: ptrace(PTRACE_TRACEME, ...)");
exit(1);
}
if (debug)
kill(pid, SIGSTOP);
}
if (username != NULL || geteuid() == 0) {
uid_t run_euid = run_uid;
gid_t run_egid = run_gid;
if (statbuf.st_mode & S_ISUID)
run_euid = statbuf.st_uid;
if (statbuf.st_mode & S_ISGID)
run_egid = statbuf.st_gid;
/*
* It is important to set groups before we
* lose privileges on setuid.
*/
if (username != NULL) {
if (initgroups(username, run_gid) < 0) {
perror("initgroups");
exit(1);
}
if (setregid(run_gid, run_egid) < 0) {
perror("setregid");
exit(1);
}
if (setreuid(run_uid, run_euid) < 0) {
perror("setreuid");
exit(1);
}
}
}
else
setreuid(run_uid, run_uid);
if (!daemonized_tracer) {
/*
* Induce an immediate stop so that the parent
* will resume us with PTRACE_SYSCALL and display
* this execve call normally.
* Unless of course we're on a no-MMU system where
* we vfork()-ed, so we cannot stop the child.
*/
if (!strace_vforked)
kill(getpid(), SIGSTOP);
} else {
struct sigaction sv_sigchld;
sigaction(SIGCHLD, NULL, &sv_sigchld);
/*
* Make sure it is not SIG_IGN, otherwise wait
* will not block.
*/
signal(SIGCHLD, SIG_DFL);
/*
* Wait for grandchild to attach to us.
* It kills child after that, and wait() unblocks.
*/
alarm(3);
wait(NULL);
alarm(0);
sigaction(SIGCHLD, &sv_sigchld, NULL);
}
#endif /* !USE_PROCFS */
execv(pathname, argv);
perror("strace: exec");
_exit(1);
}
/* We are the tracer. */
tcp = alloctcb(daemonized_tracer ? getppid() : pid);
if (daemonized_tracer) {
/* We want subsequent startup_attach() to attach to it. */
tcp->flags |= TCB_ATTACHED;
}
#ifdef USE_PROCFS
if (proc_open(tcp, 0) < 0) {
fprintf(stderr, "trouble opening proc file\n");
cleanup();
exit(1);
}
#endif /* USE_PROCFS */
}
#ifdef LINUX
/*
* Test whether the kernel support PTRACE_O_TRACECLONE et al options.
* First fork a new child, call ptrace with PTRACE_SETOPTIONS on it,
* and then see which options are supported by the kernel.
*/
static int
test_ptrace_setoptions(void)
{
int pid, expected_grandchild = 0, found_grandchild = 0;
const unsigned int test_options = PTRACE_O_TRACECLONE |
PTRACE_O_TRACEFORK |
PTRACE_O_TRACEVFORK;
if ((pid = fork()) < 0)
return -1;
else if (pid == 0) {
if (ptrace(PTRACE_TRACEME, 0, (char *)1, 0) < 0)
_exit(1);
kill(getpid(), SIGSTOP);
_exit(fork() < 0);
}
while (1) {
int status, tracee_pid;
tracee_pid = wait(&status);
if (tracee_pid == -1) {
if (errno == EINTR)
continue;
else if (errno == ECHILD)
break;
perror("test_ptrace_setoptions");
return -1;
}
if (tracee_pid != pid) {
found_grandchild = tracee_pid;
if (ptrace(PTRACE_CONT, tracee_pid, 0, 0) < 0 &&
errno != ESRCH)
kill(tracee_pid, SIGKILL);
}
else if (WIFSTOPPED(status)) {
switch (WSTOPSIG(status)) {
case SIGSTOP:
if (ptrace(PTRACE_SETOPTIONS, pid,
NULL, test_options) < 0) {
kill(pid, SIGKILL);
return -1;
}
break;
case SIGTRAP:
if (status >> 16 == PTRACE_EVENT_FORK) {
long msg = 0;
if (ptrace(PTRACE_GETEVENTMSG, pid,
NULL, (long) &msg) == 0)
expected_grandchild = msg;
}
break;
}
if (ptrace(PTRACE_SYSCALL, pid, 0, 0) < 0 &&
errno != ESRCH)
kill(pid, SIGKILL);
}
}
if (expected_grandchild && expected_grandchild == found_grandchild)
ptrace_setoptions |= test_options;
return 0;
}
#endif
int
main(int argc, char *argv[])
{
struct tcb *tcp;
int c, pid = 0;
int optF = 0;
struct sigaction sa;
static char buf[BUFSIZ];
progname = argv[0] ? argv[0] : "strace";
/* Allocate the initial tcbtab. */
tcbtabsize = argc; /* Surely enough for all -p args. */
if ((tcbtab = calloc(tcbtabsize, sizeof tcbtab[0])) == NULL) {
fprintf(stderr, "%s: out of memory\n", progname);
exit(1);
}
if ((tcbtab[0] = calloc(tcbtabsize, sizeof tcbtab[0][0])) == NULL) {
fprintf(stderr, "%s: out of memory\n", progname);
exit(1);
}
for (tcp = tcbtab[0]; tcp < &tcbtab[0][tcbtabsize]; ++tcp)
tcbtab[tcp - tcbtab[0]] = &tcbtab[0][tcp - tcbtab[0]];
outf = stderr;
interactive = 1;
set_sortby(DEFAULT_SORTBY);
set_personality(DEFAULT_PERSONALITY);
qualify("trace=all");
qualify("abbrev=all");
qualify("verbose=all");
qualify("signal=all");
while ((c = getopt(argc, argv,
"+cCdfFhiqrtTvVxz"
#ifndef USE_PROCFS
"D"
#endif
"a:e:o:O:p:s:S:u:E:")) != EOF) {
switch (c) {
case 'c':
if (cflag == CFLAG_BOTH) {
fprintf(stderr, "%s: -c and -C are mutually exclusive options\n",
progname);
exit(1);
}
cflag = CFLAG_ONLY_STATS;
break;
case 'C':
if (cflag == CFLAG_ONLY_STATS) {
fprintf(stderr, "%s: -c and -C are mutually exclusive options\n",
progname);
exit(1);
}
cflag = CFLAG_BOTH;
break;
case 'd':
debug++;
break;
#ifndef USE_PROCFS
case 'D':
daemonized_tracer = 1;
break;
#endif
case 'F':
optF = 1;
break;
case 'f':
followfork++;
break;
case 'h':
usage(stdout, 0);
break;
case 'i':
iflag++;
break;
case 'q':
qflag++;
break;
case 'r':
rflag++;
tflag++;
break;
case 't':
tflag++;
break;
case 'T':
dtime++;
break;
case 'x':
xflag++;
break;
case 'v':
qualify("abbrev=none");
break;
case 'V':
printf("%s -- version %s\n", PACKAGE_NAME, VERSION);
exit(0);
break;
case 'z':
not_failing_only = 1;
break;
case 'a':
acolumn = atoi(optarg);
break;
case 'e':
qualify(optarg);
break;
case 'o':
outfname = strdup(optarg);
break;
case 'O':
set_overhead(atoi(optarg));
break;
case 'p':
if ((pid = atoi(optarg)) <= 0) {
fprintf(stderr, "%s: Invalid process id: %s\n",
progname, optarg);
break;
}
if (pid == getpid()) {
fprintf(stderr, "%s: I'm sorry, I can't let you do that, Dave.\n", progname);
break;
}
tcp = alloc_tcb(pid, 0);
tcp->flags |= TCB_ATTACHED;
pflag_seen++;
break;
case 's':
max_strlen = atoi(optarg);
if (max_strlen < 0) {
fprintf(stderr,
"%s: invalid -s argument: %s\n",
progname, optarg);
exit(1);
}
break;
case 'S':
set_sortby(optarg);
break;
case 'u':
username = strdup(optarg);
break;
case 'E':
if (putenv(optarg) < 0) {
fprintf(stderr, "%s: out of memory\n",
progname);
exit(1);
}
break;
default:
usage(stderr, 1);
break;
}
}
if ((optind == argc) == !pflag_seen)
usage(stderr, 1);
if (pflag_seen && daemonized_tracer) {
fprintf(stderr,
"%s: -D and -p are mutually exclusive options\n",
progname);
exit(1);
}
if (!followfork)
followfork = optF;
if (followfork > 1 && cflag) {
fprintf(stderr,
"%s: (-c or -C) and -ff are mutually exclusive options\n",
progname);
exit(1);
}
/* See if they want to run as another user. */
if (username != NULL) {
struct passwd *pent;
if (getuid() != 0 || geteuid() != 0) {
fprintf(stderr,
"%s: you must be root to use the -u option\n",
progname);
exit(1);
}
if ((pent = getpwnam(username)) == NULL) {
fprintf(stderr, "%s: cannot find user `%s'\n",
progname, username);
exit(1);
}
run_uid = pent->pw_uid;
run_gid = pent->pw_gid;
}
else {
run_uid = getuid();
run_gid = getgid();
}
#ifdef LINUX
if (followfork) {
if (test_ptrace_setoptions() < 0) {
fprintf(stderr,
"Test for options supported by PTRACE_SETOPTIONS "
"failed, giving up using this feature.\n");
ptrace_setoptions = 0;
}
if (debug)
fprintf(stderr, "ptrace_setoptions = %#x\n",
ptrace_setoptions);
}
#endif
/* Check if they want to redirect the output. */
if (outfname) {
/* See if they want to pipe the output. */
if (outfname[0] == '|' || outfname[0] == '!') {
/*
* We can't do the <outfname>.PID funny business
* when using popen, so prohibit it.
*/
if (followfork > 1) {
fprintf(stderr, "\
%s: piping the output and -ff are mutually exclusive options\n",
progname);
exit(1);
}
if ((outf = strace_popen(outfname + 1)) == NULL)
exit(1);
}
else if (followfork <= 1 &&
(outf = strace_fopen(outfname, "w")) == NULL)
exit(1);
}
if (!outfname || outfname[0] == '|' || outfname[0] == '!')
setvbuf(outf, buf, _IOLBF, BUFSIZ);
if (outfname && optind < argc) {
interactive = 0;