-
LD_PRELOADLinux Basic 2023. 2. 26. 02:14
리눅스에 LD_PRELOAD라는 예약어가 있다.
동적 라이브러리를 먼저 참조할 수 있도록 제공하는 기능이다.
정적 라이브러리는 내가 해보니 잘 안된다.
이론적으로 생각해봐도 정적 라이브러리 형식으로 사용하면 힘들어 보이기는 하다.
이유는 동적 라이브러리를 바꿔치기하는것인데 정적 라이브러리 사용하면 상관 없지 않나?
이런 생각이 들어서 이다.
Q. 그래서 해당기능은 뭐에 유용한가?
코드를 수정하지 않고 외부에서 변경하고 싶을때 가능한 기능임.
https://www.opensourceforu.com/2011/08/lets-hook-a-library-function/
Let's Hook a Library Function - LINUX For You
If you want to change the way a library function works, this article will give you a basic idea of how to get started -- just enough knowledge to be able to experiment with your library functions.
www.opensourceforu.com
위에 설명이 잘 나와 있고
https://github.com/freddiekimN/learning-linux-example/
GitHub - freddiekimN/learning-linux-example
Contribute to freddiekimN/learning-linux-example development by creating an account on GitHub.
github.com
study/LD_PRELOAD_1 라는 브렌치 이름에 ex5 폴더에 구현 해놨다.
예1)
만일 함수의 연산시간을 측정하고 싶을때 위 방식을 이용하면 코드 수정 없이 측정할 수 있다.
study/LD_PRELOAD_1 라는 branch 네임 ex3 폴더에 구현해놨다.
간단하게 설명하면
void foo(char *a) { puts(a); }
위 함수를 아래 처럼 수정하면 연산시간 값을 얻을 수 있다.
RTLD_NEXT를 사용해서 다음에 정의된 함수를 호출 즉 LD_PRELOAD에 정의된 함수를 호출 한다는 내용임.
#define _GNU_SOURCE #include <stdio.h> #include <dlfcn.h> #include <time.h> void foo(char *a) { clock_t start, end; double cpu_time_used; void (*new_foo)(char *a); new_foo = dlsym(RTLD_NEXT, "foo"); start = clock(); new_foo("Hello, I am not a original shared library"); end = clock(); cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC; printf("fun() took %f milliseconds to execute \n", cpu_time_used*1e3); }
출력 This is a shared library test... Hello, I am a shared library --> hook 사용 This is a shared library test... Hello, I am not a original shared library fun() took 0.020000 milliseconds to execute # 일반적인 동적 라이브러리 사용 예 gcc foo.c -o foo.so -fPIC -shared -ldl clang main.c ./foo.so -o main # HOOK을 이용해서 함수를 바꿔치기하는 예 gcc foo_hook.c -o foo_hook.so -fPIC -shared -ldl LD_PRELOAD=${PWD}/foo_hook.so ./main
결론
동적 라이브러는 hook을 이용해서 구현 가능함.
그러나 정적 라이브러리와 보안으로 막혀있으면 안됨을 유의함.
반응형'Linux Basic' 카테고리의 다른 글
gcc & LD_PRELOAD & 동적 라이브러리 & makefile -2 (0) 2024.04.29 gcc & 정적 라이브러리 & 동적 라이브러리 & makefile - 1 (0) 2024.04.27 cmake on linux (2) 2023.09.17 onnx docker 사용하기 (1) 2023.07.16 ONNX 무작정 따라하기 (2) 2023.07.16