Dynamic Linking at Run-Time
dlopen으로 라이브러리를 열고
dlsym으로 fucntiond을 찾는다.
Library interpositioning
임의의 fucntion에 추가적인 기능을 시킬 수 있다.
다음과 같은 시점들에 가능하다.
- Complie time
- Link time
- Load/run time
목적
- Security
- Monitoring and Profiling
Complie time interpositioning
실제로 코드가 있어야 한다. 컴파일을 다시 해야한다.
maloc을 mymalloc으로 바꾼다.
#define malloc(size ) mymalloc(size , __FILE__, __LINE__)
#define free(ptr ) myfree(ptr , __FILE__, __LINE__)
void *mymalloc(size_t size, char *file, int line);
void myfree(void ptr , char *file, int line);
Link time interpositioning
#ifdef LINKTIME
--wrap symbol을 사용한다.
__Wrap_malloc을 사용한다.
__Wrap_malloc은 안에서 __real_malloc(size)를 부른다.
gcc -O2 -Wall -DLINKTIME -c mymalloc.c
gcc -O2 -Wall -Wl, --wrap,malloc -Wl, --wrap,free -o hellol hello.c mymalloc.o
-w1 flag는 linker에게 argument를 준다.
--wrap,malloc은 malloc대신 __wrap_malloc을 사용하고, __real_malloc에서 원래 malloc을 사용하도록 만든다.
Load/run time interpositioning
dlsym을 사용해 malloc의 위치를 가져온다.
mallocp = dlsym(RTLD_NEXT , "malloc");
LD_PRELOAD는 먼저 확인할 곳의 경로를 넣어준다.
gcc -O2 -Wall -DRUNTIME -shared -fPIC -o mymalloc.so mymalloc.c
gcc -O2 -Wall -o hellor hello.c
Load/Run-time interpositioning과 관련된 GCC의 Parameter
| 파라미터 | 설명 |
| LD_PRELOAD | 변수에 설정된 라이브러리를 기존이 라이브러리가 로딩. 중복된 이름의 함수가 있는 경우 LD_PRELOAD에 설정된 라이브러리의 함수가 사용된다. |
| -shared | shared libarary(.so)를 생성 |
| -fPIC | 상대적인 위치를 저장하여 PIC(Position Independent Code)로 컴파일 되도록 한다. 주로 공유라이브러리를 만들 때 사용된다. |
동적 메모리 할당과 관련된 함수
| 함수 | 설명 |
| void* malloc(size_t size) | size만큼의 바이트를 메모리 공간에 할당한 후 그 첫 번째 주소값을 리턴 |
| void* calloc(size_t n, size_t size) | n은 할당할 메모리의 단위 개수이며, size는 하나당 크기이다. malloc은 할당된 메모리를 초기화 하지않아 쓰레기 값이 들어있는 반면 calloc은 모두 0으로 초기화 시켜준다. |
| void* realloc(void* p, size_t size) | malloc이나 calloc을 통해 할당한 메모리의 공간을 더 늘이거나 줄이는데 사용 된다. |
| void *free (void* p) | 메모리 누수를 방지하기 위해 dynamic하게 생성한 메모리를 해제해 주는 역할을 한다. |
'System programming' 카테고리의 다른 글
| Linker 문제2 (0) | 2022.04.06 |
|---|---|
| Linker 문제1 (0) | 2022.04.06 |
| Linker2 (0) | 2022.04.05 |
| Linking1 (0) | 2022.04.04 |
| 시스템프로그래밍1 - Overview (0) | 2022.04.04 |
댓글