Posted on 2015-01-25 18:37:38 c
对一个应用程序员来讲,了解汇编不是必需的,更少有手写纯汇编的需求。但是如果能了解些基本的汇编知识,对程序调试和一些语言特性的理解是大有裨益的。本文介绍 AT&T 语法的汇编的要点以及 GCC 使用的内联汇编(inline assembly)的使用。
AT&T 汇编是 GCC 所采用的语法,要点:
通用寄存器(x86_64):
X86_64 下 ABI 调用约定:
内联汇编允许在 C/C++ 代码中嵌入汇编代码,以优化关键代码或者使用架构特有的指令。内联汇编的基本格式如下:
asm [volatile] ( <assembler template>
: ["constraints"(var)] [,"constraints"(var)] /* output operands */
: ["constraints"(var)] [,"constraints"(var)] /* input operands */
: ["register"] [,"register"] [,"memory"] /* clobbered registers */
);
中括号中为可选部分,尖括号为必选部分。圆括号内由 ‘:’ 分割为四个部分:
常用的 constraints 为:
输出 constraints 中需要下面至少一个『修饰符』(constraints modifier)作为前缀:
下面看几个示例:
asm ("":::); //~ nothing
asm ("incl %%eax\n\t":::"eax"); //~ access register directly
asm ("movq $1, %0\n\t" : "=m"(var)); //~ write 1 to var
asm ("mov %0, %%eax\n\t" : : "m"(var)); //~ read from var to eax
//~ read a to eax, read b to either ebx|ecx|edx|edi|esi, add it to eax, write back eax to a
asm ("addl %1, %0\n\t" : "+a"(a) : "r"(b));
asm ("incq global_var\n\t" :::"memory"); //~ access global_var directly
asm ("incl %0\n\t" : "+q"(var)); //~ read var to either eax|ebx|ecx|edx, increase it, write it back to var
asm ("incl %0\n\t" : "=q"(var) : "0"(var)) //~ the same as above, constraint 0 means using the same register
asm ("incl %[__var__]\n\t" : [__var__]"+q"(var)); //~ use user-defined placeholder
最后一个示例使用了用户自定义的占位符,通常在输入输入变量较多的情况下使用,省得逐个地对应。
在汇编中调用 printf:
#include <stdio.h>
int
main()
{
char *fmt = "Hello, %s\n";
char *s = "World";
int ret = 0;
asm (" callq printf\n\t"
: "=a"(ret)
: "D"(fmt), "S"(s));
printf("ret: %d\n", ret);
return 0;
}
在汇编中进行系统调用:
int
sys_write(int fd, const char *buf, size_t n)
{
int ret;
asm (
"syscall\n\t"
: "=a"(ret)
: "0"(1), "D"(fd), "S"(buf), "d"(n)
);
return ret;
}
int
main()
{
char *s = "Hello, World\n";
printf("%d\n", sys_write(fileno(stdout), s, strlen(s)));
return 0;
}
If you wrote an article about life we’d all reach enthtigenmenl.
At last, soomnee comes up with the “right” answer!
That’s really shwerd! Good to see the logic set out so well.
http://jeuxdecasino.top/telephone-gratuit-banque-casino.html
http://destinedfg.com/auto-insurance-west-palm-beach-florida.html
generic viagra sildenafil vietnamese viagra cost of viagra natural viagra alternative comprar viagra generic sildenafil
Zithromax Side Effects Sleep