1 /*
2 * Copyright (C) 2020 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 #include "kallsyms.h"
17
18 #include <inttypes.h>
19
20 #include <string>
21
22 #include <android-base/file.h>
23 #include <android-base/logging.h>
24 #include <android-base/properties.h>
25
26 #include "environment.h"
27 #include "read_elf.h"
28 #include "utils.h"
29
30 namespace simpleperf {
31
32 #if defined(__linux__)
33
34 namespace {
35
36 const char kKallsymsPath[] = "/proc/kallsyms";
37 const char kProcModulesPath[] = "/proc/modules";
38 const char kPtrRestrictPath[] = "/proc/sys/kernel/kptr_restrict";
39 const char kLowerPtrRestrictAndroidProp[] = "security.lower_kptr_restrict";
40 const unsigned int kMinLineTestNonNullSymbols = 10;
41
42 // Tries to read the kernel symbol file and ensure that at least some symbol
43 // addresses are non-null.
CanReadKernelSymbolAddresses()44 bool CanReadKernelSymbolAddresses() {
45 LineReader reader(kKallsymsPath);
46 if (!reader.Ok()) {
47 LOG(DEBUG) << "Failed to read " << kKallsymsPath;
48 return false;
49 }
50 auto symbol_callback = [&](const KernelSymbol& symbol) { return (symbol.addr != 0u); };
51 for (unsigned int i = 0; i < kMinLineTestNonNullSymbols; i++) {
52 std::string* line = reader.ReadLine();
53 if (line == nullptr) {
54 return false;
55 }
56 if (ProcessKernelSymbols(*line, symbol_callback)) {
57 return true;
58 }
59 }
60 return false;
61 }
62
63 // Define a scope in which access to kallsyms is possible.
64 // This is based on the Perfetto implementation.
65 class ScopedKptrUnrestrict {
66 public:
67 ScopedKptrUnrestrict(); // Lowers kptr_restrict if necessary.
68 ~ScopedKptrUnrestrict(); // Restores the initial kptr_restrict.
69
70 // Indicates if access to kallsyms should be successful.
KallsymsAvailable()71 bool KallsymsAvailable() { return kallsyms_available_; }
72
ResetWarning()73 static void ResetWarning() { kernel_address_warning_printed_ = false; }
74
75 private:
76 bool WriteKptrRestrict(const std::string& value);
77 void PrintWarning();
78
79 bool restore_property_ = false;
80 bool restore_restrict_value_ = false;
81 std::string saved_restrict_value_;
82 bool kallsyms_available_ = false;
83
84 static bool kernel_address_warning_printed_;
85 };
86
87 bool ScopedKptrUnrestrict::kernel_address_warning_printed_ = false;
88
ScopedKptrUnrestrict()89 ScopedKptrUnrestrict::ScopedKptrUnrestrict() {
90 if (CanReadKernelSymbolAddresses()) {
91 // Everything seems to work (e.g., we are running as root and kptr_restrict
92 // is < 2). Don't touching anything.
93 kallsyms_available_ = true;
94 return;
95 }
96
97 if (GetAndroidVersion() >= 12 && IsRoot()) {
98 // Enable kernel addresses by setting property.
99 if (!android::base::SetProperty(kLowerPtrRestrictAndroidProp, "1")) {
100 LOG(DEBUG) << "Unable to set " << kLowerPtrRestrictAndroidProp << " to 1.";
101 PrintWarning();
102 return;
103 }
104 restore_property_ = true;
105 // Init takes some time to react to the property change.
106 // Unfortunately, we cannot read kptr_restrict because of SELinux. Instead,
107 // we detect this by reading the initial lines of kallsyms and checking
108 // that they are non-zero. This loop waits for at most 250ms (50 * 5ms).
109 for (int attempt = 1; attempt <= 50; ++attempt) {
110 usleep(5000);
111 if (CanReadKernelSymbolAddresses()) {
112 kallsyms_available_ = true;
113 return;
114 }
115 }
116 LOG(DEBUG) << "kallsyms addresses are still masked after setting "
117 << kLowerPtrRestrictAndroidProp;
118 PrintWarning();
119 return;
120 }
121
122 // Otherwise, read the kptr_restrict value and lower it if needed.
123 if (!android::base::ReadFileToString(kPtrRestrictPath, &saved_restrict_value_)) {
124 LOG(DEBUG) << "Failed to read " << kPtrRestrictPath;
125 PrintWarning();
126 return;
127 }
128
129 // Progressively lower kptr_restrict until we can read kallsyms.
130 for (int value = atoi(saved_restrict_value_.c_str()); value > 0; --value) {
131 if (!WriteKptrRestrict(std::to_string(value))) {
132 break;
133 }
134 restore_restrict_value_ = true;
135 if (CanReadKernelSymbolAddresses()) {
136 kallsyms_available_ = true;
137 return;
138 }
139 }
140 PrintWarning();
141 }
142
~ScopedKptrUnrestrict()143 ScopedKptrUnrestrict::~ScopedKptrUnrestrict() {
144 if (restore_property_) {
145 android::base::SetProperty(kLowerPtrRestrictAndroidProp, "0");
146 }
147 if (restore_restrict_value_) {
148 WriteKptrRestrict(saved_restrict_value_);
149 }
150 }
151
WriteKptrRestrict(const std::string & value)152 bool ScopedKptrUnrestrict::WriteKptrRestrict(const std::string& value) {
153 if (!android::base::WriteStringToFile(value, kPtrRestrictPath)) {
154 LOG(DEBUG) << "Failed to set " << kPtrRestrictPath << " to " << value;
155 return false;
156 }
157 return true;
158 }
159
PrintWarning()160 void ScopedKptrUnrestrict::PrintWarning() {
161 if (!kernel_address_warning_printed_) {
162 kernel_address_warning_printed_ = true;
163 LOG(WARNING) << "Access to kernel symbol addresses is restricted. If "
164 << "possible, please do `echo 0 >/proc/sys/kernel/kptr_restrict` "
165 << "to fix this.";
166 }
167 }
168
169 } // namespace
170
GetLoadedModules()171 std::vector<KernelMmap> GetLoadedModules() {
172 ScopedKptrUnrestrict kptr_unrestrict;
173 if (!kptr_unrestrict.KallsymsAvailable()) return {};
174 std::vector<KernelMmap> result;
175 LineReader reader(kProcModulesPath);
176 if (!reader.Ok()) {
177 // There is no /proc/modules on Android devices, so we don't print error if failed to open it.
178 PLOG(DEBUG) << "failed to open file /proc/modules";
179 return result;
180 }
181 std::string* line;
182 std::string name_buf;
183 while ((line = reader.ReadLine()) != nullptr) {
184 // Parse line like: nf_defrag_ipv6 34768 1 nf_conntrack_ipv6, Live 0xffffffffa0fe5000
185 name_buf.resize(line->size());
186 char* name = name_buf.data();
187 uint64_t addr;
188 uint64_t len;
189 if (sscanf(line->data(), "%s%" PRIu64 "%*u%*s%*s 0x%" PRIx64, name, &len, &addr) == 3) {
190 KernelMmap map;
191 map.name = name;
192 map.start_addr = addr;
193 map.len = len;
194 result.push_back(map);
195 }
196 }
197 bool all_zero = true;
198 for (const auto& map : result) {
199 if (map.start_addr != 0) {
200 all_zero = false;
201 }
202 }
203 if (all_zero) {
204 LOG(DEBUG) << "addresses in /proc/modules are all zero, so ignore kernel modules";
205 return std::vector<KernelMmap>();
206 }
207 return result;
208 }
209
GetKernelStartAddress()210 uint64_t GetKernelStartAddress() {
211 ScopedKptrUnrestrict kptr_unrestrict;
212 if (!kptr_unrestrict.KallsymsAvailable()) return 0;
213 LineReader reader(kKallsymsPath);
214 if (!reader.Ok()) {
215 return 0;
216 }
217 std::string* line;
218 while ((line = reader.ReadLine()) != nullptr) {
219 if (strstr(line->data(), "_stext") != nullptr) {
220 uint64_t addr;
221 if (sscanf(line->data(), "%" PRIx64, &addr) == 1) {
222 return addr;
223 }
224 }
225 }
226 return 0;
227 }
228
LoadKernelSymbols(std::string * kallsyms)229 bool LoadKernelSymbols(std::string* kallsyms) {
230 ScopedKptrUnrestrict kptr_unrestrict;
231 if (kptr_unrestrict.KallsymsAvailable()) {
232 return android::base::ReadFileToString(kKallsymsPath, kallsyms);
233 }
234 return false;
235 }
236
ResetKernelAddressWarning()237 void ResetKernelAddressWarning() {
238 ScopedKptrUnrestrict::ResetWarning();
239 }
240
241 #endif // defined(__linux__)
242
ProcessKernelSymbols(std::string & symbol_data,const std::function<bool (const KernelSymbol &)> & callback)243 bool ProcessKernelSymbols(std::string& symbol_data,
244 const std::function<bool(const KernelSymbol&)>& callback) {
245 char* p = &symbol_data[0];
246 char* data_end = p + symbol_data.size();
247 while (p < data_end) {
248 char* line_end = strchr(p, '\n');
249 if (line_end != nullptr) {
250 *line_end = '\0';
251 }
252 size_t line_size = (line_end != nullptr) ? (line_end - p) : (data_end - p);
253 // Parse line like: ffffffffa005c4e4 d __warned.41698 [libsas]
254 char name[line_size];
255 char module[line_size];
256 strcpy(module, "");
257
258 KernelSymbol symbol;
259 int ret = sscanf(p, "%" PRIx64 " %c %s%s", &symbol.addr, &symbol.type, name, module);
260 if (line_end != nullptr) {
261 *line_end = '\n';
262 p = line_end + 1;
263 } else {
264 p = data_end;
265 }
266 if (ret >= 3) {
267 if (IsArmMappingSymbol(name)) {
268 continue;
269 }
270
271 symbol.name = name;
272 size_t module_len = strlen(module);
273 if (module_len > 2 && module[0] == '[' && module[module_len - 1] == ']') {
274 module[module_len - 1] = '\0';
275 symbol.module = &module[1];
276 } else {
277 symbol.module = nullptr;
278 }
279
280 if (callback(symbol)) {
281 return true;
282 }
283 }
284 }
285 return false;
286 }
287
288 } // namespace simpleperf
289