|
12 | 12 | void *extract_addr(char *strack_info)
|
13 | 13 | {
|
14 | 14 | #ifdef __linux__
|
15 |
| - char *cp = strchr(strack_info, '['); |
16 |
| - if (cp) |
| 15 | + char *cp_addr = strchr(strack_info, '['); |
| 16 | + char *cp_offset = strchr(strack_info, '+'); |
| 17 | + if (cp_addr && cp_offset) |
17 | 18 | {
|
18 | 19 | void *p;
|
19 |
| - int code = sscanf(cp, "[%p]", &p); |
20 |
| - if (code == 1) |
21 |
| - return p; |
| 20 | + int offset; |
| 21 | + int rcode = sscanf(cp_addr, "[%p]", &p); |
| 22 | + int rcode2 = sscanf(cp_offset, "+%x)", &offset); |
| 23 | + if (rcode == 1 && rcode2 == 1) |
| 24 | + { |
| 25 | + return p - offset; |
| 26 | + } |
22 | 27 | }
|
23 |
| -#elif defined(__MACH__) |
24 |
| - char *hex=strstr(strack_info, "0x"); |
25 |
| - if (hex) |
| 28 | +#elif defined(__APPLE__) |
| 29 | + char *cp_addr=strstr(strack_info, "0x"); |
| 30 | + char *cp_offset=strstr(strack_info, "+ "); |
| 31 | + |
| 32 | + if (cp_addr && cp_offset) |
26 | 33 | {
|
27 | 34 | void *p;
|
28 |
| - int fc = sscanf(hex, "%p ", &p); |
29 |
| - if (fc) |
30 |
| - return p; |
| 35 | + int offset; |
| 36 | + int rcode = sscanf(cp_addr, "%p ", &p); |
| 37 | + int rcode2 = sscanf(cp_offset, "+ %d", &offset); |
| 38 | + |
| 39 | + printf("p=%p, offset=%d\n", p, offset); |
| 40 | + if (rcode == 1 && rcode2 == 1) |
| 41 | + return p - offset; |
31 | 42 | }
|
| 43 | +#else |
| 44 | +#error "unsupported platform" |
32 | 45 | #endif
|
33 | 46 | return NULL;
|
34 | 47 |
|
@@ -78,10 +91,35 @@ typedef struct
|
78 | 91 | int money;
|
79 | 92 | } foo_t;
|
80 | 93 |
|
| 94 | +void *extract_caller_func_addr(int iLevel) |
| 95 | +{ |
| 96 | + void *ip_out = NULL; |
| 97 | + void * array[8]; |
| 98 | + int size = sizeof(array)/sizeof(void *); |
| 99 | + int stack_num = backtrace(array, size); |
| 100 | + char ** stacktrace = backtrace_symbols(array, stack_num); |
| 101 | + for (int i = iLevel; i < stack_num; ++i) |
| 102 | + { |
| 103 | + printf("\t[%d] %p \t %s\n", i, extract_addr(stacktrace[i]), stacktrace[i]); |
| 104 | + } |
| 105 | + if (iLevel < stack_num) |
| 106 | + { |
| 107 | + ip_out = extract_addr(stacktrace[iLevel]); |
| 108 | + } |
| 109 | + free(stacktrace); |
| 110 | + |
| 111 | + |
| 112 | + |
| 113 | + printf("__builtin_return_address[0]=%p\n" , __builtin_return_address(0)); |
| 114 | + return ip_out;; |
| 115 | +} |
| 116 | + |
81 | 117 | int main()
|
82 | 118 | {
|
83 | 119 | foo_t foo = { .id=9, .money=8 };
|
84 | 120 | printf("main=%p g=%p f=%p\n", main, g, f);
|
85 | 121 | printf("foo.id=%d\n", foo.age);
|
86 |
| - g(); |
| 122 | + //g(); |
| 123 | + void *ip=extract_caller_func_addr(1); |
| 124 | + printf("main=%p, extract_caller_func_addr(1)=%p, is_equals=%s\n", main, ip, (ip == &main) ? "true" : "false"); |
87 | 125 | }
|
0 commit comments