Implementing Functions in x86 Assembly

Scott Cosentino
5 min readDec 21, 2019

When we use functions in high-level languages, a lot of the details of what is happening is abstracted from us. When we work in assembly, we need to do more work to implement the structure properly. In general, there are five problems we need to be able to solve in order to create a function:

1. Call/Return: How do we get to the function, and how do we know where to return to once the function execution is completed?

2. Parameters: If the function requires parameters, where can they be stored so that the function can access them?

3. Storing local variables: Where can the called function store variables declared in a local context?

4. Handling registers: How do we preserve registers from the caller while using the registers in the called function?

5. Returning a value: How does the function return a value back to the calling function?

The first problem that we will address relates to the storage of parameters. One idea for this could be to store them in registers, however this has several drawbacks. Mainly, if we want to call a function inside of a function, we will quickly run out of registers to store parameters on. To solve this problem, we turn to the memory stack. The memory stack is a stack provided by the system as an alternative to register storage.

To properly utilize the stack, we need to first discuss a few special registers and operations in x86. The first register is the esp

--

--

Scott Cosentino
Scott Cosentino

No responses yet