库打桩机制
1.编译时打桩
linux>gcc -DCOMPILETIME -c mymalloc.c
linux>gcc -I. -o intc int.c mymalloc.o
linux>./intc
使用-I.参数,它会使C预处理器会在搜索通常的系统目录之前,现在当前目录中查找
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | mymalloc.c: #ifdef COMPILETIME #include <stdio.h> #include <malloc.h> void * mymalloc( size_t size){ void * ptr= malloc (size); printf ( "malloc(%d)=%p\n" ,( int )size,ptr); return ptr; } void myfree( void * ptr){ free (ptr); printf ( "free(%p)\n" ,ptr); } #endif malloc .h: #define malloc(size) mymalloc(size) #define free(ptr) myfree(ptr) void * mymalloc( size_t size); void myfree( void * ptr); int .c: #include <stdio.h> #include <malloc.h> int main(){ int * p= malloc (32); free (p); return 0; } |
2.链接时打桩
Linux静态连接器支持使用--wrap f标志来进行链接时打桩,链接器会将f解析为__wrap_f,还要把对符号__real_f解析为f。
linux>gcc -DLINKTIME -c mymalloc.c
linux>gcc -c int.c
linux>gcc -Wl,--wrap,malloc --Wl,--wrap,free -o intl int.o mymalloc.o
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | mymalloc: #ifdef LINKTIME #include <stdio.h> void * __real_malloc( size_t size); void __real_free( void * ptr); void * __wrap_malloc( size_t size){ void * ptr=__real_malloc(size); printf ( "malloc(%d)=%p\n" ,( int )size,ptr); return ptr; } void __wrap_free( void * ptr){ __real_free(ptr); printf ( "free(%p)\n" ,ptr); } #endif malloc .h: #define malloc(size) mymalloc(size) #define free(ptr) myfree(ptr) void * mymalloc( size_t size) void myfree( void * free ) int .c #include <stdio.h> #include <malloc.h> int main() { int * p= malloc (32); free (p); return 0; } |
3.运行时打桩
通过设置LD_PRELOAD环境变量,来使动态链接器先搜索LD_PRELOAD库,然后再搜索其他的库。
linux>gcc -DRUNTIME -shared -fpic -o mymalloc.so mymalloc.c -ldl
linux>gcc -o intr int.c
linux>LD_PRELOAD="./mymalloc.so" ./intr
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | mymalloc.c: #ifdef RUNTIME #define _GNU_SOURCE #include <stdio.h> #include <stdlib.h> #include <dlfcn.h> void * malloc ( size_t size){ void *(*mallocp)( size_t size); char * error; mallocp=dlsym(RTLD_NEXT, "malloc" ); if ((error=dlerror())!=NULL){ fputs (error,stderr); exit (1); } char * ptr=mallocp(size); printf ( "malloc(%d)=%p\n" ,( int )size,ptr); return ptr; } void free ( void * ptr){ void (*freep)( void *)=NULL; char * error; if (!ptr) return ; freep=dlsym(RTLD_NEXT, "free" ); if ((error=dlerror())!=NULL){ fputs (error,stderr); exit (1); } freep(ptr); printf ( "free(%p)\n" ,ptr); } #endif 其他两个一样 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
2016-04-17 jQuery实现隐藏标签