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