aboutsummaryrefslogtreecommitdiff
path: root/options.c
blob: d4e16a8a7367a22accab3a59ce369ed4c68f65c6 (plain)
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
#include "config.h"

#include <sys/ioctl.h>
#include <assert.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <getopt.h>
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "common.h"
#include "filter.h"
#include "glob.h"

#ifndef SYSCONFDIR
#define SYSCONFDIR "/etc"
#endif

#define SYSTEM_CONFIG_FILE SYSCONFDIR "/ltrace.conf"
#define USER_CONFIG_FILE "~/.ltrace.conf"

struct options_t options = {
	.align    = DEFAULT_ALIGN,    /* alignment column for results */
	.user     = NULL,             /* username to run command as */
	.syscalls = 0,                /* display syscalls */
	.libcalls = 1,                /* display library calls */
#ifdef USE_DEMANGLE
	.demangle = 0,                /* Demangle low-level symbol names */
#endif
	.indent = 0,                  /* indent output according to program flow */
	.output = NULL,               /* output to a specific file */
	.summary = 0,                 /* Report a summary on program exit */
	.debug = 0,                   /* debug */
	.arraylen = DEFAULT_ARRAYLEN, /* maximum # array elements to print */
	.strlen = DEFAULT_STRLEN,     /* maximum # of bytes printed in strings */
	.follow = 0,                  /* trace child processes */
};

static char *progname;		/* Program name (`ltrace') */
int opt_i = 0;			/* instruction pointer */
int opt_r = 0;			/* print relative timestamp */
int opt_t = 0;			/* print absolute timestamp */
int opt_T = 0;			/* show the time spent inside each call */

/* List of pids given to option -p: */
struct opt_p_t *opt_p = NULL;	/* attach to process with a given pid */

/* List of global function names given to -x: */
struct opt_x_t *opt_x = NULL;
unsigned int opt_x_cnt = 0;

/* List of filenames give to option -F: */
struct opt_F_t *opt_F = NULL;	/* alternate configuration file(s) */

#ifdef PLT_REINITALISATION_BP
/* Set a break on the routine named here in order to re-initialize breakpoints
   after all the PLTs have been initialzed */
char *PLTs_initialized_by_here = PLT_REINITALISATION_BP;
#endif

static void
err_usage(void) {
	fprintf(stderr, "Try `%s --help' for more information\n", progname);
	exit(1);
}

static void
usage(void) {
	fprintf(stdout, "Usage: %s [option ...] [command [arg ...]]\n"
		"Trace library calls of a given program.\n\n"
		"  -a, --align=COLUMN  align return values in a secific column.\n"
		"  -A ARRAYLEN         maximum number of array elements to print.\n"
		"  -b, --no-signals    don't print signals.\n"
		"  -c                  count time and calls, and report a summary on exit.\n"
# ifdef USE_DEMANGLE
		"  -C, --demangle      decode low-level symbol names into user-level names.\n"
# endif
		"  -D, --debug=LEVEL   enable debugging (see -Dh or --debug=help).\n"
		"  -Dh, --debug=help   show help on debugging.\n"
		"  -e expr             modify which events to trace.\n"
		"  -f                  trace children (fork() and clone()).\n"
		"  -F, --config=FILE   load alternate configuration file (may be repeated).\n"
		"  -g, --no-plt        disable breakpoints on PLT entries.\n"
		"  -h, --help          display this help and exit.\n"
		"  -i                  print instruction pointer at time of library call.\n"
		"  -l, --library=FILE  print library calls from this library only.\n"
		"  -L                  do NOT display library calls.\n"
		"  -n, --indent=NR     indent output by NR spaces for each call level nesting.\n"
		"  -o, --output=FILE   write the trace output to that file.\n"
		"  -p PID              attach to the process with the process ID pid.\n"
		"  -r                  print relative timestamps.\n"
		"  -s STRLEN           specify the maximum string size to print.\n"
		"  -S                  display system calls.\n"
		"  -t, -tt, -ttt       print absolute timestamps.\n"
		"  -T                  show the time spent inside each call.\n"
		"  -u USERNAME         run command with the userid, groupid of username.\n"
		"  -V, --version       output version information and exit.\n"
#if defined(HAVE_LIBUNWIND)
		"  -w=NR, --where=NR   print backtrace showing NR stack frames at most.\n"
#endif /* defined(HAVE_LIBUNWIND) */
		"  -x NAME             treat the global NAME like a library subroutine.\n"
#ifdef PLT_REINITALISATION_BP
		"  -X NAME             same as -x; and PLT's will be initialized by here.\n"
#endif
		"\nReport bugs to ltrace-devel@lists.alioth.debian.org\n",
		progname);
}

