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