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