0% found this document useful (0 votes)
2 views5 pages

Inline Assembly Programming

Inline assembly programming allows C programmers to insert assembly language instructions into their code, providing low-level control for performance-critical applications. It is particularly useful for performance optimization, hardware access, and utilizing specific CPU instructions not available in standard C. The document explains the syntax for basic and extended inline assembly using GCC, including the importance of using 'volatile' to prevent compiler optimizations that could disrupt assembly logic.

Uploaded by

manedhanaji1414
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Inline Assembly Programming

Inline assembly programming allows C programmers to insert assembly language instructions into their code, providing low-level control for performance-critical applications. It is particularly useful for performance optimization, hardware access, and utilizing specific CPU instructions not available in standard C. The document explains the syntax for basic and extended inline assembly using GCC, including the importance of using 'volatile' to prevent compiler optimizations that could disrupt assembly logic.

Uploaded by

manedhanaji1414
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programing with Inline Assembly using GCC

In system-level and performance-critical applications, higher-level languages such as C typically


lack the ability to offer low-level control that is required for direct interaction with hardware
or even optimizing some operations. Inline assembly programming fills in this gap.
Inline Assembly Programming is the process of inserting assembly language instructions into C
code. This enables programmers to use the efficiency and control of assembly language with the
structure and portability of C. In using the GNU Compiler Collection (GCC) in Linux operating
systems like Ubuntu, inline assembly offers a robust tool for optimal coding, accessing special
CPU instructions, and manipulating hardware.
Why to Use Inline Assembly?
Inline assembly is typically used in the following situations:
 Performance Optimization: For time-critical code, inline assembly can produce faster or
more efficient machine code than what a compiler may generate.
 Hardware Access: System-level programs, such as operating system kernels or device
drivers, may require direct control over CPU instructions or memory-mapped I/O.
 Instruction Set Access: Certain processor-specific instructions are not accessible through
standard C syntax.
 Custom Calling Conventions: Assembly is sometimes used to enforce non-standard
calling sequences or return value mechanisms.
What is AT&T Syntax?
AT&T syntax is the assembly language format originally used by Unix systems and the GNU
Assembler (as). It is used by default in GCC inline assembly and by gas (GNU assembler).
AT&T Syntax vs Intel Syntax

Types of GCC Inline Assembly


1. Basic Inline Assembly: Minimal control, just injects raw assembly into the code.
2. Extended Inline Assembly: Allows specifying operands, constraints, and clobbered
registers.
Basic Inline Assembly Syntax:
The GNU C compiler uses the asm keyword to denote a section of source code that is written in
assembly language. The basic format of the asm section is as follows:
asm( “assembly code” );
The assembly code contained within the parentheses must be in a specific format:
 The instructions must be enclosed in quotation marks.
 If more than one instruction is included, the newline character must be used to separate
each line of assembly language code. Often, a tab character is also included to help indent
the assembly language code to make lines more readable
Example:
#include <stdio.h>
int main()
{
asm (“movl $1, %eax\n\t
movl $0, %ebx\n\t
int $0x80”);
return 0;
}
It is important to note that the data variables must be declared as global. We are not allowed to use
local variables within the asm section.
How to use a Global Variable in Inline Assembly?
Assume that we have a global variable, and we want to use it inside an inline assembly block in
our C code. Following example show how one can achieve it.
Directly Using Global Variable by Name
/* globaltest.c - An example of using C variables */
#include <stdio.h>
int First = 10;
int Second = 20;
int Result;
int main()
{
asm( “pusha\n\t”
“movl First, %eax\n\t”
“movl Second, %ebx\n\t”
“imull %ebx, %eax\n\t”
“movl %eax, Result\n\t”
“popa”);
/* imul is used for integer multiplication */
printf(“the answer is %d\n”, Result);
return 0;
}
Form Meaning
asm The compiler might optimize away the assembly block if it thinks it has no effect.
asm volatile The compiler is forced to keep the assembly block and not optimize it away.

Why one should use asm volatile?


