Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does equals sign g "=g" in GCC inline assembly mean / do?

Tags:

c

x86

gcc

assembly

I'm not sure what this inline assembly does:

asm ("mov %%esp, %0" : "=g" (esp));

especially the : "=g" (esp) part.

like image 282
ladookie Avatar asked Jun 12 '11 02:06

ladookie


People also ask

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 assembly syntax does GCC use?

GCC always produces asm output that the GNU assembler can assemble, on any platform. (GAS / GNU as is part of GNU Binutils, along with tools like ld , a linker.)

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 does R mean in assembly?

The “r” in the operand constraint string indicates that the operand must be located in a register. The “=” indicates that the operand is written. Each output operand must have “=” in its constraint.


2 Answers

"=g" (esp) defines an output for the inline assembly. The g tells the compiler that it can use any general register, or memory, to store the result. The (esp) means that the result will be stored in the c variable named esp. mov %%esp, %0 is the assembly command, which simply moves the stack pointer into the 0th operand (the output). Therefore, this assembly simply stores the stack pointer in the variable named esp.

like image 159
ughoavgfhw Avatar answered Sep 21 '22 08:09

ughoavgfhw


If you want the gory details, read the GCC documentation on Extended Asm.

The short answer is that this moves the x86 stack pointer (%esp register) into the C variable named "esp". The "=g" tells the compiler what sorts of operands it can substitute for the %0 in the assembly code. (In this case, it is a "general operand", which means pretty much any register or memory reference is allowed.)

like image 25
Nemo Avatar answered Sep 22 '22 08:09

Nemo