Determine 32/64 bit architecture in assembly

后端 未结 2 1470
广开言路
广开言路 2021-01-12 17:08

I was reading over this question and wondered if the accepted answer might also be a way to determine the architecture. For instance, in asm could I push a WORD onto the sta

相关标签:
2条回答
  • 2021-01-12 18:00

    No, because the size of your stack is based on what mode you are running in (real, protected, long/64, vm86, smm, etc), not on the architecture. If your assembly is running in protected mode for instance, your stack will be 32 bits (or 16 if your operands are 16 bits), even if your processor is x86-64.

    Like someone in the comments mentioned, CPUID is the only reliable way to tell what your architecture is.

    0 讨论(0)
  • 2021-01-12 18:05

    For machine code that detects what mode it's running in, see this code-golf x86 machine-code function that returns 16, 32, or 64: Determine your language's version. The same machine-code bytes give different results depending on what mode they're decoded in.

    Or for just 32 vs. 64, see x86-32 / x86-64 polyglot machine-code fragment that detects 64bit mode at run-time?

    In most cases, you won't need to detect the current mode, because you know what your code was compiled/assembled for. (e.g. in NASM, %ifidn __BITS__ 32, or check %ifidn __OUTPUT_FORMAT__, elf32 which works in YASM as well.)


    To detect CPU capability regardless of current mode, use CPUID. How do you detect the CPU architecture type during run-time with GCC and inline asm? (or use cpuid.h: How do I call "cpuid" in Linux?)

    This still doesn't tell you whether the OS you're running under will support 64-bit executables; if you want to know that you should just check that you're running under a 64-bit OS. CPUID can't help you with that: the mechanisms for 32-bit programs to query the OS are of course OS-specific.

    IMO "the architecture" of your CPU is not the right question to be asking, in almost all cases. (i.e. unless you're writing your own kernel, or writing a CPU-info program). Knowing it doesn't help your program decide what to do.

    32-bit-only x86 CPUs haven't been made for years, and are getting more and more rare. But 32-bit OSes are still in use on 64-bit-capable CPUs.

    0 讨论(0)
提交回复
热议问题