[unicorn-engine] Re: Calling external code

  • From: Oliver James <oli@xxxxxxxxxxxxxxxx>
  • To: unicorn-engine@xxxxxxxxxxxxx
  • Date: Fri, 25 Oct 2019 15:07:45 +0100

Hi Sam,

Thanks for the information. This is extremely close to what I had
prototyped with a trampoline function but thanks to you I realised I don't
need to do any trickery in assembly as I have full control over the CPU
state in the emulator! I was trying to keep the stack balanced forgetting I
could just force its state from the host's side!

Kind regards,

Oliver James
Chromalabs | Developer


On Thu, 24 Oct 2019 at 22:12, Samuel Hopstock <masrepus97@xxxxxxxxx> wrote:

Hi Oliver,

For our Unipacker project, we also needed to hook imported functions. You
could take a look at how we did it: In core.py line 507 (
https://github.com/unipacker/unipacker/blob/master/unipacker/core.py#L507),
you can see that we use the kind of trampoline you had in mind. We define a
"hook address" that is unique for each import and store which function name
was associated with this address. Then we write this address to the space
where the loader would put the actual function address.
Now when the program wants to call the imported function, it lands at our
hook address. At this place, we put "mov eax, [HOOK_BASE]; ret". When we
see that a hook address is about to be executed, we check which function
name has been associated with it, perform the necessary API call algorithm,
and then write the return value to the HOOK_BASE address. Like this, the
trampoline automatically moves the return value to eax and returns to the
normal execution flow, as it should be.
I could imagine that there might be a more memory saving way of doing
this, but for us this approach works perfectly fine.

If you want to see how we handle specific API calls, check out
https://github.com/unipacker/unipacker/blob/master/unipacker/apicalls.py

Best regards,
Samuel
On Oct 23, 2019, 22:09 +0200, Oliver James <oli@xxxxxxxxxxxxxxxx>, wrote:

Hey guys,

I'm currently using Unicorn in a little project to run old Windows games
on other platforms.

I've got it loading an executable and emulating the TEB/PEB etc, I am
having some issues finding a decent way to hook the imported DLL calls
though.

I understand the __stdcall ABI and know how to marshal various data
between the emulated process space and the host process space but I can't
seem to work out what type of hook I should use to call the host code.

My attempts at hooking memory access at the import thunk address results
in me getting access before the call actually takes place.

I have a feeling I need some sort of trampoline function in the emulated
process to handle me getting clean access etc, is this correct or are there
known ways to handle something like this?

Kind regards,

Oliver James
Chromalabs | Developer


Other related posts: