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
18 #include <cutils/cpu_info.h>
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <string.h>
22
23 // we cache the serial number here.
24 // this is also used as a fgets() line buffer when we are reading /proc/cpuinfo
25 static char serial_number[100] = { 0 };
26
get_cpu_serial_number(void)27 extern const char* get_cpu_serial_number(void)
28 {
29 if (serial_number[0] == 0)
30 {
31 FILE* file;
32 char* chp, *end;
33 char* whitespace;
34 int length;
35
36 // read serial number from /proc/cpuinfo
37 file = fopen("proc/cpuinfo", "r");
38 if (! file)
39 return NULL;
40
41 while ((chp = fgets(serial_number, sizeof(serial_number), file)) != NULL)
42 {
43 // look for something like "Serial : 999206122a03591c"
44
45 if (strncmp(chp, "Serial", 6) != 0)
46 continue;
47
48 chp = strchr(chp, ':');
49 if (!chp)
50 continue;
51
52 // skip colon and whitespace
53 while ( *(++chp) == ' ') {}
54
55 // truncate trailing whitespace
56 end = chp;
57 while (*end && *end != ' ' && *end != '\t' && *end != '\n' && *end != '\r')
58 ++end;
59 *end = 0;
60
61 whitespace = strchr(chp, ' ');
62 if (whitespace)
63 *whitespace = 0;
64 whitespace = strchr(chp, '\t');
65 if (whitespace)
66 *whitespace = 0;
67 whitespace = strchr(chp, '\r');
68 if (whitespace)
69 *whitespace = 0;
70 whitespace = strchr(chp, '\n');
71 if (whitespace)
72 *whitespace = 0;
73
74 // shift serial number to beginning of the buffer
75 memmove(serial_number, chp, strlen(chp) + 1);
76 break;
77 }
78
79 fclose(file);
80 }
81
82 return (serial_number[0] ? serial_number : NULL);
83 }
84