2 * This file is part of ltrace.
3 * Copyright (C) 2012, 2013 Petr Machata, Red Hat Inc.
4 * Copyright (C) 2009,2010 Joe Damato
5 * Copyright (C) 1998,1999,2002,2003,2004,2007,2008,2009 Juan Cespedes
6 * Copyright (C) 2006 Ian Wienand
7 * Copyright (C) 2006 Steve Fink
8 * Copyright (C) 2006 Paul Gilliam, IBM Corporation
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License as
12 * published by the Free Software Foundation; either version 2 of the
13 * License, or (at your option) any later version.
15 * This program is distributed in the hope that it will be useful, but
16 * WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 * General Public License for more details.
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, write to the Free Software
22 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
28 #include <sys/ioctl.h>
30 #include <sys/types.h>
46 struct options_t options = {
47 .align = DEFAULT_ALIGN, /* alignment column for results */
48 .user = NULL, /* username to run command as */
49 .syscalls = 0, /* display syscalls */
51 .demangle = 0, /* Demangle low-level symbol names */
53 .indent = 0, /* indent output according to program flow */
54 .output = NULL, /* output to a specific file */
55 .summary = 0, /* Report a summary on program exit */
56 .debug = 0, /* debug */
57 .arraylen = DEFAULT_ARRAYLEN, /* maximum # array elements to print */
58 .strlen = DEFAULT_STRLEN, /* maximum # of bytes printed in strings */
59 .follow = 0, /* trace child processes */
62 static char *progname; /* Program name (`ltrace') */
63 int opt_i = 0; /* instruction pointer */
64 int opt_r = 0; /* print relative timestamp */
65 int opt_t = 0; /* print absolute timestamp */
66 int opt_T = 0; /* show the time spent inside each call */
68 /* List of pids given to option -p: */
69 struct opt_p_t *opt_p = NULL; /* attach to process with a given pid */
71 /* Vector of struct opt_F_t. */
76 fprintf(stderr, "Try `%s --help' for more information.\n", progname);
82 fprintf(stdout, "Usage: %s [option ...] [command [arg ...]]\n"
83 "Trace library calls of a given program.\n\n"
84 " -a, --align=COLUMN align return values in a secific column.\n"
85 " -A MAXELTS maximum number of array elements to print.\n"
86 " -b, --no-signals don't print signals.\n"
87 " -c count time and calls, and report a summary on exit.\n"
89 " -C, --demangle decode low-level symbol names into user-level names.\n"
91 " -D, --debug=MASK enable debugging (see -Dh or --debug=help).\n"
92 " -Dh, --debug=help show help on debugging.\n"
93 " -e FILTER modify which library calls to trace.\n"
94 " -f trace children (fork() and clone()).\n"
95 " -F, --config=FILE load alternate configuration file (may be repeated).\n"
96 " -h, --help display this help and exit.\n"
97 " -i print instruction pointer at time of library call.\n"
98 " -l, --library=LIBRARY_PATTERN only trace symbols implemented by this library.\n"
99 " -L do NOT display library calls.\n"
100 " -n, --indent=NR indent output by NR spaces for each call level nesting.\n"
101 " -o, --output=FILENAME write the trace output to file with given name.\n"
102 " -p PID attach to the process with the process ID pid.\n"
103 " -r print relative timestamps.\n"
104 " -s STRSIZE specify the maximum string size to print.\n"
105 " -S trace system calls as well as library calls.\n"
106 " -t, -tt, -ttt print absolute timestamps.\n"
107 " -T show the time spent inside each call.\n"
108 " -u USERNAME run command with the userid, groupid of username.\n"
109 " -V, --version output version information and exit.\n"
110 #if defined(HAVE_LIBUNWIND)
111 " -w, --where=NR print backtrace showing NR stack frames at most.\n"
112 #endif /* defined(HAVE_LIBUNWIND) */
113 " -x FILTER modify which static functions to trace.\n"
114 "\nReport bugs to ltrace-devel@lists.alioth.debian.org\n",
120 fprintf(stdout, "%s debugging option, --debug=<octal> or -D<octal>:\n", progname);
123 " number ref. in source description\n"
124 " 1 general Generally helpful progress information\n"
125 " 10 event Shows every event received by a traced process\n"
126 " 20 process Shows actions carried upon a traced processes\n"
127 " 40 function Shows every entry to internal functions\n"
129 "Debugging options are mixed using bitwise-or.\n"
130 "Note that the meanings and values are subject to change.\n"
135 search_for_command(char *filename) {
136 static char pathname[PATH_MAX];
140 if (strchr(filename, '/')) {
143 for (path = getenv("PATH"); path && *path; path += m) {
144 if (strchr(path, ':')) {
145 n = strchr(path, ':') - path;
148 m = n = strlen(path);
150 if (n + strlen(filename) + 1 >= PATH_MAX) {
151 fprintf(stderr, "Error: filename too long.\n");
154 strncpy(pathname, path, n);
155 if (n && pathname[n - 1] != '/') {
158 strcpy(pathname + n, filename);
159 if (!access(pathname, X_OK)) {
171 options.align = DEFAULT_ALIGN;
172 c = getenv("COLUMNS");
176 cols = strtol(c, &endptr, 0);
177 if (cols > 0 && !*endptr) {
178 options.align = cols * 5 / 8;
180 } else if (ioctl(1, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
181 options.align = ws.ws_col * 5 / 8;
182 } else if (ioctl(2, TIOCGWINSZ, &ws) != -1 && ws.ws_col > 0) {
183 options.align = ws.ws_col * 5 / 8;
188 compile_libname(const char *expr, const char *a_lib, int lib_re_p,
189 struct filter_lib_matcher *matcher)
191 if (strcmp(a_lib, "MAIN") == 0) {
192 filter_lib_matcher_main_init(matcher);
194 /* Add ^ and $ to the library expression as well. */
195 char lib[strlen(a_lib) + 3];
196 sprintf(lib, "^%s$", a_lib);
198 enum filter_lib_matcher_type type
199 = lib[0] == '/' ? FLM_PATHNAME : FLM_SONAME;
202 int status = (lib_re_p ? regcomp : globcomp)(&lib_re, lib, 0);
205 regerror(status, &lib_re, buf, sizeof buf);
206 fprintf(stderr, "Couldn't compile '%s': %s.\n",
210 filter_lib_matcher_name_init(matcher, type, lib_re);
216 add_filter_rule(struct filter *filt, const char *expr,
217 enum filter_rule_type type,
218 const char *a_sym, int sym_re_p,
219 const char *a_lib, int lib_re_p)
221 struct filter_rule *rule = malloc(sizeof(*rule));
222 struct filter_lib_matcher *matcher = malloc(sizeof(*matcher));
224 if (rule == NULL || matcher == NULL) {
233 /* Add ^ to the start of expression and $ to the end, so that
234 * we match the whole symbol name. Let the user write the "*"
235 * explicitly if they wish. */
236 char sym[strlen(a_sym) + 3];
237 sprintf(sym, "^%s$", a_sym);
238 int status = (sym_re_p ? regcomp : globcomp)
239 (&symbol_re, sym, 0);
242 regerror(status, &symbol_re, buf, sizeof buf);
243 fprintf(stderr, "Couldn't compile '%s': %s.\n",
249 if (compile_libname(expr, a_lib, lib_re_p, matcher) < 0) {
254 filter_rule_init(rule, type, matcher, symbol_re);
255 filter_add_rule(filt, rule);
260 grok_libname_pattern(char **libnamep, char **libendp)
262 char *libname = *libnamep;
263 char *libend = *libendp;
265 if (libend[0] != '/')
269 if (libname != libend && libname[0] == '/')
272 fprintf(stderr, "Unmatched '/' in library name.\n");
280 parse_filter(struct filter *filt, char *expr, int operators)
282 /* Filter is a chain of sym@lib rules separated by '-' or '+'.
283 * If the filter expression starts with '-', the missing
284 * initial rule is implicitly *@*. */
286 enum filter_rule_type type = FR_ADD;
289 size_t s = strcspn(expr, &"-+@"[operators ? 0 : 2]);
290 char *symname = expr;
292 char *next = expr + s + 1;
293 enum filter_rule_type this_type = type;
299 } else if (expr[s] == '-' || expr[s] == '+') {
300 type = expr[s] == '-' ? FR_SUBTRACT : FR_ADD;
306 assert(expr[s] == '@');
308 s = strcspn(next, &"-+"[operators ? 0 : 2]);
312 } else if (next[s] == 0) {
316 assert(next[s] == '-' || next[s] == '+');
317 type = next[s] == '-' ? FR_SUBTRACT : FR_ADD;
324 assert(*libname != 0);
325 char *symend = symname + strlen(symname) - 1;
326 char *libend = libname + strlen(libname) - 1;
331 * /xxx/@... and ...@/xxx/ means that xxx are regular
332 * expressions. They are globs otherwise.
334 * /xxx@yyy/ is the same as /xxx/@/yyy/
336 * @/xxx matches library path name
337 * @.xxx matches library relative path name
339 if (symname[0] == '/') {
340 if (symname != symend && symend[0] == '/') {
350 /* /XXX@YYY/ is the same as
352 if (libend[0] != '/')
353 fprintf(stderr, "Unmatched '/'"
354 " in symbol name.\n");
360 /* If libname ends in '/', then we expect '/' in the
361 * beginning too. Otherwise the initial '/' is part
362 * of absolute file name. */
364 lib_is_re = grok_libname_pattern(&libname, &libend);
366 if (*symname == 0) /* /@AA/ */
368 if (*libname == 0) /* /aa@/ */
371 add_filter_rule(filt, expr, this_type,
379 static struct filter *
380 recursive_parse_chain(const char *orig, char *expr, int operators)
382 struct filter *filt = malloc(sizeof(*filt));
384 fprintf(stderr, "(Part of) filter will be ignored: '%s': %s.\n",
385 expr, strerror(errno));
390 if (parse_filter(filt, expr, operators) < 0) {
391 fprintf(stderr, "Filter '%s' will be ignored.\n", orig);
399 static struct filter **
400 slist_chase_end(struct filter **begin)
402 for (; *begin != NULL; begin = &(*begin)->next)
408 parse_filter_chain(const char *expr, struct filter **retp)
410 char *str = strdup(expr);
412 fprintf(stderr, "Filter '%s' will be ignored: %s.\n",
413 expr, strerror(errno));
416 /* Support initial '!' for backward compatibility. */
420 *slist_chase_end(retp) = recursive_parse_chain(expr, str, 1);
425 parse_int(const char *optarg, char opt, int min, int max)
428 long int l = strtol(optarg, &endptr, 0);
429 if (l < min || (max != 0 && l > max)
430 || *optarg == 0 || *endptr != 0) {
431 const char *fmt = max != 0
432 ? "Invalid argument to -%c: '%s'. Use integer %d..%d.\n"
433 : "Invalid argument to -%c: '%s'. Use integer >=%d.\n";
434 fprintf(stderr, fmt, opt, optarg, min, max);
441 parse_colon_separated_list(const char *paths, struct vect *vec)
443 /* PATHS contains a colon-separated list of directories and
444 * files to load. It's modeled after shell PATH variable,
445 * which doesn't allow escapes. PYTHONPATH in CPython behaves
446 * the same way. So let's follow suit, it makes things easier
449 char *clone = strdup(paths);
451 fprintf(stderr, "Couldn't parse argument %s: %s.\n",
452 paths, strerror(errno));
456 /* It's undesirable to use strtok, because we want the string
457 * "a::b" to have three elements. */
458 char *tok = clone - 1;
459 char *end = clone + strlen(clone);
462 size_t len = strcspn(tok, ":");
465 struct opt_F_t arg = {
467 .own_pathname = tok == clone,
469 if (VECT_PUSHBACK(vec, &arg) < 0)
470 /* Presumably this is not a deal-breaker. */
471 fprintf(stderr, "Couldn't store component of %s: %s.\n",
472 paths, strerror(errno));
481 opt_F_destroy(struct opt_F_t *entry)
485 if (entry->own_pathname)
486 free(entry->pathname);
490 opt_F_get_kind(struct opt_F_t *entry)
492 if (entry->kind == OPT_F_UNKNOWN) {
494 if (lstat(entry->pathname, &st) < 0) {
495 fprintf(stderr, "Couldn't stat %s: %s\n",
496 entry->pathname, strerror(errno));
497 entry->kind = OPT_F_BROKEN;
498 } else if (S_ISDIR(st.st_mode)) {
499 entry->kind = OPT_F_DIR;
500 } else if (S_ISREG(st.st_mode) || S_ISLNK(st.st_mode)) {
501 entry->kind = OPT_F_FILE;
503 fprintf(stderr, "%s is neither a regular file, "
504 "nor a directory.\n", entry->pathname);
505 entry->kind = OPT_F_BROKEN;
508 assert(entry->kind != OPT_F_UNKNOWN);
513 process_options(int argc, char **argv)
515 VECT_INIT(&opt_F, struct opt_F_t);
518 options.output = stderr;
519 options.no_signals = 0;
520 #if defined(HAVE_LIBUNWIND)
521 options.bt_depth = -1;
522 #endif /* defined(HAVE_LIBUNWIND) */
531 #ifdef HAVE_GETOPT_LONG
532 int option_index = 0;
533 static struct option long_options[] = {
534 {"align", 1, 0, 'a'},
535 {"config", 1, 0, 'F'},
536 {"debug", 1, 0, 'D'},
538 {"demangle", 0, 0, 'C'},
540 {"indent", 1, 0, 'n'},
542 {"library", 1, 0, 'l'},
543 {"output", 1, 0, 'o'},
544 {"version", 0, 0, 'V'},
545 {"no-signals", 0, 0, 'b'},
546 # if defined(HAVE_LIBUNWIND)
547 {"where", 1, 0, 'w'},
548 # endif /* defined(HAVE_LIBUNWIND) */
553 const char *opts = "+"
557 #if defined(HAVE_LIBUNWIND)
560 "cfhiLrStTVba:A:D:e:F:l:n:o:p:s:u:x:X:";
562 #ifdef HAVE_GETOPT_LONG
563 c = getopt_long(argc, argv, opts, long_options, &option_index);
565 c = getopt(argc, argv, opts);
572 options.align = parse_int(optarg, 'a', 0, 0);
575 options.arraylen = parse_int(optarg, 'A', 0, 0);
578 options.no_signals = 1;
589 if (optarg[0]=='h') {
593 options.debug = strtoul(optarg,&p,8);
595 fprintf(stderr, "%s: --debug requires an octal argument\n", progname);
601 parse_filter_chain(optarg, &options.plt_filter);
608 parse_colon_separated_list(optarg, &opt_F);
618 size_t patlen = strlen(optarg);
619 char buf[patlen + 2];
620 sprintf(buf, "@%s", optarg);
621 *slist_chase_end(&options.export_filter)
622 = recursive_parse_chain(buf, buf, 0);
630 options.indent = parse_int(optarg, 'n', 0, 20);
633 options.output = fopen(optarg, "w");
634 if (!options.output) {
636 "can't open %s for writing: %s\n",
637 optarg, strerror(errno));
640 setvbuf(options.output, (char *)NULL, _IOLBF, 0);
641 fcntl(fileno(options.output), F_SETFD, FD_CLOEXEC);
645 struct opt_p_t *tmp = malloc(sizeof(struct opt_p_t));
647 perror("ltrace: malloc");
650 tmp->pid = parse_int(optarg, 'p', 1, 0);
659 options.strlen = parse_int(optarg, 's', 0, 0);
662 options.syscalls = 1;
671 options.user = optarg;
674 printf("ltrace " PACKAGE_VERSION "\n"
675 "Copyright (C) 2010-2013 Petr Machata, Red Hat Inc.\n"
676 "Copyright (C) 1997-2009 Juan Cespedes <cespedes@debian.org>.\n"
677 "License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>\n"
678 "This is free software: you are free to change and redistribute it.\n"
679 "There is NO WARRANTY, to the extent permitted by law.\n");
682 #if defined(HAVE_LIBUNWIND)
684 options.bt_depth = parse_int(optarg, 'w', 1, 0);
686 #endif /* defined(HAVE_LIBUNWIND) */
689 parse_filter_chain(optarg, &options.static_filter);
699 /* If neither -e, nor -l, nor -L are used, set default -e.
700 * Use @MAIN for now, as that's what ltrace used to have in
701 * the past. XXX Maybe we should make this "*" instead. */
703 && options.plt_filter == NULL
704 && options.export_filter == NULL) {
705 parse_filter_chain("@MAIN", &options.plt_filter);
706 options.hide_caller = 1;
708 if (!libcalls && options.plt_filter != NULL) {
710 "%s: Option -L can't be used with -e or -l.\n",
715 if (!opt_p && argc < 1) {
716 fprintf(stderr, "%s: too few arguments\n", progname);
719 if (opt_r && opt_t) {
721 "%s: Options -r and -t can't be used together\n",
726 command = search_for_command(argv[0]);