libmodprobe_module-加载内核模块

概述

android/system/core/libmodprobe-first stage init阶段用来加载内核模块的

源码解析

1. Modprobe模块

1.1 Modprobe构造函数

// "/lib/modules","modules.load"
Modprobe::Modprobe(const std::vector<std::string>& base_paths, const std::string load_file) {
    using namespace std::placeholders;

    for (const auto& base_path : base_paths) {
        auto alias_callback = std::bind(&Modprobe::ParseAliasCallback, this, _1);
        ParseCfg(base_path + "/modules.alias", alias_callback);

        auto dep_callback = std::bind(&Modprobe::ParseDepCallback, this, base_path, _1);
        ParseCfg(base_path + "/modules.dep", dep_callback);

        auto softdep_callback = std::bind(&Modprobe::ParseSoftdepCallback, this, _1);
        ParseCfg(base_path + "/modules.softdep", softdep_callback);
// "modules.load"
        auto load_callback = std::bind(&Modprobe::ParseLoadCallback, this, _1);
        ParseCfg(base_path + "/" + load_file, load_callback);
// 没有这个文件
        auto options_callback = std::bind(&Modprobe::ParseOptionsCallback, this, _1);
        ParseCfg(base_path + "/modules.options", options_callback);
// 没有这个文件
        auto blocklist_callback = std::bind(&Modprobe::ParseBlocklistCallback, this, _1);
        ParseCfg(base_path + "/modules.blocklist", blocklist_callback);
    }

    ParseKernelCmdlineOptions();
    android::base::SetMinimumLogSeverity(android::base::INFO);
}

1.2 ParseCfg-读文件,然后将读到的文件内容传递给callback

void Modprobe::ParseCfg(const std::string& cfg,
                        std::function<bool(const std::vector<std::string>&)> f) {
    std::string cfg_contents;
    // 读文件
    if (!android::base::ReadFileToString(cfg, &cfg_contents, false)) {
        return;
    }

    std::vector<std::string> lines = android::base::Split(cfg_contents, "\n");
    for (const std::string line : lines) {
        if (line.empty() || line[0] == '#') {
            continue;
        }
        const std::vector<std::string> args = android::base::Split(line, " ");
        if (args.empty()) continue;
        // 调用callback
        f(args);
    }
    return;
}

1.3 ParseAliasCallback-解析modules.alias文件

// alias(type) ecb(arc4)(alias) arc4(module_name)
// alias crypto-ecb(arc4) arc4
bool Modprobe::ParseAliasCallback(const std::vector<std::string>& args) {
    auto it = args.begin();
    const std::string& type = *it++;

    if (type != "alias") {
        LOG(ERROR) << "non-alias line encountered in modules.alias, found " << type;
        return false;
    }

    if (args.size() != 3) {
        // 所以这句是正常的打印
        LOG(ERROR) << "alias lines in modules.alias must have 3 entries, not " << args.size();
        return false;
    }

    const std::string& alias = *it++;
    const std::string& module_name = *it++;
    this->module_aliases_.emplace_back(alias, module_name);

    return true;
}

1.4 ParseDepCallback-解析依赖

// base_path为/lib/modules
// /lib/modules/gl620a.ko:
// /lib/modules/usb_wwan.ko: /lib/modules/usbserial.ko
bool Modprobe::ParseDepCallback(const std::string& base_path,
                                const std::vector<std::string>& args) {
    std::vector<std::string> deps;
    std::string prefix = "";

    // Set first item as our modules path
    std::string::size_type pos = args[0].find(':');
    // 不会走这里
    if (args[0][0] != '/') {
        prefix = base_path + "/";
    }
    if (pos != std::string::npos) {
        // 一般走这里
        deps.emplace_back(prefix + args[0].substr(0, pos));
    } else {
        LOG(ERROR) << "dependency lines must start with name followed by ':'";
    }

    // Remaining items are dependencies of our module
    for (auto arg = args.begin() + 1; arg != args.end(); ++arg) {
        if ((*arg)[0] != '/') {
            prefix = base_path + "/";
        } else {
            prefix = "";
        }
        deps.push_back(prefix + *arg);
    }
// 提取内核模块的名字
    std::string canonical_name = MakeCanonical(args[0].substr(0, pos));
    if (canonical_name.empty()) {
        return false;
    }// unordered_map类型
    this->module_deps_[canonical_name] = deps;

    return true;
}

1.5 MakeCanonical-提取内核模块的名字

std::string Modprobe::MakeCanonical(const std::string& module_path) {
    auto start = module_path.find_last_of('/');
    if (start == std::string::npos) {
        start = 0;
    } else {
        start += 1;
    }
    auto end = module_path.size();
    if (android::base::EndsWith(module_path, ".ko")) {
        end -= 3;
    }
    if ((end - start) <= 1) {
        LOG(ERROR) << "malformed module name: " << module_path;
        return "";
    }
    std::string module_name = module_path.substr(start, end - start);
    // module names can have '-', but their file names will have '_'
    // 这里为啥要做一次替换呢?
    std::replace(module_name.begin(), module_name.end(), '-', '_');
    return module_name;
}

