header.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include <sys/types.h>
  2. #include <unistd.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include "../../util/header.h"
  7. static inline void
  8. cpuid(unsigned int op, unsigned int *a, unsigned int *b, unsigned int *c,
  9. unsigned int *d)
  10. {
  11. __asm__ __volatile__ (".byte 0x53\n\tcpuid\n\t"
  12. "movl %%ebx, %%esi\n\t.byte 0x5b"
  13. : "=a" (*a),
  14. "=S" (*b),
  15. "=c" (*c),
  16. "=d" (*d)
  17. : "a" (op));
  18. }
  19. static int
  20. __get_cpuid(char *buffer, size_t sz, const char *fmt)
  21. {
  22. unsigned int a, b, c, d, lvl;
  23. int family = -1, model = -1, step = -1;
  24. int nb;
  25. char vendor[16];
  26. cpuid(0, &lvl, &b, &c, &d);
  27. strncpy(&vendor[0], (char *)(&b), 4);
  28. strncpy(&vendor[4], (char *)(&d), 4);
  29. strncpy(&vendor[8], (char *)(&c), 4);
  30. vendor[12] = '\0';
  31. if (lvl >= 1) {
  32. cpuid(1, &a, &b, &c, &d);
  33. family = (a >> 8) & 0xf; /* bits 11 - 8 */
  34. model = (a >> 4) & 0xf; /* Bits 7 - 4 */
  35. step = a & 0xf;
  36. /* extended family */
  37. if (family == 0xf)
  38. family += (a >> 20) & 0xff;
  39. /* extended model */
  40. if (family >= 0x6)
  41. model += ((a >> 16) & 0xf) << 4;
  42. }
  43. nb = scnprintf(buffer, sz, fmt, vendor, family, model, step);
  44. /* look for end marker to ensure the entire data fit */
  45. if (strchr(buffer, '$')) {
  46. buffer[nb-1] = '\0';
  47. return 0;
  48. }
  49. return -1;
  50. }
  51. int
  52. get_cpuid(char *buffer, size_t sz)
  53. {
  54. return __get_cpuid(buffer, sz, "%s,%u,%u,%u$");
  55. }
  56. char *
  57. get_cpuid_str(void)
  58. {
  59. char *buf = malloc(128);
  60. if (buf && __get_cpuid(buf, 128, "%s-%u-%X$") < 0) {
  61. free(buf);
  62. return NULL;
  63. }
  64. return buf;
  65. }