【发布时间】:2014-09-20 16:42:53
【问题描述】:
我在 C 中有这个功能:
int write(int fd, char *buffer, int size)
{
int ret;
__asm__("mov $4, %%eax;"
"mov %0, %%ebx;"
"mov %1, %%ecx;"
"mov %2, %%edx;"
"int $0x80"
: "=r"(ret)
: "g"(fd), "g"(buffer), "g"(size)
: "eax", "ebx", "ecx", "edx");
if (ret < 0) {
return -1;
} else {
return 0;
}
}
在 ASM 中转换为这段代码:
push %ebp
mov %esp,%ebp
push %esi
push %ebx
mov $0x4,%eax
mov %esi,%ebx
mov 0x8(%ebp),%ecx
mov 0xc(%ebp),%edx
int $0x80
mov %esi,%eax
sar $0x1f,%eax
pop %ebx
pop %esi
pop %ebp
ret
由于 fd、*buffer 和 size 是函数参数,它们分别位于 0x8(%ebp)、0xc(%ebp) 和 0x10(%ebp) 中。为什么 GCC 会识别 fd 在 %esi 中的位置,而另外两个变量在堆栈中移位?我怎样才能让这个函数运行(正确获取寄存器中的变量)?
【问题讨论】:
-
正如我在下面评论的那样,我正在编写自己的操作系统作为大学科目的一部分。显然,在使用 Linux 时,我会使用 write。
-
注意int(中断)例程没有返回值,所以这个代码序列会失败。
标签: c gcc assembly inline-assembly i386