Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulating c variable via inline assembly [duplicate]

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?

like image 664
user1888502 Avatar asked Jan 31 '13 15:01

user1888502


People also ask

What is __ asm __ in C?

The __asm keyword invokes the inline assembler and can appear wherever a C or C++ statement is legal. It cannot appear by itself. It must be followed by an assembly instruction, a group of instructions enclosed in braces, or, at the very least, an empty pair of braces.

What is inline assembly explain with an example?

In computer programming, an inline assembler is a feature of some compilers that allows low-level code written in assembly language to be embedded within a program, among code that otherwise has been compiled from a higher-level language such as C or Ada.

What is inline assembly how it is different from mixing assembly language with C code?

Because the inline assembler doesn't require separate assembly and link steps, it is more convenient than a separate assembler. Inline assembly code can use any C variable or function name that is in scope, so it is easy to integrate it with your program's C code.


1 Answers

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

like image 121
MOHAMED Avatar answered Sep 20 '22 01:09

MOHAMED