static void
usage_debug(void) {
	fprintf(stdout, "%s debugging option, --debug=<octal> or -D<octal>:\n", progname);
	fprintf(stdout, 
			"\n"
			" number  ref. in source   description\n"
			"      1   general           Generally helpful progress information\n"
			"     10   event             Shows every event received by a traced process\n"
			"     20   process           Shows actions carried upon a traced processes\n"
			"     40   function          Shows every entry to internal functions\n"
			"\n"
			"Debugging options are mixed using bitwise-or.\n"
			"Note that the meanings and values are subject to change.\n"
		   );
}

static char *
search_for_command(char *filename) {
	static char pathname[PATH_MAX];
	char *path;
	int m, n;

	if (strchr(filename, '/')) {
		return filename;
	}
	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 + strlen(filename) + 1 >= PATH_MAX) {
			fprintf(stderr, "Error: filename too long\n");
			exit(1);
		}
		strncpy(pathname, path, n);
		if (n && pathname[n - 1] != '/') {
			pathname[n++] = '/';
		}
		strcpy(pathname + n, filename);
		if (!access(pathname, X_OK)) {
			return pathname;
		}
	}
	return filename;
}

static void
guess_cols(void) {
	struct winsize ws;
	char *c;

	options.align = DEFAULT_ALIGN;
	c = getenv("COLUMNS");
	if (c && *c) {
		char *endptr;
		int cols;
		cols = strtol(c, &endptr, 0);
		if (cols > 0 && !*endptr) {
			options.align = cols * 5 / 8;
		}
	} else if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
		options.align = ws.ws_col * 5 / 8;
	} else if (ioctl(2, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
		options.align = ws.ws_col * 5 / 8;
	}
}

static void
add_filter_rule(struct filter *filt, const char *expr,
		enum filter_rule_type type,
		const char *sym, int sym_re_p,
		const char *lib, int lib_re_p)
{
	fprintf(stderr, "add_filter_rule, type = %d\n", type);
	fprintf(stderr, "+ symname = %s (re=%d)\n", sym, sym_re_p);
	fprintf(stderr, "+ libname = %s (re=%d)\n", lib, lib_re_p);
	struct filter_rule *rule = malloc(sizeof(*rule));
	struct filter_lib_matcher *matcher = malloc(sizeof(*matcher));

	if (rule == NULL || matcher == NULL) {
		error(0, errno, "rule near '%s' will be ignored", expr);
	fail:
		free(rule);
		free(matcher);
		return;
	}

	regex_t symbol_re;
	int status = (sym_re_p ? regcomp : globcomp)(&symbol_re, sym, 0);
	if (status != 0) {
		char buf[100];
		regerror(status, &symbol_re, buf, sizeof buf);
		error(0, 0, "rule near '%s' will be ignored: %s", expr, buf);
		goto fail;
	}

	if (strcmp(lib, "MAIN") == 0) {
		filter_lib_matcher_main_init(matcher);
	} else {
		enum filter_lib_matcher_type type
			= lib[0] == '/' ? FLM_PATHNAME : FLM_SONAME;

		regex_t lib_re;
		status = (lib_re_p ? regcomp : globcomp)(&lib_re, lib, 0);
		if (status != 0) {
			char buf[100];
			regerror(status, &lib_re, buf, sizeof buf);
			error(0, 0, "rule near '%s' will be ignored: %s",
			      expr, buf);

			regfree(&symbol_re);
			goto fail;
		}
		filter_lib_matcher_name_init(matcher, type, lib_re);
	}

	filter_rule_init(rule, type, matcher, symbol_re);
	filter_add_rule(filt, rule);
}

