将 c 结构的指针传递给 x86-32 程序集会自动取消引用
Pass in pointer of c struct to x86-32 assembly becomes automatically dereference
我需要将地址传递给汇编函数,但我似乎做不到。
这是 c 文件:
int asm_func(void *arg);
struct foo {
int len;
char *buf;
};
int bar(int size, char *buf){
struct foo arg_to_asm_function;
arg_to_asm_function.len = size;
arg_to_asm_function.buf = buf;
return asm_func(&arg_to_asm_function);
}
程序集如下:
.global asm_func
asm_func:
pushl %esi
movl 8(%ebp), %esi
/* do something with &arg_to_asm_function, which is in esi */
popl %esi
ret
如果我使用参数 bar(5, "hello world") 调用 c 函数 bar,并且我进入指令
movl 8(%ebp), %esi
我在 %esi 中得到值 5(结构 foo 中第一个字段的值)。
%esi 中的预期值是指向我声明的结构 foo 的指针,即 &arg_to_asm_function,而不是该地址中的值。
为什么会这样?编译器会自动为我取消引用指针吗?我如何将结构的地址传递给 %esi?
你没有在汇编函数中设置栈帧,所以8(%ebp)
不会给你正确的值。因为 ebp
仍然具有来自您的 C 函数的值,所以您看到的是传递给该函数的第一个参数的值。
您需要使用
设置栈帧
push %ebp
mov %esp, %ebp
...
pop %ebp
这是假设调用约定在堆栈上传递函数参数 - 否则您需要从寄存器中获取参数值。
我需要将地址传递给汇编函数,但我似乎做不到。
这是 c 文件:
int asm_func(void *arg);
struct foo {
int len;
char *buf;
};
int bar(int size, char *buf){
struct foo arg_to_asm_function;
arg_to_asm_function.len = size;
arg_to_asm_function.buf = buf;
return asm_func(&arg_to_asm_function);
}
程序集如下:
.global asm_func
asm_func:
pushl %esi
movl 8(%ebp), %esi
/* do something with &arg_to_asm_function, which is in esi */
popl %esi
ret
如果我使用参数 bar(5, "hello world") 调用 c 函数 bar,并且我进入指令
movl 8(%ebp), %esi
我在 %esi 中得到值 5(结构 foo 中第一个字段的值)。
%esi 中的预期值是指向我声明的结构 foo 的指针,即 &arg_to_asm_function,而不是该地址中的值。
为什么会这样?编译器会自动为我取消引用指针吗?我如何将结构的地址传递给 %esi?
你没有在汇编函数中设置栈帧,所以8(%ebp)
不会给你正确的值。因为 ebp
仍然具有来自您的 C 函数的值,所以您看到的是传递给该函数的第一个参数的值。
您需要使用
设置栈帧push %ebp
mov %esp, %ebp
...
pop %ebp
这是假设调用约定在堆栈上传递函数参数 - 否则您需要从寄存器中获取参数值。