http://www.dllhook.com/post/60.html
- /* 语句块结构
- __asm__("汇编语句"
- :输出
- :输入 // 可以省略
- :会被修改的寄存器 // 可以省略
- );
-
- // 或者
- asm volatile("汇编语句"
- :输出
- :输入 // 可以省略
- :会被修改的寄存器 // 可以省略
- );
- */
-
-
- demo:
-
- void asm_test()
- {
- int myebp = 0;
- __asm__("mov %%ebp, %0\n\n\t"
- : "=g" (myebp)
- :
- :);
- printf("Dyld return address: %x\n", (myebp - 0xc));
- }
-
- // 加法函数简洁写法
- int asm_sum(int a, int b)
- {
- int c = 0; // %0 注意这里c == %0 a、b分别为%1, %2
-
- __asm__("addl %2, %1 \n\t"
- :"=r"(c)
- :"r"(a), "r"(b) // 输入参数
- :);
-
- return c;
- }
-
- // 另外一种写法-直观一点,但是不简洁
- int asm_sum2(int a, int b)
- {
- int c = 0; // %0
- __asm__("movl %1, %%eax;"
- "movl %2, %%ebx;"
- "addl %%ebx, %%eax;"
- "movl %%eax, %0;"
- :"=r"(c)
- :"r"(a), "r"(b)
- :"eax", "ebx");
-
- return c;
- }
-
- // 减法函数简洁写法
- int asm_sub(int a, int b)
- {
- int c = 0; // %0
-
- __asm__("subl %2, %1 \n\t"
- :"=r"(c)
- :"r"(a), "r"(b) // 输入参数
- :);
-
- return c;
- }
-
- void get_cpuid()
- {
- unsigned int s1,s2;
- asm volatile (
- "movl $0x01 , %%eax;"
- "cpuid;"
- "movl %%edx ,%0;"
- "movl %%eax ,%1;"
- :"=m"(s1),"=m"(s2)
- :
- :
- );
- printf("%08X%08X\n",s1,s2);
- }
复制代码
// 2015-07-21 增加两种写法,更加通俗易懂 // 纯汇编+裸函数 __attribute__((naked)) int asm_add_naked(int a, int b){
__asm__("add %0, %1\n\r" "mov %1, %%eax\n\r" "ret" // 别偷懒-自行返回 : :"r"(a), "r"(b) :"memory" ); }
// 推荐这种写法,可读性极高 int asm_add_new(int a, int b){
int c; __asm__("add %[aa], %[bb]\n\r" "mov %[bb], %[cc]\n\r" :[cc]"=r"(c) :[aa]"r"(a), [bb]"r"(b) :"memory" ); return c; }
|