GCC Inline ASM

Question about which tools to use, bugs, the best way to implement a function, etc should go here. Don't forget to see if your question is answered in the wiki first! When in doubt post here.
Post Reply
PlayOS

GCC Inline ASM

Post by PlayOS »

Hi all,

I want to learn some basic inline assembler with gcc, I only need at the moment to learn really basic stuff, I already know things like asm("jmp _start") and asm("cli") and really really simple things like this, but now I need to know how to use variables in the code, like say I want to load the lidt register with a variable called idt_ptr or something, just simple input and output, nothing to complex, just something to get me by for now.

thanks.
dronkit

Re:GCC Inline ASM

Post by dronkit »

inline asm with gcc can get quite complicated. why don't you use normal asm functions and then call them from c?
User avatar
Pype.Clicker
Member
Member
Posts: 5964
Joined: Wed Oct 18, 2006 2:31 am
Location: In a galaxy, far, far away
Contact:

Re:GCC Inline ASM

Post by Pype.Clicker »

dronkit:
because inlined asm can be optimized by GCC. i mean, with a pure asm function, you will have to push arguments on the stack, do a call, etc.

if you're writing a static inline function (which is quite common for bits operation or just re-write a custom memcpy function), the inlined assembly can detect which register is still available in the current compiled code (and thus saves the cost of push/pop of those registers ;), get the values directly from the actual variables place (either from their memory location or - better - from the registers that have been allocated to them.

To learn inline asm, you will have to
1) learn the dull syntax from AT&T (i personnally write nasm code, assemble it and disassemble it into AT&T syntax ;)
2) check info gcc and print the sections about assembler (extend asm & machine constraints)
3) know that the generic form is

Code: Select all

asm("your code goes here":"outputs description":"inputs description":"scratchpad description");
the fun part is that your asm code can contain jokers. for instance, if you want to put a variable content into eax (before calling an interrupt, for instance :p ), you can code it as

Code: Select all

asm volatile ("movl %0,%%eax"::"g"(your_var));
where "%0" means "the first external stuff i'll declare later", which happens to be "g" (your_var). the "g" is the constraint on the location: i set it to "general", so it could be in any register or memory reference.

note that this forces the compiler to issue the "mov" instruction. if you just want to have something in eax becuase you need to multiply it, then you can do

Code: Select all

asm volatile("imul %1":"=a"(product):"0"(multiplicand),"r"(multiplier));
Post Reply