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