static int
parse_filter(struct filter *filt, char *expr)
{
	fprintf(stderr, "filter '%s'\n", expr);

	/* Filter is a chain of sym@lib rules separated by '-'.  If
	 * the filter expression starts with '-', the missing initial
	 * rule is implicitly *@*.  */

	enum filter_rule_type type = FR_ADD;

	while (*expr != 0) {
		size_t s = strcspn(expr, "@-");
		char *symname = expr;
		char *libname;
		char *next = expr + s + 1;
		enum filter_rule_type this_type = type;

		if (expr[s] == 0) {
			libname = "*";
			expr = next - 1;

		} else if (expr[s] == '-') {
			libname = "*";
			expr = next;
			type = FR_SUBTRACT;

		} else {
			assert(expr[s] == '@');
			expr[s] = 0;
			s = strcspn(next, "-");
			if (s == 0) {
				libname = "*";
				expr = next;
			} else if (next[s] == 0) {
				expr = next + s;
				libname = next;

			} else {
				assert(next[s] == '-');
				type = FR_SUBTRACT;
				next[s] = 0;
				expr = next + s + 1;
				libname = next;
			}
		}

		assert(*libname != 0);
		char *symend = symname + strlen(symname) - 1;
		char *libend = libname + strlen(libname) - 1;
		int sym_is_re = 0;
		int lib_is_re = 0;

		/*
		 * /xxx/@... and ...@/xxx/ means that xxx are regular
		 * expressions.  They are globs otherwise.
		 *
		 * /xxx@yyy/ is the same as /xxx/@/yyy/
		 *
		 * @/xxx matches library path name
		 * @.xxx matches library relative path name
		 */
		if (symname[0] == '/') {
			if (symname != symend && symend[0] == '/') {
				++symname;
				*symend-- = 0;
				sym_is_re = 1;

			} else {
				sym_is_re = 1;
				lib_is_re = 1;
				++symname;

				/* /XXX@YYY/ is the same as
				 * /XXX/@/YYY/.  */
				if (libend[0] != '/')
					error(0, 0, "unmatched '/'"
					      " in symbol name");
				else
					*libend-- = 0;
			}
		}

		/* If libname ends in '/', then we expect '/' in the
		 * beginning too.  Otherwise the initial '/' is part
		 * of absolute file name.  */
		if (!lib_is_re && libend[0] == '/') {
			lib_is_re = 1;
			*libend-- = 0;
			if (libname != libend && libname[0] == '/')
				++libname;
			else
				error(0, 0, "unmatched '/' in library name");
		}

		if (*symname == 0) /* /@AA/ */
			symname = "*";
		if (*libname == 0) /* /aa@/ */
			libname = "*";

		add_filter_rule(filt, expr, this_type,
				symname, sym_is_re,
				libname, lib_is_re);
	}

	return 0;
}

static struct filter *
recursive_parse_chain(char *expr)
{
	/* Event expression grammar:
	 *
	 *  Chain ::= Filter FilterList
	 *  FilterList ::= eps | ',' Filter FilterList
	 *  Filter ::= Rule RuleList
	 *  RuleList ::= eps | '-' Rule RuleList
	 *  Rule ::= eps | Glob Soname
	 *  Soname ::= eps | '@' Glob | '@' '/' Filename
	 *  Glob ::= '/' Regex '/'
	 */

	struct filter *filt = malloc(sizeof(*filt));
	if (filt == NULL) {
		error(0, errno, "(part of) filter will be ignored: '%s'", expr);
		return NULL;
	}

	filter_init(filt);
	struct filter *next = NULL;
	char *it;
	int escape = 0;
	for (it = expr; ; ++it) {
		if (*it == 0)
			goto done;

		if (escape) {
			escape = 0;
			continue;
		}

		if (*it == '\\') {
			escape = 1;

		} else if (*it == ',') {
			*it = 0;
			next = recursive_parse_chain(it + 1);
		done:
			filt->next = next;
			if (parse_filter(filt, expr) < 0) {
				fprintf(stderr,
					"Filter '%s' will be ignored.\n", expr);
				free(filt);
				filt = next;
			}
			return filt;
		}
	}
}

