options.c revision bbca48329c87640e54054c48f87317b637f8477c
1#include "config.h"
2
3#include <sys/ioctl.h>
4#include <assert.h>
5#include <errno.h>
6#include <fcntl.h>
7#include <getopt.h>
8#include <limits.h>
9#include <stdio.h>
10#include <stdlib.h>
11#include <string.h>
12#include <unistd.h>
13
14#include "common.h"
15#include "filter.h"
16#include "glob.h"
17
18#ifndef SYSCONFDIR
19#define SYSCONFDIR "/etc"
20#endif
21
22#define SYSTEM_CONFIG_FILE SYSCONFDIR "/ltrace.conf"
23#define USER_CONFIG_FILE "~/.ltrace.conf"
24
25struct options_t options = {
26	.align    = DEFAULT_ALIGN,    /* alignment column for results */
27	.user     = NULL,             /* username to run command as */
28	.syscalls = 0,                /* display syscalls */
29#ifdef USE_DEMANGLE
30	.demangle = 0,                /* Demangle low-level symbol names */
31#endif
32	.indent = 0,                  /* indent output according to program flow */
33	.output = NULL,               /* output to a specific file */
34	.summary = 0,                 /* Report a summary on program exit */
35	.debug = 0,                   /* debug */
36	.arraylen = DEFAULT_ARRAYLEN, /* maximum # array elements to print */
37	.strlen = DEFAULT_STRLEN,     /* maximum # of bytes printed in strings */
38	.follow = 0,                  /* trace child processes */
39};
40
41static char *progname;		/* Program name (`ltrace') */
42int opt_i = 0;			/* instruction pointer */
43int opt_r = 0;			/* print relative timestamp */
44int opt_t = 0;			/* print absolute timestamp */
45int opt_T = 0;			/* show the time spent inside each call */
46
47/* List of pids given to option -p: */
48struct opt_p_t *opt_p = NULL;	/* attach to process with a given pid */
49
50/* List of filenames give to option -F: */
51struct opt_F_t *opt_F = NULL;	/* alternate configuration file(s) */
52
53#ifdef PLT_REINITALISATION_BP
54/* Set a break on the routine named here in order to re-initialize breakpoints
55   after all the PLTs have been initialzed */
56char *PLTs_initialized_by_here = PLT_REINITALISATION_BP;
57#endif
58
59static void
60err_usage(void) {
61	fprintf(stderr, "Try `%s --help' for more information\n", progname);
62	exit(1);
63}
64
65static void
66usage(void) {
67	fprintf(stdout, "Usage: %s [option ...] [command [arg ...]]\n"
68		"Trace library calls of a given program.\n\n"
69		"  -a, --align=COLUMN  align return values in a secific column.\n"
70		"  -A ARRAYLEN         maximum number of array elements to print.\n"
71		"  -b, --no-signals    don't print signals.\n"
72		"  -c                  count time and calls, and report a summary on exit.\n"
73# ifdef USE_DEMANGLE
74		"  -C, --demangle      decode low-level symbol names into user-level names.\n"
75# endif
76		"  -D, --debug=LEVEL   enable debugging (see -Dh or --debug=help).\n"
77		"  -Dh, --debug=help   show help on debugging.\n"
78		"  -e expr             modify which events to trace.\n"
79		"  -f                  trace children (fork() and clone()).\n"
80		"  -F, --config=FILE   load alternate configuration file (may be repeated).\n"
81		"  -h, --help          display this help and exit.\n"
82		"  -i                  print instruction pointer at time of library call.\n"
83		"  -l, --library=FILE  print library calls from this library only.\n"
84		"  -L                  do NOT display library calls.\n"
85		"  -n, --indent=NR     indent output by NR spaces for each call level nesting.\n"
86		"  -o, --output=FILE   write the trace output to that file.\n"
87		"  -p PID              attach to the process with the process ID pid.\n"
88		"  -r                  print relative timestamps.\n"
89		"  -s STRLEN           specify the maximum string size to print.\n"
90		"  -S                  display system calls.\n"
91		"  -t, -tt, -ttt       print absolute timestamps.\n"
92		"  -T                  show the time spent inside each call.\n"
93		"  -u USERNAME         run command with the userid, groupid of username.\n"
94		"  -V, --version       output version information and exit.\n"
95#if defined(HAVE_LIBUNWIND)
96		"  -w=NR, --where=NR   print backtrace showing NR stack frames at most.\n"
97#endif /* defined(HAVE_LIBUNWIND) */
98		"  -x NAME             treat the global NAME like a library subroutine.\n"
99#ifdef PLT_REINITALISATION_BP
100		"  -X NAME             same as -x; and PLT's will be initialized by here.\n"
101#endif
102		"\nReport bugs to ltrace-devel@lists.alioth.debian.org\n",
103		progname);
104}
105
106static void
107usage_debug(void) {
108	fprintf(stdout, "%s debugging option, --debug=<octal> or -D<octal>:\n", progname);
109	fprintf(stdout,
110			"\n"
111			" number  ref. in source   description\n"
112			"      1   general           Generally helpful progress information\n"
113			"     10   event             Shows every event received by a traced process\n"
114			"     20   process           Shows actions carried upon a traced processes\n"
115			"     40   function          Shows every entry to internal functions\n"
116			"\n"
117			"Debugging options are mixed using bitwise-or.\n"
118			"Note that the meanings and values are subject to change.\n"
119		   );
120}
121
122static char *
123search_for_command(char *filename) {
124	static char pathname[PATH_MAX];
125	char *path;
126	int m, n;
127
128	if (strchr(filename, '/')) {
129		return filename;
130	}
131	for (path = getenv("PATH"); path && *path; path += m) {
132		if (strchr(path, ':')) {
133			n = strchr(path, ':') - path;
134			m = n + 1;
135		} else {
136			m = n = strlen(path);
137		}
138		if (n + strlen(filename) + 1 >= PATH_MAX) {
139			fprintf(stderr, "Error: filename too long\n");
140			exit(1);
141		}
142		strncpy(pathname, path, n);
143		if (n && pathname[n - 1] != '/') {
144			pathname[n++] = '/';
145		}
146		strcpy(pathname + n, filename);
147		if (!access(pathname, X_OK)) {
148			return pathname;
149		}
150	}
151	return filename;
152}
153
154static void
155guess_cols(void) {
156	struct winsize ws;
157	char *c;
158
159	options.align = DEFAULT_ALIGN;
160	c = getenv("COLUMNS");
161	if (c && *c) {
162		char *endptr;
163		int cols;
164		cols = strtol(c, &endptr, 0);
165		if (cols > 0 && !*endptr) {
166			options.align = cols * 5 / 8;
167		}
168	} else if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
169		options.align = ws.ws_col * 5 / 8;
170	} else if (ioctl(2, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
171		options.align = ws.ws_col * 5 / 8;
172	}
173}
174
175static void
176add_filter_rule(struct filter *filt, const char *expr,
177		enum filter_rule_type type,
178		const char *a_sym, int sym_re_p,
179		const char *a_lib, int lib_re_p)
180{
181	struct filter_rule *rule = malloc(sizeof(*rule));
182	struct filter_lib_matcher *matcher = malloc(sizeof(*matcher));
183
184	if (rule == NULL || matcher == NULL) {
185		fprintf(stderr, "rule near '%s' will be ignored: %s\n",
186			expr, strerror(errno));
187	fail:
188		free(rule);
189		free(matcher);
190		return;
191	}
192
193	regex_t symbol_re;
194	int status;
195	{
196		/* Add ^ to the start of expression and $ to the end, so that
197		 * we match the whole symbol name.  Let the user write the "*"
198		 * explicitly if they wish.  */
199		char sym[strlen(a_sym) + 3];
200		sprintf(sym, "^%s$", a_sym);
201		status = (sym_re_p ? regcomp : globcomp)(&symbol_re, sym, 0);
202		if (status != 0) {
203			char buf[100];
204			regerror(status, &symbol_re, buf, sizeof buf);
205			fprintf(stderr, "rule near '%s' will be ignored: %s\n",
206				expr, buf);
207			goto fail;
208		}
209	}
210
211	if (strcmp(a_lib, "MAIN") == 0) {
212		filter_lib_matcher_main_init(matcher);
213	} else {
214		/* Add ^ and $ to the library expression as well.  */
215		char lib[strlen(a_lib) + 3];
216		sprintf(lib, "^%s$", a_lib);
217
218		enum filter_lib_matcher_type type
219			= lib[0] == '/' ? FLM_PATHNAME : FLM_SONAME;
220
221		regex_t lib_re;
222		status = (lib_re_p ? regcomp : globcomp)(&lib_re, lib, 0);
223		if (status != 0) {
224			char buf[100];
225			regerror(status, &lib_re, buf, sizeof buf);
226			fprintf(stderr, "rule near '%s' will be ignored: %s\n",
227				expr, buf);
228
229			regfree(&symbol_re);
230			goto fail;
231		}
232		filter_lib_matcher_name_init(matcher, type, lib_re);
233	}
234
235	filter_rule_init(rule, type, matcher, symbol_re);
236	filter_add_rule(filt, rule);
237}
238
239static int
240parse_filter(struct filter *filt, char *expr)
241{
242	/* Filter is a chain of sym@lib rules separated by '-'.  If
243	 * the filter expression starts with '-', the missing initial
244	 * rule is implicitly *@*.  */
245
246	enum filter_rule_type type = FR_ADD;
247
248	while (*expr != 0) {
249		size_t s = strcspn(expr, "@-+");
250		char *symname = expr;
251		char *libname;
252		char *next = expr + s + 1;
253		enum filter_rule_type this_type = type;
254
255		if (expr[s] == 0) {
256			libname = "*";
257			expr = next - 1;
258
259		} else if (expr[s] == '-' || expr[s] == '+') {
260			type = expr[s] == '-' ? FR_SUBTRACT : FR_ADD;
261			expr[s] = 0;
262			libname = "*";
263			expr = next;
264
265		} else {
266			assert(expr[s] == '@');
267			expr[s] = 0;
268			s = strcspn(next, "-+");
269			if (s == 0) {
270				libname = "*";
271				expr = next;
272			} else if (next[s] == 0) {
273				expr = next + s;
274				libname = next;
275			} else {
276				assert(next[s] == '-' || next[s] == '+');
277				type = next[s] == '-' ? FR_SUBTRACT : FR_ADD;
278				next[s] = 0;
279				expr = next + s + 1;
280				libname = next;
281			}
282		}
283
284		assert(*libname != 0);
285		char *symend = symname + strlen(symname) - 1;
286		char *libend = libname + strlen(libname) - 1;
287		int sym_is_re = 0;
288		int lib_is_re = 0;
289
290		/*
291		 * /xxx/@... and ...@/xxx/ means that xxx are regular
292		 * expressions.  They are globs otherwise.
293		 *
294		 * /xxx@yyy/ is the same as /xxx/@/yyy/
295		 *
296		 * @/xxx matches library path name
297		 * @.xxx matches library relative path name
298		 */
299		if (symname[0] == '/') {
300			if (symname != symend && symend[0] == '/') {
301				++symname;
302				*symend-- = 0;
303				sym_is_re = 1;
304
305			} else {
306				sym_is_re = 1;
307				lib_is_re = 1;
308				++symname;
309
310				/* /XXX@YYY/ is the same as
311				 * /XXX/@/YYY/.  */
312				if (libend[0] != '/')
313					fprintf(stderr, "unmatched '/'"
314						" in symbol name\n");
315				else
316					*libend-- = 0;
317			}
318		}
319
320		/* If libname ends in '/', then we expect '/' in the
321		 * beginning too.  Otherwise the initial '/' is part
322		 * of absolute file name.  */
323		if (!lib_is_re && libend[0] == '/') {
324			lib_is_re = 1;
325			*libend-- = 0;
326			if (libname != libend && libname[0] == '/')
327				++libname;
328			else
329				fprintf(stderr, "unmatched '/'"
330					" in library name\n");
331		}
332
333		if (*symname == 0) /* /@AA/ */
334			symname = "*";
335		if (*libname == 0) /* /aa@/ */
336			libname = "*";
337
338		add_filter_rule(filt, expr, this_type,
339				symname, sym_is_re,
340				libname, lib_is_re);
341	}
342
343	return 0;
344}
345
346static struct filter *
347recursive_parse_chain(char *expr)
348{
349	struct filter *filt = malloc(sizeof(*filt));
350	if (filt == NULL) {
351		fprintf(stderr, "(part of) filter will be ignored: '%s': %s\n",
352			expr, strerror(errno));
353		return NULL;
354	}
355
356	filter_init(filt);
357	if (parse_filter(filt, expr) < 0) {
358		fprintf(stderr, "Filter '%s' will be ignored.\n", expr);
359		free(filt);
360		filt = NULL;
361	}
362
363	return filt;
364}
365
366static void
367parse_filter_chain(const char *expr, struct filter **retp)
368{
369	char *str = strdup(expr);
370	if (str == NULL) {
371		fprintf(stderr, "filter '%s' will be ignored: %s\n",
372			expr, strerror(errno));
373		return;
374	}
375	/* Support initial '!' for backward compatibility.  */
376	if (str[0] == '!')
377		str[0] = '-';
378
379	struct filter **tailp;
380	for (tailp = retp; *tailp != NULL; tailp = &(*tailp)->next)
381		;
382	*tailp = recursive_parse_chain(str);
383}
384
385char **
386process_options(int argc, char **argv)
387{
388	progname = argv[0];
389	options.output = stderr;
390	options.no_signals = 0;
391#if defined(HAVE_LIBUNWIND)
392	options.bt_depth = -1;
393#endif /* defined(HAVE_LIBUNWIND) */
394
395	guess_cols();
396
397	int libcalls = 1;
398
399	while (1) {
400		int c;
401		char *p;
402		int option_index = 0;
403		static struct option long_options[] = {
404			{"align", 1, 0, 'a'},
405			{"config", 1, 0, 'F'},
406			{"debug", 1, 0, 'D'},
407# ifdef USE_DEMANGLE
408			{"demangle", 0, 0, 'C'},
409#endif
410			{"indent", 1, 0, 'n'},
411			{"help", 0, 0, 'h'},
412			{"library", 1, 0, 'l'},
413			{"output", 1, 0, 'o'},
414			{"version", 0, 0, 'V'},
415			{"no-signals", 0, 0, 'b'},
416#if defined(HAVE_LIBUNWIND)
417			{"where", 1, 0, 'w'},
418#endif /* defined(HAVE_LIBUNWIND) */
419			{0, 0, 0, 0}
420		};
421		c = getopt_long(argc, argv, "+cfhiLrStTVb"
422# ifdef USE_DEMANGLE
423				"C"
424# endif
425#if defined(HAVE_LIBUNWIND)
426				"a:A:D:e:F:l:n:o:p:s:u:x:X:w:", long_options,
427#else /* !defined(HAVE_LIBUNWIND) */
428				"a:A:D:e:F:l:n:o:p:s:u:x:X:", long_options,
429#endif
430				&option_index);
431		if (c == -1) {
432			break;
433		}
434		switch (c) {
435		case 'a':
436			options.align = atoi(optarg);
437			break;
438		case 'A':
439			options.arraylen = atoi(optarg);
440			break;
441		case 'b':
442			options.no_signals = 1;
443			break;
444		case 'c':
445			options.summary++;
446			break;
447#ifdef USE_DEMANGLE
448		case 'C':
449			options.demangle++;
450			break;
451#endif
452		case 'D':
453			if (optarg[0]=='h') {
454				usage_debug();
455				exit(0);
456			}
457			options.debug = strtoul(optarg,&p,8);
458			if (*p) {
459				fprintf(stderr, "%s: --debug requires an octal argument\n", progname);
460				err_usage();
461			}
462			break;
463
464		case 'e':
465			parse_filter_chain(optarg, &options.plt_filter);
466			break;
467
468		case 'f':
469			options.follow = 1;
470			break;
471		case 'F':
472			{
473				struct opt_F_t *tmp = malloc(sizeof(struct opt_F_t));
474				if (!tmp) {
475					perror("ltrace: malloc");
476					exit(1);
477				}
478				tmp->filename = strdup(optarg);
479				tmp->next = opt_F;
480				opt_F = tmp;
481				break;
482			}
483		case 'h':
484			usage();
485			exit(0);
486		case 'i':
487			opt_i++;
488			break;
489		case 'l':
490			// XXX TODO
491			fprintf(stderr, "-l support not yet implemented\n");
492			break;
493		case 'L':
494			libcalls = 0;
495			break;
496		case 'n': {
497			char *endptr;
498			long int l = strtol(optarg, &endptr, 0);
499			/* Arbitrary cut-off.  Nobody needs to indent
500			 * more than, say, 8, anyway.  */
501			if (l < 0 || l > 20 || *optarg == 0 || *endptr != 0) {
502				fprintf(stderr, "Invalid argument to -n: '%s'."
503					"  Use integer 0..20.\n", optarg);
504				exit(1);
505			}
506			options.indent = (int)l;
507			break;
508		}
509		case 'o':
510			options.output = fopen(optarg, "w");
511			if (!options.output) {
512				fprintf(stderr,
513					"can't open %s for writing: %s\n",
514					optarg, strerror(errno));
515				exit(1);
516			}
517			setvbuf(options.output, (char *)NULL, _IOLBF, 0);
518			fcntl(fileno(options.output), F_SETFD, FD_CLOEXEC);
519			break;
520		case 'p':
521			{
522				struct opt_p_t *tmp = malloc(sizeof(struct opt_p_t));
523				if (!tmp) {
524					perror("ltrace: malloc");
525					exit(1);
526				}
527				tmp->pid = atoi(optarg);
528				tmp->next = opt_p;
529				opt_p = tmp;
530				break;
531			}
532		case 'r':
533			opt_r++;
534			break;
535		case 's':
536			options.strlen = atoi(optarg);
537			break;
538		case 'S':
539			options.syscalls = 1;
540			break;
541		case 't':
542			opt_t++;
543			break;
544		case 'T':
545			opt_T++;
546			break;
547		case 'u':
548			options.user = optarg;
549			break;
550		case 'V':
551			printf("ltrace version " PACKAGE_VERSION ".\n"
552					"Copyright (C) 1997-2009 Juan Cespedes <cespedes@debian.org>.\n"
553					"This is free software; see the GNU General Public Licence\n"
554					"version 2 or later for copying conditions.  There is NO warranty.\n");
555			exit(0);
556			break;
557#if defined(HAVE_LIBUNWIND)
558		case 'w':
559			options.bt_depth = atoi(optarg);
560			break;
561#endif /* defined(HAVE_LIBUNWIND) */
562		case 'X':
563#ifdef PLT_REINITALISATION_BP
564			PLTs_initialized_by_here = optarg;
565#else
566			fprintf(stderr, "WARNING: \"-X\" not used for this "
567				"architecture: assuming you meant \"-x\"\n");
568#endif
569			/* Fall Thru */
570
571		case 'x':
572			parse_filter_chain(optarg, &options.static_filter);
573			break;
574
575		default:
576			err_usage();
577		}
578	}
579	argc -= optind;
580	argv += optind;
581
582	if (!opt_F) {
583		opt_F = malloc(sizeof(struct opt_F_t));
584		opt_F->next = malloc(sizeof(struct opt_F_t));
585		opt_F->next->next = NULL;
586		opt_F->filename = USER_CONFIG_FILE;
587		opt_F->next->filename = SYSTEM_CONFIG_FILE;
588	}
589	/* Reverse the config file list since it was built by
590	 * prepending, and it would make more sense to process the
591	 * files in the order they were given. Probably it would make
592	 * more sense to keep a tail pointer instead? */
593	{
594		struct opt_F_t *egg = NULL;
595		struct opt_F_t *chicken;
596		while (opt_F) {
597			chicken = opt_F->next;
598			opt_F->next = egg;
599			egg = opt_F;
600			opt_F = chicken;
601		}
602		opt_F = egg;
603	}
604
605	/* Set default filter.  Use @MAIN for now, as that's what
606	 * ltrace used to have in the past.  XXX Maybe we should make
607	 * this "*" instead.  */
608	if (options.plt_filter == NULL && libcalls) {
609		parse_filter_chain("@MAIN", &options.plt_filter);
610		options.hide_caller = 1;
611	}
612
613	if (!opt_p && argc < 1) {
614		fprintf(stderr, "%s: too few arguments\n", progname);
615		err_usage();
616	}
617	if (opt_r && opt_t) {
618		fprintf(stderr, "%s: Incompatible options -r and -t\n",
619			progname);
620		err_usage();
621	}
622	if (argc > 0) {
623		command = search_for_command(argv[0]);
624	}
625	return &argv[0];
626}
627