1.6 ParseSoftdepCallback-没有softdep文件

// # Soft dependencies extracted from modules themselves.
bool Modprobe::ParseSoftdepCallback(const std::vector<std::string>& args) {
    auto it = args.begin();
    const std::string& type = *it++;
    std::string state = "";

    if (type != "softdep") {
        // 这里直接退出了
        LOG(ERROR) << "non-softdep line encountered in modules.softdep, found " << type;
        return false;
    }

    if (args.size() < 4) {
        LOG(ERROR) << "softdep lines in modules.softdep must have at least 4 entries";
        return false;
    }

    const std::string& module = *it++;
    while (it != args.end()) {
        const std::string& token = *it++;
        if (token == "pre:" || token == "post:") {
            state = token;
            continue;
        }
        if (state == "") {
            LOG(ERROR) << "malformed modules.softdep at token " << token;
            return false;
        }
        if (state == "pre:") {
            this->module_pre_softdep_.emplace_back(module, token);
        } else {
            this->module_post_softdep_.emplace_back(module, token);
        }
    }

    return true;
}

1.7 ParseLoadCallback-解析modules.load文件-要加载的内核模块

bool Modprobe::ParseLoadCallback(const std::vector<std::string>& args) {
    auto it = args.begin();
    const std::string& module = *it++;

    const std::string& canonical_name = MakeCanonical(module);
    if (canonical_name.empty()) {
        return false;
    }
    this->module_load_.emplace_back(canonical_name);

    return true;
}

1.8 ParseKernelCmdlineOptions-解析cmdline中的内核模块的选项

std::string Modprobe::GetKernelCmdline(void) {
    std::string cmdline;
    if (!android::base::ReadFileToString("/proc/cmdline", &cmdline)) {
        return "";
    }
    return cmdline;
}
void Modprobe::ParseKernelCmdlineOptions(void) {
    // 读/proc/cmdline文件
    std::string cmdline = GetKernelCmdline();
    // 第一次初始化操作
    std::string module_name = "";
    std::string option_name = "";
    std::string value = "";
    bool in_module = true;
    bool in_option = false;
    bool in_value = false;
    bool in_quotes = false;
    int start = 0;

    for (int i = 0; i < cmdline.size(); i++) {
        // 处理引号的
        if (cmdline[i] == '"') {
            in_quotes = !in_quotes;
        }
// 第一个引号,直接跳过
        if (in_quotes) continue;
// 处理空格的,空格表示下一个
        if (cmdline[i] == ' ') {
            // 获得value的值,获得value的值
            if (in_value) {
                value = cmdline.substr(start, i - start);
                if (!module_name.empty() && !option_name.empty()) {
                    AddOption(module_name, option_name, value);
                }
            }
            // 进行初始化操作
            module_name = "";
            option_name = "";
            value = "";
            in_value = false;
            start = i + 1;
            in_module = true;
            continue;
        }
// 处理.的,.前面就是module_name,.后面就是in_option
        if (cmdline[i] == '.') {
            if (in_module) {
                module_name = cmdline.substr(start, i - start);
                start = i + 1;
                in_module = false;
            }
            in_option = true;
            continue;
        }
// =前面就是option_name,=后面就是in_value
        if (cmdline[i] == '=') {
            if (in_option) {
                option_name = cmdline.substr(start, i - start);
                start = i + 1;
                in_option = false;
            }
            in_value = true;
            continue;
        }
    }// 获得value的值,这应该是最后一个的值了
    if (in_value && !in_quotes) {
        value = cmdline.substr(start, cmdline.size() - start);
        if (!module_name.empty() && !option_name.empty()) {
            AddOption(module_name, option_name, value);
        }
    }
}
void Modprobe::AddOption(const std::string& module_name, const std::string& option_name,
                         const std::string& value) {
    auto canonical_name = MakeCanonical(module_name);
    // 没有modules.options文件,所以options_iter为module_options_.end()
    auto options_iter = module_options_.find(canonical_name);
    auto option_str = option_name + "=" + value;
    if (options_iter != module_options_.end()) {
        options_iter->second = options_iter->second + " " + option_str;
    } else {
        // 走这里,所以就是module_name.option_name=value
        module_options_.emplace(canonical_name, option_str);
    }
}

1.9 LoadListedModules-加载内核模块

bool Modprobe::LoadListedModules(bool strict) {
    auto ret = true;
    for (const auto& module : module_load_) {
        if (!LoadWithAliases(module, true)) {
            ret = false;
            if (strict) break;
        }
    }
    return ret;
}

1.10 LoadWithAliases-从alias匹配中加载内核模块

