1 /*
2 ** Copyright 2007, The Android Open Source Project
3 **
4 ** Licensed under the Apache License, Version 2.0 (the "License");
5 ** you may not use this file except in compliance with the License.
6 ** You may obtain a copy of the License at
7 **
8 ** http://www.apache.org/licenses/LICENSE-2.0
9 **
10 ** Unless required by applicable law or agreed to in writing, software
11 ** distributed under the License is distributed on an "AS IS" BASIS,
12 ** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 ** See the License for the specific language governing permissions and
14 ** limitations under the License.
15 */
16
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20
21 #include <cutils/cpu_info.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
35 // read serial number from /proc/cpuinfo
36 file = fopen("proc/cpuinfo", "r");
37 if (! file)
38 return NULL;
39
40 while ((chp = fgets(serial_number, sizeof(serial_number), file)) != NULL)
41 {
42 // look for something like "Serial : 999206122a03591c"
43
44 if (strncmp(chp, "Serial", 6) != 0)
45 continue;
46
47 chp = strchr(chp, ':');
48 if (!chp)
49 continue;
50
51 // skip colon and whitespace
52 while ( *(++chp) == ' ') {}
53
54 // truncate trailing whitespace
55 end = chp;
56 while (*end && *end != ' ' && *end != '\t' && *end != '\n' && *end != '\r')
57 ++end;
58 *end = 0;
59
60 whitespace = strchr(chp, ' ');
61 if (whitespace)
62 *whitespace = 0;
63 whitespace = strchr(chp, '\t');
64 if (whitespace)
65 *whitespace = 0;
66 whitespace = strchr(chp, '\r');
67 if (whitespace)
68 *whitespace = 0;
69 whitespace = strchr(chp, '\n');
70 if (whitespace)
71 *whitespace = 0;
72
73 // shift serial number to beginning of the buffer
74 memmove(serial_number, chp, strlen(chp) + 1);
75 break;
76 }
77
78 fclose(file);
79 }
80
81 return (serial_number[0] ? serial_number : NULL);
82 }
83