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