When we are doing something important inside assembly (like reading or writing variables, or
calling hardware instructions), and we don't want the compiler to skip or optimize it out — which
it might do if it thinks it's unused.
When we write inline assembly in C language, the compiler might try to optimize code written by
removing unused parts, reordering instructions, or sharing registers. Sometimes this can be
dangerous for assembly blocks, because even small changes can break the logic we wrote. So to
prevent the compiler from optimizing or changing our assembly code, one can use:
asm volatile("our assembly code here");
This tells the compiler:
"Don't touch this assembly code — it's important just the way it is."
However, one still need to handle register saving/restoring properly — volatile only stops
optimizations, not other compiler responsibilities.
Extended Inline Assembly Syntax:
asm volatile ("assembly code": output operands: input operands: clobbered registers);
This format consists of four parts, each separated by a colon:
 Assembly code: The inline assembly code using the same syntax used for the basic asm
format
 Output locations: A list of registers and memory locations that will contain the output
values
from the inline assembly code
 Input operands: A list of registers and memory locations that contain input values for the
inline assembly code
 Changed registers: A list of any additional registers that are changed by the inline code
In the extended asm format, not all sections are required:
 If no output values are produced, the output section is left blank, but two colons :: must
still separate the assembly code from the input operands.
 If no registers are changed by the assembly code, the last colon (for clobbered registers)
can be omitted.
So let us revise what we discussed above
1) asm or __asm__ : This is the keyword used to embed assembly code into our C program.
 asm and __asm__ are interchangeable.
 __asm__ is used for compatibility with C, especially when strict compiler flags are
enabled.
2) volatile : Prevents Optimization
 Adding volatile tells the compiler not to optimize or move this block of assembly.
 Because compilers might:
 Remove code that appears to have no effect
 Reorder or combine instructions
 One can Use __volatile__ when Programmer want to interact with hardware via
I/O ports.
3) Output Operands
 Placed after the first colon (:).
 These are C variables that our assembly will write to. GCC will link them to CPU
registers or memory and update the C variable after assembly executes.
4) Input Operands
 Placed after the second colon (:), these are C variables passed into our assembly
program.
5) Clobber List
 The clobber list is the final part of the GCC extended inline assembly syntax.
 It tells the compiler about the side effects of our assembly code — specifically,
which registers, flags, or memory might be modified even if they're not declared
in the input/output lists.
 Compilers rely on register allocation and instruction reordering for optimization.
If we don’t inform the compiler about what our assembly modifies:
 It may reuse or overwrite a register we have just modified in assembly.
 It may incorrectly assume memory or flags remain unchanged, causing subtle
bugs.
 The clobber list helps preventing incorrect optimizations.
In the extended inline assembly format, the input and output values are tied to C variables, and
their locations (either registers or memory) are controlled by constraints.
Constraints in Extended Inline Assembly:
The constraints tell the compiler how to treat the input and output operands — whether they should
be placed in registers or memory locations.
The general format is:
"constraint" (variable)
Where:
 constraint is a single-character code that specifies where to place the variable.
 variable is a C variable declared in our program.
Input and Output Values:
Input values: These are the values we pass into the assembly code.
Output values: These are the values that will hold the results after the assembly code executes.

Source: Professional Assembly Language book by Richard Blum

Output Modifiers in Extended Inline Assembly


When using output operands in extended inline assembly, we can add a modifier to the constraint
to give the compiler more details on how the variable should be treated. These modifiers are
particularly useful for ensuring that the output values are handled correctly by the compiler.

Source: Professional Assembly Language book by Richard Blum


/* regtest1.c – An example of using registers */
#include <stdio.h>
int main()
{
int data1 = 10;
int data2 = 20;
int result;
asm (“imull %%edx, %%ecx\n\t”
“movl %%ecx, %%eax”
: “=a”(result)
: “d”(data1), “c”(data2));
printf(“The result is %d\n”, result);
return 0;
}

/* movstest.s - An example of instructions with only input values */


#include <stdio.h>
int main()
{
char input[30] = {“This is a test message.\n”};
char output[30];
int length = 25;
asm volatile (“cld\n\t”
“rep movsb”
:
: “S”(input), “D”(output), “c”(length));
printf(“%s”, output);
return 0;
}

You might also like