1

I'm working with some low-level C code and I don't quite understand what's going on here:

/* Description of the current CPU.  */
struct cpuid { unsigned eax, ebx, ecx, edx; };

/* Return information about the CPU.  See <http://wiki.osdev.org/CPUID>.  */
static struct cpuid
cpuid (unsigned int leaf, unsigned int subleaf)
{
  struct cpuid result;
  asm ("cpuid"
       : "=a" (result.eax), "=b" (result.ebx),
     "=c" (result.ecx), "=d" (result.edx)
       : "a" (leaf), "c" (subleaf));
  return result;
}

I've tried looking for information on the asm() function, including that wiki page, but I'm still struggling in deciphering the code. I understand that the : syntax is an old-school, deprecated way to initialize structs, but I don't really see how it's working here.

edit:

my question is specifically about what this snippet of code is doing, not the syntax or any of that. just this section and what's going on.

user18348324
  • 244
  • 10
  • GNU C inline asm isn't a function call, it's not standard C syntax. https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html / https://stackoverflow.com/tags/inline-assembly/info / https://gcc.gnu.org/wiki/DontUseInlineAsm / [Intrinsics for CPUID like informations?](https://stackoverflow.com/q/17758409) – Peter Cordes Feb 20 '23 at 07:18
  • 1
    As for what the snippet does, it runs the [`cpuid`](https://c9x.me/x86/html/file_module_x86_id_45.html) opcode, which gives various informations about the installed CPU. The part of the `asm` statement between the first colon and the second matches CPU registers (which contain said information) to C variables (i.e., output of the opcode), the part after the second colon matches C variables **to** CPU registers (i.e., input of the opcode). Hope this helps. – DevSolar Feb 20 '23 at 07:29
  • It's a C wrapper for `cpuid`, which has 2 inputs (implicitly EAX and ECX) and 4 outputs (implicitly EAX through EDX). The inline asm looks correct, telling the compiler about those inputs and outputs. The lack of `volatile` means it's not usable for serializing purposes, since it can optimize away or be hoisted out of loops if used multiple times with the same inputs, or if the outputs aren't used. But it's fine for retrieving CPUID outputs. – Peter Cordes Feb 20 '23 at 07:38
  • "_I understand that the : syntax is an old-school, deprecated way to initialize structs_" - really? Never heard of that. It is used for declaring bitfields in a structure. That is not relevant here. – Clifford Feb 20 '23 at 07:47
  • [What does "cpuid level" mean?](https://superuser.com/q/134297) / [What is the CPUID standard function 01H?](https://stackoverflow.com/q/38494702) / [How to use CPUID instruction to get x86 CPU features correctly?](https://stackoverflow.com/q/46168169) – Peter Cordes Feb 20 '23 at 07:58

0 Answers0