static void
parse_filter_chain(const char *expr, struct filter **retp)
{
	char *str = strdup(expr);
	if (str == NULL) {
		error(0, errno, "filter '%s' will be ignored", expr);
		return;
	}
	*retp = recursive_parse_chain(str);
}

char **
process_options(int argc, char **argv) {
	progname = argv[0];
	options.output = stderr;
	options.no_plt = 0;
	options.no_signals = 0;
#if defined(HAVE_LIBUNWIND)
	options.bt_depth = -1;
#endif /* defined(HAVE_LIBUNWIND) */

	guess_cols();

	while (1) {
		int c;
		char *p;
		int option_index = 0;
		static struct option long_options[] = {
			{"align", 1, 0, 'a'},
			{"config", 1, 0, 'F'},
			{"debug", 1, 0, 'D'},
# ifdef USE_DEMANGLE
			{"demangle", 0, 0, 'C'},
#endif
			{"indent", 1, 0, 'n'},
			{"help", 0, 0, 'h'},
			{"library", 1, 0, 'l'},
			{"output", 1, 0, 'o'},
			{"version", 0, 0, 'V'},
			{"no-plt", 0, 0, 'g'},
			{"no-signals", 0, 0, 'b'},
#if defined(HAVE_LIBUNWIND)
			{"where", 1, 0, 'w'},
#endif /* defined(HAVE_LIBUNWIND) */
			{0, 0, 0, 0}
		};
		c = getopt_long(argc, argv, "+cfhiLrStTVgb"
# ifdef USE_DEMANGLE
				"C"
# endif
#if defined(HAVE_LIBUNWIND)
				"a:A:D:e:F:l:n:o:p:s:u:x:X:w:", long_options,
#else /* !defined(HAVE_LIBUNWIND) */
				"a:A:D:e:F:l:n:o:p:s:u:x:X:", long_options,
#endif
				&option_index);
		if (c == -1) {
			break;
		}
		switch (c) {
		case 'a':
			options.align = atoi(optarg);
			break;
		case 'A':
			options.arraylen = atoi(optarg);
			break;
		case 'b':
			options.no_signals = 1;
			break;
		case 'c':
			options.summary++;
			break;
#ifdef USE_DEMANGLE
		case 'C':
			options.demangle++;
			break;
#endif
		case 'D':
			if (optarg[0]=='h') {
				usage_debug();
				exit(0);
			}
			options.debug = strtoul(optarg,&p,8);
			if (*p) {
				fprintf(stderr, "%s: --debug requires an octal argument\n", progname);
				err_usage();
			}
			break;

		case 'e':
			parse_filter_chain(optarg, &options.plt_filter);
			break;

		case 'f':
			options.follow = 1;
			break;
		case 'F':
			{
				struct opt_F_t *tmp = malloc(sizeof(struct opt_F_t));
				if (!tmp) {
					perror("ltrace: malloc");
					exit(1);
				}
				tmp->filename = strdup(optarg);
				tmp->next = opt_F;
				opt_F = tmp;
				break;
			}
		case 'g':
			options.no_plt = 1;
			break;
		case 'h':
			usage();
			exit(0);
		case 'i':
			opt_i++;
			break;
		case 'l':
			assert(!"-l support not yet implemented");
			abort();
			break;
		case 'L':
			options.libcalls = 0;
			break;
		case 'n':
			options.indent = atoi(optarg);
			break;
		case 'o':
			options.output = fopen(optarg, "w");
			if (!options.output) {
				fprintf(stderr,
					"Can't open %s for output: %s\n",
					optarg, strerror(errno));
				exit(1);
			}
			setvbuf(options.output, (char *)NULL, _IOLBF, 0);
			fcntl(fileno(options.output), F_SETFD, FD_CLOEXEC);
			break;
		case 'p':
			{
				struct opt_p_t *tmp = malloc(sizeof(struct opt_p_t));
				if (!tmp) {
					perror("ltrace: malloc");
					exit(1);
				}
				tmp->pid = atoi(optarg);
				tmp->next = opt_p;
				opt_p = tmp;
				break;
			}
		case 'r':
			opt_r++;
			break;
		case 's':
			options.strlen = atoi(optarg);
			break;
		case 'S':
			options.syscalls = 1;
			break;
		case 't':
			opt_t++;
			break;
		case 'T':
			opt_T++;
			break;
		case 'u':
			options.user = optarg;
			break;
		case 'V':
			printf("ltrace version " PACKAGE_VERSION ".\n"
					"Copyright (C) 1997-2009 Juan Cespedes <cespedes@debian.org>.\n"
					"This is free software; see the GNU General Public Licence\n"
					"version 2 or later for copying conditions.  There is NO warranty.\n");
			exit(0);
			break;
#if defined(HAVE_LIBUNWIND)
		case 'w':
			options.bt_depth = atoi(optarg);
			break;
#endif /* defined(HAVE_LIBUNWIND) */
		case 'X':
#ifdef PLT_REINITALISATION_BP
			PLTs_initialized_by_here = optarg;
#else
			fprintf(stderr, "WARNING: \"-X\" not used for this "
				"architecture: assuming you meant \"-x\"\n");
#endif
			/* Fall Thru */

		case 'x':
			{
				struct opt_x_t *p = opt_x;

				/* First, check for duplicate. */
				while (p && strcmp(p->name, optarg)) {
					p = p->next;
				}
				if (p) {
					break;
				}

				/* If not duplicate, add to list. */
				p = malloc(sizeof(struct opt_x_t));
				if (!p) {
					perror("ltrace: malloc");
					exit(1);
				}
				opt_x_cnt++;
				p->name = optarg;
				p->found = 0;
				p->next = opt_x;
				p->hash = ~(0UL);
				opt_x = p;
				break;
			}

		default:
			err_usage();
		}
	}
	argc -= optind;
	argv += optind;

	if (!opt_F) {
		opt_F = malloc(sizeof(struct opt_F_t));
		opt_F->next = malloc(sizeof(struct opt_F_t));
		opt_F->next->next = NULL;
		opt_F->filename = USER_CONFIG_FILE;
		opt_F->next->filename = SYSTEM_CONFIG_FILE;
	}
	/* Reverse the config file list since it was built by
	 * prepending, and it would make more sense to process the
	 * files in the order they were given. Probably it would make
	 * more sense to keep a tail pointer instead? */
	{
		struct opt_F_t *egg = NULL;
		struct opt_F_t *chicken;
		while (opt_F) {
			chicken = opt_F->next;
			opt_F->next = egg;
			egg = opt_F;
			opt_F = chicken;
		}
		opt_F = egg;
	}

	/* Set default filter.  Use @MAIN for now, as that's what
	 * ltrace used to have in the past.  XXX Maybe we should make
	 * this "*" instead.  */
	if (options.plt_filter == NULL) {
		parse_filter_chain("@MAIN", &options.plt_filter);
		options.hide_caller = 1;
	}

	if (!opt_p && argc < 1) {
		fprintf(stderr, "%s: too few arguments\n", progname);
		err_usage();
	}
	if (opt_r && opt_t) {
		fprintf(stderr, "%s: Incompatible options -r and -t\n",
			progname);
		err_usage();
	}
	if (argc > 0) {
		command = search_for_command(argv[0]);
	}
	return &argv[0];
}