1 /*
2 * Copyright (C) 2018 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 <modprobe/modprobe.h>
18
19 #include <fnmatch.h>
20 #include <sys/stat.h>
21 #include <sys/syscall.h>
22
23 #include <algorithm>
24 #include <map>
25 #include <set>
26 #include <string>
27 #include <thread>
28 #include <vector>
29
30 #include <android-base/chrono_utils.h>
31 #include <android-base/file.h>
32 #include <android-base/logging.h>
33 #include <android-base/strings.h>
34 #include <android-base/unique_fd.h>
35
MakeCanonical(const std::string & module_path)36 std::string Modprobe::MakeCanonical(const std::string& module_path) {
37 auto start = module_path.find_last_of('/');
38 if (start == std::string::npos) {
39 start = 0;
40 } else {
41 start += 1;
42 }
43 auto end = module_path.size();
44 if (android::base::EndsWith(module_path, ".ko")) {
45 end -= 3;
46 }
47 if ((end - start) <= 1) {
48 LOG(ERROR) << "malformed module name: " << module_path;
49 return "";
50 }
51 std::string module_name = module_path.substr(start, end - start);
52 // module names can have '-', but their file names will have '_'
53 std::replace(module_name.begin(), module_name.end(), '-', '_');
54 return module_name;
55 }
56
ParseDepCallback(const std::string & base_path,const std::vector<std::string> & args)57 bool Modprobe::ParseDepCallback(const std::string& base_path,
58 const std::vector<std::string>& args) {
59 std::vector<std::string> deps;
60 std::string prefix = "";
61
62 // Set first item as our modules path
63 std::string::size_type pos = args[0].find(':');
64 if (args[0][0] != '/') {
65 prefix = base_path + "/";
66 }
67 if (pos != std::string::npos) {
68 deps.emplace_back(prefix + args[0].substr(0, pos));
69 } else {
70 LOG(ERROR) << "dependency lines must start with name followed by ':'";
71 return false;
72 }
73
74 // Remaining items are dependencies of our module
75 for (auto arg = args.begin() + 1; arg != args.end(); ++arg) {
76 if ((*arg)[0] != '/') {
77 prefix = base_path + "/";
78 } else {
79 prefix = "";
80 }
81 deps.push_back(prefix + *arg);
82 }
83
84 std::string canonical_name = MakeCanonical(args[0].substr(0, pos));
85 if (canonical_name.empty()) {
86 return false;
87 }
88 this->module_deps_[canonical_name] = deps;
89
90 return true;
91 }
92
ParseAliasCallback(const std::vector<std::string> & args)93 bool Modprobe::ParseAliasCallback(const std::vector<std::string>& args) {
94 auto it = args.begin();
95 const std::string& type = *it++;
96
97 if (type != "alias") {
98 LOG(ERROR) << "non-alias line encountered in modules.alias, found " << type;
99 return false;
100 }
101
102 if (args.size() != 3) {
103 LOG(ERROR) << "alias lines in modules.alias must have 3 entries, not " << args.size();
104 return false;
105 }
106
107 const std::string& alias = *it++;
108 const std::string& module_name = *it++;
109 this->module_aliases_.emplace_back(alias, module_name);
110
111 return true;
112 }
113
ParseSoftdepCallback(const std::vector<std::string> & args)114 bool Modprobe::ParseSoftdepCallback(const std::vector<std::string>& args) {
115 auto it = args.begin();
116 const std::string& type = *it++;
117 std::string state = "";
118
119 if (type != "softdep") {
120 LOG(ERROR) << "non-softdep line encountered in modules.softdep, found " << type;
121 return false;
122 }
123
124 if (args.size() < 4) {
125 LOG(ERROR) << "softdep lines in modules.softdep must have at least 4 entries";
126 return false;
127 }
128
129 const std::string& module = *it++;
130 while (it != args.end()) {
131 const std::string& token = *it++;
132 if (token == "pre:" || token == "post:") {
133 state = token;
134 continue;
135 }
136 if (state == "") {
137 LOG(ERROR) << "malformed modules.softdep at token " << token;
138 return false;
139 }
140 if (state == "pre:") {
141 this->module_pre_softdep_.emplace_back(module, token);
142 } else {
143 this->module_post_softdep_.emplace_back(module, token);
144 }
145 }
146
147 return true;
148 }
149
ParseLoadCallback(const std::vector<std::string> & args)150 bool Modprobe::ParseLoadCallback(const std::vector<std::string>& args) {
151 auto it = args.begin();
152 const std::string& module = *it++;
153
154 const std::string& canonical_name = MakeCanonical(module);
155 if (canonical_name.empty()) {
156 return false;
157 }
158 this->module_load_.emplace_back(canonical_name);
159
160 return true;
161 }
162
ParseOptionsCallback(const std::vector<std::string> & args)163 bool Modprobe::ParseOptionsCallback(const std::vector<std::string>& args) {
164 auto it = args.begin();
165 const std::string& type = *it++;
166
167 if (type != "options") {
168 LOG(ERROR) << "non-options line encountered in modules.options";
169 return false;
170 }
171
172 if (args.size() < 2) {
173 LOG(ERROR) << "lines in modules.options must have at least 2 entries, not " << args.size();
174 return false;
175 }
176
177 const std::string& module = *it++;
178 std::string options = "";
179
180 const std::string& canonical_name = MakeCanonical(module);
181 if (canonical_name.empty()) {
182 return false;
183 }
184
185 while (it != args.end()) {
186 options += *it++;
187 if (it != args.end()) {
188 options += " ";
189 }
190 }
191
192 auto [unused, inserted] = this->module_options_.emplace(canonical_name, options);
193 if (!inserted) {
194 LOG(ERROR) << "multiple options lines present for module " << module;
195 return false;
196 }
197 return true;
198 }
199
ParseBlocklistCallback(const std::vector<std::string> & args)200 bool Modprobe::ParseBlocklistCallback(const std::vector<std::string>& args) {
201 auto it = args.begin();
202 const std::string& type = *it++;
203
204 if (type != "blocklist") {
205 LOG(ERROR) << "non-blocklist line encountered in modules.blocklist";
206 return false;
207 }
208
209 if (args.size() != 2) {
210 LOG(ERROR) << "lines in modules.blocklist must have exactly 2 entries, not " << args.size();
211 return false;
212 }
213
214 const std::string& module = *it++;
215
216 const std::string& canonical_name = MakeCanonical(module);
217 if (canonical_name.empty()) {
218 return false;
219 }
220 this->module_blocklist_.emplace(canonical_name);
221
222 return true;
223 }
224
ParseCfg(const std::string & cfg,std::function<bool (const std::vector<std::string> &)> f)225 void Modprobe::ParseCfg(const std::string& cfg,
226 std::function<bool(const std::vector<std::string>&)> f) {
227 std::string cfg_contents;
228 if (!android::base::ReadFileToString(cfg, &cfg_contents, false)) {
229 return;
230 }
231
232 std::vector<std::string> lines = android::base::Split(cfg_contents, "\n");
233 for (const auto& line : lines) {
234 if (line.empty() || line[0] == '#') {
235 continue;
236 }
237 const std::vector<std::string> args = android::base::Split(line, " ");
238 if (args.empty()) continue;
239 f(args);
240 }
241 return;
242 }
243
AddOption(const std::string & module_name,const std::string & option_name,const std::string & value)244 void Modprobe::AddOption(const std::string& module_name, const std::string& option_name,
245 const std::string& value) {
246 auto canonical_name = MakeCanonical(module_name);
247 auto options_iter = module_options_.find(canonical_name);
248 auto option_str = option_name + "=" + value;
249 if (options_iter != module_options_.end()) {
250 options_iter->second = options_iter->second + " " + option_str;
251 } else {
252 module_options_.emplace(canonical_name, option_str);
253 }
254 }
255
ParseKernelCmdlineOptions(void)256 void Modprobe::ParseKernelCmdlineOptions(void) {
257 std::string cmdline = GetKernelCmdline();
258 std::string module_name = "";
259 std::string option_name = "";
260 std::string value = "";
261 bool in_module = true;
262 bool in_option = false;
263 bool in_value = false;
264 bool in_quotes = false;
265 int start = 0;
266
267 for (int i = 0; i < cmdline.size(); i++) {
268 if (cmdline[i] == '"') {
269 in_quotes = !in_quotes;
270 }
271
272 if (in_quotes) continue;
273
274 if (cmdline[i] == ' ') {
275 if (in_value) {
276 value = cmdline.substr(start, i - start);
277 if (!module_name.empty() && !option_name.empty()) {
278 AddOption(module_name, option_name, value);
279 }
280 }
281 module_name = "";
282 option_name = "";
283 value = "";
284 in_value = false;
285 start = i + 1;
286 in_module = true;
287 continue;
288 }
289
290 if (cmdline[i] == '.') {
291 if (in_module) {
292 module_name = cmdline.substr(start, i - start);
293 start = i + 1;
294 in_module = false;
295 }
296 in_option = true;
297 continue;
298 }
299
300 if (cmdline[i] == '=') {
301 if (in_option) {
302 option_name = cmdline.substr(start, i - start);
303 start = i + 1;
304 in_option = false;
305 }
306 in_value = true;
307 continue;
308 }
309 }
310 if (in_value && !in_quotes) {
311 value = cmdline.substr(start, cmdline.size() - start);
312 if (!module_name.empty() && !option_name.empty()) {
313 AddOption(module_name, option_name, value);
314 }
315 }
316 }
317
Modprobe(const std::vector<std::string> & base_paths,const std::string load_file,bool use_blocklist)318 Modprobe::Modprobe(const std::vector<std::string>& base_paths, const std::string load_file,
319 bool use_blocklist)
320 : blocklist_enabled(use_blocklist) {
321 using namespace std::placeholders;
322
323 for (const auto& base_path : base_paths) {
324 auto alias_callback = std::bind(&Modprobe::ParseAliasCallback, this, _1);
325 ParseCfg(base_path + "/modules.alias", alias_callback);
326
327 auto dep_callback = std::bind(&Modprobe::ParseDepCallback, this, base_path, _1);
328 ParseCfg(base_path + "/modules.dep", dep_callback);
329
330 auto softdep_callback = std::bind(&Modprobe::ParseSoftdepCallback, this, _1);
331 ParseCfg(base_path + "/modules.softdep", softdep_callback);
332
333 auto load_callback = std::bind(&Modprobe::ParseLoadCallback, this, _1);
334 ParseCfg(base_path + "/" + load_file, load_callback);
335
336 auto options_callback = std::bind(&Modprobe::ParseOptionsCallback, this, _1);
337 ParseCfg(base_path + "/modules.options", options_callback);
338
339 auto blocklist_callback = std::bind(&Modprobe::ParseBlocklistCallback, this, _1);
340 ParseCfg(base_path + "/modules.blocklist", blocklist_callback);
341 }
342
343 ParseKernelCmdlineOptions();
344 }
345
GetDependencies(const std::string & module)346 std::vector<std::string> Modprobe::GetDependencies(const std::string& module) {
347 auto it = module_deps_.find(module);
348 if (it == module_deps_.end()) {
349 return {};
350 }
351 return it->second;
352 }
353
InsmodWithDeps(const std::string & module_name,const std::string & parameters)354 bool Modprobe::InsmodWithDeps(const std::string& module_name, const std::string& parameters) {
355 if (module_name.empty()) {
356 LOG(ERROR) << "Need valid module name, given: " << module_name;
357 return false;
358 }
359
360 auto dependencies = GetDependencies(module_name);
361 if (dependencies.empty()) {
362 LOG(ERROR) << "Module " << module_name << " not in dependency file";
363 return false;
364 }
365
366 // load module dependencies in reverse order
367 for (auto dep = dependencies.rbegin(); dep != dependencies.rend() - 1; ++dep) {
368 LOG(VERBOSE) << "Loading hard dep for '" << module_name << "': " << *dep;
369 if (!LoadWithAliases(*dep, true)) {
370 return false;
371 }
372 }
373
374 // try to load soft pre-dependencies
375 for (const auto& [module, softdep] : module_pre_softdep_) {
376 if (module_name == module) {
377 LOG(VERBOSE) << "Loading soft pre-dep for '" << module << "': " << softdep;
378 LoadWithAliases(softdep, false);
379 }
380 }
381
382 // load target module itself with args
383 if (!Insmod(dependencies[0], parameters)) {
384 return false;
385 }
386
387 // try to load soft post-dependencies
388 for (const auto& [module, softdep] : module_post_softdep_) {
389 if (module_name == module) {
390 LOG(VERBOSE) << "Loading soft post-dep for '" << module << "': " << softdep;
391 LoadWithAliases(softdep, false);
392 }
393 }
394
395 return true;
396 }
397
LoadWithAliases(const std::string & module_name,bool strict,const std::string & parameters)398 bool Modprobe::LoadWithAliases(const std::string& module_name, bool strict,
399 const std::string& parameters) {
400 auto canonical_name = MakeCanonical(module_name);
401 if (module_loaded_.count(canonical_name)) {
402 return true;
403 }
404
405 std::set<std::string> modules_to_load = {canonical_name};
406 bool module_loaded = false;
407
408 // use aliases to expand list of modules to load (multiple modules
409 // may alias themselves to the requested name)
410 for (const auto& [alias, aliased_module] : module_aliases_) {
411 if (fnmatch(alias.c_str(), module_name.c_str(), 0) != 0) continue;
412 LOG(VERBOSE) << "Found alias for '" << module_name << "': '" << aliased_module;
413 if (module_loaded_.count(MakeCanonical(aliased_module))) continue;
414 modules_to_load.emplace(aliased_module);
415 }
416
417 // attempt to load all modules aliased to this name
418 for (const auto& module : modules_to_load) {
419 if (!ModuleExists(module)) continue;
420 if (InsmodWithDeps(module, parameters)) module_loaded = true;
421 }
422
423 if (strict && !module_loaded) {
424 LOG(ERROR) << "LoadWithAliases was unable to load " << module_name
425 << ", tried: " << android::base::Join(modules_to_load, ", ");
426 return false;
427 }
428 return true;
429 }
430
IsBlocklisted(const std::string & module_name)431 bool Modprobe::IsBlocklisted(const std::string& module_name) {
432 if (!blocklist_enabled) return false;
433
434 auto canonical_name = MakeCanonical(module_name);
435 auto dependencies = GetDependencies(canonical_name);
436 for (auto dep = dependencies.begin(); dep != dependencies.end(); ++dep) {
437 if (module_blocklist_.count(MakeCanonical(*dep))) return true;
438 }
439
440 return module_blocklist_.count(canonical_name) > 0;
441 }
442
443 // Another option to load kernel modules. load independent modules dependencies
444 // in parallel and then update dependency list of other remaining modules,
445 // repeat these steps until all modules are loaded.
446 // Discard all blocklist.
447 // Softdeps are taken care in InsmodWithDeps().
LoadModulesParallel(int num_threads)448 bool Modprobe::LoadModulesParallel(int num_threads) {
449 bool ret = true;
450 std::unordered_map<std::string, std::vector<std::string>> mod_with_deps;
451
452 // Get dependencies
453 for (const auto& module : module_load_) {
454 // Skip blocklist modules
455 if (IsBlocklisted(module)) {
456 LOG(VERBOSE) << "LMP: Blocklist: Module " << module << " skipping...";
457 continue;
458 }
459 auto dependencies = GetDependencies(MakeCanonical(module));
460 if (dependencies.empty()) {
461 LOG(ERROR) << "LMP: Hard-dep: Module " << module
462 << " not in .dep file";
463 return false;
464 }
465 mod_with_deps[MakeCanonical(module)] = dependencies;
466 }
467
468 while (!mod_with_deps.empty()) {
469 std::vector<std::thread> threads;
470 std::vector<std::string> mods_path_to_load;
471 std::mutex vector_lock;
472
473 // Find independent modules
474 for (const auto& [it_mod, it_dep] : mod_with_deps) {
475 auto itd_last = it_dep.rbegin();
476 if (itd_last == it_dep.rend())
477 continue;
478
479 auto cnd_last = MakeCanonical(*itd_last);
480 // Hard-dependencies cannot be blocklisted
481 if (IsBlocklisted(cnd_last)) {
482 LOG(ERROR) << "LMP: Blocklist: Module-dep " << cnd_last
483 << " : failed to load module " << it_mod;
484 return false;
485 }
486
487 std::string str = "load_sequential=1";
488 auto it = module_options_[cnd_last].find(str);
489 if (it != std::string::npos) {
490 module_options_[cnd_last].erase(it, it + str.size());
491
492 if (!LoadWithAliases(cnd_last, true)) {
493 return false;
494 }
495 } else {
496 if (std::find(mods_path_to_load.begin(), mods_path_to_load.end(),
497 cnd_last) == mods_path_to_load.end()) {
498 mods_path_to_load.emplace_back(cnd_last);
499 }
500 }
501 }
502
503 // Load independent modules in parallel
504 auto thread_function = [&] {
505 std::unique_lock lk(vector_lock);
506 while (!mods_path_to_load.empty()) {
507 auto ret_load = true;
508 auto mod_to_load = std::move(mods_path_to_load.back());
509 mods_path_to_load.pop_back();
510
511 lk.unlock();
512 ret_load &= LoadWithAliases(mod_to_load, true);
513 lk.lock();
514 if (!ret_load) {
515 ret &= ret_load;
516 }
517 }
518 };
519
520 std::generate_n(std::back_inserter(threads), num_threads,
521 [&] { return std::thread(thread_function); });
522
523 // Wait for the threads.
524 for (auto& thread : threads) {
525 thread.join();
526 }
527
528 if (!ret) return ret;
529
530 std::lock_guard guard(module_loaded_lock_);
531 // Remove loaded module form mod_with_deps and soft dependencies of other modules
532 for (const auto& module_loaded : module_loaded_)
533 mod_with_deps.erase(module_loaded);
534
535 // Remove loaded module form dependencies of other modules which are not loaded yet
536 for (const auto& module_loaded_path : module_loaded_paths_) {
537 for (auto& [mod, deps] : mod_with_deps) {
538 auto it = std::find(deps.begin(), deps.end(), module_loaded_path);
539 if (it != deps.end()) {
540 deps.erase(it);
541 }
542 }
543 }
544 }
545
546 return ret;
547 }
548
LoadListedModules(bool strict)549 bool Modprobe::LoadListedModules(bool strict) {
550 auto ret = true;
551 for (const auto& module : module_load_) {
552 if (!LoadWithAliases(module, true)) {
553 if (IsBlocklisted(module)) continue;
554 ret = false;
555 if (strict) break;
556 }
557 }
558 return ret;
559 }
560
Remove(const std::string & module_name)561 bool Modprobe::Remove(const std::string& module_name) {
562 auto dependencies = GetDependencies(MakeCanonical(module_name));
563 for (auto dep = dependencies.begin(); dep != dependencies.end(); ++dep) {
564 Rmmod(*dep);
565 }
566 Rmmod(module_name);
567 return true;
568 }
569
ListModules(const std::string & pattern)570 std::vector<std::string> Modprobe::ListModules(const std::string& pattern) {
571 std::vector<std::string> rv;
572 for (const auto& [module, deps] : module_deps_) {
573 // Attempt to match both the canonical module name and the module filename.
574 if (!fnmatch(pattern.c_str(), module.c_str(), 0)) {
575 rv.emplace_back(module);
576 } else if (!fnmatch(pattern.c_str(), android::base::Basename(deps[0]).c_str(), 0)) {
577 rv.emplace_back(deps[0]);
578 }
579 }
580 return rv;
581 }
582
GetAllDependencies(const std::string & module,std::vector<std::string> * pre_dependencies,std::vector<std::string> * dependencies,std::vector<std::string> * post_dependencies)583 bool Modprobe::GetAllDependencies(const std::string& module,
584 std::vector<std::string>* pre_dependencies,
585 std::vector<std::string>* dependencies,
586 std::vector<std::string>* post_dependencies) {
587 std::string canonical_name = MakeCanonical(module);
588 if (pre_dependencies) {
589 pre_dependencies->clear();
590 for (const auto& [it_module, it_softdep] : module_pre_softdep_) {
591 if (canonical_name == it_module) {
592 pre_dependencies->emplace_back(it_softdep);
593 }
594 }
595 }
596 if (dependencies) {
597 dependencies->clear();
598 auto hard_deps = GetDependencies(canonical_name);
599 if (hard_deps.empty()) {
600 return false;
601 }
602 for (auto dep = hard_deps.rbegin(); dep != hard_deps.rend(); dep++) {
603 dependencies->emplace_back(*dep);
604 }
605 }
606 if (post_dependencies) {
607 for (const auto& [it_module, it_softdep] : module_post_softdep_) {
608 if (canonical_name == it_module) {
609 post_dependencies->emplace_back(it_softdep);
610 }
611 }
612 }
613 return true;
614 }
615