manipulating c variable via inline assembly [duplicate]

自作多情 提交于 2020-02-14 06:51:32

问题


Possible Duplicate:
How to access c variable for inline assembly manipulation

Given this code:

#include <stdio.h>

int main(int argc, char **argv)
{
  int x = 1;
  printf("Hello x = %d\n", x);


  }

I'd like to access and manipulate the variable x in inline assembly. Ideally, I want to change its value using inline assembly. GNU assembler, and using the AT&T syntax. Suppose I want to change the value of x to 11, right after the printf statement, how would I go by doing this?


回答1:


The asm() function follows this order:

asm ( "assembly code"
           : output operands                  /* optional */
           : input operands                   /* optional */
           : list of clobbered registers      /* optional */
);

and to put 11 to x with assembly via your c code:

int main()
{
    int x = 1;

    asm ("movl %1, %%eax;"
         "movl %%eax, %0;"
         :"=r"(x) /* x is output operand and it's related to %0 */
         :"r"(11)  /* 11 is input operand and it's related to %1 */
         :"%eax"); /* %eax is clobbered register */

   printf("Hello x = %d\n", x);
}

You can simplify the above asm code by avoiding the clobbered register

asm ("movl %1, %0;"
    :"=r"(x) /* related to %0*/
    :"r"(11) /* related to %1*/
    :);

You can simplify more by avoiding the input operand and by using local constant value from asm instead from c:

asm ("movl $11, %0;" /* $11 is the value 11 to assign to %0 (related to x)*/
    :"=r"(x) /* %0 is related x */
    :
    :);

Another example: compare 2 numbers with assembly



来源:https://stackoverflow.com/questions/14628885/manipulating-c-variable-via-inline-assembly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!