Question

I'm trying to learn x86 assembly, by looking at the generated assembly from clang. For instance, I'd like to learn how an automatic array in C is initialized to all 0's.

int64_t my_array [3000] = {0};

It looks like the assembly is reserving 24000B on the stack ( 3000 * 64b / 8B/b ) then calling memset. From memset's man page, it's signature looks like:

void *
memset(void *b, int c, size_t len);

So I know that the second argument should be passed in %rsi is 0 (the value I want every byte set to), and the third argument (%rdx) to be $24000, but what about the first argument (%rdi)? The two relevant instructions from the generated assembly appear to be:

leaq  -24016(%rbp), %rax
movq  %rax, %rdi

but I don't understand why negative 24016 from the base pointer? Why store in %rax then immediately move to %rdi (maybe because I just didn't compile with optimizations)?

Either way, I'm not sure how to pass the address of the first byte of the array to memset. I'm on OSX too, so I've already had to offset my stack pointer by 8B to assemble.

Was it helpful?

Solution

You have allocated my_array on the stack (automatic storage), this means the compiler has to decrement the stack pointer (the stack grows towards lower addresses) by the size of your local variables plus room to save registers and such. The %ebp base pointer is set to point to the frame pointer of the caller (after saving the caller's base pointer by pushing it on the stack). This is part of the convention necessary for proper stack unwinding. See Chapter 9 Exception handling and stack unwinding in Agner Fog's comprehensive Calling Conventions document

http://www.agner.org/optimize/calling_conventions.pdf.

Since %ebp is pointing to the caller's frame, the compiler uses a negative offset from it to point to the beginning of my_array, a local variable in the called function.

I don't have an answer as to why the compiler stored the address in %rax and immediately copied it to %rdi, it seems it could have done that in one step

leaq  -24016(%rbp), %rdi
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top