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