about summary refs log tree commit diff stats
path: root/tests/test19.c
blob: f65137d1f8b7ed3a30abab6520a8e4531f6aa736 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <execinfo.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
/// build with `gcc -march=core2 -g -O2 test19.c -o test19 -no-pie -rdynamic`

#define BT_BUF_SIZE 100

void myfunc3()
{
  int nptrs;
  void *buffer[BT_BUF_SIZE];
  char **strings;

  nptrs = backtrace(buffer, BT_BUF_SIZE);
  printf("backtrace() returned %d addresses\n", nptrs);

 /* The call backtrace_symbols_fd(buffer, nptrs, STDOUT_FILENO)
    would produce similar output to the following: */

  strings = backtrace_symbols(buffer, nptrs);
  if (strings == NULL) {
    perror("backtrace_symbols");
    exit(EXIT_FAILURE);
  }

  for (int j = 0; j < nptrs; j++) {
    // clean-up output so it can be compared
    char* p = strchr(strings[j], '[');
    if(p)
      p[-1] = '\0';
    p = strchr(strings[j], '(');
    if(p)
      *p = ':';
    p = strchr(p?p:strings[j], '+');
    if(p)
      *p = '\0';
    p = strchr(p?p:strings[j], ')');
    if(p)
      *p = '\0';
    p = strchr(strings[j], ':');
    if(!p)
      p = strings[j];
    if(!strcmp(p, ":ExitEmulation"))
      p = "???";
    printf("%s\n", p);
  }
  free(strings);
}

static void   /* "static" means don't export the symbol... */
myfunc2(void)
{
  myfunc3();
}

void myfunc(int ncalls)
{
  if (ncalls > 1)
    myfunc(ncalls - 1);
  else
    myfunc2();
}

int main(int argc, char *argv[])
{
  int ncall = 4;
  if (argc == 2) {
    ncall = atoi(argv[1]);
  }

  myfunc(ncall);
  exit(EXIT_SUCCESS);
}