将代码插入elf

时间:2014-06-07 15:17:43

标签: assembly x86 elf

我想在汇编中编写代码,将自己置于给定的ELF中。我的代码如下:

func_start:
; Getting file descriptor, and additional code here
mov eax, 4; Write Sys_call
mov ebx, [fileDesc]
mov ecx, func_start
mov edx, func_end - func_start
func_end:

但我也希望文件(在版本之后)能够做同样的事情,但为此我必须把我的代码写成与位置无关的。为了在运行时获取func_start标签的地址,我试图做的所有事情都失败了。

有什么想法吗?

编辑:我实际要问的是:如何以与位置无关的方式使用我的标签?

1 个答案:

答案 0 :(得分:1)

当你调用一个函数时,指令指针被推到堆栈上;你可以像这样利用这个:

func_start:
    ; Call uses a relative address so it's fine
    call real_start
pushed_addr:
    ; We don't want to recurse infinitely once real_start returns
    ret
real_start:
    ; Get the pushed instruction pointer from the stack
    mov ecx, dword [esp]
    ; It points to pushed_addr, adjust it so that it points to func_start
    sub ecx, pushed_addr-func_start

    ; Now the address of func_start should be in ecx
    ; (The length is still func_end - func_start, of course)

    ; This returns to pushed_addr, which returns to wherever func_start was called
    ret
func_end:

我测试过这是正确的地址,但我并没有真正尝试移动代码 - 我希望我不会错过任何可以搞砸的内容。