前語:
馬上就要過年了,在關(guān)機(jī)下班之際华坦,寫一篇文章实辑,記錄一下這兩天踩的一個坑,也不枉別人放假回家過年了我還在堅(jiān)持在一線解bug
正文:
因?yàn)橐粋€需求买雾,需要修改init.target.rc
文件,在某個屬性生效的時候觸發(fā)某些流程杨帽,這里簡化代碼流程漓穿,以一個簡單的例子說明:
on property:persist.test=test
setprop persist.test.result "ok"
正常情況下,在系統(tǒng)其他地方設(shè)置了屬性persist.test
的值為test之后就會觸發(fā)下面那個設(shè)置屬性的動作注盈,然而實(shí)際上并沒有生效晃危,測試步驟如下:
$ adb shell setprop persist.test test
$ adb shell getprop | grep test
[persist.test]:[test]
獲取到了persist.test
屬性,然而persist.test.result
屬性并沒有設(shè)置成功
為排查selinux權(quán)限問題老客,先把selinux權(quán)限關(guān)閉再去設(shè)置屬性的值僚饭,排查selinux權(quán)限的方法可以通過setenforce 0
的方式快速驗(yàn)證:
$ adb shell setenforce 0
$ adb shell getenforce
$ adb shell setprop persist.test test1 // 需要變化一次屬性值,不然同樣的值不會觸發(fā)
$ adb shell setprop persist.test test
$ adb shell getprop | grep test
[persist.test]:[test]
要確認(rèn)getenforce的值返回的Permissive才可以胧砰,這時候看到屬性還是設(shè)置不成功的鳍鸵,這里不確定是因?yàn)?code>on property:persist.test=test這個動作沒執(zhí)行,還是說setprop persist.test.result "ok"
有權(quán)限問題尉间。這里再做一個測試偿乖,把設(shè)置屬性的動作放到on boot階段:
on boot
...
setprop persist.test.result "ok"
...
結(jié)果是放到on boot也是設(shè)置不成功的,那應(yīng)該是有存在權(quán)限問題了哲嘲,需要慢慢排查贪薪。
第一步:排查代碼有沒有加載到這個文件
檢查的方法是修改這個文件的其他地方,看是否生效眠副,這次依然是修改on boot
on boot
...
# write /dev/cpuset/camera-daemon/cpus 0-3
# 這里原本是0-3画切,修改成0-2,重啟后去查看這個節(jié)點(diǎn)的值是否有寫入成功
write /dev/cpuset/camera-daemon/cpus 0-2
setprop persist.test.result "ok"
...
修改后驗(yàn)證囱怕,節(jié)點(diǎn)的值是有寫入的霍弹,屬性還是設(shè)置不成功
(PS:這個文件其實(shí)能比較肯定的是有加載到的,因?yàn)榉謪^(qū)的掛載動作就在這個文件中光涂,如果沒有加載到那不能開機(jī)了庞萍,這里只是多做一次確認(rèn))
第二步:排查selinux權(quán)限
為了方便驗(yàn)證,這次把屬性放到另外一個地方:
on property:vold.decrypt=trigger_restart_framework
...
setprop persist.test.result "ok"
...
修改后驗(yàn)證方法:
$ adb shell setprop vold.decrypt trigger_restart_framework
$ adb shell getprop persist.test.result
設(shè)置屬性后可以看到設(shè)備上層服務(wù)已經(jīng)重啟忘闻,現(xiàn)象是有開機(jī)動畫钝计,但是去查屬性后還是沒有設(shè)置成功,這時候把selinux權(quán)限關(guān)閉再去測試:
$ adb shell setenforce 0
$ adb shell getenforce
$ adb shell setprop vold.decrypt trigger_restart_framework
$ adb shell getprop persist.test.result
[persist.test.result]:[ok]
這時候就可以看到屬性已經(jīng)設(shè)置成功了。那么私恬,問題就來了债沮,為什么一開始關(guān)閉權(quán)限去設(shè)置的時候還是不成功呢?
既然setprop persist.test.result "ok"
是可以成功的本鸣,那么問題就應(yīng)該是出在on property:persist.test=test
這個動作上了疫衩,至于是什么原因,那么就需要去跟代碼分析流程了
第三步:分析on property
實(shí)現(xiàn)流程
init.rc文件是在init進(jìn)程解析的荣德,那要分析流程得從init進(jìn)程開始分析闷煤,Android P的init初始化代碼較之前的版本還是有很大的不同的,這是還是要從init.cpp的main函數(shù)開始分析:
init.cpp
int main() {
...
// 初始化init.rc解析動作的管理類
ActionManager& am = ActionManager::GetInstance();
ServiceList& sm = ServiceList::GetInstance();
LoadBootScripts(am, sm); // 加載解析init.rc
...
}
Parser CreateParser(ActionManager& action_manager, ServiceList& service_list) {
Parser parser;
// 以service開頭的行交給ServiceParser解析
parser.AddSectionParser("service", std::make_unique<ServiceParser>(&service_list, subcontexts));
// 以on開頭的行交給ActionParser解析
parser.AddSectionParser("on", std::make_unique<ActionParser>(&action_manager, subcontexts));
// 以import開頭的行交給ImportParser解析
parser.AddSectionParser("import", std::make_unique<ImportParser>(&parser));
return parser;
}
static void LoadBootScripts(ActionManager& action_manager, ServiceList& service_list) {
Parser parser = CreateParser(action_manager, service_list); // 創(chuàng)建一個Parser對象
std::string bootscript = GetProperty("ro.boot.init_rc", "");
if (bootscript.empty()) {
parser.ParseConfig("/init.rc"); // 解析根目錄的init.rc文件
if (!parser.ParseConfig("/system/etc/init")) {
late_import_paths.emplace_back("/system/etc/init");
}
if (!parser.ParseConfig("/product/etc/init")) {
late_import_paths.emplace_back("/product/etc/init");
}
if (!parser.ParseConfig("/odm/etc/init")) {
late_import_paths.emplace_back("/odm/etc/init");
}
if (!parser.ParseConfig("/vendor/etc/init")) {
late_import_paths.emplace_back("/vendor/etc/init");
}
} else {
parser.ParseConfig(bootscript);
}
}
這里需要看一下Parser類的設(shè)計(jì):
Parser類定義在parser.h
namespace android {
namespace init {
class SectionParser {
public:
virtual ~SectionParser() {}
virtual Result<Success> ParseSection(std::vector<std::string>&& args,
const std::string& filename, int line) = 0;
virtual Result<Success> ParseLineSection(std::vector<std::string>&&, int) { return Success(); };
virtual Result<Success> EndSection() { return Success(); };
virtual void EndFile(){};
};
class Parser {
public:
// LineCallback is the type for callbacks that can parse a line starting with a given prefix.
//
// They take the form of bool Callback(std::vector<std::string>&& args, std::string* err)
//
// Similar to ParseSection() and ParseLineSection(), this function returns bool with false
// indicating a failure and has an std::string* err parameter into which an error string can
// be written.
using LineCallback = std::function<Result<Success>(std::vector<std::string>&&)>;
Parser();
bool ParseConfig(const std::string& path);
bool ParseConfig(const std::string& path, size_t* parse_errors);
void AddSectionParser(const std::string& name, std::unique_ptr<SectionParser> parser);
void AddSingleLineParser(const std::string& prefix, LineCallback callback);
private:
void ParseData(const std::string& filename, const std::string& data, size_t* parse_errors);
bool ParseConfigFile(const std::string& path, size_t* parse_errors);
bool ParseConfigDir(const std::string& path, size_t* parse_errors);
std::map<std::string, std::unique_ptr<SectionParser>> section_parsers_;
std::vector<std::pair<std::string, LineCallback>> line_callbacks_;
};
} // namespace init
} // namespace android
Parser包含兩個成員變量涮瞻,一個是section_parsers_
鲤拿,是負(fù)責(zé)解析語法的,在初始化的時候添加了三個解析類ServiceParser
署咽、ActionParser
近顷、ImportParser
,通過AddSectionParser函數(shù)添加:
void Parser::AddSectionParser(const std::string& name, std::unique_ptr<SectionParser> parser) {
section_parsers_[name] = std::move(parser);
}
line_callbacks_
是判斷當(dāng)前行的前綴是否匹配prefix宁否,如果匹配則取消當(dāng)前的section的配置窒升,perfix主要通過AddSingleLineParser添加:
void Parser::AddSingleLineParser(const std::string& prefix, LineCallback callback) {
line_callbacks_.emplace_back(prefix, callback);
}
目前用到這個函數(shù)的是uevent.cpp:
DeviceHandler CreateDeviceHandler() {
parser.AddSingleLineParser("/sys/",
std::bind(ParsePermissionsLine, _1, &sysfs_permissions, nullptr));
parser.AddSingleLineParser("/dev/",
std::bind(ParsePermissionsLine, _1, nullptr, &dev_permissions));
}
在Parser類里面,公開的成員函數(shù)ParseConfig是外部調(diào)用解析的入口慕匠,調(diào)用流程如下:
ParseConfig
|
--> ParseConfigFile
|
--> ParseData
ParseData的實(shí)現(xiàn)如下:
void Parser::ParseData(const std::string& filename, const std::string& data, size_t* parse_errors) {
// 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.line = 0;
state.ptr = &data_copy[0];
state.nexttoken = 0;
SectionParser* section_parser = nullptr;
int section_start_line = -1;
std::vector<std::string> args;
// 一個lambda表達(dá)式饱须,可以理解為內(nèi)部函數(shù),作用是判斷這個section是否解析到最后
auto end_section = [&] {
if (section_parser == nullptr) return;
if (auto result = section_parser->EndSection(); !result) {
(*parse_errors)++;
LOG(ERROR) << filename << ": " << section_start_line << ": " << result.error();
}
section_parser = nullptr;
section_start_line = -1;
};
for (;;) {
switch (next_token(&state)) { // 語法解析器
case T_EOF: // 解析結(jié)束
end_section();
return;
case T_NEWLINE: // 解析新行
state.line++;
if (args.empty()) break;
// If we have a line matching a prefix we recognize, call its callback and unset any
// current section parsers. This is meant for /sys/ and /dev/ line entries for
// uevent.
for (const auto& [prefix, callback] : line_callbacks_) { // line_callbacks_ 匹配規(guī)則
if (android::base::StartsWith(args[0], prefix)) {
end_section();
if (auto result = callback(std::move(args)); !result) {
(*parse_errors)++;
LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
}
break;
}
}
if (section_parsers_.count(args[0])) { // section_parsers_ 匹配規(guī)則
end_section();
section_parser = section_parsers_[args[0]].get(); // 根據(jù)參數(shù)獲取解析器
section_start_line = state.line;
if (auto result =
section_parser->ParseSection(std::move(args), filename, state.line); // 解析內(nèi)容
!result) {
(*parse_errors)++;
LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
section_parser = nullptr;
}
} else if (section_parser) {
if (auto result = section_parser->ParseLineSection(std::move(args), state.line);
!result) {
(*parse_errors)++;
LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
}
}
args.clear();
break;
case T_TEXT: // 加載文件內(nèi)容
args.emplace_back(state.text);
break;
}
}
}
parseData主要是通過parse_state
控制狀態(tài)從而解析不同的規(guī)則絮重,parse_state
是一個結(jié)構(gòu)體冤寿,定義在tokenizer.h:
namespace android {
namespace init {
struct parse_state
{
char *ptr;
char *text;
int line;
int nexttoken;
};
int next_token(struct parse_state *state);
} // namespace init
} // namespace android
next_token是主要語法解析函數(shù),在tokenizer.cpp實(shí)現(xiàn):
int next_token(struct parse_state *state)
{
char *x = state->ptr;
char *s;
if (state->nexttoken) {
int t = state->nexttoken;
state->nexttoken = 0;
return t;
}
for (;;) {
switch (*x) {
case 0:
state->ptr = x;
return T_EOF;
case '\n':
x++;
state->ptr = x;
return T_NEWLINE;
case ' ':
case '\t':
case '\r':
x++;
continue;
case '#':
while (*x && (*x != '\n')) x++;
if (*x == '\n') {
state->ptr = x+1;
return T_NEWLINE;
} else {
state->ptr = x;
return T_EOF;
}
default:
goto text;
}
}
textdone:
state->ptr = x;
*s = 0;
return T_TEXT;
text:
state->text = s = x;
textresume:
for (;;) {
switch (*x) {
case 0:
goto textdone;
case ' ':
case '\t':
case '\r':
x++;
goto textdone;
case '\n':
state->nexttoken = T_NEWLINE;
x++;
goto textdone;
case '"':
x++;
for (;;) {
switch (*x) {
case 0:
/* unterminated quoted thing */
state->ptr = x;
return T_EOF;
case '"':
x++;
goto textresume;
default:
*s++ = *x++;
}
}
break;
case '\\':
x++;
switch (*x) {
case 0:
goto textdone;
case 'n':
*s++ = '\n';
break;
case 'r':
*s++ = '\r';
break;
case 't':
*s++ = '\t';
break;
case '\\':
*s++ = '\\';
break;
case '\r':
/* \ <cr> <lf> -> line continuation */
if (x[1] != '\n') {
x++;
continue;
}
case '\n':
/* \ <lf> -> line continuation */
state->line++;
x++;
/* eat any extra whitespace */
while((*x == ' ') || (*x == '\t')) x++;
continue;
default:
/* unknown escape -- just copy */
*s++ = *x++;
}
continue;
default:
*s++ = *x++;
}
}
return T_EOF;
}
這里不細(xì)究代碼實(shí)現(xiàn)青伤,主要分析思路督怜,next_token函數(shù)通過解析文件的行來返回狀態(tài)給parseData函數(shù)進(jìn)行處理:
// 解析到行時 on property:persist.test=test
// 此時section_parser是ActionParser
section_parser = section_parsers_[args[0]].get();
// 再調(diào)用section_parser的ParseSection函數(shù)也就是ActionParser的ParseSection函數(shù)
section_parser->ParseSection(std::move(args), filename, state.line)
這里看一下ActionParser的定義(action_parser.h):
namespace android {
namespace init {
class ActionParser : public SectionParser {
public:
ActionParser(ActionManager* action_manager, std::vector<Subcontext>* subcontexts)
: action_manager_(action_manager), subcontexts_(subcontexts), action_(nullptr) {}
Result<Success> ParseSection(std::vector<std::string>&& args, const std::string& filename,
int line) override;
Result<Success> ParseLineSection(std::vector<std::string>&& args, int line) override;
Result<Success> EndSection() override;
private:
ActionManager* action_manager_;
std::vector<Subcontext>* subcontexts_;
std::unique_ptr<Action> action_;
};
} // namespace init
} // namespace android
實(shí)現(xiàn)在action_parser.cpp,這里主要看ParseSection的實(shí)現(xiàn):
Result<Success> ActionParser::ParseSection(std::vector<std::string>&& args,
const std::string& filename, int line) {
std::vector<std::string> triggers(args.begin() + 1, args.end());
if (triggers.size() < 1) {
return Error() << "Actions must have a trigger";
}
Subcontext* action_subcontext = nullptr;
if (subcontexts_) {
for (auto& subcontext : *subcontexts_) {
if (StartsWith(filename, subcontext.path_prefix())) {
action_subcontext = &subcontext;
break;
}
}
}
std::string event_trigger;
std::map<std::string, std::string> property_triggers;
// 解析和觸發(fā)動作
if (auto result = ParseTriggers(triggers, action_subcontext, &event_trigger, &property_triggers);
!result) {
return Error() << "ParseTriggers() failed: " << result.error();
}
auto action = std::make_unique<Action>(false, action_subcontext, filename, line, event_trigger,
property_triggers);
action_ = std::move(action);
return Success();
}
Result<Success> ParseTriggers(const std::vector<std::string>& args, Subcontext* subcontext,
std::string* event_trigger,
std::map<std::string, std::string>* property_triggers) {
const static std::string prop_str("property:");
for (std::size_t i = 0; i < args.size(); ++i) {
if (args[i].empty()) {
return Error() << "empty trigger is not valid";
}
if (i % 2) {
if (args[i] != "&&") {
return Error() << "&& is the only symbol allowed to concatenate actions";
} else {
continue;
}
}
// 判斷是不是 on property: 類型
if (!args[i].compare(0, prop_str.length(), prop_str)) {
// 符合條件的調(diào)用ParsePropertyTrigger解析
if (auto result = ParsePropertyTrigger(args[i], subcontext, property_triggers);
!result) {
return result;
}
} else {
if (!event_trigger->empty()) {
return Error() << "multiple event triggers are not allowed";
}
*event_trigger = args[i];
}
}
return Success();
}
Result<Success> ParsePropertyTrigger(const std::string& trigger, Subcontext* subcontext,
std::map<std::string, std::string>* property_triggers) {
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) {
return Error() << "property trigger found without matching '='";
}
std::string prop_value(prop_name.substr(equal_pos + 1));
prop_name.erase(equal_pos);
// 判斷屬性是否合法
if (!IsActionableProperty(subcontext, prop_name)) {
return Error() << "unexported property tigger found: " << prop_name;
}
if (auto [it, inserted] = property_triggers->emplace(prop_name, prop_value); !inserted) {
return Error() << "multiple property triggers found for same property";
}
return Success();
}
bool IsActionableProperty(Subcontext* subcontext, const std::string& prop_name) {
static bool enabled = GetBoolProperty("ro.actionable_compatible_property.enabled", false);
if (subcontext == nullptr || !enabled) {
return true;
}
// 判斷屬性是否在kExportedActionableProperties數(shù)組狠角,prop_name出現(xiàn)次數(shù)==1說明在數(shù)組里
if (kExportedActionableProperties.count(prop_name) == 1) {
return true;
}
// 遍歷kPartnerPrefixes這個set号杠,判斷prop_name是不是符合set中要求的前綴
for (const auto& prefix : kPartnerPrefixes) {
if (android::base::StartsWith(prop_name, prefix)) {
return true;
}
}
return false;
}
kExportedActionableProperties和kPartnerPrefixes定義在stable_properties.h:
static constexpr const char* kPartnerPrefixes[] = {
"init.svc.vendor.", "ro.vendor.", "persist.vendor.", "vendor.", "init.svc.odm.", "ro.odm.",
"persist.odm.", "odm.", "ro.boot.",
};
static const std::set<std::string> kExportedActionableProperties = {
"dev.bootcomplete",
"init.svc.console",
"init.svc.mediadrm",
"init.svc.surfaceflinger",
"init.svc.zygote",
"persist.bluetooth.btsnoopenable",
"persist.sys.crash_rcu",
"persist.sys.usb.usbradio.config",
"persist.sys.zram_enabled",
"ro.board.platform",
"ro.bootmode",
"ro.build.type",
"ro.crypto.state",
"ro.crypto.type",
"ro.debuggable",
"sys.boot_completed",
"sys.boot_from_charger_mode",
"sys.retaildemo.enabled",
"sys.shutdown.requested",
"sys.usb.config",
"sys.usb.configfs",
"sys.usb.ffs.mtp.ready",
"sys.usb.ffs.ready",
"sys.user.0.ce_available",
"sys.vdso",
"vold.decrypt",
"vold.post_fs_data_done",
"vts.native_server.on",
"wlan.driver.status",
};
到這里流程就跟完了,問題原因也找到了丰歌,屬性trigger是有一個類似于白名單的機(jī)制姨蟋,不在白名單的屬性是無法觸發(fā)動作的,前面嘗試的vold.decrypt在白名單中立帖,所以可以生效眼溶,而自己的添加的屬性不生效
那找到原因了也就好修改了,修改方式有兩種:
- 使用白名單中原本就有的屬性或?qū)傩郧熬Y
- 在白名單中加入自己的屬性
修改方式要根據(jù)自己的場景進(jìn)行選擇晓勇,我在實(shí)際項(xiàng)目中采用了第一種堂飞,使用了sys.boot_completed這個屬性:
on property:sys.boot_completed=1
# do my things
后來因?yàn)閳鼍坝行?fù)雜灌旧,只由sys.boot_completed(開機(jī)完成后由AMS設(shè)置的一個屬性)控制可能會出問題,后來加入了自己的屬性到白名單里面绰筛,測試也是沒有問題的
static const std::set<std::string> kExportedActionableProperties = {
"dev.bootcomplete",
"init.svc.console",
"init.svc.mediadrm",
"init.svc.surfaceflinger",
"init.svc.zygote",
"persist.bluetooth.btsnoopenable",
"persist.sys.crash_rcu",
"persist.sys.usb.usbradio.config",
"persist.sys.zram_enabled",
"ro.board.platform",
"ro.bootmode",
"ro.build.type",
"ro.crypto.state",
"ro.crypto.type",
"ro.debuggable",
"sys.boot_completed",
"sys.boot_from_charger_mode",
"sys.retaildemo.enabled",
"sys.shutdown.requested",
"sys.usb.config",
"sys.usb.configfs",
"sys.usb.ffs.mtp.ready",
"sys.usb.ffs.ready",
"sys.user.0.ce_available",
"sys.vdso",
"vold.decrypt",
"vold.post_fs_data_done",
"vts.native_server.on",
"wlan.driver.status",
"persist.test" // 添加自己的屬性
};
on property:persist.test=test
# do my things
一開始擔(dān)心修改了白名單會引起CTS枢泰、VTS問題,在跑了一整輪的CTS和VTS測試后铝噩,并沒有報(bào)出相關(guān)問題衡蚂,也就是說這兩種修改方式都是可控的,沒什么大的問題骏庸。
后話:
在解決實(shí)際問題的時候還是比較復(fù)雜的毛甲,不只是說流程弄清除后簡單修改就行,在分析這個問題的時候具被,遇到的selinux權(quán)限問題還會觸發(fā)neverallow機(jī)制丽啡,規(guī)避neverallow機(jī)制的同時又不能引起CTS問題,要考量的因素比較多硬猫,印象深刻,故做此筆記
六點(diǎn)一到改执,關(guān)機(jī)下班啸蜜,回家過年!