Skip to content

Commit 5abfaa0

Browse files
committed
fixed
1 parent 3e975be commit 5abfaa0

File tree

2 files changed

+51
-13
lines changed

2 files changed

+51
-13
lines changed

mem-layout/Makefile

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ raii: raii.c
99
$(CC) -o $@ -Wall -std=c99 $<
1010

1111
backtrace: backtrace.c
12-
$(CC) -o $@ -Wall -std=c99 $<
12+
$(CC) -o $@ -Wall -std=c99 -rdynamic $<
1313

1414
clean:
1515
@true && \

mem-layout/backtrace.c

Lines changed: 50 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,36 @@
1212
void *extract_addr(char *strack_info)
1313
{
1414
#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)
1718
{
1819
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+
}
2227
}
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)
2633
{
2734
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;
3142
}
43+
#else
44+
#error "unsupported platform"
3245
#endif
3346
return NULL;
3447

@@ -78,10 +91,35 @@ typedef struct
7891
int money;
7992
} foo_t;
8093

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+
81117
int main()
82118
{
83119
foo_t foo = { .id=9, .money=8 };
84120
printf("main=%p g=%p f=%p\n", main, g, f);
85121
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");
87125
}

0 commit comments

Comments
 (0)