Page 1 of 1

writing and calling functions in assembler

PostPosted: Fri Jan 26, 2018 10:29 am
by KG_is_back
In atopic long time ago MyCo had found a way to do function calls from assembler to arbitrary memory block (which cantains machine code). In the end not much had come from that project, mainly because writing and managing machine code is not exactly easy task.

First some theory:

eip register is the register in your CPU that holds the address of next machine code instruction that should be executed. Each instruction increments it by its own memory size, so the code is executed one instruction after another. Exceptions being the jump instructions, which add offset to eip and thus allow your CPU to "jump" to different parts of the code. Another notable exceptions are call and ret instructions, which are used for calling functions.
call instruction pushes the current value if eip onto the stack and replaces it with provided address - it jumps to function while saving the location where the function should return to. ret does it in reverse - pops value from the stack and puts it into eip register.
eip register can't be directly accessed. However, since call instruction pushes its value onto stack, you can write function that reads that. This gives you memory address of the very next instruction after the call instruction. I dubbed this function call the Call of Cuthulu (because it grants you access to forbidden knowledge ;) )
Code: Select all
mov eax,[esp]; //puts contents that are on top of the stack (the value of eip for return) into eax register
ret;


Why is this useful?
You can read the exact memory address of specific part of your code and then access it later!!

Code: Select all

stage0;
mov eax,CallOfCuthulu[0]; //CallOfCuthulu contains the address of mem that contains the CallOfCuthulu machine code


call eax; //perform the call of cuthulu -> puts eip into eax
jmp endOfFunction; //this will skip the code of the function during normal running of stage0;

///your function starts here
   //arbitrary code here
   ret;
///you function ends here

endOfFunction:

add eax,5; //5 is added to skip the jmp instruction (which is 5 bytes long)
mov functionPointer[0],eax; //now functionPointer[0] contains the address of the very next instruction after "jmp endOfFunction;"

stage2;

...
//this will do a function call.

mov eax,functionPointer[0];
call eax;

....



Note, there are several precautions you must take if you really want to use this. Like, testing whether the memory address is valid. See the example schematic below...

Re: writing and calling functions in assembler

PostPosted: Sat Jan 27, 2018 1:16 am
by FlowStoner
ok, next step :geek: