1/* libunwind - a platform-independent unwind library
2   Copyright (C) 2009 Google, Inc
3	Contributed by Arun Sharma <arun.sharma@google.com>
4
5Permission is hereby granted, free of charge, to any person obtaining
6a copy of this software and associated documentation files (the
7"Software"), to deal in the Software without restriction, including
8without limitation the rights to use, copy, modify, merge, publish,
9distribute, sublicense, and/or sell copies of the Software, and to
10permit persons to whom the Software is furnished to do so, subject to
11the following conditions:
12
13The above copyright notice and this permission notice shall be
14included in all copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.  */
23
24#include <unistd.h>
25#include <stdio.h>
26#include <stdlib.h>
27#include <dlfcn.h>
28#include <libunwind.h>
29
30#define panic(args...)				\
31	{ fprintf (stderr, args); exit (-1); }
32
33int verbose;
34int num_errors;
35int in_unwind;
36
37void *
38malloc(size_t s)
39{
40  static void * (*func)();
41
42  if(!func)
43    func = (void *(*)()) dlsym(RTLD_NEXT, "malloc");
44
45  if (in_unwind) {
46    num_errors++;
47    return NULL;
48  } else {
49    return func(s);
50  }
51}
52
53static void
54do_backtrace (void)
55{
56  unw_word_t ip, sp;
57  unw_cursor_t cursor;
58  unw_context_t uc;
59  int ret;
60
61  in_unwind = 1;
62  unw_getcontext (&uc);
63  if (unw_init_local (&cursor, &uc) < 0)
64    panic ("unw_init_local failed!\n");
65
66  do
67    {
68      unw_get_reg (&cursor, UNW_REG_IP, &ip);
69      unw_get_reg (&cursor, UNW_REG_SP, &sp);
70
71      ret = unw_step (&cursor);
72      if (ret < 0)
73	{
74	  ++num_errors;
75	}
76    }
77  while (ret > 0);
78  in_unwind = 0;
79}
80
81void
82foo3 (void)
83{
84  do_backtrace ();
85}
86
87void
88foo2 (void)
89{
90  foo3 ();
91}
92
93void
94foo1 (void)
95{
96  foo2 ();
97}
98
99int
100main (void)
101{
102  foo1();
103
104  if (num_errors > 0)
105    {
106      fprintf (stderr, "FAILURE: detected %d errors\n", num_errors);
107      exit (-1);
108    }
109  return 0;
110}
111