一个运行时打桩的模板

被打桩的函数是STUB_FUN, 可以替换成如__cudaRegisterFunction, 另外插入的函数zwl_profiler可另外定义,

	.text
	.section	.rodata
.LC0:
	.string	"STUB_FUN"
	.text
	.globl	STUB_FUN
	.type	STUB_FUN, @function
STUB_FUN:
.LFB15:
	endbr64
	pushq	%rbp
	movq	%rsp, %rbp
	subq	$64, %rsp
	movq	%rdi, -24(%rbp)
	movq	%rsi, -32(%rbp)
	movq	%rdx, -40(%rbp)
	movq	%rcx, -48(%rbp)
	movq	%r8, -56(%rbp)
	movq	%r9, -64(%rbp)
	call	zwl_profiler
	leaq	.LC0(%rip), %rax
	movq	%rax, %rsi
	movq	$-1, %rdi
	call	dlsym@PLT
	movq	%rax, -8(%rbp)
	movq	-8(%rbp), %r8
	movq	-48(%rbp), %rcx
	movq	-40(%rbp), %rdx
	movq	-32(%rbp), %rsi
	movq	-24(%rbp), %rax
	movq	%rax, %rdi
	call	*%r8
	leave
	ret
.LFE15:
	.size	STUB_FUN, .-STUB_FUN
	.ident	"GCC: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0"
	.section	.note.GNU-stack,"",@progbits
	.section	.note.gnu.property,"a"
	.align 8
	.long	1f - 0f
	.long	4f - 1f
	.long	5
0:
	.string	"GNU"
1:
	.align 8
	.long	0xc0000002
	.long	3f - 2f
2:
	.long	0x3
3:
	.align 8
4: 

zwl_prifler定义,

#include <stdio.h>

void zwl_profiler(void* handle, void* func, char* funcName) {
  printf("register %p: %s\n", func, funcName);
}

需要注意的点是被打桩的函数STUB_FUN不能在zwl_profiler中使用,如printf, malloc函数不行,需要另外想办法。

gcc stub.s zwl_profiler.c -g -shared -o ll.so
export LD_PRELOAD=$PWD/ll.so
posted @ 2025-01-05 22:33  zwlwf  阅读(25)  评论(0)    收藏  举报