【发布时间】:2019-07-31 17:35:48
【问题描述】:
我想使用 C 语言中的扩展 asm 来处理系统调用(写入)。 一切都很好,我正在使用
#define write(RESULT, FD, BUFF, SIZE) \
asm volatile ("syscall" : \
"=a" (RESULT) : \
"D" (FD), "S" (BUFF), "d" (SIZE), "a" (1))
这没有任何问题......例如
#define write(RESULT, FD, BUFF, SIZE) \
asm volatile ("syscall" : \
"=a" (RESULT) : \
"D" (FD), "S" (BUFF), "d" (SIZE), "a" (1))
int
main() {
int res;
write(res, 1, "Hello\n", 6);
return 0;
}
我对这段代码没有任何问题,但我的问题是当我拨打这个电话时
write(res, 1, "Hello\n", 6);
循环使用100次
#define write(RESULT, FD, BUFF, SIZE) \
asm volatile ("syscall" : \
"=a" (RESULT) : \
"D" (FD), "S" (BUFF), "d" (SIZE), "a" (1))
int
main() {
int res;
for (int i = 0; i < 100; i++) {
write(res, 1, "Hello\n", 6);
}
return 0;
}
但是有一点……我对这段代码也没有问题,但只是在调试模式下……如果我将程序设置为(发布)或优化模式,这个循环将永远执行! !!!好像没有 100 次的限制……这仅在“发布”模式下发生,该模式优化了我的代码并使其出错!!
是的......打击源代码在“debug”中找到,但它在“Release”模式下永远写“Hello”(没有限制)
这是我使用的汇编代码online check 带 -O3 选项 (GCC x86_64)
.LC0:
.string "Hello\n"
main:
movl $100, %ecx
movl $.LC0, %esi
movl $1, %edi
movl $6, %edx
.L2:
movl %edi, %eax
syscall
subl $1, %ecx
jne .L2
xorl %eax, %eax
ret
【问题讨论】:
-
您知道您不需要内联汇编程序来调用系统调用,对吧?
-
为什么我不需要??如果我使用“写”功能,它将使用这个系统调用将在其中发生的 std wirte 函数......而且如果我使用(系统调用)函数,仍然有一个额外的调用“系统调用”函数
-
只需包含
unistd.h并从那里使用write。无需非便携式内联汇编。 -
因为它更简单、更便携、更快。
-
我认为您大大高估了函数调用需要多长时间。
标签: c assembly inline-assembly