blob: 52e308fabc9bad5f724a32816831e5b7cfe9d1ee [file] [log] [blame]
Steve Muckle18b981e2019-04-15 17:43:02 -07001/*
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 <sys/stat.h>
18#include <sys/syscall.h>
19
20#include <android-base/logging.h>
21#include <android-base/unique_fd.h>
22
23#include <modprobe/modprobe.h>
24
Steve Muckle13700a62019-07-31 09:59:48 -070025bool Modprobe::Insmod(const std::string& path_name, const std::string& parameters) {
Steve Muckle18b981e2019-04-15 17:43:02 -070026 android::base::unique_fd fd(
27 TEMP_FAILURE_RETRY(open(path_name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
28 if (fd == -1) {
29 LOG(ERROR) << "Could not open module '" << path_name << "'";
30 return false;
31 }
32
33 std::string options = "";
34 auto options_iter = module_options_.find(MakeCanonical(path_name));
35 if (options_iter != module_options_.end()) {
36 options = options_iter->second;
37 }
Steve Muckle13700a62019-07-31 09:59:48 -070038 if (!parameters.empty()) {
39 options = options + " " + parameters;
40 }
Steve Muckle18b981e2019-04-15 17:43:02 -070041
42 LOG(INFO) << "Loading module " << path_name << " with args \"" << options << "\"";
43 int ret = syscall(__NR_finit_module, fd.get(), options.c_str(), 0);
44 if (ret != 0) {
45 if (errno == EEXIST) {
46 // Module already loaded
47 return true;
48 }
49 LOG(ERROR) << "Failed to insmod '" << path_name << "' with args '" << options << "'";
50 return false;
51 }
52
53 LOG(INFO) << "Loaded kernel module " << path_name;
54 return true;
55}
56
Steve Mucklebb58b012019-07-30 11:58:11 -070057bool Modprobe::Rmmod(const std::string& module_name) {
58 int ret = syscall(__NR_delete_module, MakeCanonical(module_name).c_str(), O_NONBLOCK);
59 if (ret != 0) {
60 PLOG(ERROR) << "Failed to remove module '" << module_name << "'";
61 return false;
62 }
63 return true;
64}
65
Steve Muckle18b981e2019-04-15 17:43:02 -070066bool Modprobe::ModuleExists(const std::string& module_name) {
67 struct stat fileStat;
68 auto deps = GetDependencies(module_name);
69 if (deps.empty()) {
70 // missing deps can happen in the case of an alias
71 return false;
72 }
73 if (stat(deps.front().c_str(), &fileStat)) {
74 return false;
75 }
76 if (!S_ISREG(fileStat.st_mode)) {
77 return false;
78 }
79 return true;
80}