Relocatable Functions in NASM

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
SFX

Relocatable Functions in NASM

Post by SFX »

Hi,

I have a question about relocating assembler code, if I write a function like this:

Code: Select all

[bits 32]

_some_func:
   mov      eax, 0x45
   cmp      eax, 0x46
   je      .sf_locala
   mov      ebx, 0x46
   jmp      short .sf_localb
.sf_locala:
   mov      ebx, 0x46
.sf_localb:
   add      eax, ebx
   ret
once this is assembled can I copy this code to anywhere in memory and have it function as expected or would the jumps go to the wrong place?

When I disassemble this it produces this:

Code: Select all

00000000  B845000000        mov eax,0x45
00000005  3D46000000        cmp eax,0x46
0000000A  7407              jz 0x13
0000000C  BB46000000        mov ebx,0x46
00000011  EB05              jmp short 0x18
00000013  BB46000000        mov ebx,0x46
00000018  01D8              add eax,ebx
0000001A  C3                ret
as you can see the jumps have immediate memory locations, this means if I moved this code to say 0x08000 then the jumps would go to the wrong place??

can someone show me how to write relocatable functions? I did try a test but it didn't appear to work, also I don't know if I need it but would the org directive work? I would rather not need it as I want to be able to move the code in memory to any location without knowing where that location is.

thanks.
Adek336

Re:Relocatable Functions in NASM

Post by Adek336 »

00000011 EB05 jmp short 0x18
Look at the dissambly: EB - probably a jmp opcode, 05 - ~relative~ offset.

0x05 + 0x11 + 0x2 = 0x18, yea? so it will work unless you make a mistake outside the function.

0x05 - from the disassembly;
0x02 - size of the opcode
0x11 - offset of the opcode.

And here:
0000000A 7407 jz 0x13
0x0A + 0x07 + 0x02 = 19 = 16 + 3 = 0x13. see?

Cheers,
Adrian
Schol-R-LEA

Re:Relocatable Functions in NASM

Post by Schol-R-LEA »

Both the [tt]JE[/tt] and the [tt]JMP short[/tt] are relative jumps; they use the immediate operand as an offset from the jump location, not as direct address. If you look at the actual opcodes in the disassembly, you will see that the conditional jump comes out as

74 07

0x74 is the opcode for "short jump if the zero flag is clear", and 0x07 is the offset to jump by. Since the next instruction following the operand is 0x0C, and 0x0C + 0x07 = 0x13, the disassembler shows it as branching to address 0x13; however, the opcode itself is in fact relative.
Post Reply