code_junkie

How to detect what CPU is being used during runtime

Nov 13th, 2011
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. void get_vendor_id(char *vendor_id) // must be at least 13 bytes
  2. {
  3. FILE *cpuinfo = fopen("/proc/cpuinfo", "r");
  4. if(cpuinfo == NULL)
  5. ; // handle error
  6. char line[256];
  7. while(fgets(line, 256, cpuinfo))
  8. {
  9. if(strncmp(line, "vendor_id", 9) == 0)
  10. {
  11. char *colon = strchr(line, ':');
  12. if(colon == NULL || colon[1] == 0)
  13. ; // handle error
  14. strncpy(vendor_id, 12, colon + 2);
  15. fclose(cpuinfo);
  16. return;
  17. }
  18. }
  19.  
  20. // if we got here, handle error
  21. fclose(cpuinfo);
  22. }
  23.  
  24. void get_vendor_id(char *vendor_id) // must be at least 13 bytes
  25. {
  26. // GCC inline assembler
  27. __asm__ __volatile__
  28. ("movl $0, %%eaxnt"
  29. "cpuidnt"
  30. "movl %%ebx, %0nt"
  31. "movl %%edx, %1nt"
  32. "movl %%ecx, %2nt"
  33. : "=m"(vendor_id), "=m"(vendor_id + 4), "=m"(vendor_id + 8) // outputs
  34. : // no inputs
  35. : "%eax", "%ebx", "%edx", "%ecx", "memory"); // clobbered registers
  36. vendor_id[12] = 0;
  37. }
  38.  
  39. int main(void)
  40. {
  41. char vendor_id[13];
  42. get_vendor_id(vendor_id);
  43.  
  44. if(strcmp(vendor_id, "GenuineIntel") == 0)
  45. ; // it's Intel
  46. else if(strcmp(vendor_id, "AuthenticAMD") == 0)
  47. ; // it's AMD
  48. else
  49. ; // other
  50. return 0;
  51. }
  52.  
  53. bool IsIntel() // returns true on an Intel processor, false on anything else
  54. {
  55. int id_str; // The first four characters of the vendor ID string
  56.  
  57. __asm__ ("cpuid": // run the cpuid instruction with...
  58. "=c" (id_str) : // id_str set to the value of EBX after cpuid runs...
  59. "a" (0) : // and EAX set to 0 to run the proper cpuid function.
  60. "eax", "ebx", "edx"); // cpuid clobbers EAX, ECX, and EDX, in addition to EBX.
  61.  
  62. if(id_str==0x6c65746e) // letn. little endian clobbering of GenuineI[ntel]
  63. return true;
  64. else
  65. return false;
  66. }
Add Comment
Please, Sign In to add comment