Miket25
Miket25

Reputation: 1903

Push address of stack location instead of the value at the address

I'm working on a small compiler project, and I can't seem to figure out how to push the address of a stack location instead of the value at that stack location. My goal is to push a stack location address, that holds an integer value, as a void pointer to a C function that prints it. My ultimate goal is to do some pointer-integer arithmetic in the function. I am successful in calling the C function from a runtime library extension, but the issue is just figuring out how to push the address in assembly.

My C function.

void print(void* ptr){
    int* int_ptr = (int*)ptr;
    printf("*int_ptr is %d\n",*int_ptr);
}

My Assembly

.globl main
main:
pushl %ebp
movl %esp, %ebp
subl $4, %esp

movl $42, %eax
movl %eax, -4(%ebp)

pushl -4(%ebp) 
//Instead of the value at -4(%ebp), I would like the address of -4(%ebp)
call print

addl $8, %esp
leave
ret

As for what I have now, it'll crash since I'm casting the value 42 to an address. Can someone please direct me to some reference or resources to learn more?

Upvotes: 2

Views: 1467

Answers (1)

Michael Petch
Michael Petch

Reputation: 47573

In general you can get the address of a stack based value by using the LEA instruction to get the effective address of -4(%ebp) and place it in a register. You can then push that register to the stack. The LEA instruction is described in the instruction set reference this way:

Computes the effective address of the second operand (the source operand) and stores it in the first operand (destination operand). The source operand is a memory address (offset part) specified with one of the processors addressing modes; the destination operand is a general-purpose register.

In your code something like this would have worked:

lea -4(%ebp), %eax
push %eax

This should effectively pass the address of -4(%ebp) on the stack for use by your function print.

Upvotes: 3

Related Questions