I now read the DWARF data in addition to the .conf files
[platform/upstream/ltrace.git] / output.c
1 /*
2  * This file is part of ltrace.
3  * Copyright (C) 2011,2012,2013,2014 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 #include <inttypes.h>
37
38 #include "output.h"
39 #include "demangle.h"
40 #include "fetch.h"
41 #include "lens_default.h"
42 #include "library.h"
43 #include "memstream.h"
44 #include "options.h"
45 #include "param.h"
46 #include "proc.h"
47 #include "prototype.h"
48 #include "summary.h"
49 #include "type.h"
50 #include "value.h"
51 #include "value_dict.h"
52 #include "filter.h"
53
54 #if defined(HAVE_LIBDW)
55 #include "dwarf_prototypes.h"
56 #endif
57
58 static struct process *current_proc = NULL;
59 static size_t current_depth = 0;
60 static int current_column = 0;
61
62 static void
63 output_indent(struct process *proc)
64 {
65         int d = options.indent * (proc->callstack_depth - 1);
66         current_column += fprintf(options.output, "%*s", d, "");
67 }
68
69 static void
70 begin_of_line(struct process *proc, int is_func, int indent)
71 {
72         current_column = 0;
73         if (!proc) {
74                 return;
75         }
76         if ((options.output != stderr) && (opt_p || options.follow)) {
77                 current_column += fprintf(options.output, "%u ", proc->pid);
78         } else if (options.follow) {
79                 current_column += fprintf(options.output, "[pid %u] ", proc->pid);
80         }
81         if (opt_r) {
82                 struct timeval tv;
83                 static struct timeval old_tv = { 0, 0 };
84                 struct timeval diff;
85
86                 gettimeofday(&tv, NULL);
87
88                 if (old_tv.tv_sec == 0 && old_tv.tv_usec == 0) {
89                         old_tv.tv_sec = tv.tv_sec;
90                         old_tv.tv_usec = tv.tv_usec;
91                 }
92                 diff.tv_sec = tv.tv_sec - old_tv.tv_sec;
93                 if (tv.tv_usec >= old_tv.tv_usec) {
94                         diff.tv_usec = tv.tv_usec - old_tv.tv_usec;
95                 } else {
96                         diff.tv_sec--;
97                         diff.tv_usec = 1000000 + tv.tv_usec - old_tv.tv_usec;
98                 }
99                 old_tv.tv_sec = tv.tv_sec;
100                 old_tv.tv_usec = tv.tv_usec;
101                 current_column += fprintf(options.output, "%3lu.%06d ",
102                                           (unsigned long)diff.tv_sec,
103                                           (int)diff.tv_usec);
104         }
105         if (opt_t) {
106                 struct timeval tv;
107                 gettimeofday(&tv, NULL);
108                 if (opt_t > 2) {
109                         current_column += fprintf(options.output, "%lu.%06d ",
110                                                   (unsigned long)tv.tv_sec,
111                                                   (int)tv.tv_usec);
112                 } else if (opt_t > 1) {
113                         struct tm *tmp = localtime(&tv.tv_sec);
114                         current_column +=
115                             fprintf(options.output, "%02d:%02d:%02d.%06d ",
116                                     tmp->tm_hour, tmp->tm_min, tmp->tm_sec,
117                                     (int)tv.tv_usec);
118                 } else {
119                         struct tm *tmp = localtime(&tv.tv_sec);
120                         current_column += fprintf(options.output, "%02d:%02d:%02d ",
121                                                   tmp->tm_hour, tmp->tm_min,
122                                                   tmp->tm_sec);
123                 }
124         }
125         if (opt_i) {
126                 if (is_func) {
127                         struct callstack_element *stel
128                                 = &proc->callstack[proc->callstack_depth - 1];
129                         current_column += fprintf(options.output, "[%p] ",
130                                                   stel->return_addr);
131                 } else {
132                         current_column += fprintf(options.output, "[%p] ",
133                                                   proc->instruction_pointer);
134                 }
135         }
136         if (options.indent > 0 && indent) {
137                 output_indent(proc);
138         }
139 }
140
141 static struct arg_type_info *
142 get_unknown_type(void)
143 {
144         static struct arg_type_info *ret = NULL;
145         if (ret != NULL)
146                 return ret;
147
148         static struct arg_type_info info;
149         info = *type_get_simple(ARGTYPE_LONG);
150         info.lens = &guess_lens;
151         ret = &info;
152         return ret;
153 }
154
155 /* The default prototype is: long X(long, long, long, long).  */
156 static struct prototype *
157 build_default_prototype(void)
158 {
159         static struct prototype *ret = NULL;
160         if (ret != NULL)
161                 return ret;
162
163         static struct prototype proto;
164         prototype_init(&proto);
165
166         struct arg_type_info *unknown_type = get_unknown_type();
167         assert(unknown_type != NULL);
168         proto.return_info = unknown_type;
169         proto.own_return_info = 0;
170
171         struct param unknown_param;
172         param_init_type(&unknown_param, unknown_type, 0);
173
174         size_t i;
175         for (i = 0; i < 4; ++i)
176                 if (prototype_push_param(&proto, &unknown_param) < 0) {
177                         report_global_error("build_default_prototype: %s",
178                                             strerror(errno));
179                         prototype_destroy(&proto);
180                         return NULL;
181                 }
182
183         ret = &proto;
184         return ret;
185 }
186
187 static bool
188 snip_period(char *buf)
189 {
190         char *period = strrchr(buf, '.');
191         if (period != NULL && strcmp(period, ".so") != 0) {
192                 *period = 0;
193                 return true;
194         } else {
195                 return false;
196         }
197 }
198
199 static struct prototype *
200 library_get_prototype(struct library *lib, const char *name)
201 {
202         if (lib->protolib == NULL) {
203                 size_t sz = strlen(lib->soname);
204                 char buf[sz + 1];
205                 memcpy(buf, lib->soname, sz + 1);
206
207                 do {
208                         if (protolib_cache_maybe_load(&g_protocache, buf, 0,
209                                                       true, &lib->protolib) < 0)
210                                 return NULL;
211                 } while (lib->protolib == NULL
212                          && lib->type == LT_LIBTYPE_DSO
213                          && snip_period(buf));
214
215 #if defined(HAVE_LIBDW)
216                 // DWARF data fills in the gaps in the .conf files, so I don't check for
217                 // lib->protolib==NULL here
218                 if (lib->dwfl != NULL &&
219                         (filter_matches_library(options.plt_filter,    lib ) ||
220                          filter_matches_library(options.static_filter, lib ) ||
221                          filter_matches_library(options.export_filter, lib )))
222                         import_DWARF_prototypes(lib);
223 #endif
224
225                 if (lib->protolib == NULL)
226                         lib->protolib = protolib_cache_default(&g_protocache,
227                                                                buf, 0);
228         }
229         if (lib->protolib == NULL)
230                 return NULL;
231
232         return protolib_lookup_prototype(lib->protolib, name,
233                                          lib->type != LT_LIBTYPE_SYSCALL);
234 }
235
236 struct find_proto_data {
237         const char *name;
238         struct prototype *ret;
239 };
240
241 static enum callback_status
242 find_proto_cb(struct process *proc, struct library *lib, void *d)
243 {
244         struct find_proto_data *data = d;
245         data->ret = library_get_prototype(lib, data->name);
246         return CBS_STOP_IF(data->ret != NULL);
247 }
248
249 static struct prototype *
250 lookup_symbol_prototype(struct process *proc, struct library_symbol *libsym)
251 {
252         if (libsym->proto != NULL)
253                 return libsym->proto;
254
255         struct library *lib = libsym->lib;
256         if (lib != NULL) {
257                 struct find_proto_data data = { libsym->name };
258                 data.ret = library_get_prototype(lib, libsym->name);
259                 if (data.ret == NULL
260                     && libsym->plt_type == LS_TOPLT_EXEC)
261                         proc_each_library(proc, NULL, find_proto_cb, &data);
262                 if (data.ret != NULL)
263                         return data.ret;
264         }
265
266         return build_default_prototype();
267 }
268
269 void
270 output_line(struct process *proc, const char *fmt, ...)
271 {
272         if (options.summary)
273                 return;
274
275         if (current_proc != NULL) {
276                 if (current_proc->callstack[current_depth].return_addr)
277                         fprintf(options.output, " <unfinished ...>\n");
278                 else
279                         fprintf(options.output, " <no return ...>\n");
280         }
281         current_proc = NULL;
282         if (fmt == NULL)
283                 return;
284
285         begin_of_line(proc, 0, 0);
286
287         va_list args;
288         va_start(args, fmt);
289         vfprintf(options.output, fmt, args);
290         fprintf(options.output, "\n");
291         va_end(args);
292
293         current_column = 0;
294 }
295
296 static void
297 tabto(int col) {
298         if (current_column < col) {
299                 fprintf(options.output, "%*s", col - current_column, "");
300         }
301 }
302
303 static int
304 output_error(FILE *stream)
305 {
306         return fprintf(stream, "?");
307 }
308
309 static int
310 fetch_simple_param(enum tof type, struct process *proc,
311                    struct fetch_context *context,
312                    struct value_dict *arguments,
313                    struct arg_type_info *info, int own,
314                    struct value *valuep)
315 {
316         /* Arrays decay into pointers per C standard.  We check for
317          * this here, because here we also capture arrays that come
318          * from parameter packs.  */
319         if (info->type == ARGTYPE_ARRAY) {
320                 struct arg_type_info *tmp = malloc(sizeof(*tmp));
321                 if (tmp != NULL) {
322                         type_init_pointer(tmp, info, own);
323                         tmp->lens = info->lens;
324                         info = tmp;
325                         own = 1;
326                 }
327         }
328
329         struct value value;
330         value_init(&value, proc, NULL, info, own);
331         if (fetch_arg_next(context, type, proc, info, &value) < 0)
332                 return -1;
333
334         if (val_dict_push_next(arguments, &value) < 0) {
335                 value_destroy(&value);
336                 return -1;
337         }
338
339         if (valuep != NULL)
340                 *valuep = value;
341
342         return 0;
343 }
344
345 static void
346 fetch_param_stop(struct value_dict *arguments, ssize_t *params_leftp)
347 {
348         if (*params_leftp == -1)
349                 *params_leftp = val_dict_count(arguments);
350 }
351
352 static int
353 fetch_param_pack(enum tof type, struct process *proc,
354                  struct fetch_context *context,
355                  struct value_dict *arguments, struct param *param,
356                  ssize_t *params_leftp)
357 {
358         struct param_enum *e = param_pack_init(param, arguments);
359         if (e == NULL)
360                 return -1;
361
362         int ret = 0;
363         while (1) {
364                 int insert_stop = 0;
365                 struct arg_type_info *info = malloc(sizeof(*info));
366                 if (info == NULL
367                     || param_pack_next(param, e, info, &insert_stop) < 0) {
368                 fail:
369                         free(info);
370                         ret = -1;
371                         break;
372                 }
373
374                 if (insert_stop)
375                         fetch_param_stop(arguments, params_leftp);
376
377                 if (info->type == ARGTYPE_VOID) {
378                         type_destroy(info);
379                         free(info);
380                         break;
381                 }
382
383                 struct value val;
384                 if (fetch_simple_param(type, proc, context, arguments,
385                                        info, 1, &val) < 0)
386                         goto fail;
387
388                 int stop = 0;
389                 switch (param_pack_stop(param, e, &val)) {
390                 case PPCB_ERR:
391                         goto fail;
392                 case PPCB_STOP:
393                         stop = 1;
394                 case PPCB_CONT:
395                         break;
396                 }
397
398                 if (stop)
399                         break;
400         }
401
402         param_pack_done(param, e);
403         return ret;
404 }
405
406 static int
407 fetch_one_param(enum tof type, struct process *proc,
408                 struct fetch_context *context,
409                 struct value_dict *arguments, struct param *param,
410                 ssize_t *params_leftp)
411 {
412         switch (param->flavor) {
413                 int rc;
414         case PARAM_FLAVOR_TYPE:
415                 return fetch_simple_param(type, proc, context, arguments,
416                                           param->u.type.type, 0, NULL);
417
418         case PARAM_FLAVOR_PACK:
419                 if (fetch_param_pack_start(context,
420                                            param->u.pack.ppflavor) < 0)
421                         return -1;
422                 rc = fetch_param_pack(type, proc, context, arguments,
423                                       param, params_leftp);
424                 fetch_param_pack_end(context);
425                 return rc;
426
427         case PARAM_FLAVOR_STOP:
428                 fetch_param_stop(arguments, params_leftp);
429                 return 0;
430         }
431
432         assert(!"Invalid param flavor!");
433         abort();
434 }
435
436 struct fetch_one_param_data
437 {
438         struct process *proc;
439         struct fetch_context *context;
440         struct value_dict *arguments;
441         ssize_t *params_leftp;
442         enum tof tof;
443 };
444
445 static enum callback_status
446 fetch_one_param_cb(struct prototype *proto, struct param *param, void *data)
447 {
448         struct fetch_one_param_data *cb_data = data;
449         return CBS_STOP_IF(fetch_one_param(cb_data->tof, cb_data->proc,
450                                            cb_data->context,
451                                            cb_data->arguments, param,
452                                            cb_data->params_leftp) < 0);
453 }
454
455 static int
456 fetch_params(enum tof type, struct process *proc,
457              struct fetch_context *context,
458              struct value_dict *arguments, struct prototype *func,
459              ssize_t *params_leftp)
460 {
461         struct fetch_one_param_data cb_data
462                 = { proc, context, arguments, params_leftp, type };
463         if (prototype_each_param(func, NULL,
464                                  &fetch_one_param_cb, &cb_data) != NULL)
465                 return -1;
466
467         /* Implicit stop at the end of parameter list.  */
468         fetch_param_stop(arguments, params_leftp);
469
470         return 0;
471 }
472
473 struct format_argument_data
474 {
475         struct value *value;
476         struct value_dict *arguments;
477 };
478
479 static int
480 format_argument_cb(FILE *stream, void *ptr)
481 {
482         struct format_argument_data *data = ptr;
483         int o = format_argument(stream, data->value, data->arguments);
484         if (o < 0)
485                 o = output_error(stream);
486         return o;
487 }
488
489 static int
490 output_params(struct value_dict *arguments, size_t start, size_t end,
491               int *need_delimp)
492 {
493         size_t i;
494         for (i = start; i < end; ++i) {
495                 struct value *value = val_dict_get_num(arguments, i);
496                 if (value == NULL)
497                         return -1;
498
499                 struct format_argument_data data = { value, arguments };
500                 int o = delim_output(options.output, need_delimp,
501                                      format_argument_cb, &data);
502                 if (o < 0)
503                         return -1;
504                 current_column += o;
505         }
506         return 0;
507 }
508
509 void
510 output_left(enum tof type, struct process *proc,
511             struct library_symbol *libsym)
512 {
513         assert(! options.summary);
514
515         if (current_proc) {
516                 fprintf(options.output, " <unfinished ...>\n");
517                 current_column = 0;
518         }
519         current_proc = proc;
520         current_depth = proc->callstack_depth;
521         begin_of_line(proc, type == LT_TOF_FUNCTION, 1);
522         if (!options.hide_caller && libsym->lib != NULL
523             && libsym->plt_type != LS_TOPLT_NONE)
524                 /* We don't terribly mind failing this.  */
525                 account_output(&current_column,
526                                fprintf(options.output, "%s->",
527                                        libsym->lib->soname));
528
529         const char *name = libsym->name;
530 #ifdef USE_DEMANGLE
531         if (options.demangle)
532                 name = my_demangle(libsym->name);
533 #endif
534         if (account_output(&current_column,
535                            fprintf(options.output, "%s", name)) < 0)
536                 return;
537
538         if (libsym->lib != NULL
539             && libsym->lib->type != LT_LIBTYPE_MAIN
540             && libsym->plt_type == LS_TOPLT_NONE
541             && account_output(&current_column,
542                               fprintf(options.output, "@%s",
543                                       libsym->lib->soname)) < 0)
544                 /* We do mind failing this though.  */
545                 return;
546
547         account_output(&current_column, fprintf(options.output, "("));
548
549         struct prototype *func = lookup_symbol_prototype(proc->leader, libsym);
550         if (func == NULL) {
551         fail:
552                 account_output(&current_column, fprintf(options.output, "???"));
553                 return;
554         }
555
556         struct fetch_context *context = fetch_arg_init(type, proc,
557                                                        func->return_info);
558         if (context == NULL)
559                 goto fail;
560
561         struct value_dict *arguments = malloc(sizeof(*arguments));
562         if (arguments == NULL) {
563                 fetch_arg_done(context);
564                 goto fail;
565         }
566         val_dict_init(arguments);
567
568         ssize_t params_left = -1;
569         int need_delim = 0;
570         if (fetch_params(type, proc, context, arguments, func, &params_left) < 0
571             || output_params(arguments, 0, params_left, &need_delim) < 0) {
572                 val_dict_destroy(arguments);
573                 fetch_arg_done(context);
574                 arguments = NULL;
575                 context = NULL;
576         }
577
578         struct callstack_element *stel
579                 = &proc->callstack[proc->callstack_depth - 1];
580         stel->fetch_context = context;
581         stel->arguments = arguments;
582         stel->out.params_left = params_left;
583         stel->out.need_delim = need_delim;
584 }
585
586 #if defined(HAVE_LIBDW)
587 /* Prints information about one frame of a thread.  Called by
588    dwfl_getthread_frames in output_right.  Returns 1 when done (max
589    number of frames reached).  Returns -1 on error.  Returns 0 on
590    success (if there are more frames in the thread, call us again).  */
591 static int
592 frame_callback (Dwfl_Frame *state, void *arg)
593 {
594         Dwarf_Addr pc;
595         bool isactivation;
596
597         int *frames = (int *) arg;
598
599         if (!dwfl_frame_pc(state, &pc, &isactivation))
600                 return -1;
601
602         if (!isactivation)
603                 pc--;
604
605         Dwfl *dwfl = dwfl_thread_dwfl(dwfl_frame_thread(state));
606         Dwfl_Module *mod = dwfl_addrmodule(dwfl, pc);
607         const char *modname = NULL;
608         const char *symname = NULL;
609         GElf_Off off = 0;
610         if (mod != NULL) {
611                 GElf_Sym sym;
612                 modname = dwfl_module_info(mod, NULL, NULL, NULL, NULL,
613                                            NULL, NULL, NULL);
614                 symname = dwfl_module_addrinfo(mod, pc, &off, &sym,
615                                                NULL, NULL, NULL);
616         }
617
618         /* This mimics the output produced by libunwind below.  */
619         fprintf(options.output, " > %s(%s+0x%" PRIx64 ") [%" PRIx64 "]\n",
620                 modname, symname, off, pc);
621
622         /* See if we can extract the source line too and print it on
623            the next line if we can find it.  */
624         if (mod != NULL) {
625                 Dwfl_Line *l = dwfl_module_getsrc(mod, pc);
626                 if (l != NULL) {
627                         int line, col;
628                         line = col = -1;
629                         const char *src = dwfl_lineinfo(l, NULL, &line, &col,
630                                                         NULL, NULL);
631                         if (src != NULL) {
632                                 fprintf(options.output, "\t%s", src);
633                                 if (line > 0) {
634                                         fprintf(options.output, ":%d", line);
635                                         if (col > 0)
636                                                 fprintf(options.output,
637                                                         ":%d", col);
638                                 }
639                                 fprintf(options.output, "\n");
640                         }
641
642                 }
643         }
644
645         /* Max number of frames to print reached? */
646         if ((*frames)-- == 0)
647                 return 1;
648
649         return 0;
650 }
651 #endif /* defined(HAVE_LIBDW) */
652
653 void
654 output_right(enum tof type, struct process *proc, struct library_symbol *libsym,
655              struct timedelta *spent)
656 {
657         assert(! options.summary);
658
659         struct prototype *func = lookup_symbol_prototype(proc, libsym);
660         if (func == NULL)
661                 return;
662
663         if (current_proc != NULL
664                     && (current_proc != proc
665                         || current_depth != proc->callstack_depth)) {
666                 fprintf(options.output, " <unfinished ...>\n");
667                 current_proc = NULL;
668         }
669         if (current_proc != proc) {
670                 begin_of_line(proc, type == LT_TOF_FUNCTIONR, 1);
671 #ifdef USE_DEMANGLE
672                 current_column +=
673                     fprintf(options.output, "<... %s resumed> ",
674                             options.demangle ? my_demangle(libsym->name)
675                             : libsym->name);
676 #else
677                 current_column +=
678                     fprintf(options.output, "<... %s resumed> ", libsym->name);
679 #endif
680         }
681
682         struct callstack_element *stel
683                 = &proc->callstack[proc->callstack_depth - 1];
684
685         struct fetch_context *context = stel->fetch_context;
686
687         /* Fetch & enter into dictionary the retval first, so that
688          * other values can use it in expressions.  */
689         struct value retval;
690         bool own_retval = false;
691         if (context != NULL) {
692                 value_init(&retval, proc, NULL, func->return_info, 0);
693                 own_retval = true;
694                 if (fetch_retval(context, type, proc, func->return_info,
695                                  &retval) < 0)
696                         value_set_type(&retval, NULL, 0);
697                 else if (stel->arguments != NULL
698                          && val_dict_push_named(stel->arguments, &retval,
699                                                 "retval", 0) == 0)
700                         own_retval = false;
701         }
702
703         if (stel->arguments != NULL)
704                 output_params(stel->arguments, stel->out.params_left,
705                               val_dict_count(stel->arguments),
706                               &stel->out.need_delim);
707
708         current_column += fprintf(options.output, ") ");
709         tabto(options.align - 1);
710         fprintf(options.output, "= ");
711
712         if (context != NULL && retval.type != NULL) {
713                 struct format_argument_data data = { &retval, stel->arguments };
714                 format_argument_cb(options.output, &data);
715         }
716
717         if (own_retval)
718                 value_destroy(&retval);
719
720         if (opt_T) {
721                 assert(spent != NULL);
722                 fprintf(options.output, " <%lu.%06d>",
723                         (unsigned long) spent->tm.tv_sec,
724                         (int) spent->tm.tv_usec);
725         }
726
727         fprintf(options.output, "\n");
728
729 #if defined(HAVE_LIBUNWIND)
730         if (options.bt_depth > 0
731             && proc->unwind_priv != NULL
732             && proc->unwind_as != NULL) {
733                 unw_cursor_t cursor;
734                 arch_addr_t ip, function_offset;
735                 struct library *lib = NULL;
736                 int unwind_depth = options.bt_depth;
737                 char fn_name[100];
738                 const char *lib_name;
739                 size_t distance;
740
741                 /* Verify that we can safely cast arch_addr_t* to
742                  * unw_word_t*.  */
743                 (void)sizeof(char[1 - 2*(sizeof(unw_word_t)
744                                         != sizeof(arch_addr_t))]);
745                 unw_init_remote(&cursor, proc->unwind_as, proc->unwind_priv);
746                 while (unwind_depth) {
747
748                         int rc = unw_get_reg(&cursor, UNW_REG_IP,
749                                              (unw_word_t *) &ip);
750                         if (rc < 0) {
751                                 fprintf(options.output, " > Error: %s\n",
752                                         unw_strerror(rc));
753                                 goto cont;
754                         }
755
756                         /* We are looking for the library with the base address
757                          * closest to the current ip.  */
758                         lib_name = "unmapped_area";
759                         distance = (size_t) -1;
760                         lib = proc->libraries;
761                         while (lib != NULL) {
762                                 /* N.B.: Assumes sizeof(size_t) ==
763                                  * sizeof(arch_addr_t).
764                                  * Keyword: double cast.  */
765                                 if ((ip >= lib->base) &&
766                                             ((size_t)(ip - lib->base)
767                                             < distance)) {
768                                         distance = ip - lib->base;
769                                         lib_name = lib->pathname;
770                                 }
771                                 lib = lib->next;
772                         }
773
774                         rc = unw_get_proc_name(&cursor, fn_name,
775                                                sizeof(fn_name),
776                                                (unw_word_t *) &function_offset);
777                         if (rc == 0 || rc == -UNW_ENOMEM)
778                                 fprintf(options.output, " > %s(%s+%p) [%p]\n",
779                                         lib_name, fn_name, function_offset, ip);
780                         else
781                                 fprintf(options.output, " > %s(??\?) [%p]\n",
782                                         lib_name, ip);
783
784                 cont:
785                         if (unw_step(&cursor) <= 0)
786                                 break;
787                         unwind_depth--;
788                 }
789                 fprintf(options.output, "\n");
790         }
791 #endif /* defined(HAVE_LIBUNWIND) */
792
793 #if defined(HAVE_LIBDW)
794         if (options.bt_depth > 0 && proc->leader->dwfl != NULL) {
795                 int frames = options.bt_depth;
796                 if (dwfl_getthread_frames(proc->leader->dwfl, proc->pid,
797                                           frame_callback, &frames) < 0) {
798                         // Only print an error if we couldn't show anything.
799                         // Otherwise just show there might be more...
800                         if (frames == options.bt_depth)
801                                 fprintf(stderr,
802                                         "dwfl_getthread_frames tid %d: %s\n",
803                                         proc->pid, dwfl_errmsg(-1));
804                         else
805                                 fprintf(options.output, " > [...]\n");
806                 }
807                 fprintf(options.output, "\n");
808           }
809 #endif /* defined(HAVE_LIBDW) */
810
811         current_proc = NULL;
812         current_column = 0;
813 }
814
815 int
816 delim_output(FILE *stream, int *need_delimp,
817              int (*writer)(FILE *stream, void *data),
818              void *data)
819 {
820         int o;
821
822         /* If we don't need a delimiter, then we don't need to go
823          * through a temporary stream.  It's all the same whether
824          * WRITER emits anything or not.  */
825         if (!*need_delimp) {
826                 o = writer(stream, data);
827
828         } else {
829                 struct memstream ms;
830                 if (memstream_init(&ms) < 0)
831                         return -1;
832                 o = writer(ms.stream, data);
833                 if (memstream_close(&ms) < 0)
834                         o = -1;
835                 if (o > 0 && ((*need_delimp
836                                && account_output(&o, fprintf(stream, ", ")) < 0)
837                               || fwrite(ms.buf, 1, ms.size, stream) != ms.size))
838                         o = -1;
839
840                 memstream_destroy(&ms);
841         }
842
843         if (o < 0)
844                 return -1;
845
846         *need_delimp = *need_delimp || o > 0;
847         return o;
848 }
849
850 int
851 account_output(int *countp, int c)
852 {
853         if (c > 0)
854                 *countp += c;
855         return c;
856 }
857
858 static void
859 do_report(const char *filename, unsigned line_no, const char *severity,
860           const char *fmt, va_list args)
861 {
862         char buf[128];
863         vsnprintf(buf, sizeof(buf), fmt, args);
864         buf[sizeof(buf) - 1] = 0;
865         if (filename != NULL)
866                 output_line(0, "%s:%d: %s: %s",
867                             filename, line_no, severity, buf);
868         else
869                 output_line(0, "%s: %s", severity, buf);
870 }
871
872 void
873 report_error(const char *filename, unsigned line_no, const char *fmt, ...)
874 {
875         va_list args;
876         va_start(args, fmt);
877         do_report(filename, line_no, "error", fmt, args);
878         va_end(args);
879 }
880
881 void
882 report_warning(const char *filename, unsigned line_no, const char *fmt, ...)
883 {
884         va_list args;
885         va_start(args, fmt);
886         do_report(filename, line_no, "warning", fmt, args);
887         va_end(args);
888 }
889
890 void
891 report_global_error(const char *fmt, ...)
892 {
893         va_list args;
894         va_start(args, fmt);
895         do_report(NULL, 0, "error", fmt, args);
896         va_end(args);
897 }