x86 Calling Convention 16-bit
Here is the text modified to describe the x86 calling convention for 16-bit:
The x86 calling convention is a set of rules that dictate how functions receive parameters and return values, how the stack is managed, and how registers are used. This ensures that code generated by different compilers can interoperate.
Key Points of the x86 Calling Convention (16-bit)
Registers:
General-purpose registers: AX, BX, CX, DX, SI, DI, BP, SP.
Stack pointer: SP.
Base pointer: BP.
Parameter Passing:
Parameters are passed on the stack in right-to-left order.
The caller pushes the arguments onto the stack before calling the function.
Return Values:
The primary return value is placed in AX.
If a function returns a structure or a union, the address of the return value is passed as a hidden first parameter.
Stack Management:
The stack must be 2-byte aligned at the point of a function call.
The caller is responsible for cleaning up the stack after the function call (cdecl) or the callee cleans up the stack (stdcall).
Callee-saved Registers:
Registers BX, SI, DI, BP must be preserved by the callee.
The callee must save and restore these registers if it uses them.
Example
Here is an example of a simple function in x86 assembly that adds two integers:
Explanation (1)
The function
addtakes two integer arguments passed on the stack.It loads the first argument from
[sp+2]intoAX.It adds the second argument from
[sp+4]toAX.The
retinstruction returns to the caller, with the result inAX.
Example with Stack Usage
Here is an example of a function that uses the stack to store local variables:
Explanation (2)
The function
sum_arraytakes two arguments: a pointer to an array and the array length, both passed on the stack.It saves the base pointer (
BP) and sets up the stack frame.It allocates space for local variables.
It initializes the sum and index to 0.
It enters a loop to iterate over the array, loading each element, adding it to the sum, and incrementing the index.
After the loop, it moves the sum to the return register (
AX), deallocates the local variables, and restores the base pointer.It returns with the sum in
AX.
These examples illustrate the basic principles of the x86 16-bit calling convention, including register usage, parameter passing, and stack management.