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