0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

[AIX] Wrapper function(dlopen/dlsym/LDR_PRELOAD使用)

Last updated at Posted at 2024-04-09

[AIX] Wrapper function(dlopen/dlsym/LDR_PRELOAD使用)

libc等で提供される関数と同名の関数を定義し、その中でlibcの関数をdlsymで呼び出すことで本来の関数実行の前にデバッグ出力等を行うことが可能です。
LDR_PRELOADで自作の共有オブジェクトを指定することで、モジュール内では自作の関数が優先的に呼び出されます。

  1. Wrapperとなるソースコード作成(gethostbynameの例)
# cat gethostbyname_wrapper.c
#include <stdio.h>
#include <stdlib.h>
#include <dlfcn.h>

struct hostent *gethostbyname (char* Name){
    void *handle = NULL;
    struct hostent* (*real_gethostbyname)(char* Name) = NULL;

    /* print debug output */
    printf("output from wrapper function: gethostbyname is called with [%s]\n",
Name);

    handle = dlopen("libc.a(shr.o)", RTLD_GLOBAL|RTLD_NOW|RTLD_MEMBER);
    if( handle == NULL){
        printf("dlopen failed\n");
        return(NULL);
    }

    real_gethostbyname = dlsym(handle, "gethostbyname");
    if(real_gethostbyname == NULL){
        printf("real_gethostbyname not found\n");
        return(NULL);
    }

    return(real_gethostbyname(Name));
}
  1. コンパイルと実行
# ibm-clang -shared -Wl,-G gethostbyname_wrapper.c -o gethostbyname_wrapper.shr.o
# LDR_PRELOAD=./gethostbyname_wrapper.shr.o ping localhost
output from wrapper function: gethostbyname is called with [localhost]
PING loopback: (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=255 time=0 ms

参考:プリロードされた共用ライブラリー
https://www.ibm.com/docs/ja/aix/7.2?topic=techniques-preloaded-shared-libraries

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?