• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* libunwind - a platform-independent unwind library
2    Copyright (C) 2010, 2011 by FERMI NATIONAL ACCELERATOR LABORATORY
3    Copyright (C) 2014 CERN and Aalto University
4         Contributed by Filip Nyback
5 
6 This file is part of libunwind.
7 
8 Permission is hereby granted, free of charge, to any person obtaining
9 a copy of this software and associated documentation files (the
10 "Software"), to deal in the Software without restriction, including
11 without limitation the rights to use, copy, modify, merge, publish,
12 distribute, sublicense, and/or sell copies of the Software, and to
13 permit persons to whom the Software is furnished to do so, subject to
14 the following conditions:
15 
16 The above copyright notice and this permission notice shall be
17 included in all copies or substantial portions of the Software.
18 
19 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  */
26 
27 #include "unwind_i.h"
28 #include "offsets.h"
29 #include <signal.h>
30 #include <limits.h>
31 #include <stdio.h>
32 
33 #pragma weak pthread_once
34 #pragma weak pthread_key_create
35 #pragma weak pthread_getspecific
36 #pragma weak pthread_setspecific
37 
38 /* Initial hash table size. Table expands by 2 bits (times four). */
39 #define HASH_MIN_BITS 14
40 
41 typedef struct
42 {
43   unw_tdep_frame_t *frames;
44   size_t log_size;
45   size_t used;
46   size_t dtor_count;  /* Counts how many times our destructor has already
47                          been called. */
48 } unw_trace_cache_t;
49 
50 static const unw_tdep_frame_t empty_frame = { 0, UNW_ARM_FRAME_OTHER, -1, -1, 0, -1, -1, -1 };
51 static define_lock (trace_init_lock);
52 static pthread_once_t trace_cache_once = PTHREAD_ONCE_INIT;
53 static sig_atomic_t trace_cache_once_happen;
54 static pthread_key_t trace_cache_key;
55 static struct mempool trace_cache_pool;
56 static _Thread_local  unw_trace_cache_t *tls_cache;
57 static _Thread_local  int tls_cache_destroyed;
58 
59 /* Free memory for a thread's trace cache. */
60 static void
trace_cache_free(void * arg)61 trace_cache_free (void *arg)
62 {
63   unw_trace_cache_t *cache = arg;
64   if (++cache->dtor_count < PTHREAD_DESTRUCTOR_ITERATIONS)
65   {
66     /* Not yet our turn to get destroyed. Re-install ourselves into the key. */
67     pthread_setspecific(trace_cache_key, cache);
68     Debug(5, "delayed freeing cache %p (%zx to go)\n", cache,
69           PTHREAD_DESTRUCTOR_ITERATIONS - cache->dtor_count);
70     return;
71   }
72   tls_cache_destroyed = 1;
73   tls_cache = NULL;
74   munmap (cache->frames, (1u << cache->log_size) * sizeof(unw_tdep_frame_t));
75   mempool_free (&trace_cache_pool, cache);
76   Debug(5, "freed cache %p\n", cache);
77 }
78 
79 /* Initialise frame tracing for threaded use. */
80 static void
trace_cache_init_once(void)81 trace_cache_init_once (void)
82 {
83   pthread_key_create (&trace_cache_key, &trace_cache_free);
84   mempool_init (&trace_cache_pool, sizeof (unw_trace_cache_t), 0);
85   trace_cache_once_happen = 1;
86 }
87 
88 static unw_tdep_frame_t *
trace_cache_buckets(size_t n)89 trace_cache_buckets (size_t n)
90 {
91   unw_tdep_frame_t *frames;
92   size_t i;
93 
94   GET_MEMORY(frames, n * sizeof (unw_tdep_frame_t));
95   if (likely(frames != NULL))
96     for (i = 0; i < n; ++i)
97       frames[i] = empty_frame;
98 
99   return frames;
100 }
101 
102 /* Allocate and initialise hash table for frame cache lookups.
103    Returns the cache initialised with (1u << HASH_LOW_BITS) hash
104    buckets, or NULL if there was a memory allocation problem. */
105 static unw_trace_cache_t *
trace_cache_create(void)106 trace_cache_create (void)
107 {
108   unw_trace_cache_t *cache;
109 
110   if (tls_cache_destroyed)
111   {
112     /* The current thread is in the process of exiting. Don't recreate
113        cache, as we wouldn't have another chance to free it. */
114     Debug(5, "refusing to reallocate cache: "
115              "thread-locals are being deallocated\n");
116     return NULL;
117   }
118 
119   if (! (cache = mempool_alloc(&trace_cache_pool)))
120   {
121     Debug(5, "failed to allocate cache\n");
122     return NULL;
123   }
124 
125   if (! (cache->frames = trace_cache_buckets(1u << HASH_MIN_BITS)))
126   {
127     Debug(5, "failed to allocate buckets\n");
128     mempool_free(&trace_cache_pool, cache);
129     return NULL;
130   }
131 
132   cache->log_size = HASH_MIN_BITS;
133   cache->used = 0;
134   cache->dtor_count = 0;
135   tls_cache_destroyed = 0;  /* Paranoia: should already be 0. */
136   Debug(5, "allocated cache %p\n", cache);
137   return cache;
138 }
139 
140 /* Expand the hash table in the frame cache if possible. This always
141    quadruples the hash size, and clears all previous frame entries. */
142 static int
trace_cache_expand(unw_trace_cache_t * cache)143 trace_cache_expand (unw_trace_cache_t *cache)
144 {
145   size_t old_size = (1u << cache->log_size);
146   size_t new_log_size = cache->log_size + 2;
147   unw_tdep_frame_t *new_frames = trace_cache_buckets (1u << new_log_size);
148 
149   if (unlikely(! new_frames))
150   {
151     Debug(5, "failed to expand cache to 2^%u buckets\n", new_log_size);
152     return -UNW_ENOMEM;
153   }
154 
155   Debug(5, "expanded cache from 2^%u to 2^%u buckets\n", cache->log_size,
156         new_log_size);
157   munmap(cache->frames, old_size * sizeof(unw_tdep_frame_t));
158   cache->frames = new_frames;
159   cache->log_size = new_log_size;
160   cache->used = 0;
161   return 0;
162 }
163 
164 static unw_trace_cache_t *
trace_cache_get_unthreaded(void)165 trace_cache_get_unthreaded (void)
166 {
167   unw_trace_cache_t *cache;
168   intrmask_t saved_mask;
169   static unw_trace_cache_t *global_cache = NULL;
170   lock_acquire (&trace_init_lock, saved_mask);
171   if (! global_cache)
172   {
173     mempool_init (&trace_cache_pool, sizeof (unw_trace_cache_t), 0);
174     global_cache = trace_cache_create ();
175   }
176   cache = global_cache;
177   lock_release (&trace_init_lock, saved_mask);
178   Debug(5, "using cache %p\n", cache);
179   return cache;
180 }
181 
182 /* Get the frame cache for the current thread. Create it if there is none. */
183 static unw_trace_cache_t *
trace_cache_get(void)184 trace_cache_get (void)
185 {
186   unw_trace_cache_t *cache;
187   if (likely (pthread_once != NULL))
188   {
189     pthread_once(&trace_cache_once, &trace_cache_init_once);
190     if (!trace_cache_once_happen)
191     {
192       return trace_cache_get_unthreaded();
193     }
194     if (! (cache = tls_cache))
195     {
196       cache = trace_cache_create();
197       pthread_setspecific(trace_cache_key, cache);
198       tls_cache = cache;
199     }
200     Debug(5, "using cache %p\n", cache);
201     return cache;
202   }
203   else
204   {
205     return trace_cache_get_unthreaded();
206   }
207 }
208 
209 /* Initialise frame properties for address cache slot F at address
210    PC using current CFA, R7 and SP values.  Modifies CURSOR to
211    that location, performs one unw_step(), and fills F with what
212    was discovered about the location.  Returns F.
213 
214    FIXME: This probably should tell DWARF handling to never evaluate
215    or use registers other than R7, SP and PC in case there is
216    highly unusual unwind info which uses these creatively. */
217 static unw_tdep_frame_t *
trace_init_addr(unw_tdep_frame_t * f,unw_cursor_t * cursor,unw_word_t cfa,unw_word_t pc,unw_word_t r7,unw_word_t sp)218 trace_init_addr (unw_tdep_frame_t *f,
219                  unw_cursor_t *cursor,
220                  unw_word_t cfa,
221                  unw_word_t pc,
222                  unw_word_t r7,
223                  unw_word_t sp)
224 {
225   struct cursor *c = (struct cursor *) cursor;
226   struct dwarf_cursor *d = &c->dwarf;
227   int ret = -UNW_EINVAL;
228 
229   /* Initialise frame properties: unknown, not last. */
230   f->virtual_address = pc;
231   f->frame_type = UNW_ARM_FRAME_OTHER;
232   f->last_frame = 0;
233   f->cfa_reg_sp = -1;
234   f->cfa_reg_offset = 0;
235   f->r7_cfa_offset = -1;
236   f->lr_cfa_offset = -1;
237   f->sp_cfa_offset = -1;
238 
239   /* Reinitialise cursor to this instruction - but undo next/prev RIP
240      adjustment because unw_step will redo it - and force PC, R7 and
241      SP into register locations (=~ ucontext we keep), then set
242      their desired values. Then perform the step. */
243   d->ip = pc + d->use_prev_instr;
244   d->cfa = cfa;
245   d->loc[UNW_ARM_R7] = DWARF_REG_LOC (d, UNW_ARM_R7);
246   d->loc[UNW_ARM_R13] = DWARF_REG_LOC (d, UNW_ARM_R13);
247   d->loc[UNW_ARM_R15] = DWARF_REG_LOC (d, UNW_ARM_R15);
248   c->frame_info = *f;
249 
250   if (likely(dwarf_put (d, d->loc[UNW_ARM_R7], r7) >= 0)
251       && likely(dwarf_put (d, d->loc[UNW_ARM_R13], sp) >= 0)
252       && likely(dwarf_put (d, d->loc[UNW_ARM_R15], pc) >= 0)
253       && likely((ret = unw_step (cursor)) >= 0))
254     *f = c->frame_info;
255 
256   /* If unw_step() stopped voluntarily, remember that, even if it
257      otherwise could not determine anything useful.  This avoids
258      failing trace if we hit frames without unwind info, which is
259      common for the outermost frame (CRT stuff) on many systems.
260      This avoids failing trace in very common circumstances; failing
261      to unw_step() loop wouldn't produce any better result. */
262   if (ret == 0)
263     f->last_frame = -1;
264 
265   Debug (3, "frame va %x type %d last %d cfa %s+%d r7 @ cfa%+d lr @ cfa%+d sp @ cfa%+d\n",
266          f->virtual_address, f->frame_type, f->last_frame,
267          f->cfa_reg_sp ? "sp" : "r7", f->cfa_reg_offset,
268          f->r7_cfa_offset, f->lr_cfa_offset, f->sp_cfa_offset);
269 
270   return f;
271 }
272 
273 /* Look up and if necessary fill in frame attributes for address PC
274    in CACHE using current CFA, R7 and SP values.  Uses CURSOR to
275    perform any unwind steps necessary to fill the cache.  Returns the
276    frame cache slot which describes RIP. */
277 static unw_tdep_frame_t *
trace_lookup(unw_cursor_t * cursor,unw_trace_cache_t * cache,unw_word_t cfa,unw_word_t pc,unw_word_t r7,unw_word_t sp)278 trace_lookup (unw_cursor_t *cursor,
279               unw_trace_cache_t *cache,
280               unw_word_t cfa,
281               unw_word_t pc,
282               unw_word_t r7,
283               unw_word_t sp)
284 {
285   /* First look up for previously cached information using cache as
286      linear probing hash table with probe step of 1.  Majority of
287      lookups should be completed within few steps, but it is very
288      important the hash table does not fill up, or performance falls
289      off the cliff. */
290   uint32_t i, addr;
291   uint32_t cache_size = 1u << cache->log_size;
292   uint32_t slot = ((pc * 0x9e3779b9) >> 11) & (cache_size-1);
293   unw_tdep_frame_t *frame;
294 
295   for (i = 0; i < 16; ++i)
296   {
297     frame = &cache->frames[slot];
298     addr = frame->virtual_address;
299 
300     /* Return if we found the address. */
301     if (likely(addr == pc))
302     {
303       Debug (4, "found address after %d steps\n", i);
304       return frame;
305     }
306 
307     /* If slot is empty, reuse it. */
308     if (likely(! addr))
309       break;
310 
311     /* Linear probe to next slot candidate, step = 1. */
312     if (++slot >= cache_size)
313       slot -= cache_size;
314   }
315 
316   /* If we collided after 16 steps, or if the hash is more than half
317      full, force the hash to expand. Fill the selected slot, whether
318      it's free or collides. Note that hash expansion drops previous
319      contents; further lookups will refill the hash. */
320   Debug (4, "updating slot %u after %d steps, replacing 0x%x\n", slot, i, addr);
321   if (unlikely(addr || cache->used >= cache_size / 2))
322   {
323     if (unlikely(trace_cache_expand (cache) < 0))
324       return NULL;
325 
326     cache_size = 1u << cache->log_size;
327     slot = ((pc * 0x9e3779b9) >> 11) & (cache_size-1);
328     frame = &cache->frames[slot];
329     addr = frame->virtual_address;
330   }
331 
332   if (! addr)
333     ++cache->used;
334 
335   return trace_init_addr (frame, cursor, cfa, pc, r7, sp);
336 }
337 
338 /* Fast stack backtrace for ARM.
339 
340    This is used by backtrace() implementation to accelerate frequent
341    queries for current stack, without any desire to unwind. It fills
342    BUFFER with the call tree from CURSOR upwards for at most SIZE
343    stack levels. The first frame, backtrace itself, is omitted. When
344    called, SIZE should give the maximum number of entries that can be
345    stored into BUFFER. Uses an internal thread-specific cache to
346    accelerate queries.
347 
348    The caller should fall back to a unw_step() loop if this function
349    fails by returning -UNW_ESTOPUNWIND, meaning the routine hit a
350    stack frame that is too complex to be traced in the fast path.
351 
352    This function is tuned for clients which only need to walk the
353    stack to get the call tree as fast as possible but without any
354    other details, for example profilers sampling the stack thousands
355    to millions of times per second.  The routine handles the most
356    common ARM ABI stack layouts: CFA is R7 or SP plus/minus
357    constant offset, return address is in LR, and R7, LR and SP are
358    either unchanged or saved on stack at constant offset from the CFA;
359    the signal return frame; and frames without unwind info provided
360    they are at the outermost (final) frame or can conservatively be
361    assumed to be frame-pointer based.
362 
363    Any other stack layout will cause the routine to give up. There
364    are only a handful of relatively rarely used functions which do
365    not have a stack in the standard form: vfork, longjmp, setcontext
366    and _dl_runtime_profile on common linux systems for example.
367 
368    On success BUFFER and *SIZE reflect the trace progress up to *SIZE
369    stack levels or the outermost frame, which ever is less.  It may
370    stop short of outermost frame if unw_step() loop would also do so,
371    e.g. if there is no more unwind information; this is not reported
372    as an error.
373 
374    The function returns a negative value for errors, -UNW_ESTOPUNWIND
375    if tracing stopped because of an unusual frame unwind info.  The
376    BUFFER and *SIZE reflect tracing progress up to the error frame.
377 
378    Callers of this function would normally look like this:
379 
380      unw_cursor_t     cur;
381      unw_context_t    ctx;
382      void             addrs[128];
383      int              depth = 128;
384      int              ret;
385 
386      unw_getcontext(&ctx);
387      unw_init_local(&cur, &ctx);
388      if ((ret = unw_tdep_trace(&cur, addrs, &depth)) < 0)
389      {
390        depth = 0;
391        unw_getcontext(&ctx);
392        unw_init_local(&cur, &ctx);
393        while ((ret = unw_step(&cur)) > 0 && depth < 128)
394        {
395          unw_word_t ip;
396          unw_get_reg(&cur, UNW_REG_IP, &ip);
397          addresses[depth++] = (void *) ip;
398        }
399      }
400 */
401 HIDDEN int
tdep_trace(unw_cursor_t * cursor,void ** buffer,int * size)402 tdep_trace (unw_cursor_t *cursor, void **buffer, int *size)
403 {
404   struct cursor *c = (struct cursor *) cursor;
405   struct dwarf_cursor *d = &c->dwarf;
406   unw_trace_cache_t *cache;
407   unw_word_t sp, pc, cfa, r7, lr;
408   int maxdepth = 0;
409   int depth = 0;
410   int ret;
411 
412   /* Check input parametres. */
413   if (unlikely(! cursor || ! buffer || ! size || (maxdepth = *size) <= 0))
414     return -UNW_EINVAL;
415 
416   Debug (1, "begin ip 0x%x cfa 0x%x\n", d->ip, d->cfa);
417 
418   /* Tell core dwarf routines to call back to us. */
419   d->stash_frames = 1;
420 
421   /* Determine initial register values. These are direct access safe
422      because we know they come from the initial machine context. */
423   pc = d->ip;
424   sp = cfa = d->cfa;
425   ACCESS_MEM_FAST(ret, 0, d, DWARF_GET_LOC(d->loc[UNW_ARM_R7]), r7);
426   assert(ret == 0);
427   lr = 0;
428 
429   /* Get frame cache. */
430   if (unlikely(! (cache = trace_cache_get())))
431   {
432     Debug (1, "returning %d, cannot get trace cache\n", -UNW_ENOMEM);
433     *size = 0;
434     d->stash_frames = 0;
435     return -UNW_ENOMEM;
436   }
437 
438   /* Trace the stack upwards, starting from current PC.  Adjust
439      the PC address for previous/next instruction as the main
440      unwinding logic would also do.  We undo this before calling
441      back into unw_step(). */
442   while (depth < maxdepth)
443   {
444     pc -= d->use_prev_instr;
445     Debug (2, "depth %d cfa 0x%x pc 0x%x sp 0x%x r7 0x%x\n",
446            depth, cfa, pc, sp, r7);
447 
448     /* See if we have this address cached.  If not, evaluate enough of
449        the dwarf unwind information to fill the cache line data, or to
450        decide this frame cannot be handled in fast trace mode.  We
451        cache negative results too to prevent unnecessary dwarf parsing
452        for common failures. */
453     unw_tdep_frame_t *f = trace_lookup (cursor, cache, cfa, pc, r7, sp);
454 
455     /* If we don't have information for this frame, give up. */
456     if (unlikely(! f))
457     {
458       ret = -UNW_ENOINFO;
459       break;
460     }
461 
462     Debug (3, "frame va %x type %d last %d cfa %s+%d r7 @ cfa%+d lr @ cfa%+d sp @ cfa%+d\n",
463            f->virtual_address, f->frame_type, f->last_frame,
464            f->cfa_reg_sp ? "sp" : "r7", f->cfa_reg_offset,
465            f->r7_cfa_offset, f->lr_cfa_offset, f->sp_cfa_offset);
466 
467     assert (f->virtual_address == pc);
468 
469     /* Stop if this was the last frame.  In particular don't evaluate
470        new register values as it may not be safe - we don't normally
471        run with full validation on, and do not want to - and there's
472        enough bad unwind info floating around that we need to trust
473        what unw_step() previously said, in potentially bogus frames. */
474     if (f->last_frame)
475       break;
476 
477     /* Evaluate CFA and registers for the next frame. */
478     switch (f->frame_type)
479     {
480     case UNW_ARM_FRAME_GUESSED:
481       /* Fall thru to standard processing after forcing validation. */
482       c->validate = 1;
483 
484     case UNW_ARM_FRAME_STANDARD:
485       /* Advance standard traceable frame. */
486       cfa = (f->cfa_reg_sp ? sp : r7) + f->cfa_reg_offset;
487       if (likely(f->lr_cfa_offset != -1))
488         ACCESS_MEM_FAST(ret, c->validate, d, cfa + f->lr_cfa_offset, pc);
489       else if (lr != 0)
490       {
491         /* Use the saved link register as the new pc. */
492         pc = lr;
493         lr = 0;
494       }
495       if (likely(ret >= 0) && likely(f->r7_cfa_offset != -1))
496         ACCESS_MEM_FAST(ret, c->validate, d, cfa + f->r7_cfa_offset, r7);
497 
498       /* Don't bother reading SP from DWARF, CFA becomes new SP. */
499       sp = cfa;
500 
501       /* Next frame needs to back up for unwind info lookup. */
502       d->use_prev_instr = 1;
503       break;
504 
505     case UNW_ARM_FRAME_SIGRETURN:
506       cfa = cfa + f->cfa_reg_offset; /* cfa now points to ucontext_t.  */
507 #if defined(__linux__)
508       ACCESS_MEM_FAST(ret, c->validate, d, cfa + LINUX_SC_PC_OFF, pc);
509       if (likely(ret >= 0))
510         ACCESS_MEM_FAST(ret, c->validate, d, cfa + LINUX_SC_R7_OFF, r7);
511       if (likely(ret >= 0))
512         ACCESS_MEM_FAST(ret, c->validate, d, cfa + LINUX_SC_SP_OFF, sp);
513       /* Save the link register here in case we end up in a function that
514          doesn't save the link register in the prologue, e.g. kill. */
515       if (likely(ret >= 0))
516         ACCESS_MEM_FAST(ret, c->validate, d, cfa + LINUX_SC_LR_OFF, lr);
517 #elif defined(__FreeBSD__)
518       printf("XXX\n");
519 #endif
520 
521       /* Resume stack at signal restoration point. The stack is not
522          necessarily continuous here, especially with sigaltstack(). */
523       cfa = sp;
524 
525       /* Next frame should not back up. */
526       d->use_prev_instr = 0;
527       break;
528 
529     case UNW_ARM_FRAME_SYSCALL:
530       printf("XXX1\n");
531       break;
532 
533     default:
534       /* We cannot trace through this frame, give up and tell the
535           caller we had to stop.  Data collected so far may still be
536           useful to the caller, so let it know how far we got.  */
537       ret = -UNW_ESTOPUNWIND;
538       break;
539     }
540 
541     Debug (4, "new cfa 0x%x pc 0x%x sp 0x%x r7 0x%x\n",
542            cfa, pc, sp, r7);
543 
544     /* If we failed or ended up somewhere bogus, stop. */
545     if (unlikely(ret < 0 || pc < 0x4000))
546       break;
547 
548     /* Record this address in stack trace. We skipped the first address. */
549     buffer[depth++] = (void *) (pc - d->use_prev_instr);
550   }
551 
552 #if UNW_DEBUG
553   Debug (1, "returning %d, depth %d\n", ret, depth);
554 #endif
555   *size = depth;
556   return ret;
557 }
558 
559