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