1

I want to write code in assembly which puts itself in a given ELF. My code looks like:

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:

But I also want that the file (after the edition) will be able to do the same thing, but for this I have to write my code as position independent. Everything I tried to do in order to get the address of func_start label at runtime failed.

Any ideas?

Edit: What I actually ask is: How can I use my labels in a position-independent way?

AstroCB
  • 12,337
  • 20
  • 57
  • 73
Mickey
  • 480
  • 4
  • 13
  • 1
    http://stackoverflow.com/questions/4062403/how-to-check-the-eip-value-with-assembly-language – 0x90 Jun 08 '14 at 19:42

1 Answers1

1

When you call a function, the instruction pointer gets pushed on the stack; You can take advantage of this like so:

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:

I tested that this gets the address correctly, but I didn't actually try moving the code - let's hope I didn't miss anything that'd screw this up.

Aleksi Torhamo
  • 6,452
  • 2
  • 34
  • 44