本系列文章,着重讲__attribute__的用途
此属性,可以借助uClibc里面的弱符号来对库里符号进行一些更改,可以用于调试,我最近就用
这个功能来调试system,很好用,类似可以实现hook函数的还有LD_PRELOAD,
参见 http://blog.csdn.net/green369258/article/details/7314298
uClibc 库里面的所有accept 等等 符号都是若符号,因为他都是这样定义的
weak_alias(__libc_accept,accept)
weak_alias(__libc_connect,connect)
被重新命名的函数原型
int __libc_connect(int sockfd, const struct sockaddr *saddr, socklen_t addrlen)
int __libc_accept(int s, struct sockaddr *addr, socklen_t * addrlen)
在编译恰默认搜索路径的头文件中搜索weak_alias ,无法找到,在uClibc中找到它的声明实际上
也很简单
# define weak_alias(name, aliasname) _weak_alias (name, aliasname)
# define _weak_alias(name, aliasname) \
extern __typeof (name) aliasname __attribute__ ((weak, alias (#name)));
一个简单的例子
#include <stdio.h>
#include <stdlib.h>
# define weak_alias(name, aliasname) _weak_alias (name, aliasname)
# define _weak_alias(name, aliasname) \
extern __typeof (name) aliasname __attribute__ ((weak, alias (#name)));
char* const_foo() __attribute__ ((const));
void __foo() { printf("this is foo\n");}
void f() __attribute__ ((weak,alias("__foo")));
weak_alias(__foo, f1);
char* const_foo()
{
char* err = (char*)malloc(10*sizeof(char));
sprintf(err,"%s","hello");
return err;
}
int main()
{
char* str;
__foo();
f();
f1();
str = const_foo();
free(str);
str = NULL;
return 0;
}
程序输出
this is foo
this is foo
this is foo
说明函数__foo被重命名了。