Here's a complete example of an x86-64 assembly program that sums the elements of an array using the stack to store temporary values, wrapped inside a C program for ease of use and compilation.
✅ Summary of What This Program Does:
Declares an array of 10 integers in C.
Passes it to an x86-64 assembly function.
The assembly function:
Initializes sum = 0.
Iterates over the array.
Loads each element into a register.
Pushes it onto the stack (simulating temporary storage).
Adds it to sum.
Restores the stack pointer after use.
Returns the sum back to C.
The result is printed on the console.
📁 File Structure
You will have two files:
main.c – the C wrapper
sum_array.s – the x86-64 assembly code
🔧 Compilation Command
bash
gcc main.c sum_array.s -o sum_array
Then run with:
bash
./sum_array
📄 main.c
c
#include <stdio.h>
// Declare the external assembly function
extern int sum_array(int *array, int length);
int main() {
int array[] = {10, 20, 30, 40, 50, 60, 70, 80, 90, 100};
int length = sizeof(array) / sizeof(array[0]);
int total = sum_array(array, length);
printf("Sum of array elements: %d\n", total);
return 0;
}
📄 sum_array.s (x86-64 Assembly)
asm
.global sum_array
sum_array:
push %rbp
mov %rsp, %rbp
xor %eax, %eax # sum = 0
mov %rsi, %rcx # rcx = length (counter)
lea 0(,%rdi,4), %r8 # r8 = base address of array (pointer arithmetic)
jmp .Lcheck_loop
.Lloop:
mov (%r8), %r9d # load current array element into r9d
push %r9 # push temp value to stack
add %r9d, %eax # add to sum
add $4, %r8 # move to next element
.Lcheck_loop:
loop .Lloop # loop while rcx > 0
mov %rbp, %rsp # restore stack pointer
pop %rbp
ret
📝 Notes:
We use push %r9 as a way to simulate storing temporary values on the stack, even though we don't actually pop or use them later. If you wanted to preserve values across function calls or complex operations, this pattern becomes more useful.
%rdi holds the first argument (array), %rsi holds the second (length) per the System V AMD64 ABI calling convention used on Unix-like systems.
The .Lloop and .Lcheck_loop labels are standard local labels in GAS syntax.
✅ Sample Output
code
Sum of array elements: 550
Let me know if you want to modify this to work on Windows (using different calling conventions), or if you'd like to implement full stack restoration or debugging features!