Decompiling/Stack

From OpenDUNE

Jump to: navigation, search

Intro

Stacks grow to the bottom. The lower the 'sp', the newer the entry.

emu_push(0x0);
emu_push(0x1);

Value 0x1 is now at ss:sp, and value 0x0 is at ss:sp+2 (all stack entries are 2 bytes big). This needs getting used to.

Functions and stack

When there is a call to a function, the (cs:)ip is pushed on the stack. When you return from a function, those two values are popped. In result, it returns to the position indicated by the function call. This is how the stack works with calls, and the reason it can find its way back. For interrupts it also pushes the flags on the stack. Flags, cs, ip is the order. So when you are inside a function, the ip is at ss:sp, the cs at ss:sp+2, and the flags at ss:sp+4. Of course if the cs and flags are there.

Parameters / Return values / Local variables

Parameters to a function can be given via a register, or via the stack. Return values are mostly given via the register, but sometimes via the stack. Local variables are also put on the stack. In more detail:

emu_push(0x1);
emu_push(0x1234); f__NNNN();

First there is 0x1 on the stack, than the ip for the function call. Now inside the function f__NNNN we can get the parameter 0x1 by reading ss:sp+2. So: positive numbers always read parameters of functions.

Often you see at the begin of a function:

emu_bp = emu_sp;
emu_sp -= 6;

This means it just reserved 6 bytes of stack for local variables. Now those 6 bytes are safe. If you call another function, it won't use those 6 bytes, as the sp is moved passed it. You can now refer to parameters via bp, like: ss:bp+2 gets the 0x1 above. Local variables now can be reached via ss:bp-2 for example. Remember that at ss:bp still is the ip, and should be kept untouched. If you do

emu_push(0x2);

Now, it will be at ss:sp, but at ss:bp-8. At the end of a function bp is mostly reset to its original value, by first pushing it on the stack in the first place.

In general it is a good idea to write down the entries that are pushed on the stack on a piece of paper. You will often get confused. This is normal. Just remember: parameters are +, local variables are -. Of course a lot of variation is possible, and there can be enough hacks to trick the system. But in general, it is used like this.

Personal tools