涉及相关文件:
\system\core\init\init.cpp
\system\core\init\action.cpp
\system\core\init\action.h
\system\core\init\import_parser.cpp
\system\core\init\import_parser.h
\system\core\init\init_parser.cpp
\system\core\init\init_parser.h
\system\core\init\parser.cpp
\system\core\init\parser.h
\system\core\init\service.cpp
\system\core\init\service.h
\system\core\init\builtins.h
\system\core\init\keyword_map.h
\system\core\rootdir\init.rc
1、init.cpp中main函数分析:
int main(int argc, char** argv) {
........省略无关项,
比如kernel_log设置、文件夹创建、selinux初始化文件夹权限、
property初始化已经property服务的启动
const BuiltinFunctionMap function_map;
Action::set_function_map(&function_map);
从这里开始通过ActionParser、ServiceParser、ImportParser一步步解析并且执行init.tc中的内容
Parser& parser = Parser::GetInstance();
}
将service、on、import一次性加入到section_parsers_列表中:
parser.AddSectionParser("service",std::make_unique<ServiceParser>());
parser.AddSectionParser("on", std::make_unique<ActionParser>());
parser.AddSectionParser("import", std::make_unique<ImportParser>());
parser.ParseConfig("/init.rc");
ActionManager& am = ActionManager::GetInstance();
am.QueueEventTrigger("early-init");
// Queue an action that waits for coldboot done so we know ueventd has set up all of /d ev...
am.QueueBuiltinAction(wait_for_coldboot_done_action, "wait_for_coldboot_done");
// ... so that we can start queuing up actions that require stuff from /dev.
am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
am.QueueBuiltinAction(keychord_init_action, "keychord_init");
am.QueueBuiltinAction(console_init_action, "console_init");
// Trigger all the boot actions to get us started.
am.QueueEventTrigger("init");
// Repeat mix_hwrng_into_linux_rng in case /dev/hw_random or /dev/random
// wasn't ready immediately after wait_for_coldboot_done
am.QueueBuiltinAction(mix_hwrng_into_linux_rng_action, "mix_hwrng_into_linux_rng");
........
}
init_parser.h部分代码片段
class SectionParser {
public:
virtual ~SectionParser() {
}
virtual bool ParseSection(const std::vector<std::string>& args,
std::string* err) = 0;
virtual bool ParseLineSection(const std::vector<std::string>& args,
const std::string& filename, int line,
std::string* err) const = 0;
virtual void EndSection() = 0;
virtual void EndFile(const std::string& filename) = 0;
};
class Parser {
public:
static Parser& GetInstance();
void DumpState() const;
bool ParseConfig(const std::string& path);
void AddSectionParser(const std::string& name,
std::unique_ptr<SectionParser> parser);
private:
Parser();
void ParseData(const std::string& filename, const std::string& data);
bool ParseConfigFile(const std::string& path);
bool ParseConfigDir(const std::string& path);
std::map<std::string, std::unique_ptr<SectionParser>> section_parsers_;
};
action.h片段
class ActionParser : public SectionParser {
public:
ActionParser() : action_(nullptr) {
}
bool ParseSection(const std::vector<std::string>& args,
std::string* err) override;
bool ParseLineSection(const std::vector<std::string>& args,
const std::string& filename, int line,
std::string* err) const override;
void EndSection() override;
void EndFile(const std::string&) override {
}
private:
std::unique_ptr<Action> action_;
};
import_parse.h片段
class ImportParser : public SectionParser {
public:
ImportParser() {
}
bool ParseSection(const std::vector<std::string>& args,
std::string* err) override;
bool ParseLineSection(const std::vector<std::string>& args,
const std::string& filename, int line,
std::string* err) const override {
return true;
}
void EndSection() override {
}
void EndFile(const std::string& filename) override;
private:
std::vector<std::string> imports_;
};
service.h片段
class ServiceParser : public SectionParser {
public:
ServiceParser() : service_(nullptr) {
}
bool ParseSection(const std::vector<std::string>& args,
std::string* err) override;
bool ParseLineSection(const std::vector<std::string>& args,
const std::string& filename, int line,
std::string* err) const override;
void EndSection() override;
void EndFile(const std::string&) override {
}
private:
bool IsValidName(const std::string& name) const;
std::unique_ptr<Service> service_;
};
system\core\init\init_parser.cpp中:
void Parser::AddSectionParser(const std::string& name,
std::unique_ptr<SectionParser> parser) {
section_parsers_[name] = std::move(parser);
}
bool Parser::ParseConfig(const std::string& path) {
if (is_dir(path.c_str())) {
return ParseConfigDir(path);
}
return ParseConfigFile(path);
}
bool Parser::ParseConfigFile(const std::string& path) {
INFO("Parsing file %s...\n", path.c_str());
Timer t;
std::string data;
if (!read_file(path.c_str(), &data)) {
return false;
}
data.push_back('\n'); // TODO: fix parse_config.
ParseData(path, data); //这里进行实际的init.rc文件解析操作
for (const auto& sp : section_parsers_) {
sp.second->EndFile(path);
}
// Turning this on and letting the INFO logging be discarded adds 0.2s to
// Nexus 9 boot time, so it's disabled by default.
if (false) DumpState();
NOTICE("(Parsing %s took %.2fs.)\n", path.c_str(), t.duration());
return true;
}
void Parser::ParseData(const std::string& filename, const std::string& data) {
//TODO: Use a parser with const input and remove this copy
std::vector<char> data_copy(data.begin(), data.end());
data_copy.push_back('\0');
parse_state state;
state.filename = filename.c_str();
state.line = 0;
state.ptr = &data_copy[0];
state.nexttoken = 0;
SectionParser* section_parser = nullptr;
std::vector<std::string> args;
for (;;) {
switch (next_token(&state)) {
case T_EOF:
if (section_parser) {
section_parser->EndSection();
}
return;
case T_NEWLINE:
state.line++;
if (args.empty()) {
break;
}
if (section_parsers_.count(args[0])) {
if (section_parser) {
section_parser->EndSection();
}
section_parser = section_parsers_[args[0]].get();
std::string ret_err;
if (!section_parser->ParseSection(args, &ret_err)) {
parse_error(&state, "%s\n", ret_err.c_str());
section_parser = nullptr;
}
} else if (section_parser) {
std::string ret_err;
if (!section_parser->ParseLineSection(args, state.filename,
state.line, &ret_err)) {
parse_error(&state, "%s\n", ret_err.c_str());
}
}
args.clear();
break;
case T_TEXT:
args.emplace_back(state.text);
break;
}
}
}
void ActionManager::AddAction(std::unique_ptr<Action> action) {
auto old_action_it =
std::find_if(actions_.begin(), actions_.end(),
[&action] (std::unique_ptr<Action>& a) {
return action->TriggersEqual(*a);
});
if (old_action_it != actions_.end()) {
(*old_action_it)->CombineAction(*action);
} else {
actions_.emplace_back(std::move(action));
}
}
首先看action.cpp
void ActionParser::EndSection() {
if (action_ && action_->NumCommands() > 0) {
ActionManager::GetInstance().AddAction(std::move(action_));
}
}
void ActionManager::AddAction(std::unique_ptr<Action> action) {
auto old_action_it =
std::find_if(actions_.begin(), actions_.end(),
[&action] (std::unique_ptr<Action>& a) {
return action->TriggersEqual(*a);
});
if (old_action_it != actions_.end()) {
(*old_action_it)->CombineAction(*action);
} else {//将该命令添加到actions_列表中等待执行
actions_.emplace_back(std::move(action));
}
}
bool ActionParser::ParseLineSection(const std::vector<std::string>& args,
const std::string& filename, int line,
std::string* err) const {
return action_ ? action_->AddCommand(args, filename, line, err) : false;
}
bool ActionParser::ParseSection(const std::vector<std::string>& args,
std::string* err) {
std::vector<std::string> triggers(args.begin() + 1, args.end());
if (triggers.size() < 1) {
*err = "actions must have a trigger";
return false;
}
auto action = std::make_unique<Action>(false);
if (!action->InitTriggers</span>(triggers, err)) {
return false;
}
action_ = std::move(action);
return true;
}
bool Action::ParsePropertyTrigger(const std::string& trigger, std::string* err) {
const static std::string prop_str("property:");
std::string prop_name(trigger.substr(prop_str.length()));
size_t equal_pos = prop_name.find('=');
if (equal_pos == std::string::npos) {
*err = "property trigger found without matching '='";
return false;
}
std::string prop_value(prop_name.substr(equal_pos + 1));
prop_name.erase(equal_pos);
//将该property触发操作添加到liebia
auto res = property_triggers_.emplace(prop_name,prop_value);
if (res.second == false) {
*err = "multiple property triggers found for same property";
return false;
}
return true;
}
由以上三个函数可知,主要操作均是将从init.rc中解析的字符转换成action添加到_action列表中,中间附带执行了property的执行函数操作
init.cpp中main函数下循环如下:
while (true) {
if (!waiting_for_exec) {//该值初始化为false,该处if必进
am.ExecuteOneCommand(); 执行_action中的action
restart_processes(); 执行_service中的service
}
int timeout = -1;
if (process_needs_restart) {
timeout = (process_needs_restart - gettime()) * 1000;
if (timeout < 0)
timeout = 0;
}
if (am.HasMoreCommands()) {
timeout = 0;
}
bootchart_sample(&timeout);
epoll_event ev;
int nr = TEMP_FAILURE_RETRY(epoll_wait(epoll_fd, &ev, 1, timeout));
if (nr == -1) {
ERROR("epoll_wait failed: %s\n", strerror(errno));
} else if (nr == 1) {
((void (*)()) ev.data.ptr)();
}
}
void ActionManager::ExecuteOneCommand() {
// Loop through the trigger queue until we have an action to execute
while (current_executing_actions_.empty() && !trigger_queue_.empty()) {
for (const auto& action : actions_) {
if (trigger_queue_.front()->CheckTriggers(*action)) {
current_executing_actions_.emplace(action.get());
}
}
trigger_queue_.pop();
}
if (current_executing_actions_.empty()) {
return;
}
auto action = current_executing_actions_.front();
if (current_command_ == 0) {
std::string trigger_name = action->BuildTriggersString();
INFO("processing action (%s)\n", trigger_name.c_str());
}
action->ExecuteOneCommand(current_command_); //执行单个action命令
// If this was the last command in the current action, then remove
// the action from the executing list.
// If this action was oneshot, then also remove it from actions_.
++current_command_;
if (current_command_ == action->NumCommands()) {
current_executing_actions_.pop();
current_command_ = 0;
if (action->oneshot()) {
auto eraser = [&action] (std::unique_ptr<Action>& a) {
return a.get() == action;
};
actions_.erase(std::remove_if(actions_.begin(), actions_.end(), eraser));
}
}
}
void Action::ExecuteOneCommand(std::size_t command) const {
ExecuteCommand(commands_[command]);
}
void Action::ExecuteCommand(const Command& command) const {
Timer t;
int result = command.InvokeFunc(); 执行command中的命令操作
//执行完成后输出日志信息
if (klog_get_level() >= KLOG_INFO_LEVEL) {
std::string trigger_name = BuildTriggersString();
std::string cmd_str = command.BuildCommandString();
std::string source = command.BuildSourceString();
INFO("Command '%s' action=%s%s returned %d took %.2fs\n",
cmd_str.c_str(), trigger_name.c_str(), source.c_str(),
result, t.duration());
}
}
int Command::InvokeFunc() const {
std::vector<std::string> expanded_args;
expanded_args.resize(args_.size());
expanded_args[0] = args_[0];
for (std::size_t i = 1; i < args_.size(); ++i) {
if (!expand_props(args_[i], &expanded_args[i])) {
ERROR("%s: cannot expand '%s'\n", args_[0].c_str(), args_[i].c_str());
return -EINVAL;
}
}
//执行命令
return func_(expanded_args);
}
至此action部分流程简略分析完成,接下来看service部分执行流程。
void ServiceParser::EndSection() {
if (service_) {
ServiceManager::GetInstance().AddService(std::move(service_));
}
}
bool ServiceParser::ParseSection(const std::vector<std::string>& args,
std::string* err) {
if (args.size() < 3) {
*err = "services must have a name and a program";
return false;
}
const std::string& name = args[1];
if (!IsValidName(name)) {
*err = StringPrintf("invalid service name '%s'", name.c_str());
return false;
}
std::vector<std::string> str_args(args.begin() + 2, args.end());
service_ = std::make_unique<Service>(name, "default", str_args);
return true;
}
将解析出来的服务都加入到service_列表中。
static void restart_processes()
{
process_needs_restart = 0;
ServiceManager::GetInstance().
ForEachServiceWithFlags(SVC_RESTARTING, [] (Service* s) {
s->RestartIfNeeded(process_needs_restart);
});
}
void ServiceManager::ForEachServiceWithFlags(unsigned matchflags,
void (*func)(Service* svc)) const {
for (const auto& s : services_) {
if (s->flags() & matchflags) {
func(s.get()); //执行服务
}
}
}
至此init.rc中的定义的service、action、command等都已被执行,一些重要文件目录已经创建,很多守护进程也已经启动,android系统进程启动的条件已经具备,接下来就可以启动zygote进程,去开启按android systemserver了:
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server