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