output.c revision 1b02c7398257f4b62cde3907c8f2d3b8348c2f74
1/*
2 * This file is part of ltrace.
3 * Copyright (C) 2011,2012,2013 Petr Machata, Red Hat Inc.
4 * Copyright (C) 2010 Joe Damato
5 * Copyright (C) 1997,1998,1999,2001,2002,2003,2004,2007,2008,2009 Juan Cespedes
6 * Copyright (C) 2006 Paul Gilliam, IBM Corporation
7 * Copyright (C) 2006 Ian Wienand
8 *
9 * This program is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU General Public License as
11 * published by the Free Software Foundation; either version 2 of the
12 * License, or (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17 * General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program; if not, write to the Free Software
21 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
22 * 02110-1301 USA
23 */
24
25#include "config.h"
26
27#include <stdio.h>
28#include <stdlib.h>
29#include <stdarg.h>
30#include <string.h>
31#include <time.h>
32#include <sys/time.h>
33#include <unistd.h>
34#include <errno.h>
35#include <assert.h>
36
37#include "output.h"
38#include "demangle.h"
39#include "fetch.h"
40#include "lens_default.h"
41#include "library.h"
42#include "memstream.h"
43#include "options.h"
44#include "param.h"
45#include "proc.h"
46#include "prototype.h"
47#include "type.h"
48#include "value.h"
49#include "value_dict.h"
50
51/* TODO FIXME XXX: include in common.h: */
52extern struct timeval current_time_spent;
53
54struct dict *dict_opt_c = NULL;
55
56static struct process *current_proc = 0;
57static size_t current_depth = 0;
58static int current_column = 0;
59
60static void
61output_indent(struct process *proc)
62{
63	int d = options.indent * (proc->callstack_depth - 1);
64	current_column += fprintf(options.output, "%*s", d, "");
65}
66
67static void
68begin_of_line(struct process *proc, int is_func, int indent)
69{
70	current_column = 0;
71	if (!proc) {
72		return;
73	}
74	if ((options.output != stderr) && (opt_p || options.follow)) {
75		current_column += fprintf(options.output, "%u ", proc->pid);
76	} else if (options.follow) {
77		current_column += fprintf(options.output, "[pid %u] ", proc->pid);
78	}
79	if (opt_r) {
80		struct timeval tv;
81		static struct timeval old_tv = { 0, 0 };
82		struct timeval diff;
83
84		gettimeofday(&tv, NULL);
85
86		if (old_tv.tv_sec == 0 && old_tv.tv_usec == 0) {
87			old_tv.tv_sec = tv.tv_sec;
88			old_tv.tv_usec = tv.tv_usec;
89		}
90		diff.tv_sec = tv.tv_sec - old_tv.tv_sec;
91		if (tv.tv_usec >= old_tv.tv_usec) {
92			diff.tv_usec = tv.tv_usec - old_tv.tv_usec;
93		} else {
94			diff.tv_sec--;
95			diff.tv_usec = 1000000 + tv.tv_usec - old_tv.tv_usec;
96		}
97		old_tv.tv_sec = tv.tv_sec;
98		old_tv.tv_usec = tv.tv_usec;
99		current_column += fprintf(options.output, "%3lu.%06d ",
100					  (unsigned long)diff.tv_sec,
101					  (int)diff.tv_usec);
102	}
103	if (opt_t) {
104		struct timeval tv;
105		gettimeofday(&tv, NULL);
106		if (opt_t > 2) {
107			current_column += fprintf(options.output, "%lu.%06d ",
108						  (unsigned long)tv.tv_sec,
109						  (int)tv.tv_usec);
110		} else if (opt_t > 1) {
111			struct tm *tmp = localtime(&tv.tv_sec);
112			current_column +=
113			    fprintf(options.output, "%02d:%02d:%02d.%06d ",
114				    tmp->tm_hour, tmp->tm_min, tmp->tm_sec,
115				    (int)tv.tv_usec);
116		} else {
117			struct tm *tmp = localtime(&tv.tv_sec);
118			current_column += fprintf(options.output, "%02d:%02d:%02d ",
119						  tmp->tm_hour, tmp->tm_min,
120						  tmp->tm_sec);
121		}
122	}
123	if (opt_i) {
124		if (is_func)
125			current_column += fprintf(options.output, "[%p] ",
126						  proc->return_addr);
127		else
128			current_column += fprintf(options.output, "[%p] ",
129						  proc->instruction_pointer);
130	}
131	if (options.indent > 0 && indent) {
132		output_indent(proc);
133	}
134}
135
136static struct arg_type_info *
137get_unknown_type(void)
138{
139	static struct arg_type_info *ret = NULL;
140	if (ret != NULL)
141		return ret;
142
143	static struct arg_type_info info;
144	info = *type_get_simple(ARGTYPE_LONG);
145	info.lens = &guess_lens;
146	ret = &info;
147	return ret;
148}
149
150/* The default prototype is: long X(long, long, long, long).  */
151static struct prototype *
152build_default_prototype(void)
153{
154	static struct prototype *ret = NULL;
155	if (ret != NULL)
156		return ret;
157
158	static struct prototype proto;
159	prototype_init(&proto);
160
161	struct arg_type_info *unknown_type = get_unknown_type();
162	assert(unknown_type != NULL);
163	proto.return_info = unknown_type;
164	proto.own_return_info = 0;
165
166	struct param unknown_param;
167	param_init_type(&unknown_param, unknown_type, 0);
168
169	size_t i;
170	for (i = 0; i < 4; ++i)
171		if (prototype_push_param(&proto, &unknown_param) < 0) {
172			report_global_error("build_default_prototype: %s",
173					    strerror(errno));
174			prototype_destroy(&proto);
175			return NULL;
176		}
177
178	ret = &proto;
179	return ret;
180}
181
182static struct prototype *
183library_get_prototype(struct library *lib, const char *name)
184{
185	if (lib->protolib == NULL)
186		lib->protolib = protolib_cache_search(&g_protocache,
187						      lib->soname, 0, 1);
188	if (lib->protolib == NULL)
189		return NULL;
190
191	return protolib_lookup_prototype(lib->protolib, name);
192}
193
194struct find_proto_data {
195	const char *name;
196	struct prototype *ret;
197};
198
199static enum callback_status
200find_proto_cb(struct process *proc, struct library *lib, void *d)
201{
202	struct find_proto_data *data = d;
203	data->ret = library_get_prototype(lib, data->name);
204	return CBS_STOP_IF(data->ret != NULL);
205}
206
207static struct prototype *
208lookup_symbol_prototype(struct process *proc, struct library_symbol *libsym)
209{
210	struct library *lib = libsym->lib;
211	if (lib != NULL) {
212		struct find_proto_data data = { libsym->name };
213		data.ret = library_get_prototype(lib, libsym->name);
214		if (data.ret == NULL
215		    && libsym->plt_type == LS_TOPLT_EXEC)
216			proc_each_library(proc, NULL, find_proto_cb, &data);
217		if (data.ret != NULL)
218			return data.ret;
219	}
220
221	return build_default_prototype();
222}
223
224void
225output_line(struct process *proc, const char *fmt, ...)
226{
227	if (options.summary)
228		return;
229
230	if (current_proc != NULL) {
231		if (current_proc->callstack[current_depth].return_addr)
232			fprintf(options.output, " <unfinished ...>\n");
233		else
234			fprintf(options.output, " <no return ...>\n");
235	}
236	current_proc = NULL;
237	if (fmt == NULL)
238		return;
239
240	begin_of_line(proc, 0, 0);
241
242	va_list args;
243	va_start(args, fmt);
244	vfprintf(options.output, fmt, args);
245	fprintf(options.output, "\n");
246	va_end(args);
247
248	current_column = 0;
249}
250
251static void
252tabto(int col) {
253	if (current_column < col) {
254		fprintf(options.output, "%*s", col - current_column, "");
255	}
256}
257
258static int
259output_error(FILE *stream)
260{
261	return fprintf(stream, "?");
262}
263
264static int
265fetch_simple_param(enum tof type, struct process *proc,
266		   struct fetch_context *context,
267		   struct value_dict *arguments,
268		   struct arg_type_info *info, int own,
269		   struct value *valuep)
270{
271	/* Arrays decay into pointers per C standard.  We check for
272	 * this here, because here we also capture arrays that come
273	 * from parameter packs.  */
274	if (info->type == ARGTYPE_ARRAY) {
275		struct arg_type_info *tmp = malloc(sizeof(*tmp));
276		if (tmp != NULL) {
277			type_init_pointer(tmp, info, own);
278			tmp->lens = info->lens;
279			info = tmp;
280			own = 1;
281		}
282	}
283
284	struct value value;
285	value_init(&value, proc, NULL, info, own);
286	if (fetch_arg_next(context, type, proc, info, &value) < 0)
287		return -1;
288
289	if (val_dict_push_next(arguments, &value) < 0) {
290		value_destroy(&value);
291		return -1;
292	}
293
294	if (valuep != NULL)
295		*valuep = value;
296
297	return 0;
298}
299
300static void
301fetch_param_stop(struct value_dict *arguments, ssize_t *params_leftp)
302{
303	if (*params_leftp == -1)
304		*params_leftp = val_dict_count(arguments);
305}
306
307static int
308fetch_param_pack(enum tof type, struct process *proc,
309		 struct fetch_context *context,
310		 struct value_dict *arguments, struct param *param,
311		 ssize_t *params_leftp)
312{
313	struct param_enum *e = param_pack_init(param, arguments);
314	if (e == NULL)
315		return -1;
316
317	int ret = 0;
318	while (1) {
319		int insert_stop = 0;
320		struct arg_type_info *info = malloc(sizeof(*info));
321		if (info == NULL
322		    || param_pack_next(param, e, info, &insert_stop) < 0) {
323		fail:
324			free(info);
325			ret = -1;
326			break;
327		}
328
329		if (insert_stop)
330			fetch_param_stop(arguments, params_leftp);
331
332		if (info->type == ARGTYPE_VOID) {
333			type_destroy(info);
334			free(info);
335			break;
336		}
337
338		struct value val;
339		if (fetch_simple_param(type, proc, context, arguments,
340				       info, 1, &val) < 0)
341			goto fail;
342
343		int stop = 0;
344		switch (param_pack_stop(param, e, &val)) {
345		case PPCB_ERR:
346			goto fail;
347		case PPCB_STOP:
348			stop = 1;
349		case PPCB_CONT:
350			break;
351		}
352
353		if (stop)
354			break;
355	}
356
357	param_pack_done(param, e);
358	return ret;
359}
360
361static int
362fetch_one_param(enum tof type, struct process *proc,
363		struct fetch_context *context,
364		struct value_dict *arguments, struct param *param,
365		ssize_t *params_leftp)
366{
367	switch (param->flavor) {
368		int rc;
369	case PARAM_FLAVOR_TYPE:
370		return fetch_simple_param(type, proc, context, arguments,
371					  param->u.type.type, 0, NULL);
372
373	case PARAM_FLAVOR_PACK:
374		if (fetch_param_pack_start(context,
375					   param->u.pack.ppflavor) < 0)
376			return -1;
377	        rc = fetch_param_pack(type, proc, context, arguments,
378				      param, params_leftp);
379		fetch_param_pack_end(context);
380		return rc;
381
382	case PARAM_FLAVOR_STOP:
383		fetch_param_stop(arguments, params_leftp);
384		return 0;
385	}
386
387	assert(!"Invalid param flavor!");
388	abort();
389}
390
391struct fetch_one_param_data
392{
393	struct process *proc;
394	struct fetch_context *context;
395	struct value_dict *arguments;
396	ssize_t *params_leftp;
397	enum tof tof;
398};
399
400static enum callback_status
401fetch_one_param_cb(struct prototype *proto, struct param *param, void *data)
402{
403	struct fetch_one_param_data *cb_data = data;
404	return CBS_STOP_IF(fetch_one_param(cb_data->tof, cb_data->proc,
405					   cb_data->context,
406					   cb_data->arguments, param,
407					   cb_data->params_leftp) < 0);
408}
409
410static int
411fetch_params(enum tof type, struct process *proc,
412	     struct fetch_context *context,
413	     struct value_dict *arguments, struct prototype *func,
414	     ssize_t *params_leftp)
415{
416	struct fetch_one_param_data cb_data
417		= { proc, context, arguments, params_leftp, type };
418	if (prototype_each_param(func, NULL,
419				 &fetch_one_param_cb, &cb_data) != NULL)
420		return -1;
421
422	/* Implicit stop at the end of parameter list.  */
423	fetch_param_stop(arguments, params_leftp);
424
425	return 0;
426}
427
428struct format_argument_data
429{
430	struct value *value;
431	struct value_dict *arguments;
432};
433
434static int
435format_argument_cb(FILE *stream, void *ptr)
436{
437	struct format_argument_data *data = ptr;
438	int o = format_argument(stream, data->value, data->arguments);
439	if (o < 0)
440		o = output_error(stream);
441	return o;
442}
443
444static int
445output_params(struct value_dict *arguments, size_t start, size_t end,
446	      int *need_delimp)
447{
448	size_t i;
449	for (i = start; i < end; ++i) {
450		struct value *value = val_dict_get_num(arguments, i);
451		if (value == NULL)
452			return -1;
453
454		struct format_argument_data data = { value, arguments };
455		int o = delim_output(options.output, need_delimp,
456				     format_argument_cb, &data);
457		if (o < 0)
458			return -1;
459		current_column += o;
460	}
461	return 0;
462}
463
464void
465output_left(enum tof type, struct process *proc,
466	    struct library_symbol *libsym)
467{
468	if (options.summary) {
469		return;
470	}
471	if (current_proc) {
472		fprintf(options.output, " <unfinished ...>\n");
473		current_column = 0;
474	}
475	current_proc = proc;
476	current_depth = proc->callstack_depth;
477	begin_of_line(proc, type == LT_TOF_FUNCTION, 1);
478	if (!options.hide_caller && libsym->lib != NULL
479	    && libsym->plt_type != LS_TOPLT_NONE)
480		/* We don't terribly mind failing this.  */
481		account_output(&current_column,
482			       fprintf(options.output, "%s->",
483				       libsym->lib->soname));
484
485	const char *name = libsym->name;
486#ifdef USE_DEMANGLE
487	if (options.demangle)
488		name = my_demangle(libsym->name);
489#endif
490	if (account_output(&current_column,
491			   fprintf(options.output, "%s", name)) < 0)
492		return;
493
494	if (libsym->lib != NULL
495	    && libsym->lib->type != LT_LIBTYPE_MAIN
496	    && libsym->plt_type == LS_TOPLT_NONE
497	    && account_output(&current_column,
498			      fprintf(options.output, "@%s",
499				      libsym->lib->soname)) < 0)
500		/* We do mind failing this though.  */
501		return;
502
503	account_output(&current_column, fprintf(options.output, "("));
504
505	struct prototype *func = lookup_symbol_prototype(proc, libsym);
506	if (func == NULL) {
507	fail:
508		account_output(&current_column, fprintf(options.output, "???"));
509		return;
510	}
511
512	struct fetch_context *context = fetch_arg_init(type, proc,
513						       func->return_info);
514	if (context == NULL)
515		goto fail;
516
517	struct value_dict *arguments = malloc(sizeof(*arguments));
518	if (arguments == NULL) {
519		fetch_arg_done(context);
520		goto fail;
521	}
522	val_dict_init(arguments);
523
524	ssize_t params_left = -1;
525	int need_delim = 0;
526	if (fetch_params(type, proc, context, arguments, func, &params_left) < 0
527	    || output_params(arguments, 0, params_left, &need_delim) < 0) {
528		val_dict_destroy(arguments);
529		fetch_arg_done(context);
530		arguments = NULL;
531		context = NULL;
532	}
533
534	struct callstack_element *stel
535		= &proc->callstack[proc->callstack_depth - 1];
536	stel->fetch_context = context;
537	stel->arguments = arguments;
538	stel->out.params_left = params_left;
539	stel->out.need_delim = need_delim;
540}
541
542static void
543free_stringp_cb(const char **stringp, void *data)
544{
545	free((char *)*stringp);
546}
547
548void
549output_right(enum tof type, struct process *proc, struct library_symbol *libsym)
550{
551	struct prototype *func = lookup_symbol_prototype(proc, libsym);
552	if (func == NULL)
553		return;
554
555again:
556	if (options.summary) {
557		if (dict_opt_c == NULL) {
558			dict_opt_c = malloc(sizeof(*dict_opt_c));
559			if (dict_opt_c == NULL) {
560			oom:
561				fprintf(stderr,
562					"Can't allocate memory for "
563					"keeping track of -c.\n");
564				free(dict_opt_c);
565				options.summary = 0;
566				goto again;
567			}
568			DICT_INIT(dict_opt_c, const char *, struct opt_c_struct,
569				  dict_hash_string, dict_eq_string, NULL);
570		}
571
572		struct opt_c_struct *st
573			= DICT_FIND_REF(dict_opt_c, &libsym->name,
574					struct opt_c_struct);
575		if (st == NULL) {
576			const char *na = strdup(libsym->name);
577			struct opt_c_struct new_st = {.count = 0, .tv = {0, 0}};
578			if (na == NULL
579			    || DICT_INSERT(dict_opt_c, &na, &new_st) < 0) {
580				free((char *)na);
581				DICT_DESTROY(dict_opt_c, const char *,
582					     struct opt_c_struct,
583					     free_stringp_cb, NULL, NULL);
584				goto oom;
585			}
586			st = DICT_FIND_REF(dict_opt_c, &libsym->name,
587					   struct opt_c_struct);
588			assert(st != NULL);
589		}
590
591		if (st->tv.tv_usec + current_time_spent.tv_usec > 1000000) {
592			st->tv.tv_usec += current_time_spent.tv_usec - 1000000;
593			st->tv.tv_sec++;
594		} else {
595			st->tv.tv_usec += current_time_spent.tv_usec;
596		}
597		st->count++;
598		st->tv.tv_sec += current_time_spent.tv_sec;
599		return;
600	}
601
602	if (current_proc && (current_proc != proc ||
603			    current_depth != proc->callstack_depth)) {
604		fprintf(options.output, " <unfinished ...>\n");
605		current_proc = 0;
606	}
607	if (current_proc != proc) {
608		begin_of_line(proc, type == LT_TOF_FUNCTIONR, 1);
609#ifdef USE_DEMANGLE
610		current_column +=
611		    fprintf(options.output, "<... %s resumed> ",
612			    options.demangle ? my_demangle(libsym->name)
613			    : libsym->name);
614#else
615		current_column +=
616		    fprintf(options.output, "<... %s resumed> ", libsym->name);
617#endif
618	}
619
620	struct callstack_element *stel
621		= &proc->callstack[proc->callstack_depth - 1];
622
623	struct fetch_context *context = stel->fetch_context;
624
625	/* Fetch & enter into dictionary the retval first, so that
626	 * other values can use it in expressions.  */
627	struct value retval;
628	int own_retval = 0;
629	if (context != NULL) {
630		value_init(&retval, proc, NULL, func->return_info, 0);
631		own_retval = 1;
632		if (fetch_retval(context, type, proc, func->return_info,
633				 &retval) < 0)
634			value_set_type(&retval, NULL, 0);
635		else if (stel->arguments != NULL
636			   && val_dict_push_named(stel->arguments, &retval,
637						  "retval", 0) == 0)
638			own_retval = 0;
639	}
640
641	if (stel->arguments != NULL)
642		output_params(stel->arguments, stel->out.params_left,
643			      val_dict_count(stel->arguments),
644			      &stel->out.need_delim);
645
646	current_column += fprintf(options.output, ") ");
647	tabto(options.align - 1);
648	fprintf(options.output, "= ");
649
650	if (context != NULL && retval.type != NULL) {
651		struct format_argument_data data = { &retval, stel->arguments };
652		format_argument_cb(options.output, &data);
653	}
654
655	if (own_retval)
656		value_destroy(&retval);
657
658	if (opt_T) {
659		fprintf(options.output, " <%lu.%06d>",
660			(unsigned long)current_time_spent.tv_sec,
661			(int)current_time_spent.tv_usec);
662	}
663	fprintf(options.output, "\n");
664
665#if defined(HAVE_LIBUNWIND)
666	if (options.bt_depth > 0
667	    && proc->unwind_priv != NULL
668	    && proc->unwind_as != NULL) {
669		unw_cursor_t cursor;
670		unw_word_t ip, sp;
671		int unwind_depth = options.bt_depth;
672		char fn_name[100];
673
674		unw_init_remote(&cursor, proc->unwind_as, proc->unwind_priv);
675		while (unwind_depth) {
676			unw_get_reg(&cursor, UNW_REG_IP, &ip);
677			unw_get_reg(&cursor, UNW_REG_SP, &sp);
678			unw_get_proc_name(&cursor, fn_name, 100, NULL);
679			fprintf(options.output, "\t\t\t%s (ip = 0x%lx)\n", fn_name, (long) ip);
680			if (unw_step(&cursor) <= 0)
681				break;
682			unwind_depth--;
683		}
684		fprintf(options.output, "\n");
685	}
686#endif /* defined(HAVE_LIBUNWIND) */
687
688	current_proc = 0;
689	current_column = 0;
690}
691
692int
693delim_output(FILE *stream, int *need_delimp,
694	     int (*writer)(FILE *stream, void *data),
695	     void *data)
696{
697	int o;
698
699	/* If we don't need a delimiter, then we don't need to go
700	 * through a temporary stream.  It's all the same whether
701	 * WRITER emits anything or not.  */
702	if (!*need_delimp) {
703		o = writer(stream, data);
704
705	} else {
706		struct memstream ms;
707		if (memstream_init(&ms) < 0)
708			return -1;
709		o = writer(ms.stream, data);
710		if (memstream_close(&ms) < 0)
711			o = -1;
712		if (o > 0 && ((*need_delimp
713			       && account_output(&o, fprintf(stream, ", ")) < 0)
714			      || fwrite(ms.buf, 1, ms.size, stream) != ms.size))
715			o = -1;
716
717		memstream_destroy(&ms);
718	}
719
720	if (o < 0)
721		return -1;
722
723	*need_delimp = *need_delimp || o > 0;
724	return o;
725}
726
727int
728account_output(int *countp, int c)
729{
730	if (c > 0)
731		*countp += c;
732	return c;
733}
734
735static void
736do_report(const char *filename, unsigned line_no, const char *severity,
737	  const char *fmt, va_list args)
738{
739	char buf[128];
740	vsnprintf(buf, sizeof(buf), fmt, args);
741	buf[sizeof(buf) - 1] = 0;
742	if (filename != NULL)
743		output_line(0, "%s:%d: %s: %s",
744			    filename, line_no, severity, buf);
745	else
746		output_line(0, "%s: %s", severity, buf);
747}
748
749void
750report_error(const char *filename, unsigned line_no, const char *fmt, ...)
751{
752	va_list args;
753	va_start(args, fmt);
754	do_report(filename, line_no, "error", fmt, args);
755	va_end(args);
756}
757
758void
759report_warning(const char *filename, unsigned line_no, const char *fmt, ...)
760{
761	va_list args;
762	va_start(args, fmt);
763	do_report(filename, line_no, "warning", fmt, args);
764	va_end(args);
765}
766
767void
768report_global_error(const char *fmt, ...)
769{
770	va_list args;
771	va_start(args, fmt);
772	do_report(NULL, 0, "error", fmt, args);
773	va_end(args);
774}
775