GCC Inline Assembly

From here, here and here

#include <stdio.h>

int func(int a, int b); 
void cpuid(int info, int *eax, int *ebx, int *ecx, int *edx);

int func(int a, int b)
{
	int out = 0;

	__asm__(
		"movl %1, %%eax;"
		"addl %2, %%eax;"
		"movl %%eax, %0;"
		:"=r"(out)      /* output */
		:"r"(a),"r"(b)▸ /* input */
		:"eax"▸ 		/* clobbered register */
	);
	return out;
}

void cpuid(int info, int *eax, int *ebx, int *ecx, int *edx)
{
	*eax = info;
	__asm__(
		"movl %%ebx, %%edi;"	/* 32bit PIC: don't clobber ebx */
		"cpuid;"
		"movl %%ebx, %%esi;"
		"movl %%edi, %%ebx;"
		:"+a"(*eax),"=S"(*ebx),"=c"(*ecx),"=d"(*edx)
		:
		:"edi"
	);
}


int main(int args, char* argv[])
{
	int eax, ebx, ecx, edx;
	printf("ret=%d\n", func(3,5));
	cpuid(1, &eax, &ebx, &ecx, &edx);
	printf("eax:0x%08x, ebx:0x%08x, ecx:0x%08x, edx:0x%08x\n", eax, ebx, ecx, edx);
	printf("stepping:        0x%x\n", eax & 0xF);
	printf("model:           0x%x\n", (eax>>4) & 0xF);
	printf("family:          0x%x\n", (eax>>8) & 0xF);
	printf("processor type:  0x%x\n", (eax>>12) & 0x3);
	printf("extended model:  0x%x\n", (eax>>16) & 0xF);
	printf("extended family: 0x%x\n", (eax>>20) & 0xFF);
	return 0;
}

Result:

ret=8
eax:0x000206a7, ebx:0x00100800, ecx:0x1fbae3ff, edx:0xbfebfbff
stepping:        0x7
model:           0xa
family:          0x6
processor type:  0x0
extended model:  0x2
extended family: 0x0

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.