cpu_info.c 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /* libs/cutils/cpu_info.c
  2. **
  3. ** Copyright 2007, The Android Open Source Project
  4. **
  5. ** Licensed under the Apache License, Version 2.0 (the "License");
  6. ** you may not use this file except in compliance with the License.
  7. ** You may obtain a copy of the License at
  8. **
  9. ** http://www.apache.org/licenses/LICENSE-2.0
  10. **
  11. ** Unless required by applicable law or agreed to in writing, software
  12. ** distributed under the License is distributed on an "AS IS" BASIS,
  13. ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. ** See the License for the specific language governing permissions and
  15. ** limitations under the License.
  16. */
  17. #include <cutils/cpu_info.h>
  18. #include <stdlib.h>
  19. #include <stdio.h>
  20. #include <string.h>
  21. // we cache the serial number here.
  22. // this is also used as a fgets() line buffer when we are reading /proc/cpuinfo
  23. static char serial_number[100] = { 0 };
  24. extern const char* get_cpu_serial_number(void)
  25. {
  26. if (serial_number[0] == 0)
  27. {
  28. FILE *file;
  29. char *chp, *end;
  30. char *whitespace;
  31. int length;
  32. // read serial number from /proc/cpuinfo
  33. file = fopen("proc/cpuinfo", "r");
  34. if (! file)
  35. return NULL;
  36. while ((chp = fgets(serial_number, sizeof(serial_number), file)) != NULL)
  37. {
  38. // look for something like "Serial : 999206122a03591c"
  39. if (strncmp(chp, "Serial", 6) != 0)
  40. continue;
  41. chp = strchr(chp, ':');
  42. if (!chp)
  43. continue;
  44. // skip colon and whitespace
  45. while ( *(++chp) == ' ') {}
  46. // truncate trailing whitespace
  47. end = chp;
  48. while (*end && *end != ' ' && *end != '\t' && *end != '\n' && *end != '\r')
  49. ++end;
  50. *end = 0;
  51. whitespace = strchr(chp, ' ');
  52. if (whitespace)
  53. *whitespace = 0;
  54. whitespace = strchr(chp, '\t');
  55. if (whitespace)
  56. *whitespace = 0;
  57. whitespace = strchr(chp, '\r');
  58. if (whitespace)
  59. *whitespace = 0;
  60. whitespace = strchr(chp, '\n');
  61. if (whitespace)
  62. *whitespace = 0;
  63. // shift serial number to beginning of the buffer
  64. memmove(serial_number, chp, strlen(chp) + 1);
  65. break;
  66. }
  67. fclose(file);
  68. }
  69. return (serial_number[0] ? serial_number : NULL);
  70. }