]> granicus.if.org Git - strace/blob - unwind.c
unwind.c: use xsprintf instead of sprintf
[strace] / unwind.c
1 /*
2  * Copyright (c) 2013 Luca Clementi <luca.clementi@gmail.com>
3  * Copyright (c) 2013-2017 The strace developers.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. The name of the author may not be used to endorse or promote products
14  *    derived from this software without specific prior written permission.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 #include "defs.h"
29 #include <limits.h>
30 #include <libunwind-ptrace.h>
31
32 #ifdef USE_DEMANGLE
33 # include <demangle.h>
34 #endif
35
36 #include "xstring.h"
37
38 #ifdef _LARGEFILE64_SOURCE
39 # ifdef HAVE_FOPEN64
40 #  define fopen_for_input fopen64
41 # else
42 #  define fopen_for_input fopen
43 # endif
44 #else
45 # define fopen_for_input fopen
46 #endif
47
48 /*
49  * Keep a sorted array of cache entries,
50  * so that we can binary search through it.
51  */
52 struct mmap_cache_t {
53         /**
54          * example entry:
55          * 7fabbb09b000-7fabbb09f000 r-xp 00179000 fc:00 1180246 /lib/libc-2.11.1.so
56          *
57          * start_addr  is 0x7fabbb09b000
58          * end_addr    is 0x7fabbb09f000
59          * mmap_offset is 0x179000
60          * binary_filename is "/lib/libc-2.11.1.so"
61          */
62         unsigned long start_addr;
63         unsigned long end_addr;
64         unsigned long mmap_offset;
65         char *binary_filename;
66 };
67
68 /*
69  * Type used in stacktrace walker
70  */
71 typedef void (*call_action_fn)(void *data,
72                                const char *binary_filename,
73                                const char *symbol_name,
74                                unw_word_t function_offset,
75                                unsigned long true_offset);
76 typedef void (*error_action_fn)(void *data,
77                                 const char *error,
78                                 unsigned long true_offset);
79
80 /*
81  * Type used in stacktrace capturing
82  */
83 struct call_t {
84         struct call_t *next;
85         char *output_line;
86 };
87
88 struct queue_t {
89         struct call_t *tail;
90         struct call_t *head;
91 };
92
93 static void queue_print(struct queue_t *queue);
94 static void delete_mmap_cache(struct tcb *tcp, const char *caller);
95
96 static unw_addr_space_t libunwind_as;
97 static unsigned int mmap_cache_generation;
98
99 static const char asprintf_error_str[] = "???";
100
101 void
102 unwind_init(void)
103 {
104         libunwind_as = unw_create_addr_space(&_UPT_accessors, 0);
105         if (!libunwind_as)
106                 error_msg_and_die("failed to create address space for stack tracing");
107         unw_set_caching_policy(libunwind_as, UNW_CACHE_GLOBAL);
108 }
109
110 void
111 unwind_tcb_init(struct tcb *tcp)
112 {
113         if (tcp->libunwind_ui)
114                 return;
115
116         tcp->libunwind_ui = _UPT_create(tcp->pid);
117         if (!tcp->libunwind_ui)
118                 perror_msg_and_die("_UPT_create");
119
120         tcp->queue = xmalloc(sizeof(*tcp->queue));
121         tcp->queue->head = NULL;
122         tcp->queue->tail = NULL;
123 }
124
125 void
126 unwind_tcb_fin(struct tcb *tcp)
127 {
128         queue_print(tcp->queue);
129         free(tcp->queue);
130         tcp->queue = NULL;
131
132         delete_mmap_cache(tcp, __func__);
133
134         _UPT_destroy(tcp->libunwind_ui);
135         tcp->libunwind_ui = NULL;
136 }
137
138 /*
139  * caching of /proc/ID/maps for each process to speed up stack tracing
140  *
141  * The cache must be refreshed after syscalls that affect memory mappings,
142  * e.g. mmap, mprotect, munmap, execve.
143  */
144 static void
145 build_mmap_cache(struct tcb *tcp)
146 {
147         FILE *fp;
148         struct mmap_cache_t *cache_head = NULL;
149         size_t cur_array_size = 0;
150         char filename[sizeof("/proc/4294967296/maps")];
151         char buffer[PATH_MAX + 80];
152
153         unw_flush_cache(libunwind_as, 0, 0);
154
155         xsprintf(filename, "/proc/%u/maps", tcp->pid);
156         fp = fopen_for_input(filename, "r");
157         if (!fp) {
158                 perror_msg("fopen: %s", filename);
159                 return;
160         }
161
162         while (fgets(buffer, sizeof(buffer), fp) != NULL) {
163                 struct mmap_cache_t *entry;
164                 unsigned long start_addr, end_addr, mmap_offset;
165                 char exec_bit;
166                 char binary_path[sizeof(buffer)];
167
168                 if (sscanf(buffer, "%lx-%lx %*c%*c%c%*c %lx %*x:%*x %*d %[^\n]",
169                            &start_addr, &end_addr, &exec_bit,
170                            &mmap_offset, binary_path) != 5)
171                         continue;
172
173                 /* ignore mappings that have no PROT_EXEC bit set */
174                 if (exec_bit != 'x')
175                         continue;
176
177                 if (end_addr < start_addr) {
178                         error_msg("%s: unrecognized file format", filename);
179                         break;
180                 }
181
182                 /*
183                  * sanity check to make sure that we're storing
184                  * non-overlapping regions in ascending order
185                  */
186                 if (tcp->mmap_cache_size > 0) {
187                         entry = &cache_head[tcp->mmap_cache_size - 1];
188                         if (entry->start_addr == start_addr &&
189                             entry->end_addr == end_addr) {
190                                 /* duplicate entry, e.g. [vsyscall] */
191                                 continue;
192                         }
193                         if (start_addr <= entry->start_addr ||
194                             start_addr < entry->end_addr) {
195                                 debug_msg("%s: overlapping memory region: "
196                                           "\"%s\" [%08lx-%08lx] overlaps with "
197                                           "\"%s\" [%08lx-%08lx]",
198                                           filename, binary_path, start_addr,
199                                           end_addr, entry->binary_filename,
200                                           entry->start_addr, entry->end_addr);
201                                 continue;
202                         }
203                 }
204
205                 if (tcp->mmap_cache_size >= cur_array_size)
206                         cache_head = xgrowarray(cache_head, &cur_array_size,
207                                                 sizeof(*cache_head));
208
209                 entry = &cache_head[tcp->mmap_cache_size];
210                 entry->start_addr = start_addr;
211                 entry->end_addr = end_addr;
212                 entry->mmap_offset = mmap_offset;
213                 entry->binary_filename = xstrdup(binary_path);
214                 tcp->mmap_cache_size++;
215         }
216         fclose(fp);
217         tcp->mmap_cache = cache_head;
218         tcp->mmap_cache_generation = mmap_cache_generation;
219
220         debug_func_msg("tgen=%u, ggen=%u, tcp=%p, cache=%p",
221                        tcp->mmap_cache_generation,
222                        mmap_cache_generation,
223                        tcp, tcp->mmap_cache);
224 }
225
226 /* deleting the cache */
227 static void
228 delete_mmap_cache(struct tcb *tcp, const char *caller)
229 {
230         unsigned int i;
231
232         debug_func_msg("tgen=%u, ggen=%u, tcp=%p, cache=%p, caller=%s",
233                        tcp->mmap_cache_generation,
234                        mmap_cache_generation,
235                        tcp, tcp->mmap_cache, caller);
236
237         for (i = 0; i < tcp->mmap_cache_size; i++) {
238                 free(tcp->mmap_cache[i].binary_filename);
239                 tcp->mmap_cache[i].binary_filename = NULL;
240         }
241         free(tcp->mmap_cache);
242         tcp->mmap_cache = NULL;
243         tcp->mmap_cache_size = 0;
244 }
245
246 static bool
247 rebuild_cache_if_invalid(struct tcb *tcp, const char *caller)
248 {
249         if ((tcp->mmap_cache_generation != mmap_cache_generation)
250             && tcp->mmap_cache)
251                 delete_mmap_cache(tcp, caller);
252
253         if (!tcp->mmap_cache)
254                 build_mmap_cache(tcp);
255
256         return tcp->mmap_cache && tcp->mmap_cache_size;
257 }
258
259 void
260 unwind_cache_invalidate(struct tcb *tcp)
261 {
262 #if SUPPORTED_PERSONALITIES > 1
263         if (tcp->currpers != DEFAULT_PERSONALITY) {
264                 /* disable stack trace */
265                 return;
266         }
267 #endif
268         mmap_cache_generation++;
269         debug_func_msg("tgen=%u, ggen=%u, tcp=%p, cache=%p",
270                        tcp->mmap_cache_generation,
271                        mmap_cache_generation,
272                        tcp, tcp->mmap_cache);
273 }
274
275 static void
276 get_symbol_name(unw_cursor_t *cursor, char **name,
277                 size_t *size, unw_word_t *offset)
278 {
279         for (;;) {
280                 int rc = unw_get_proc_name(cursor, *name, *size, offset);
281                 if (rc == 0)
282                         break;
283                 if (rc != -UNW_ENOMEM) {
284                         **name = '\0';
285                         *offset = 0;
286                         break;
287                 }
288                 *name = xgrowarray(*name, size, 1);
289         }
290 }
291
292 static int
293 print_stack_frame(struct tcb *tcp,
294                   call_action_fn call_action,
295                   error_action_fn error_action,
296                   void *data,
297                   unw_cursor_t *cursor,
298                   char **symbol_name,
299                   size_t *symbol_name_size)
300 {
301         unw_word_t ip;
302         int lower = 0;
303         int upper = (int) tcp->mmap_cache_size - 1;
304
305         if (unw_get_reg(cursor, UNW_REG_IP, &ip) < 0) {
306                 perror_msg("Can't walk the stack of process %d", tcp->pid);
307                 return -1;
308         }
309
310         while (lower <= upper) {
311                 struct mmap_cache_t *cur_mmap_cache;
312                 int mid = (upper + lower) / 2;
313
314                 cur_mmap_cache = &tcp->mmap_cache[mid];
315
316                 if (ip >= cur_mmap_cache->start_addr &&
317                     ip < cur_mmap_cache->end_addr) {
318                         unsigned long true_offset;
319                         unw_word_t function_offset;
320
321                         get_symbol_name(cursor, symbol_name, symbol_name_size,
322                                         &function_offset);
323                         true_offset = ip - cur_mmap_cache->start_addr +
324                                 cur_mmap_cache->mmap_offset;
325
326 #ifdef USE_DEMANGLE
327                         char *demangled_name =
328                                 cplus_demangle(*symbol_name,
329                                                DMGL_AUTO | DMGL_PARAMS);
330 #endif
331
332                         call_action(data,
333                                     cur_mmap_cache->binary_filename,
334 #ifdef USE_DEMANGLE
335                                     demangled_name ? demangled_name :
336 #endif
337                                     *symbol_name,
338                                     function_offset,
339                                     true_offset);
340 #ifdef USE_DEMANGLE
341                         free(demangled_name);
342 #endif
343
344                         return 0;
345                 } else if (ip < cur_mmap_cache->start_addr)
346                         upper = mid - 1;
347                 else
348                         lower = mid + 1;
349         }
350
351         /*
352          * there is a bug in libunwind >= 1.0
353          * after a set_tid_address syscall
354          * unw_get_reg returns IP == 0
355          */
356         if (ip)
357                 error_action(data, "unexpected_backtracing_error", ip);
358         return -1;
359 }
360
361 /*
362  * walking the stack
363  */
364 static void
365 stacktrace_walk(struct tcb *tcp,
366                 call_action_fn call_action,
367                 error_action_fn error_action,
368                 void *data)
369 {
370         char *symbol_name;
371         size_t symbol_name_size = 40;
372         unw_cursor_t cursor;
373         int stack_depth;
374
375         if (!tcp->mmap_cache)
376                 error_msg_and_die("bug: mmap_cache is NULL");
377         if (tcp->mmap_cache_size == 0)
378                 error_msg_and_die("bug: mmap_cache is empty");
379
380         symbol_name = xmalloc(symbol_name_size);
381
382         if (unw_init_remote(&cursor, libunwind_as, tcp->libunwind_ui) < 0)
383                 perror_msg_and_die("Can't initiate libunwind");
384
385         for (stack_depth = 0; stack_depth < 256; ++stack_depth) {
386                 if (print_stack_frame(tcp, call_action, error_action, data,
387                                 &cursor, &symbol_name, &symbol_name_size) < 0)
388                         break;
389                 if (unw_step(&cursor) <= 0)
390                         break;
391         }
392         if (stack_depth >= 256)
393                 error_action(data, "too many stack frames", 0);
394
395         free(symbol_name);
396 }
397
398 /*
399  * printing an entry in stack to stream or buffer
400  */
401 /*
402  * we want to keep the format used by backtrace_symbols from the glibc
403  *
404  * ./a.out() [0x40063d]
405  * ./a.out() [0x4006bb]
406  * ./a.out() [0x4006c6]
407  * /lib64/libc.so.6(__libc_start_main+0xed) [0x7fa2f8a5976d]
408  * ./a.out() [0x400569]
409  */
410 #define STACK_ENTRY_SYMBOL_FMT                  \
411         " > %s(%s+0x%lx) [0x%lx]\n",            \
412         binary_filename,                        \
413         symbol_name,                            \
414         (unsigned long) function_offset,        \
415         true_offset
416 #define STACK_ENTRY_NOSYMBOL_FMT                \
417         " > %s() [0x%lx]\n",                    \
418         binary_filename, true_offset
419 #define STACK_ENTRY_BUG_FMT                     \
420         " > BUG IN %s\n"
421 #define STACK_ENTRY_ERROR_WITH_OFFSET_FMT       \
422         " > %s [0x%lx]\n", error, true_offset
423 #define STACK_ENTRY_ERROR_FMT                   \
424         " > %s\n", error
425
426 static void
427 print_call_cb(void *dummy,
428               const char *binary_filename,
429               const char *symbol_name,
430               unw_word_t function_offset,
431               unsigned long true_offset)
432 {
433         if (symbol_name && (symbol_name[0] != '\0'))
434                 tprintf(STACK_ENTRY_SYMBOL_FMT);
435         else if (binary_filename)
436                 tprintf(STACK_ENTRY_NOSYMBOL_FMT);
437         else
438                 tprintf(STACK_ENTRY_BUG_FMT, __func__);
439
440         line_ended();
441 }
442
443 static void
444 print_error_cb(void *dummy,
445                const char *error,
446                unsigned long true_offset)
447 {
448         if (true_offset)
449                 tprintf(STACK_ENTRY_ERROR_WITH_OFFSET_FMT);
450         else
451                 tprintf(STACK_ENTRY_ERROR_FMT);
452
453         line_ended();
454 }
455
456 static char *
457 sprint_call_or_error(const char *binary_filename,
458                      const char *symbol_name,
459                      unw_word_t function_offset,
460                      unsigned long true_offset,
461                      const char *error)
462 {
463         char *output_line = NULL;
464         int n;
465
466         if (symbol_name)
467                 n = asprintf(&output_line, STACK_ENTRY_SYMBOL_FMT);
468         else if (binary_filename)
469                 n = asprintf(&output_line, STACK_ENTRY_NOSYMBOL_FMT);
470         else if (error)
471                 n = true_offset
472                         ? asprintf(&output_line, STACK_ENTRY_ERROR_WITH_OFFSET_FMT)
473                         : asprintf(&output_line, STACK_ENTRY_ERROR_FMT);
474         else
475                 n = asprintf(&output_line, STACK_ENTRY_BUG_FMT, __func__);
476
477         if (n < 0) {
478                 perror_func_msg("asprintf");
479                 output_line = (char *) asprintf_error_str;
480         }
481
482         return output_line;
483 }
484
485 /*
486  * queue manipulators
487  */
488 static void
489 queue_put(struct queue_t *queue,
490           const char *binary_filename,
491           const char *symbol_name,
492           unw_word_t function_offset,
493           unsigned long true_offset,
494           const char *error)
495 {
496         struct call_t *call;
497
498         call = xmalloc(sizeof(*call));
499         call->output_line = sprint_call_or_error(binary_filename,
500                                                  symbol_name,
501                                                  function_offset,
502                                                  true_offset,
503                                                  error);
504         call->next = NULL;
505
506         if (!queue->head) {
507                 queue->head = call;
508                 queue->tail = call;
509         } else {
510                 queue->tail->next = call;
511                 queue->tail = call;
512         }
513 }
514
515 static void
516 queue_put_call(void *queue,
517                const char *binary_filename,
518                const char *symbol_name,
519                unw_word_t function_offset,
520                unsigned long true_offset)
521 {
522         queue_put(queue,
523                   binary_filename,
524                   symbol_name,
525                   function_offset,
526                   true_offset,
527                   NULL);
528 }
529
530 static void
531 queue_put_error(void *queue,
532                 const char *error,
533                 unsigned long ip)
534 {
535         queue_put(queue, NULL, NULL, 0, ip, error);
536 }
537
538 static void
539 queue_print(struct queue_t *queue)
540 {
541         struct call_t *call, *tmp;
542
543         queue->tail = NULL;
544         call = queue->head;
545         queue->head = NULL;
546         while (call) {
547                 tmp = call;
548                 call = call->next;
549
550                 tprints(tmp->output_line);
551                 line_ended();
552
553                 if (tmp->output_line != asprintf_error_str)
554                         free(tmp->output_line);
555
556                 tmp->output_line = NULL;
557                 tmp->next = NULL;
558                 free(tmp);
559         }
560 }
561
562 /*
563  * printing stack
564  */
565 void
566 unwind_print_stacktrace(struct tcb *tcp)
567 {
568 #if SUPPORTED_PERSONALITIES > 1
569         if (tcp->currpers != DEFAULT_PERSONALITY) {
570                 /* disable stack trace */
571                 return;
572         }
573 #endif
574         if (tcp->queue->head) {
575                 debug_func_msg("head: tcp=%p, queue=%p", tcp, tcp->queue->head);
576                 queue_print(tcp->queue);
577         } else if (rebuild_cache_if_invalid(tcp, __func__)) {
578                 debug_func_msg("walk: tcp=%p, queue=%p", tcp, tcp->queue->head);
579                 stacktrace_walk(tcp, print_call_cb, print_error_cb, NULL);
580         }
581 }
582
583 /*
584  * capturing stack
585  */
586 void
587 unwind_capture_stacktrace(struct tcb *tcp)
588 {
589 #if SUPPORTED_PERSONALITIES > 1
590         if (tcp->currpers != DEFAULT_PERSONALITY) {
591                 /* disable stack trace */
592                 return;
593         }
594 #endif
595         if (tcp->queue->head)
596                 error_msg_and_die("bug: unprinted entries in queue");
597
598         if (rebuild_cache_if_invalid(tcp, __func__)) {
599                 stacktrace_walk(tcp, queue_put_call, queue_put_error,
600                                 tcp->queue);
601                 debug_func_msg("tcp=%p, queue=%p", tcp, tcp->queue->head);
602         }
603 }