http://www.ibm.com/developerworks/linux/library/l-ia.html is a great introduction to inline assembly code in C. But its code examples are not ready to run. So I write the following code to help me understand the article.
#include <stdio.h> #include <unistd.h> #define rdtscll(val) \ __asm__ __volatile__ ("rdtsc" : "=A" (val)) void test_rdtsc() { unsigned long long abc; abc = 0; rdtscll(abc); printf("%#llX\n", abc); } void test_r_constraint() { int x = 10, y; asm ("movl %1, %%eax;" "movl %%eax, %0;" :[output] "=r"(y) /* y is output operand */ :[input] "r"(x) /* x is input operand */ :"%eax"); /* %eax is clobbered register */ printf("x=%d, y=%d\n", x, y); } void test_symbolic_name() { int x = 10, y; asm ("movl %[input], %[output];" :[output] "=r"(y) /* y is output operand */ :[input] "r"(x) /* x is input operand */ :"%eax"); /* %eax is clobbered register */ printf("x=%d, y=%d\n", x, y); } void test_a() { int var = 100; asm ("incl %0" :"=a"(var):"0"(var)); printf("var: %d\n", var); } void test_m() { int x = 100; asm("incl %0\n" : :"m"(x)); __asm__("incl %0\n" : :"m"(x)); printf("x=%d\n", x); } void test_controlName() { static int foo asm("myfoo") = 2; } void test_read_write() { int foo, bar; foo = 1; bar = 2; asm("movl %1, %%eax;" "movl %2, %%ebx;" "addl %%ebx, %%eax;" "movl %%eax, %0;" :"=r" (foo) :"0" (foo), "g" (bar) :"%eax", "%ebx"); printf("sum: %d\n", foo); } void test_cpuid() { unsigned op; unsigned _eax; unsigned _ebx; unsigned _ecx; unsigned _edx; op = 0; asm("cpuid" : "=a" (_eax), "=b" (_ebx), "=c" (_ecx), "=d" (_edx) : "a" (op)); printf("eax=%#X, ebx=%#X, ecx=%#X, edx=%#X\n", _eax, _ebx, _ecx, _edx); } void asm_strcpy(char *dest, char *src, int count) { asm("cld\n\t" "rep movsb" : : "S" (src), "D" (dest), "c" (count)); } void test_asm_strcpy() { char *src = "abc"; char dest[10]; asm_strcpy(dest, src, 4); printf("dest: %s\n", dest); } void test_syscall() { int sys_number = 1; /* syscall number for exit */ int status = 100; asm("int $0x80" : : "a" (sys_number), "b" (status)); } void test_asm_memcpy() { char *src = "123"; char dst[4]; int num = 4; asm("movl %[count], %%ecx;\n" "up: lodsl;\n\t" "stosl;\n\t" "loop up;" : : "S" (src), "D" (dst), [count] "r" (num) : "%ecx", "%eax"); printf("dst: %s\n", dst); } int main(void) { test_rdtsc(); test_r_constraint(); test_symbolic_name(); test_a(); test_m(); test_controlName(); test_read_write(); test_asm_strcpy(); test_cpuid(); test_syscall(); test_asm_memcpy(); }