Error in my first build program (GCC Inline Assembly)

After much internet research, I implemented a small assembler procedure in my C ++ program to get the size of the L1 processor cache using cpuid.

int CPUID_getL1CacheSize() { int l1CacheSize = -1; asm ( "mov $5, %%eax\n\t" // EAX=80000005h: L1 Cache and TLB Identifiers "cpuid\n\t" "mov %%eax, %0" // eax into l1CacheSize : "=r"(l1CacheSize) // output : // no input : "%eax" // clobbered register ); return l1CacheSize; } 

It works fine on Windows 7 64 bit with MinGW (GCC, g ++). Then I tried this on my Mac using GCC 4.0, and somewhere there should be an error, because my program shows strange lines in ComboBoxes, and some signals cannot be connected (Qt GUI).

This is my first assembler program, I hope someone can give me a hint, thanks!

+4
source share
2 answers

I think the CPUID is actually clobbers EAX, EBX, ECX, EDX, so it is probably just a registration problem. The following code works fine with gcc 4.0.1 and 4.2.1 on Mac OS X:

 #include <stdio.h> int CPUID_getL1CacheSize() { int l1CacheSize = -1; asm ( "mov $5, %%eax\n\t" // EAX=80000005h: L1 Cache and TLB Identifiers "cpuid\n\t" "mov %%eax, %0" // eax into l1CacheSize : "=r"(l1CacheSize) // output : // no input : "%eax", "%ebx", "%ecx", "%edx" // clobbered registers ); return l1CacheSize; } int main(void) { printf("CPUID_getL1CacheSize = %d\n", CPUID_getL1CacheSize()); return 0; } 

Note that you need to compile with -fno-pic , since EBX is reserved when PIC is enabled. (Either this, or you need to take steps to save and restore EBX).

 $ gcc-4.0 -Wall -fno-pic cpuid2.c -o cpuid2 $ ./cpuid2 CPUID_getL1CacheSize = 64 $ gcc-4.2 -Wall -fno-pic cpuid2.c -o cpuid2 $ ./cpuid2 CPUID_getL1CacheSize = 64 $ 
+5
source

Finally I solved the problem. I had a compiler error during the game: "error: PIC register"% ebx ", knocked down in" asm ", and after some internet research I changed my code to:

int CPUID_getL1CacheSize () {

 int l1CacheSize = -1; asm volatile ( "mov $5, %%eax\n\t" "pushl %%ebx; cpuid; popl %%ebx\n\t" "mov %%eax, %0" : "=r"(l1CacheSize) : : "%eax" ); return l1CacheSize; 

}

Thanks, Paul. The -fno-pic compiler option is also a nice solution. Greetings

0
source

Source: https://habr.com/ru/post/1313801/


All Articles