"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Access CPU Information in Linux Using the `cpuid` Instruction?

How to Access CPU Information in Linux Using the `cpuid` Instruction?

Published on 2024-11-09
Browse:145

How to Access CPU Information in Linux Using the `cpuid` Instruction?

Accessing CPU Information on Linux Using the cpuid Instruction

In this question, a developer seeks to access CPU information in a Linux environment using a method akin to the _cpuinfo() function in the Windows API. The provided code attempts to utilize assembly instructions (cpuid) to retrieve this information, but the developer wishes to avoid the need for manual assembly.

The solution lies in utilizing the cpuid.h header file available when compiling code with GCC. This header declares two functions:

unsigned int __get_cpuid_max(unsigned int __ext, unsigned int *__sig);
int __get_cpuid(unsigned int __level, unsigned int *__eax, unsigned int *__ebx, unsigned int *__ecx, unsigned int *__edx);

The __get_cpuid_max function returns the highest supported input value for the cpuid instruction. You can specify __ext as either 0x0 for basic information or 0x8000000 for extended information.

The __get_cpuid function retrieves CPU information for a specified level and returns the data in the eax, ebx, ecx, and edx registers. It returns a non-zero value if successful and zero if the requested level is not supported.

Usage Example:

#include 
#include 

int main() {
  unsigned int eax, ebx, ecx, edx;

  // Get maximum supported CPUID level
  unsigned int max_level = __get_cpuid_max(0x0, NULL);

  // Iterate over different CPUID levels
  for (unsigned int level = 0; level 
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3