天天看點

gcc __attribute__ ((weak, alias (#name))) 1

       本系列文章,着重講__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被重命名了。

繼續閱讀