bool Modprobe::LoadWithAliases(const std::string& module_name, bool strict,
                               const std::string& parameters) {
    auto canonical_name = MakeCanonical(module_name);
    if (module_loaded_.count(canonical_name)) {
        return true;
    }

    std::set<std::string> modules_to_load = {canonical_name};
    bool module_loaded = false;

    // use aliases to expand list of modules to load (multiple modules
    // may alias themselves to the requested name)
    for (const auto& [alias, aliased_module] : module_aliases_) {
        // 看alias是否和load中的内核模块名字匹配,看起来是都不匹配的
        // alias为一个正则表达式类型的字符串
        if (fnmatch(alias.c_str(), module_name.c_str(), 0) != 0) continue;
        LOG(VERBOSE) << "Found alias for '" << module_name << "': '" << aliased_module;
        if (module_loaded_.count(MakeCanonical(aliased_module))) continue;
        modules_to_load.emplace(aliased_module);
    }
// 所以这里为初始值canonical_name,也就是模块的名字
    // attempt to load all modules aliased to this name
    for (const auto& module : modules_to_load) {
        if (!ModuleExists(module)) continue;
        if (InsmodWithDeps(module, parameters)) module_loaded = true;
    }

    if (strict && !module_loaded) {
        LOG(ERROR) << "LoadWithAliases was unable to load " << module_name;
        return false;
    }
    return true;
}

1.11 InsmodWithDeps-加载依赖模块和目标模块

bool Modprobe::InsmodWithDeps(const std::string& module_name, const std::string& parameters) {
    if (module_name.empty()) {
        LOG(ERROR) << "Need valid module name, given: " << module_name;
        return false;
    }

    auto dependencies = GetDependencies(module_name);
    if (dependencies.empty()) {
        LOG(ERROR) << "Module " << module_name << " not in dependency file";
        return false;
    }

    // load module dependencies in reverse order
    // 1. 先加载依赖项的
    for (auto dep = dependencies.rbegin(); dep != dependencies.rend() - 1; ++dep) {
        LOG(VERBOSE) << "Loading hard dep for '" << module_name << "': " << *dep;
        if (!LoadWithAliases(*dep, true)) {
            return false;
        }
    }

    // try to load soft pre-dependencies
    for (const auto& [module, softdep] : module_pre_softdep_) {
        if (module_name == module) {
            LOG(VERBOSE) << "Loading soft pre-dep for '" << module << "': " << softdep;
            LoadWithAliases(softdep, false);
        }
    }

    // load target module itself with args
    // 然后加载自己
    if (!Insmod(dependencies[0], parameters)) {
        return false;
    }

    // try to load soft post-dependencies
    for (const auto& [module, softdep] : module_post_softdep_) {
        if (module_name == module) {
            LOG(VERBOSE) << "Loading soft post-dep for '" << module << "': " << softdep;
            LoadWithAliases(softdep, false);
        }
    }

    return true;
}

2. libmodprobe_ext模块

2.1 ModuleExists-判断模块是否存在

bool Modprobe::ModuleExists(const std::string& module_name) {
    struct stat fileStat;
    if (blocklist_enabled && module_blocklist_.count(module_name)) {
        LOG(INFO) << "module " << module_name << " is blocklisted";
        return false;
    }
    // 获得dep
    auto deps = GetDependencies(module_name);
    if (deps.empty()) {
        // missing deps can happen in the case of an alias
        return false;
    }// 判断文件是否是否存在,front就是模块名字
    if (stat(deps.front().c_str(), &fileStat)) {
        LOG(INFO) << "module " << module_name << " does not exist";
        return false;
    }// 判断文件是否是个常规文件
    if (!S_ISREG(fileStat.st_mode)) {
        LOG(INFO) << "module " << module_name << " is not a regular file";
        return false;
    }
    return true;
}
std::vector<std::string> Modprobe::GetDependencies(const std::string& module) {
    auto it = module_deps_.find(module);
    if (it == module_deps_.end()) {
        return {};
    }
    return it->second;
}

2.2 Insmod-调用__NR_finit_module系统调用加载内核模块

bool Modprobe::Insmod(const std::string& path_name, const std::string& parameters) {
    android::base::unique_fd fd(
            TEMP_FAILURE_RETRY(open(path_name.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC)));
    if (fd == -1) {
        LOG(ERROR) << "Could not open module '" << path_name << "'";
        return false;
    }

    auto canonical_name = MakeCanonical(path_name);
    std::string options = "";
    auto options_iter = module_options_.find(canonical_name);
    if (options_iter != module_options_.end()) {
        options = options_iter->second;
    }
    if (!parameters.empty()) {
        options = options + " " + parameters;
    }

    LOG(INFO) << "Loading module " << path_name << " with args \"" << options << "\"";
    // 加载模块
    int ret = syscall(__NR_finit_module, fd.get(), options.c_str(), 0);
    if (ret != 0) {
        if (errno == EEXIST) {
            // Module already loaded
            module_loaded_.emplace(canonical_name);
            return true;
        }
        LOG(ERROR) << "Failed to insmod '" << path_name << "' with args '" << options << "'";
        return false;
    }

    LOG(INFO) << "Loaded kernel module " << path_name;
    module_loaded_.emplace(canonical_name);
    // 模块数加1
    module_count_++;
    return true;
}
posted @ 2021-06-15 20:12  pyjetson  阅读(1164)  评论(0编辑  收藏  举报