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