options.c revision 535e738ab59cab4fbe79270d7031b5580651349d
1#include "config.h"
2
3#include <string.h>
4#include <stdlib.h>
5#include <unistd.h>
6#include <fcntl.h>
7#include <errno.h>
8#include <limits.h>
9#include <sys/ioctl.h>
10
11#include <getopt.h>
12
13#include "common.h"
14
15#ifndef SYSCONFDIR
16#define SYSCONFDIR "/etc"
17#endif
18
19#define SYSTEM_CONFIG_FILE SYSCONFDIR "/ltrace.conf"
20#define USER_CONFIG_FILE "~/.ltrace.conf"
21
22struct options_t options = {
23	.align    = DEFAULT_ALIGN,    /* alignment column for results */
24	.user     = NULL,             /* username to run command as */
25	.syscalls = 0,                /* display syscalls */
26	.libcalls = 1,                /* display library calls */
27#ifdef USE_DEMANGLE
28	.demangle = 0,                /* Demangle low-level symbol names */
29#endif
30	.indent = 0,                  /* indent output according to program flow */
31	.output = NULL,               /* output to a specific file */
32	.summary = 0,                 /* Report a summary on program exit */
33	.debug = 0,                   /* debug */
34	.arraylen = DEFAULT_ARRAYLEN, /* maximum # array elements to print */
35	.strlen = DEFAULT_STRLEN,     /* maximum # of bytes printed in strings */
36	.follow = 0,                  /* trace child processes */
37};
38
39char *library[MAX_LIBRARIES];
40int library_num = 0;
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 function names given to option -e: */
51struct opt_e_t *opt_e = NULL;
52int opt_e_enable = 1;
53
54/* List of global function names given to -x: */
55struct opt_x_t *opt_x = NULL;
56unsigned int opt_x_cnt = 0;
57
58/* List of filenames give to option -F: */
59struct opt_F_t *opt_F = NULL;	/* alternate configuration file(s) */
60
61#ifdef PLT_REINITALISATION_BP
62/* Set a break on the routine named here in order to re-initialize breakpoints
63   after all the PLTs have been initialzed */
64char *PLTs_initialized_by_here = PLT_REINITALISATION_BP;
65#endif
66
67static void
68err_usage(void) {
69	fprintf(stderr, "Try `%s --help' for more information\n", progname);
70	exit(1);
71}
72
73static void
74usage(void) {
75	fprintf(stdout, "Usage: %s [option ...] [command [arg ...]]\n"
76		"Trace library calls of a given program.\n\n"
77		"  -a, --align=COLUMN  align return values in a secific column.\n"
78		"  -A ARRAYLEN         maximum number of array elements to print.\n"
79		"  -b, --no-signals    don't print signals.\n"
80		"  -c                  count time and calls, and report a summary on exit.\n"
81# ifdef USE_DEMANGLE
82		"  -C, --demangle      decode low-level symbol names into user-level names.\n"
83# endif
84		"  -D, --debug=LEVEL   enable debugging (see -Dh or --debug=help).\n"
85		"  -Dh, --debug=help   show help on debugging.\n"
86		"  -e expr             modify which events to trace.\n"
87		"  -f                  trace children (fork() and clone()).\n"
88		"  -F, --config=FILE   load alternate configuration file (may be repeated).\n"
89		"  -g, --no-plt        disable breakpoints on PLT entries.\n"
90		"  -h, --help          display this help and exit.\n"
91		"  -i                  print instruction pointer at time of library call.\n"
92		"  -l, --library=FILE  print library calls from this library only.\n"
93		"  -L                  do NOT display library calls.\n"
94		"  -n, --indent=NR     indent output by NR spaces for each call level nesting.\n"
95		"  -o, --output=FILE   write the trace output to that file.\n"
96		"  -p PID              attach to the process with the process ID pid.\n"
97		"  -r                  print relative timestamps.\n"
98		"  -s STRLEN           specify the maximum string size to print.\n"
99		"  -S                  display system calls.\n"
100		"  -t, -tt, -ttt       print absolute timestamps.\n"
101		"  -T                  show the time spent inside each call.\n"
102		"  -u USERNAME         run command with the userid, groupid of username.\n"
103		"  -V, --version       output version information and exit.\n"
104#if defined(HAVE_LIBUNWIND)
105		"  -w=NR, --where=NR   print backtrace showing NR stack frames at most.\n"
106#endif /* defined(HAVE_LIBUNWIND) */
107		"  -x NAME             treat the global NAME like a library subroutine.\n"
108#ifdef PLT_REINITALISATION_BP
109		"  -X NAME             same as -x; and PLT's will be initialized by here.\n"
110#endif
111		"\nReport bugs to ltrace-devel@lists.alioth.debian.org\n",
112		progname);
113}
114
115static void
116usage_debug(void) {
117	fprintf(stdout, "%s debugging option, --debug=<octal> or -D<octal>:\n", progname);
118	fprintf(stdout,
119			"\n"
120			" number  ref. in source   description\n"
121			"      1   general           Generally helpful progress information\n"
122			"     10   event             Shows every event received by a traced process\n"
123			"     20   process           Shows actions carried upon a traced processes\n"
124			"     40   function          Shows every entry to internal functions\n"
125			"\n"
126			"Debugging options are mixed using bitwise-or.\n"
127			"Note that the meanings and values are subject to change.\n"
128		   );
129}
130
131static char *
132search_for_command(char *filename) {
133	static char pathname[PATH_MAX];
134	char *path;
135	int m, n;
136
137	if (strchr(filename, '/')) {
138		return filename;
139	}
140	for (path = getenv("PATH"); path && *path; path += m) {
141		if (strchr(path, ':')) {
142			n = strchr(path, ':') - path;
143			m = n + 1;
144		} else {
145			m = n = strlen(path);
146		}
147		if (n + strlen(filename) + 1 >= PATH_MAX) {
148			fprintf(stderr, "Error: filename too long\n");
149			exit(1);
150		}
151		strncpy(pathname, path, n);
152		if (n && pathname[n - 1] != '/') {
153			pathname[n++] = '/';
154		}
155		strcpy(pathname + n, filename);
156		if (!access(pathname, X_OK)) {
157			return pathname;
158		}
159	}
160	return filename;
161}
162
163static void
164guess_cols(void) {
165	struct winsize ws;
166	char *c;
167
168	options.align = DEFAULT_ALIGN;
169	c = getenv("COLUMNS");
170	if (c && *c) {
171		char *endptr;
172		int cols;
173		cols = strtol(c, &endptr, 0);
174		if (cols > 0 && !*endptr) {
175			options.align = cols * 5 / 8;
176		}
177	} else if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
178		options.align = ws.ws_col * 5 / 8;
179	} else if (ioctl(2, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
180		options.align = ws.ws_col * 5 / 8;
181	}
182}
183
184char **
185process_options(int argc, char **argv) {
186	progname = argv[0];
187	options.output = stderr;
188	options.no_plt = 0;
189	options.no_signals = 0;
190#if defined(HAVE_LIBUNWIND)
191	options.bt_depth = -1;
192#endif /* defined(HAVE_LIBUNWIND) */
193
194	guess_cols();
195
196	while (1) {
197		int c;
198		char *p;
199		int option_index = 0;
200		static struct option long_options[] = {
201			{"align", 1, 0, 'a'},
202			{"config", 1, 0, 'F'},
203			{"debug", 1, 0, 'D'},
204# ifdef USE_DEMANGLE
205			{"demangle", 0, 0, 'C'},
206#endif
207			{"indent", 1, 0, 'n'},
208			{"help", 0, 0, 'h'},
209			{"library", 1, 0, 'l'},
210			{"output", 1, 0, 'o'},
211			{"version", 0, 0, 'V'},
212			{"no-plt", 0, 0, 'g'},
213			{"no-signals", 0, 0, 'b'},
214#if defined(HAVE_LIBUNWIND)
215			{"where", 1, 0, 'w'},
216#endif /* defined(HAVE_LIBUNWIND) */
217			{0, 0, 0, 0}
218		};
219		c = getopt_long(argc, argv, "+cfhiLrStTVgb"
220# ifdef USE_DEMANGLE
221				"C"
222# endif
223#if defined(HAVE_LIBUNWIND)
224				"a:A:D:e:F:l:n:o:p:s:u:x:X:w:", long_options,
225#else /* !defined(HAVE_LIBUNWIND) */
226				"a:A:D:e:F:l:n:o:p:s:u:x:X:", long_options,
227#endif
228				&option_index);
229		if (c == -1) {
230			break;
231		}
232		switch (c) {
233		case 'a':
234			options.align = atoi(optarg);
235			break;
236		case 'A':
237			options.arraylen = atoi(optarg);
238			break;
239		case 'b':
240			options.no_signals = 1;
241			break;
242		case 'c':
243			options.summary++;
244			break;
245#ifdef USE_DEMANGLE
246		case 'C':
247			options.demangle++;
248			break;
249#endif
250		case 'D':
251			if (optarg[0]=='h') {
252				usage_debug();
253				exit(0);
254			}
255			options.debug = strtoul(optarg,&p,8);
256			if (*p) {
257				fprintf(stderr, "%s: --debug requires an octal argument\n", progname);
258				err_usage();
259			}
260			break;
261		case 'e':
262			{
263				char *str_e = strdup(optarg);
264				if (!str_e) {
265					perror("ltrace: strdup");
266					exit(1);
267				}
268				if (str_e[0] == '!') {
269					opt_e_enable = 0;
270					str_e++;
271				}
272				while (*str_e) {
273					struct opt_e_t *tmp;
274					char *str2 = strchr(str_e, ',');
275					if (str2) {
276						*str2 = '\0';
277					}
278					tmp = malloc(sizeof(struct opt_e_t));
279					if (!tmp) {
280						perror("ltrace: malloc");
281						exit(1);
282					}
283					tmp->name = str_e;
284					tmp->next = opt_e;
285					opt_e = tmp;
286					if (str2) {
287						str_e = str2 + 1;
288					} else {
289						break;
290					}
291				}
292				break;
293			}
294		case 'f':
295			options.follow = 1;
296			break;
297		case 'F':
298			{
299				struct opt_F_t *tmp = malloc(sizeof(struct opt_F_t));
300				if (!tmp) {
301					perror("ltrace: malloc");
302					exit(1);
303				}
304				tmp->filename = strdup(optarg);
305				tmp->next = opt_F;
306				opt_F = tmp;
307				break;
308			}
309		case 'g':
310			options.no_plt = 1;
311			break;
312		case 'h':
313			usage();
314			exit(0);
315		case 'i':
316			opt_i++;
317			break;
318		case 'l':
319			if (library_num == MAX_LIBRARIES) {
320				fprintf(stderr,
321					"Too many libraries.  Maximum is %i.\n",
322					MAX_LIBRARIES);
323				exit(1);
324			}
325			library[library_num++] = optarg;
326			break;
327		case 'L':
328			options.libcalls = 0;
329			break;
330		case 'n':
331			options.indent = atoi(optarg);
332			break;
333		case 'o':
334			options.output = fopen(optarg, "w");
335			if (!options.output) {
336				fprintf(stderr,
337					"Can't open %s for output: %s\n",
338					optarg, strerror(errno));
339				exit(1);
340			}
341			setvbuf(options.output, (char *)NULL, _IOLBF, 0);
342			fcntl(fileno(options.output), F_SETFD, FD_CLOEXEC);
343			break;
344		case 'p':
345			{
346				struct opt_p_t *tmp = malloc(sizeof(struct opt_p_t));
347				if (!tmp) {
348					perror("ltrace: malloc");
349					exit(1);
350				}
351				tmp->pid = atoi(optarg);
352				tmp->next = opt_p;
353				opt_p = tmp;
354				break;
355			}
356		case 'r':
357			opt_r++;
358			break;
359		case 's':
360			options.strlen = atoi(optarg);
361			break;
362		case 'S':
363			options.syscalls = 1;
364			break;
365		case 't':
366			opt_t++;
367			break;
368		case 'T':
369			opt_T++;
370			break;
371		case 'u':
372			options.user = optarg;
373			break;
374		case 'V':
375			printf("ltrace version " PACKAGE_VERSION ".\n"
376					"Copyright (C) 1997-2009 Juan Cespedes <cespedes@debian.org>.\n"
377					"This is free software; see the GNU General Public Licence\n"
378					"version 2 or later for copying conditions.  There is NO warranty.\n");
379			exit(0);
380			break;
381#if defined(HAVE_LIBUNWIND)
382		case 'w':
383			options.bt_depth = atoi(optarg);
384			break;
385#endif /* defined(HAVE_LIBUNWIND) */
386		case 'X':
387#ifdef PLT_REINITALISATION_BP
388			PLTs_initialized_by_here = optarg;
389#else
390			fprintf(stderr, "WARNING: \"-X\" not used for this "
391				"architecture: assuming you meant \"-x\"\n");
392#endif
393			/* Fall Thru */
394
395		case 'x':
396			{
397				struct opt_x_t *p = opt_x;
398
399				/* First, check for duplicate. */
400				while (p && strcmp(p->name, optarg)) {
401					p = p->next;
402				}
403				if (p) {
404					break;
405				}
406
407				/* If not duplicate, add to list. */
408				p = malloc(sizeof(struct opt_x_t));
409				if (!p) {
410					perror("ltrace: malloc");
411					exit(1);
412				}
413				opt_x_cnt++;
414				p->name = optarg;
415				p->found = 0;
416				p->next = opt_x;
417				p->hash = ~(0UL);
418				opt_x = p;
419				break;
420			}
421
422		default:
423			err_usage();
424		}
425	}
426	argc -= optind;
427	argv += optind;
428
429	if (!opt_F) {
430		opt_F = malloc(sizeof(struct opt_F_t));
431		opt_F->next = malloc(sizeof(struct opt_F_t));
432		opt_F->next->next = NULL;
433		opt_F->filename = USER_CONFIG_FILE;
434		opt_F->next->filename = SYSTEM_CONFIG_FILE;
435	}
436	/* Reverse the config file list since it was built by
437	 * prepending, and it would make more sense to process the
438	 * files in the order they were given. Probably it would make
439	 * more sense to keep a tail pointer instead? */
440	{
441		struct opt_F_t *egg = NULL;
442		struct opt_F_t *chicken;
443		while (opt_F) {
444			chicken = opt_F->next;
445			opt_F->next = egg;
446			egg = opt_F;
447			opt_F = chicken;
448		}
449		opt_F = egg;
450	}
451
452	if (!opt_p && argc < 1) {
453		fprintf(stderr, "%s: too few arguments\n", progname);
454		err_usage();
455	}
456	if (opt_r && opt_t) {
457		fprintf(stderr, "%s: Incompatible options -r and -t\n",
458			progname);
459		err_usage();
460	}
461	if (argc > 0) {
462		command = search_for_command(argv[0]);
463	}
464	return &argv[0];
465}
466