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