Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect whether the system can run amd64 executables

Tags:

c++

c

x86

x86-64

intel

I have compiled my application to using the x86 instruction set but I need to know programatically whether the machine the executable is running on supports the amd64 instruction set or not. Is there a simple way to find this out (possibly using CPUID)?

The application needs to be able to run on multiple OSes so non-OS based methods are preferred.

like image 363
doron Avatar asked Jun 14 '16 11:06

doron


1 Answers

You're looking for code to detect Long mode.

A bit in the CPUID extended attributes field informs programs in real or protected modes if the processor can go to long mode, which allows a program to detect an x86-64 processor. This is similar to the CPUID attributes bit that Intel IA-64 processors use to allow programs to detect if they are running under IA-32 emulation.

The flag in question is bit 29 in EDX of the CPUID query for 80000001h.

The CPUID instruction infrastructure is a little longwinded: if you presume that CPUID is even available, you then have to query what it can actually support before launching into that exact query. And then you need to get the register results into your variable.


Here is some code, written in inline assembler for C/C++. If you're using gcc, sorry: you'll have to convert to the (horrible!) gasm syntax yourself!

// Only on Pentium4 or above
// Only available on 32-bit
bool HasLongMode() {
    __asm {
        mov   eax,0x80000001 // Ask for processor features
        cpuid                // from the CPU
        xor   eax,eax        // Zero return value
        test  edx,0x20000000 // Check relevant bit
        setnz al             // Was bit set?
    } // __asm
} // HasLongMode()
like image 157
John Burger Avatar answered Nov 19 '22 07:11

John Burger