-
Notifications
You must be signed in to change notification settings - Fork 9
/
strace.c
2232 lines (2036 loc) · 55.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 <[email protected]>
* Copyright (c) 1993 Branko Lankester <[email protected]>
* Copyright (c) 1993, 1994, 1995, 1996 Rick Sladkey <[email protected]>
* Copyright (c) 1996-1999 Wichert Akkerman <[email protected]>
* 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.
*/
#include "defs.h"
#include <stdarg.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 <dirent.h>
#include <sys/utsname.h>
#if defined(IA64)
# include <asm/ptrace_offsets.h>
#endif
/* In some libc, these aren't declared. Do it ourself: */
extern char **environ;
extern int optind;
extern char *optarg;
#if defined __NR_tkill
# define my_tkill(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_tkill(tid, sig) kill((tid), (sig))
#endif
#undef KERNEL_VERSION
#define KERNEL_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))
cflag_t cflag = CFLAG_NONE;
unsigned int followfork = 0;
unsigned int ptrace_setoptions = 0;
unsigned int xflag = 0;
bool debug_flag = 0;
bool Tflag = 0;
bool qflag = 0;
/* Which WSTOPSIG(status) value marks syscall traps? */
static unsigned int syscall_trap_sig = SIGTRAP;
static unsigned int tflag = 0;
static bool iflag = 0;
static bool rflag = 0;
static bool print_pid_pfx = 0;
/* -I n */
enum {
INTR_NOT_SET = 0,
INTR_ANYWHERE = 1, /* don't block/ignore any signals */
INTR_WHILE_WAIT = 2, /* block fatal signals while decoding syscall. default */
INTR_NEVER = 3, /* block fatal signals. default if '-o FILE PROG' */
INTR_BLOCK_TSTP_TOO = 4, /* block fatal signals and SIGTSTP (^Z) */
NUM_INTR_OPTS
};
static int opt_intr;
/* We play with signal mask only if this mode is active: */
#define interactive (opt_intr == INTR_WHILE_WAIT)
/*
* 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;
#ifdef USE_SEIZE
static int post_attach_sigstop = TCB_IGNORE_ONE_SIGSTOP;
# define use_seize (post_attach_sigstop == 0)
#else
# define post_attach_sigstop TCB_IGNORE_ONE_SIGSTOP
# define use_seize 0
#endif
/* Sometimes we want to print only succeeding syscalls. */
bool not_failing_only = 0;
/* Show path associated with fd arguments */
bool show_fd_path = 0;
/* are we filtering traces based on paths? */
bool tracing_paths = 0;
static bool detach_on_execve = 0;
static bool skip_startup_execve = 0;
static int exit_code = 0;
static int strace_child = 0;
static int strace_tracer_pid = 0;
static char *username = NULL;
static uid_t run_uid;
static gid_t run_gid;
unsigned int max_strlen = DEFAULT_STRLEN;
static int acolumn = DEFAULT_ACOLUMN;
static char *acolumn_spaces;
static char *outfname = NULL;
/* If -ff, points to stderr. Else, it's our common output log */
static FILE *shared_log;
struct tcb *printing_tcp = NULL;
static struct tcb *current_tcp;
static struct tcb **tcbtab;
static unsigned int nprocs, tcbtabsize;
static const char *progname;
static unsigned os_release; /* generated from uname()'s u.release */
static int detach(struct tcb *tcp);
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
static volatile int interrupted;
#endif
#ifndef HAVE_STRERROR
#if !HAVE_DECL_SYS_ERRLIST
extern int sys_nerr;
extern char *sys_errlist[];
#endif
const char *
strerror(int err_no)
{
static char buf[sizeof("Unknown error %d") + sizeof(int)*3];
if (err_no < 1 || err_no >= sys_nerr) {
sprintf(buf, "Unknown error %d", err_no);
return buf;
}
return sys_errlist[err_no];
}
#endif /* HAVE_STERRROR */
static void
usage(FILE *ofp, int exitval)
{
fprintf(ofp, "\
usage: strace [-CdffhiqrtttTvVxxy] [-I n] [-e expr]...\n\
[-a column] [-o file] [-s strsize] [-P path]...\n\
-p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
or: strace -c[df] [-I n] [-e expr]... [-O overhead] [-S sortby]\n\
-p pid... / [-D] [-E var=val]... [-u username] PROG [ARGS]\n\
-c -- count time, calls, and errors for each syscall and report summary\n\
-C -- like -c but also print regular output\n\
-d -- enable debug output to stderr\n\
-D -- run tracer process as a detached grandchild, not as parent\n\
-f -- follow forks, -ff -- with output into separate files\n\
-F -- attempt to follow vforks (deprecated, use -f)\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\n\
-v -- verbose mode: print unabbreviated argv, stat, termios, etc. args\n\
-x -- print non-ascii strings in hex, -xx -- print all strings in hex\n\
-y -- print paths associated with file descriptor arguments\n\
-h -- print help message, -V -- print version\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\
-I interruptible --\n\
1: no signals are blocked\n\
2: fatal signals are blocked while decoding syscall (default)\n\
3: fatal signals are always blocked (default if '-o FILE PROG')\n\
4: fatal signals and SIGTSTP (^Z) are always blocked\n\
(useful to make 'strace -o FILE PROG' not stop on ^Z)\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\
-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\
-P path -- trace accesses to path\n\
"
/* this is broken, so don't document it
-z -- print only succeeding syscalls\n\
*/
/* experimental, don't document it yet (option letter may change in the future!)
-b -- detach on successful execve\n\
*/
, DEFAULT_ACOLUMN, DEFAULT_STRLEN, DEFAULT_SORTBY);
exit(exitval);
}
static void die(void) __attribute__ ((noreturn));
static void die(void)
{
if (strace_tracer_pid == getpid()) {
cflag = 0;
cleanup();
}
exit(1);
}
static void verror_msg(int err_no, const char *fmt, va_list p)
{
char *msg;
fflush(NULL);
/* We want to print entire message with single fprintf to ensure
* message integrity if stderr is shared with other programs.
* Thus we use vasprintf + single fprintf.
*/
msg = NULL;
if (vasprintf(&msg, fmt, p) >= 0) {
if (err_no)
fprintf(stderr, "%s: %s: %s\n", progname, msg, strerror(err_no));
else
fprintf(stderr, "%s: %s\n", progname, msg);
free(msg);
} else {
/* malloc in vasprintf failed, try it without malloc */
fprintf(stderr, "%s: ", progname);
vfprintf(stderr, fmt, p);
if (err_no)
fprintf(stderr, ": %s\n", strerror(err_no));
else
putc('\n', stderr);
}
/* We don't switch stderr to buffered, thus fprintf(stderr)
* always flushes its output and this is not necessary: */
/* fflush(stderr); */
}
void error_msg(const char *fmt, ...)
{
va_list p;
va_start(p, fmt);
verror_msg(0, fmt, p);
va_end(p);
}
void error_msg_and_die(const char *fmt, ...)
{
va_list p;
va_start(p, fmt);
verror_msg(0, fmt, p);
die();
}
void perror_msg(const char *fmt, ...)
{
va_list p;
va_start(p, fmt);
verror_msg(errno, fmt, p);
va_end(p);
}
void perror_msg_and_die(const char *fmt, ...)
{
va_list p;
va_start(p, fmt);
verror_msg(errno, fmt, p);
die();
}
void die_out_of_memory(void)
{
static bool recursed = 0;
if (recursed)
exit(1);
recursed = 1;
error_msg_and_die("Out of memory");
}
static void
error_opt_arg(int opt, const char *arg)
{
error_msg_and_die("Invalid -%c argument: '%s'", opt, arg);
}
/* 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
#ifdef USE_SEIZE
static int
ptrace_attach_or_seize(int pid)
{
int r;
if (!use_seize)
return ptrace(PTRACE_ATTACH, pid, 0, 0);
r = ptrace(PTRACE_SEIZE, pid, 0, 0);
if (r)
return r;
r = ptrace(PTRACE_INTERRUPT, pid, 0, 0);
return r;
}
#else
# define ptrace_attach_or_seize(pid) ptrace(PTRACE_ATTACH, (pid), 0, 0)
#endif
/*
* Used when we want to unblock stopped traced process.
* Should be only used with PTRACE_CONT, PTRACE_DETACH and PTRACE_SYSCALL.
* Returns 0 on success or if error was ESRCH
* (presumably process was killed while we talk to it).
* Otherwise prints error message and returns -1.
*/
static int
ptrace_restart(int op, struct tcb *tcp, int sig)
{
int err;
const char *msg;
errno = 0;
ptrace(op, tcp->pid, (void *) 0, (long) sig);
err = errno;
if (!err)
return 0;
msg = "SYSCALL";
if (op == PTRACE_CONT)
msg = "CONT";
if (op == PTRACE_DETACH)
msg = "DETACH";
#ifdef PTRACE_LISTEN
if (op == PTRACE_LISTEN)
msg = "LISTEN";
#endif
/*
* Why curcol != 0? Otherwise sometimes we get this:
*
* 10252 kill(10253, SIGKILL) = 0
* <ptrace(SYSCALL,10252):No such process>10253 ...next decode...
*
* 10252 died after we retrieved syscall exit data,
* but before we tried to restart it. Log looks ugly.
*/
if (current_tcp && current_tcp->curcol != 0) {
tprintf(" <ptrace(%s):%s>\n", msg, strerror(err));
line_ended();
}
if (err == ESRCH)
return 0;
errno = err;
perror_msg("ptrace(PTRACE_%s,pid:%d,sig:%d)", msg, tcp->pid, sig);
return -1;
}
static void
set_cloexec_flag(int fd)
{
int flags, newflags;
flags = fcntl(fd, F_GETFD);
if (flags < 0) {
/* Can happen only if fd is bad.
* Should never happen: if it does, we have a bug
* in the caller. Therefore we just abort
* instead of propagating the error.
*/
perror_msg_and_die("fcntl(%d, F_GETFD)", fd);
}
newflags = flags | FD_CLOEXEC;
if (flags == newflags)
return;
fcntl(fd, F_SETFD, newflags); /* never fails */
}
static void kill_save_errno(pid_t pid, int sig)
{
int saved_errno = errno;
(void) kill(pid, sig);
errno = saved_errno;
}
/*
* When strace is setuid executable, we have to swap uids
* before and after filesystem and process management operations.
*/
static void
swap_uid(void)
{
int euid = geteuid(), uid = getuid();
if (euid != uid && setreuid(euid, uid) < 0) {
perror_msg_and_die("setreuid");
}
}
#if _LFS64_LARGEFILE
# define fopen_for_output fopen64
#else
# define fopen_for_output fopen
#endif
static FILE *
strace_fopen(const char *path)
{
FILE *fp;
swap_uid();
fp = fopen_for_output(path, "w");
if (!fp)
perror_msg_and_die("Can't fopen '%s'", path);
swap_uid();
set_cloexec_flag(fileno(fp));
return fp;
}
static int popen_pid = 0;
#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)
{
FILE *fp;
int fds[2];
swap_uid();
if (pipe(fds) < 0)
perror_msg_and_die("pipe");
set_cloexec_flag(fds[1]); /* never fails */
popen_pid = vfork();
if (popen_pid == -1)
perror_msg_and_die("vfork");
if (popen_pid == 0) {
/* child */
close(fds[1]);
if (fds[0] != 0) {
if (dup2(fds[0], 0))
perror_msg_and_die("dup2");
close(fds[0]);
}
execl(_PATH_BSHELL, "sh", "-c", command, NULL);
perror_msg_and_die("Can't execute '%s'", _PATH_BSHELL);
}
/* parent */
close(fds[0]);
swap_uid();
fp = fdopen(fds[1], "w");
if (!fp)
die_out_of_memory();
return fp;
}
void
tprintf(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
if (current_tcp) {
int n = strace_vfprintf(current_tcp->outf, fmt, args);
if (n < 0) {
if (current_tcp->outf != stderr)
perror(outfname == NULL
? "<writing to pipe>" : outfname);
} else
current_tcp->curcol += n;
}
va_end(args);
}
void
tprints(const char *str)
{
if (current_tcp) {
int n = fputs_unlocked(str, current_tcp->outf);
if (n >= 0) {
current_tcp->curcol += strlen(str);
return;
}
if (current_tcp->outf != stderr)
perror(!outfname ? "<writing to pipe>" : outfname);
}
}
void
line_ended(void)
{
if (current_tcp) {
current_tcp->curcol = 0;
fflush(current_tcp->outf);
}
if (printing_tcp) {
printing_tcp->curcol = 0;
printing_tcp = NULL;
}
}
void
printleader(struct tcb *tcp)
{
/* If -ff, "previous tcb we printed" is always the same as current,
* because we have per-tcb output files.
*/
if (followfork >= 2)
printing_tcp = tcp;
if (printing_tcp) {
current_tcp = printing_tcp;
if (printing_tcp->curcol != 0 && (followfork < 2 || printing_tcp == tcp)) {
/*
* case 1: we have a shared log (i.e. not -ff), and last line
* wasn't finished (same or different tcb, doesn't matter).
* case 2: split log, we are the same tcb, but our last line
* didn't finish ("SIGKILL nuked us after syscall entry" etc).
*/
tprints(" <unfinished ...>\n");
printing_tcp->curcol = 0;
}
}
printing_tcp = tcp;
current_tcp = tcp;
current_tcp->curcol = 0;
if (print_pid_pfx)
tprintf("%-5d ", tcp->pid);
else if (nprocs > 1 && !outfname)
tprintf("[pid %5u] ", tcp->pid);
if (tflag) {
char str[sizeof("HH:MM:SS")];
struct timeval tv, dtv;
static struct timeval otv;
gettimeofday(&tv, NULL);
if (rflag) {
if (otv.tv_sec == 0)
otv = tv;
tv_sub(&dtv, &tv, &otv);
tprintf("%6ld.%06ld ",
(long) dtv.tv_sec, (long) dtv.tv_usec);
otv = tv;
}
else if (tflag > 2) {
tprintf("%ld.%06ld ",
(long) tv.tv_sec, (long) tv.tv_usec);
}
else {
time_t local = tv.tv_sec;
strftime(str, sizeof(str), "%T", localtime(&local));
if (tflag > 1)
tprintf("%s.%06ld ", str, (long) tv.tv_usec);
else
tprintf("%s ", str);
}
}
if (iflag)
printcall(tcp);
}
void
tabto(void)
{
if (current_tcp->curcol < acolumn)
tprints(acolumn_spaces + current_tcp->curcol);
}
/* Should be only called directly *after successful attach* to a tracee.
* Otherwise, "strace -oFILE -ff -p<nonexistant_pid>"
* may create bogus empty FILE.<nonexistant_pid>, and then die.
*/
static void
newoutf(struct tcb *tcp)
{
tcp->outf = shared_log; /* if not -ff mode, the same file is for all */
if (followfork >= 2) {
char name[520 + sizeof(int) * 3];
sprintf(name, "%.512s.%u", outfname, tcp->pid);
tcp->outf = strace_fopen(name);
}
}
static void
expand_tcbtab(void)
{
/* Allocate some more TCBs and expand the table.
We don't want to relocate the TCBs because our
callers have pointers and it would be a pain.
So tcbtab is a table of pointers. Since we never
free the TCBs, we allocate a single chunk of many. */
int i = tcbtabsize;
struct tcb *newtcbs = calloc(tcbtabsize, sizeof(newtcbs[0]));
struct tcb **newtab = realloc(tcbtab, tcbtabsize * 2 * sizeof(tcbtab[0]));
if (!newtab || !newtcbs)
die_out_of_memory();
tcbtabsize *= 2;
tcbtab = newtab;
while (i < tcbtabsize)
tcbtab[i++] = newtcbs++;
}
static struct tcb *
alloctcb(int pid)
{
int i;
struct tcb *tcp;
if (nprocs == tcbtabsize)
expand_tcbtab();
for (i = 0; i < tcbtabsize; i++) {
tcp = tcbtab[i];
if ((tcp->flags & TCB_INUSE) == 0) {
memset(tcp, 0, sizeof(*tcp));
tcp->pid = pid;
tcp->flags = TCB_INUSE;
#if SUPPORTED_PERSONALITIES > 1
tcp->currpers = current_personality;
#endif
nprocs++;
if (debug_flag)
fprintf(stderr, "new tcb for pid %d, active tcbs:%d\n", tcp->pid, nprocs);
return tcp;
}
}
error_msg_and_die("bug in alloctcb");
}
static void
droptcb(struct tcb *tcp)
{
if (tcp->pid == 0)
return;
nprocs--;
if (debug_flag)
fprintf(stderr, "dropped tcb for pid %d, %d remain\n", tcp->pid, nprocs);
if (tcp->outf) {
if (followfork >= 2) {
if (tcp->curcol != 0)
fprintf(tcp->outf, " <detached ...>\n");
fclose(tcp->outf);
} else {
if (printing_tcp == tcp && tcp->curcol != 0)
fprintf(tcp->outf, " <detached ...>\n");
fflush(tcp->outf);
}
}
if (current_tcp == tcp)
current_tcp = NULL;
if (printing_tcp == tcp)
printing_tcp = NULL;
memset(tcp, 0, sizeof(*tcp));
}
/* detach traced process; continue with sig
* Never call DETACH twice on the same process as both unattached and
* attached-unstopped processes give the same ESRCH. For unattached process we
* would SIGSTOP it and wait for its SIGSTOP notification forever.
*/
static int
detach(struct tcb *tcp)
{
int error;
int status, sigstop_expected;
if (tcp->flags & TCB_BPTSET)
clearbpt(tcp);
/*
* Linux wrongly insists the child be stopped
* before detaching. Arghh. We go through hoops
* to make a clean break of things.
*/
#if defined(SPARC)
#undef PTRACE_DETACH
#define PTRACE_DETACH PTRACE_SUNDETACH
#endif
error = 0;
sigstop_expected = 0;
if (tcp->flags & TCB_ATTACHED) {
/*
* We attached but possibly didn't see the expected SIGSTOP.
* We must catch exactly one as otherwise the detached process
* would be left stopped (process state T).
*/
sigstop_expected = (tcp->flags & TCB_IGNORE_ONE_SIGSTOP);
error = ptrace(PTRACE_DETACH, tcp->pid, (char *) 1, 0);
if (error == 0) {
/* On a clear day, you can see forever. */
}
else if (errno != ESRCH) {
/* Shouldn't happen. */
perror("detach: ptrace(PTRACE_DETACH, ...)");
}
else if (my_tkill(tcp->pid, 0) < 0) {
if (errno != ESRCH)
perror("detach: checking sanity");
}
else if (!sigstop_expected && my_tkill(tcp->pid, SIGSTOP) < 0) {
if (errno != ESRCH)
perror("detach: stopping child");
}
else
sigstop_expected = 1;
}
if (sigstop_expected) {
for (;;) {
#ifdef __WALL
if (waitpid(tcp->pid, &status, __WALL) < 0) {
if (errno == ECHILD) /* Already gone. */
break;
if (errno != EINVAL) {
perror("detach: waiting");
break;
}
#endif /* __WALL */
/* No __WALL here. */
if (waitpid(tcp->pid, &status, 0) < 0) {
if (errno != ECHILD) {
perror("detach: waiting");
break;
}
#ifdef __WCLONE
/* If no processes, try clones. */
if (waitpid(tcp->pid, &status, __WCLONE) < 0) {
if (errno != ECHILD)
perror("detach: waiting");
break;
}
#endif /* __WCLONE */
}
#ifdef __WALL
}
#endif
if (!WIFSTOPPED(status)) {
/* Au revoir, mon ami. */
break;
}
if (WSTOPSIG(status) == SIGSTOP) {
ptrace_restart(PTRACE_DETACH, tcp, 0);
break;
}
error = ptrace_restart(PTRACE_CONT, tcp,
WSTOPSIG(status) == syscall_trap_sig ? 0
: WSTOPSIG(status));
if (error < 0)
break;
}
}
if (!qflag && (tcp->flags & TCB_ATTACHED))
fprintf(stderr, "Process %u detached\n", tcp->pid);
droptcb(tcp);
return error;
}
static void
process_opt_p_list(char *opt)
{
while (*opt) {
/*
* We accept -p PID,PID; -p "`pidof PROG`"; -p "`pgrep PROG`".
* pidof uses space as delim, pgrep uses newline. :(
*/
int pid;
char *delim = opt + strcspn(opt, ", \n\t");
char c = *delim;
*delim = '\0';
pid = string_to_uint(opt);
if (pid <= 0) {
error_msg_and_die("Invalid process id: '%s'", opt);
}
if (pid == strace_tracer_pid) {
error_msg_and_die("I'm sorry, I can't let you do that, Dave.");
}
*delim = c;
alloctcb(pid);
if (c == '\0')
break;
opt = delim + 1;
}
}
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) {
perror_msg_and_die("fork");
}
if (pid) { /* parent */
/*
* Wait for grandchild to attach to straced process
* (grandparent). Grandchild SIGKILLs us after it attached.
* Grandparent's wait() is unblocked by our death,
* it proceeds to exec the straced program.
*/
pause();
_exit(0); /* paranoia */
}
/* grandchild */
/* We will be the tracer process. Remember our new pid: */
strace_tracer_pid = getpid();
}
for (tcbi = 0; tcbi < tcbtabsize; tcbi++) {
tcp = tcbtab[tcbi];
if (!(tcp->flags & TCB_INUSE))
continue;
/* Is this a process we should attach to, but not yet attached? */
if (tcp->flags & TCB_ATTACHED)
continue; /* no, we already attached it */
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;
while ((de = readdir(dir)) != NULL) {
struct tcb *cur_tcp;
int tid;
if (de->d_fileno == 0)
continue;
/* we trust /proc filesystem */
tid = atoi(de->d_name);
if (tid <= 0)
continue;
++ntid;
if (ptrace_attach_or_seize(tid) < 0) {
++nerr;
if (debug_flag)
fprintf(stderr, "attach to pid %d failed\n", tid);
continue;
}
if (debug_flag)
fprintf(stderr, "attach to pid %d succeeded\n", tid);
cur_tcp = tcp;
if (tid != tcp->pid)
cur_tcp = alloctcb(tid);
cur_tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
newoutf(cur_tcp);
}
closedir(dir);
if (interactive) {
sigprocmask(SIG_SETMASK, &empty_set, NULL);
if (interrupted)
goto ret;
sigprocmask(SIG_BLOCK, &blocked_set, NULL);
}
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\n"
: "Process %u attached\n",
tcp->pid, ntid);
}
if (!(tcp->flags & TCB_ATTACHED)) {
/* -p PID, we failed to attach to PID itself
* but did attach to some of its sibling threads.
* Drop PID's tcp.
*/
droptcb(tcp);
}
continue;
} /* if (opendir worked) */
} /* if (-f) */
if (ptrace_attach_or_seize(tcp->pid) < 0) {
perror("attach: ptrace(PTRACE_ATTACH, ...)");
droptcb(tcp);
continue;
}
tcp->flags |= TCB_ATTACHED | TCB_STARTUP | post_attach_sigstop;
newoutf(tcp);
if (debug_flag)
fprintf(stderr, "attach to pid %d (main) succeeded\n", tcp->pid);
if (daemonized_tracer) {
/*
* Make parent go away.
* Also makes grandparent's wait() unblock.
*/
kill(getppid(), SIGKILL);
}
if (!qflag)
fprintf(stderr,
"Process %u attached\n",
tcp->pid);
} /* for each tcbtab[] */
ret:
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_msg_and_die("exec");
}