【发布时间】:2016-09-27 12:48:24
【问题描述】:
我需要编写单一测试来包装 abort() 系统调用。
这是一段sn-p代码:
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
extern void __real_abort(void);
extern void * __real_malloc(int c);
extern void __real_free(void *);
void __wrap_abort(void)
{
printf("=== Abort called !=== \n");
}
void * __wrap_malloc(int s)
{
void *p = __real_malloc(s);
printf("allocated %d bytes @%p\n",s, (void *)p);
return p;
}
void __wrap_free(void *p)
{
printf("freeing @%p\n",(void *)p);
return __real_free((void *)p);
}
int main(int ac, char **av)
{
char *p = NULL;
printf("pre malloc: p=%p\n",p);
p = malloc(40);
printf("post malloc p=%p\n",p);
printf("pre abort\n");
//abort();
printf("post abort\n");
printf("pre free\n");
free(p);
printf("post free\n");
return -1;
}
然后我使用以下命令行编译它:
gcc -Wl,--wrap=abort,--wrap=free,--wrap=malloc -ggdb -o test test.c
运行它会给出以下输出:
$ ./test
pre malloc: p=(nil)
allocated 40 bytes @0xd06010
post malloc p=0xd06010
pre abort
post abort
pre free
freeing @0xd06010
post free
所以一切都很好。 现在让我们测试相同的代码,但取消注释 abort() 调用:
$ ./test
pre malloc: p=(nil)
allocated 40 bytes @0x1bf2010
post malloc p=0x1bf2010
pre abort
=== Abort called !===
Segmentation fault (core dumped)
我真的不明白为什么在模拟 abort() 系统调用时会出现分段错误... 欢迎任何建议!
我在 x86_64 内核上运行 Debian GNU/Linux 8.5。机器是基于 Core i7 的笔记本电脑。
【问题讨论】:
-
以双下划线开头的名称保留给标准库和任何使用的实现。不应在用户代码中使用它们。
-
而
malloc采用size_t,而不是int! -
@Olaf 是使用
--wrap强制使用双下划线 -
@olaf: 1/ 看看 --wrap 用法 2/ 在我的问题中毫无意义。提醒一下,这是一个测试代码......不是生产代码......
-
@LPs:好的,在链接器中找到了(忽略了文本中的命令行-应该正确格式化)
标签: c linux debugging mocking abort