我正在开发一个小型编译器项目,我似乎无法弄清楚如何推送堆栈位置的地址而不是该堆栈位置的值。我的目标是将保存整数值的堆栈位置地址作为 void 指针推送到打印它的 C 函数。我的最终目标是在函数中进行一些指针整数运算。我成功地从运行时库扩展调用 C 函数,但问题只是弄清楚如何在汇编中推送地址。
我的 C 函数。
void print(void* ptr){
int* int_ptr = (int*)ptr;
printf("*int_ptr is %d\n",*int_ptr);
}
我的 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
就我现在所拥有的而言,它会崩溃,因为我将值 42
转换为地址。有人可以指导我引用一些引用资料或资源以了解更多信息吗?
最佳答案
通常,您可以使用 LEA 获取基于堆栈的值的地址。指令获取-4(%ebp)
的有效地址并将其放入寄存器中。然后您可以将该寄存器压入堆栈。 instruction set reference 中描述了LEA指令。这样:
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.
在您的代码中,类似这样的内容会起作用:
lea -4(%ebp), %eax
push %eax
这应该有效地传递堆栈上-4(%ebp)
的地址,以供函数print
使用。
关于c - 压入堆栈位置的地址而不是该地址处的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47732748/