Merge "Convert system/core to Result::ok()"

This commit is contained in:
Treehugger Robot 2020-02-07 06:14:16 +00:00 committed by Gerrit Code Review
commit 39e990d477
33 changed files with 240 additions and 233 deletions

View file

@ -408,11 +408,11 @@ TEST(Expected, testDereference) {
TEST(Expected, testTest) {
exp_int e = 10;
EXPECT_TRUE(e);
EXPECT_TRUE(e.ok());
EXPECT_TRUE(e.has_value());
exp_int e2 = unexpected(10);
EXPECT_FALSE(e2);
EXPECT_FALSE(e2.ok());
EXPECT_FALSE(e2.has_value());
}
@ -571,11 +571,11 @@ TEST(Expected, testDivideExample) {
}
};
EXPECT_FALSE(divide(10, 0));
EXPECT_FALSE(divide(10, 0).ok());
EXPECT_EQ("divide by zero", divide(10, 0).error().message);
EXPECT_EQ(-1, divide(10, 0).error().cause);
EXPECT_TRUE(divide(10, 3));
EXPECT_TRUE(divide(10, 3).ok());
EXPECT_EQ(QR(3, 1), *divide(10, 3));
}
@ -589,7 +589,7 @@ TEST(Expected, testPair) {
};
auto r = test(true);
EXPECT_TRUE(r);
EXPECT_TRUE(r.ok());
EXPECT_EQ("yes", r->first);
}
@ -603,9 +603,9 @@ TEST(Expected, testVoid) {
};
auto r = test(true);
EXPECT_TRUE(r);
EXPECT_TRUE(r.ok());
r = test(false);
EXPECT_FALSE(r);
EXPECT_FALSE(r.ok());
EXPECT_EQ(10, r.error());
}
@ -754,7 +754,7 @@ TEST(Expected, testNoCopyOnReturn) {
ConstructorTracker::Reset();
auto result1 = test("");
ASSERT_TRUE(result1);
ASSERT_TRUE(result1.ok());
EXPECT_EQ("literal string", result1->string);
EXPECT_EQ(1U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
@ -764,7 +764,7 @@ TEST(Expected, testNoCopyOnReturn) {
ConstructorTracker::Reset();
auto result2 = test("test2");
ASSERT_TRUE(result2);
ASSERT_TRUE(result2.ok());
EXPECT_EQ("test2test22", result2->string);
EXPECT_EQ(1U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
@ -774,7 +774,7 @@ TEST(Expected, testNoCopyOnReturn) {
ConstructorTracker::Reset();
auto result3 = test("test3");
ASSERT_TRUE(result3);
ASSERT_TRUE(result3.ok());
EXPECT_EQ("test3 test3", result3->string);
EXPECT_EQ(1U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
@ -786,22 +786,22 @@ TEST(Expected, testNoCopyOnReturn) {
TEST(Expected, testNested) {
expected<exp_string, std::string> e = "hello";
EXPECT_TRUE(e.ok());
EXPECT_TRUE(e.has_value());
EXPECT_TRUE(e.value().has_value());
EXPECT_TRUE(e);
EXPECT_TRUE(*e);
EXPECT_TRUE(e->ok());
EXPECT_EQ("hello", e.value().value());
expected<exp_string, std::string> e2 = unexpected("world");
EXPECT_FALSE(e2.has_value());
EXPECT_FALSE(e2);
EXPECT_FALSE(e2.ok());
EXPECT_EQ("world", e2.error());
expected<exp_string, std::string> e3 = exp_string(unexpected("world"));
EXPECT_TRUE(e3.has_value());
EXPECT_FALSE(e3.value().has_value());
EXPECT_TRUE(e3);
EXPECT_FALSE(*e3);
EXPECT_TRUE(e3.ok());
EXPECT_FALSE(e3->ok());
EXPECT_EQ("world", e3.value().error());
}

View file

@ -30,7 +30,7 @@ namespace base {
TEST(result, result_accessors) {
Result<std::string> result = "success";
ASSERT_TRUE(result);
ASSERT_RESULT_OK(result);
ASSERT_TRUE(result.has_value());
EXPECT_EQ("success", *result);
@ -40,7 +40,7 @@ TEST(result, result_accessors) {
}
TEST(result, result_accessors_rvalue) {
ASSERT_TRUE(Result<std::string>("success"));
ASSERT_TRUE(Result<std::string>("success").ok());
ASSERT_TRUE(Result<std::string>("success").has_value());
EXPECT_EQ("success", *Result<std::string>("success"));
@ -51,12 +51,12 @@ TEST(result, result_accessors_rvalue) {
TEST(result, result_void) {
Result<void> ok = {};
EXPECT_TRUE(ok);
EXPECT_RESULT_OK(ok);
ok.value(); // should not crash
ASSERT_DEATH(ok.error(), "");
Result<void> fail = Error() << "failure" << 1;
EXPECT_FALSE(fail);
EXPECT_FALSE(fail.ok());
EXPECT_EQ("failure1", fail.error().message());
EXPECT_EQ(0, fail.error().code());
EXPECT_TRUE(ok != fail);
@ -66,8 +66,8 @@ TEST(result, result_void) {
if (ok) return {};
else return Error() << "failure" << 1;
};
EXPECT_TRUE(test(true));
EXPECT_FALSE(test(false));
EXPECT_TRUE(test(true).ok());
EXPECT_FALSE(test(false).ok());
test(true).value(); // should not crash
ASSERT_DEATH(test(true).error(), "");
ASSERT_DEATH(test(false).value(), "");
@ -76,7 +76,7 @@ TEST(result, result_void) {
TEST(result, result_error) {
Result<void> result = Error() << "failure" << 1;
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
EXPECT_EQ(0, result.error().code());
@ -85,7 +85,7 @@ TEST(result, result_error) {
TEST(result, result_error_empty) {
Result<void> result = Error();
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
EXPECT_EQ(0, result.error().code());
@ -100,7 +100,7 @@ TEST(result, result_error_rvalue) {
// create is.
auto MakeRvalueErrorResult = []() -> Result<void> { return Error() << "failure" << 1; };
ASSERT_FALSE(MakeRvalueErrorResult());
ASSERT_FALSE(MakeRvalueErrorResult().ok());
ASSERT_FALSE(MakeRvalueErrorResult().has_value());
EXPECT_EQ(0, MakeRvalueErrorResult().error().code());
@ -112,7 +112,7 @@ TEST(result, result_errno_error) {
errno = test_errno;
Result<void> result = ErrnoError() << "failure" << 1;
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
EXPECT_EQ(test_errno, result.error().code());
@ -124,7 +124,7 @@ TEST(result, result_errno_error_no_text) {
errno = test_errno;
Result<void> result = ErrnoError();
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
EXPECT_EQ(test_errno, result.error().code());
@ -135,12 +135,12 @@ TEST(result, result_error_from_other_result) {
auto error_text = "test error"s;
Result<void> result = Error() << error_text;
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
Result<std::string> result2 = result.error();
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.ok());
ASSERT_FALSE(result2.has_value());
EXPECT_EQ(0, result2.error().code());
@ -151,12 +151,12 @@ TEST(result, result_error_through_ostream) {
auto error_text = "test error"s;
Result<void> result = Error() << error_text;
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
Result<std::string> result2 = Error() << result.error();
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.ok());
ASSERT_FALSE(result2.has_value());
EXPECT_EQ(0, result2.error().code());
@ -171,12 +171,12 @@ TEST(result, result_errno_error_through_ostream) {
errno = 0;
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_FALSE(result.has_value());
Result<std::string> result2 = Error() << result.error();
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.ok());
ASSERT_FALSE(result2.has_value());
EXPECT_EQ(test_errno, result2.error().code());
@ -186,7 +186,7 @@ TEST(result, result_errno_error_through_ostream) {
TEST(result, constructor_forwarding) {
auto result = Result<std::string>(std::in_place, 5, 'a');
ASSERT_TRUE(result);
ASSERT_RESULT_OK(result);
ASSERT_TRUE(result.has_value());
EXPECT_EQ("aaaaa", *result);
@ -254,7 +254,7 @@ TEST(result, no_copy_on_return) {
// are called.
auto result1 = ReturnConstructorTracker("");
ASSERT_TRUE(result1);
ASSERT_RESULT_OK(result1);
EXPECT_EQ("literal string", result1->string);
EXPECT_EQ(1U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
@ -263,7 +263,7 @@ TEST(result, no_copy_on_return) {
EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
auto result2 = ReturnConstructorTracker("test2");
ASSERT_TRUE(result2);
ASSERT_RESULT_OK(result2);
EXPECT_EQ("test2test22", result2->string);
EXPECT_EQ(2U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
@ -272,7 +272,7 @@ TEST(result, no_copy_on_return) {
EXPECT_EQ(0U, ConstructorTracker::move_assignment_called);
auto result3 = ReturnConstructorTracker("test3");
ASSERT_TRUE(result3);
ASSERT_RESULT_OK(result3);
EXPECT_EQ("test3 test3", result3->string);
EXPECT_EQ(3U, ConstructorTracker::constructor_called);
EXPECT_EQ(0U, ConstructorTracker::copy_constructor_called);
@ -287,11 +287,11 @@ TEST(result, no_copy_on_return) {
TEST(result, result_result_with_success) {
auto return_result_result_with_success = []() -> Result<Result<void>> { return Result<void>(); };
auto result = return_result_result_with_success();
ASSERT_TRUE(result);
ASSERT_TRUE(*result);
ASSERT_RESULT_OK(result);
ASSERT_RESULT_OK(*result);
auto inner_result = result.value();
ASSERT_TRUE(inner_result);
ASSERT_RESULT_OK(inner_result);
}
TEST(result, result_result_with_failure) {
@ -299,8 +299,8 @@ TEST(result, result_result_with_failure) {
return Result<void>(ResultError("failure string", 6));
};
auto result = return_result_result_with_error();
ASSERT_TRUE(result);
ASSERT_FALSE(*result);
ASSERT_RESULT_OK(result);
ASSERT_FALSE(result->ok());
EXPECT_EQ("failure string", (*result).error().message());
EXPECT_EQ(6, (*result).error().code());
}
@ -320,7 +320,7 @@ TEST(result, result_two_parameter_constructor_same_type) {
};
auto result = return_test_struct();
ASSERT_TRUE(result);
ASSERT_RESULT_OK(result);
EXPECT_EQ(36, result->value_);
}
@ -344,13 +344,13 @@ TEST(result, preserve_errno) {
errno = 1;
int old_errno = errno;
Result<int> result = Error() << "Failed" << SetErrnoToTwo<char>;
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
EXPECT_EQ(old_errno, errno);
errno = 1;
old_errno = errno;
Result<int> result2 = ErrnoError() << "Failed" << SetErrnoToTwo<char>;
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.ok());
EXPECT_EQ(old_errno, errno);
EXPECT_EQ(old_errno, result2.error().code());
}

View file

@ -329,7 +329,7 @@ AvbUniquePtr AvbHandle::LoadAndVerifyVbmeta(const FstabEntry& fstab_entry,
// or a string indicating multiple keys separated by ':'.
std::vector<std::string> allowed_avb_keys;
auto list_avb_keys_in_dir = ListFiles(fstab_entry.avb_keys);
if (list_avb_keys_in_dir) {
if (list_avb_keys_in_dir.ok()) {
std::sort(list_avb_keys_in_dir->begin(), list_avb_keys_in_dir->end());
allowed_avb_keys = *list_avb_keys_in_dir;
} else {

View file

@ -36,7 +36,7 @@ Result<void> RunBuiltinFunction(const BuiltinFunction& function,
builtin_arguments.args[0] = args[0];
for (std::size_t i = 1; i < args.size(); ++i) {
auto expanded_arg = ExpandProps(args[i]);
if (!expanded_arg) {
if (!expanded_arg.ok()) {
return expanded_arg.error();
}
builtin_arguments.args[i] = std::move(*expanded_arg);
@ -59,7 +59,7 @@ Result<void> Command::InvokeFunc(Subcontext* subcontext) const {
}
auto expanded_args = subcontext->ExpandArgs(args_);
if (!expanded_args) {
if (!expanded_args.ok()) {
return expanded_args.error();
}
return RunBuiltinFunction(func_, *expanded_args, subcontext->context());
@ -75,7 +75,7 @@ Result<void> Command::CheckCommand() const {
builtin_arguments.args[0] = args_[0];
for (size_t i = 1; i < args_.size(); ++i) {
auto expanded_arg = ExpandProps(args_[i]);
if (!expanded_arg) {
if (!expanded_arg.ok()) {
if (expanded_arg.error().message().find("doesn't exist while expanding") !=
std::string::npos) {
// If we failed because we won't have a property, use an empty string, which is
@ -114,7 +114,7 @@ Result<void> Action::AddCommand(std::vector<std::string>&& args, int line) {
}
auto map_result = function_map_->Find(args);
if (!map_result) {
if (!map_result.ok()) {
return Error() << map_result.error();
}
@ -134,7 +134,7 @@ std::size_t Action::NumCommands() const {
size_t Action::CheckAllCommands() const {
size_t failures = 0;
for (const auto& command : commands_) {
if (auto result = command.CheckCommand(); !result) {
if (auto result = command.CheckCommand(); !result.ok()) {
LOG(ERROR) << "Command '" << command.BuildCommandString() << "' (" << filename_ << ":"
<< command.line() << ") failed: " << result.error();
++failures;
@ -169,7 +169,7 @@ void Action::ExecuteCommand(const Command& command) const {
LOG(INFO) << "Command '" << cmd_str << "' action=" << trigger_name << " (" << filename_
<< ":" << command.line() << ") took " << duration.count() << "ms and "
<< (result ? "succeeded" : "failed: " + result.error().message());
<< (result.ok() ? "succeeded" : "failed: " + result.error().message());
}
}

View file

@ -110,14 +110,14 @@ Result<void> ParseTriggers(const std::vector<std::string>& args, Subcontext* sub
if (!args[i].compare(0, prop_str.length(), prop_str)) {
if (auto result = ParsePropertyTrigger(args[i], subcontext, property_triggers);
!result) {
!result.ok()) {
return result;
}
} else {
if (!event_trigger->empty()) {
return Error() << "multiple event triggers are not allowed";
}
if (auto result = ValidateEventTrigger(args[i]); !result) {
if (auto result = ValidateEventTrigger(args[i]); !result.ok()) {
return result;
}
@ -145,8 +145,9 @@ Result<void> ActionParser::ParseSection(std::vector<std::string>&& args,
std::string event_trigger;
std::map<std::string, std::string> property_triggers;
if (auto result = ParseTriggers(triggers, action_subcontext, &event_trigger, &property_triggers);
!result) {
if (auto result =
ParseTriggers(triggers, action_subcontext, &event_trigger, &property_triggers);
!result.ok()) {
return Error() << "ParseTriggers() failed: " << result.error();
}

View file

@ -164,7 +164,7 @@ static Result<void> do_class_start(const BuiltinArguments& args) {
// They must be started individually.
for (const auto& service : ServiceList::GetInstance()) {
if (service->classnames().count(args[1])) {
if (auto result = service->StartIfNotDisabled(); !result) {
if (auto result = service->StartIfNotDisabled(); !result.ok()) {
LOG(ERROR) << "Could not start service '" << service->name()
<< "' as part of class '" << args[1] << "': " << result.error();
}
@ -186,7 +186,7 @@ static Result<void> do_class_start_post_data(const BuiltinArguments& args) {
}
for (const auto& service : ServiceList::GetInstance()) {
if (service->classnames().count(args[1])) {
if (auto result = service->StartIfPostData(); !result) {
if (auto result = service->StartIfPostData(); !result.ok()) {
LOG(ERROR) << "Could not start service '" << service->name()
<< "' as part of class '" << args[1] << "': " << result.error();
}
@ -227,7 +227,7 @@ static Result<void> do_class_restart(const BuiltinArguments& args) {
}
static Result<void> do_domainname(const BuiltinArguments& args) {
if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result) {
if (auto result = WriteFile("/proc/sys/kernel/domainname", args[1]); !result.ok()) {
return Error() << "Unable to write to /proc/sys/kernel/domainname: " << result.error();
}
return {};
@ -237,7 +237,7 @@ static Result<void> do_enable(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindService(args[1]);
if (!svc) return Error() << "Could not find service";
if (auto result = svc->Enable(); !result) {
if (auto result = svc->Enable(); !result.ok()) {
return Error() << "Could not enable service: " << result.error();
}
@ -246,10 +246,10 @@ static Result<void> do_enable(const BuiltinArguments& args) {
static Result<void> do_exec(const BuiltinArguments& args) {
auto service = Service::MakeTemporaryOneshotService(args.args);
if (!service) {
if (!service.ok()) {
return Error() << "Could not create exec service: " << service.error();
}
if (auto result = (*service)->ExecStart(); !result) {
if (auto result = (*service)->ExecStart(); !result.ok()) {
return Error() << "Could not start exec service: " << result.error();
}
@ -259,10 +259,10 @@ static Result<void> do_exec(const BuiltinArguments& args) {
static Result<void> do_exec_background(const BuiltinArguments& args) {
auto service = Service::MakeTemporaryOneshotService(args.args);
if (!service) {
if (!service.ok()) {
return Error() << "Could not create exec background service: " << service.error();
}
if (auto result = (*service)->Start(); !result) {
if (auto result = (*service)->Start(); !result.ok()) {
return Error() << "Could not start exec background service: " << result.error();
}
@ -276,7 +276,7 @@ static Result<void> do_exec_start(const BuiltinArguments& args) {
return Error() << "Service not found";
}
if (auto result = service->ExecStart(); !result) {
if (auto result = service->ExecStart(); !result.ok()) {
return Error() << "Could not start exec service: " << result.error();
}
@ -291,7 +291,7 @@ static Result<void> do_export(const BuiltinArguments& args) {
}
static Result<void> do_hostname(const BuiltinArguments& args) {
if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result) {
if (auto result = WriteFile("/proc/sys/kernel/hostname", args[1]); !result.ok()) {
return Error() << "Unable to write to /proc/sys/kernel/hostname: " << result.error();
}
return {};
@ -349,7 +349,7 @@ static Result<void> do_interface_restart(const BuiltinArguments& args) {
static Result<void> do_interface_start(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindInterface(args[1]);
if (!svc) return Error() << "interface " << args[1] << " not found";
if (auto result = svc->Start(); !result) {
if (auto result = svc->Start(); !result.ok()) {
return Error() << "Could not start interface: " << result.error();
}
return {};
@ -413,7 +413,7 @@ static Result<void> make_dir_with_options(const MkdirOptions& options) {
// mkdir <path> [mode] [owner] [group] [<option> ...]
static Result<void> do_mkdir(const BuiltinArguments& args) {
auto options = ParseMkdir(args.args);
if (!options) return options.error();
if (!options.ok()) return options.error();
return make_dir_with_options(*options);
}
@ -681,7 +681,7 @@ static Result<void> do_mount_all(const BuiltinArguments& args) {
* and return processed return code*/
initial_mount_fstab_return_code = mount_fstab_return_code;
auto queue_fs_result = queue_fs_event(mount_fstab_return_code, false);
if (!queue_fs_result) {
if (!queue_fs_result.ok()) {
return Error() << "queue_fs_event() failed: " << queue_fs_result.error();
}
}
@ -731,7 +731,7 @@ static Result<void> do_setprop(const BuiltinArguments& args) {
static Result<void> do_setrlimit(const BuiltinArguments& args) {
auto rlimit = ParseRlimit(args.args);
if (!rlimit) return rlimit.error();
if (!rlimit.ok()) return rlimit.error();
if (setrlimit(rlimit->first, &rlimit->second) == -1) {
return ErrnoError() << "setrlimit failed";
@ -742,7 +742,7 @@ static Result<void> do_setrlimit(const BuiltinArguments& args) {
static Result<void> do_start(const BuiltinArguments& args) {
Service* svc = ServiceList::GetInstance().FindService(args[1]);
if (!svc) return Error() << "service " << args[1] << " not found";
if (auto result = svc->Start(); !result) {
if (auto result = svc->Start(); !result.ok()) {
return ErrorIgnoreEnoent() << "Could not start service: " << result.error();
}
return {};
@ -846,7 +846,7 @@ static Result<void> do_verity_update_state(const BuiltinArguments& args) {
}
static Result<void> do_write(const BuiltinArguments& args) {
if (auto result = WriteFile(args[1], args[2]); !result) {
if (auto result = WriteFile(args[1], args[2]); !result.ok()) {
return ErrorIgnoreEnoent()
<< "Unable to write to file '" << args[1] << "': " << result.error();
}
@ -904,7 +904,7 @@ static Result<void> do_readahead(const BuiltinArguments& args) {
}
android::base::Timer t;
if (S_ISREG(sb.st_mode)) {
if (auto result = readahead_file(args[1], readfully); !result) {
if (auto result = readahead_file(args[1], readfully); !result.ok()) {
LOG(WARNING) << "Unable to readahead '" << args[1] << "': " << result.error();
_exit(EXIT_FAILURE);
}
@ -921,7 +921,7 @@ static Result<void> do_readahead(const BuiltinArguments& args) {
ftsent = fts_read(fts.get())) {
if (ftsent->fts_info & FTS_F) {
const std::string filename = ftsent->fts_accpath;
if (auto result = readahead_file(filename, readfully); !result) {
if (auto result = readahead_file(filename, readfully); !result.ok()) {
LOG(WARNING)
<< "Unable to readahead '" << filename << "': " << result.error();
}
@ -938,10 +938,10 @@ static Result<void> do_readahead(const BuiltinArguments& args) {
static Result<void> do_copy(const BuiltinArguments& args) {
auto file_contents = ReadFile(args[1]);
if (!file_contents) {
if (!file_contents.ok()) {
return Error() << "Could not read input file '" << args[1] << "': " << file_contents.error();
}
if (auto result = WriteFile(args[2], *file_contents); !result) {
if (auto result = WriteFile(args[2], *file_contents); !result.ok()) {
return Error() << "Could not write to output file '" << args[2] << "': " << result.error();
}
@ -950,7 +950,7 @@ static Result<void> do_copy(const BuiltinArguments& args) {
static Result<void> do_chown(const BuiltinArguments& args) {
auto uid = DecodeUid(args[1]);
if (!uid) {
if (!uid.ok()) {
return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
}
@ -960,7 +960,7 @@ static Result<void> do_chown(const BuiltinArguments& args) {
if (args.size() == 4) {
gid = DecodeUid(args[2]);
if (!gid) {
if (!gid.ok()) {
return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
}
}
@ -995,7 +995,7 @@ static Result<void> do_chmod(const BuiltinArguments& args) {
static Result<void> do_restorecon(const BuiltinArguments& args) {
auto restorecon_info = ParseRestorecon(args.args);
if (!restorecon_info) {
if (!restorecon_info.ok()) {
return restorecon_info.error();
}
@ -1103,7 +1103,7 @@ static bool is_file_crypto() {
static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& args,
std::function<void(const std::string&)> function) {
auto service = Service::MakeTemporaryOneshotService(args);
if (!service) {
if (!service.ok()) {
function("MakeTemporaryOneshotService failed: " + service.error().message());
}
(*service)->AddReapCallback([function](const siginfo_t& siginfo) {
@ -1111,7 +1111,7 @@ static Result<void> ExecWithFunctionOnFailure(const std::vector<std::string>& ar
function(StringPrintf("Exec service failed, status %d", siginfo.si_status));
}
});
if (auto result = (*service)->ExecStart(); !result) {
if (auto result = (*service)->ExecStart(); !result.ok()) {
function("ExecStart failed: " + result.error().message());
}
ServiceList::GetInstance().AddService(std::move(*service));
@ -1133,7 +1133,7 @@ static Result<void> ExecVdcRebootOnFailure(const std::string& vdc_arg) {
LOG(ERROR) << message << ": Rebooting into recovery, reason: " << reboot_reason;
if (auto result = reboot_into_recovery(
{"--prompt_and_wipe_data", "--reason="s + reboot_reason});
!result) {
!result.ok()) {
LOG(FATAL) << "Could not reboot into recovery: " << result.error();
}
} else {
@ -1162,7 +1162,7 @@ static Result<void> do_remount_userdata(const BuiltinArguments& args) {
if (auto rc = fs_mgr_remount_userdata_into_checkpointing(&fstab); rc < 0) {
trigger_shutdown("reboot,mount_userdata_failed");
}
if (auto result = queue_fs_event(initial_mount_fstab_return_code, true); !result) {
if (auto result = queue_fs_event(initial_mount_fstab_return_code, true); !result.ok()) {
return Error() << "queue_fs_event() failed: " << result.error();
}
return {};
@ -1285,16 +1285,16 @@ static Result<void> create_apex_data_dirs() {
static Result<void> do_perform_apex_config(const BuiltinArguments& args) {
auto create_dirs = create_apex_data_dirs();
if (!create_dirs) {
if (!create_dirs.ok()) {
return create_dirs.error();
}
auto parse_configs = parse_apex_configs();
if (!parse_configs) {
if (!parse_configs.ok()) {
return parse_configs.error();
}
auto update_linker_config = do_update_linker_config(args);
if (!update_linker_config) {
if (!update_linker_config.ok()) {
return update_linker_config.error();
}

View file

@ -52,7 +52,7 @@ namespace init {
Result<void> check_chown(const BuiltinArguments& args) {
if (!args[1].empty()) {
auto uid = DecodeUid(args[1]);
if (!uid) {
if (!uid.ok()) {
return Error() << "Unable to decode UID for '" << args[1] << "': " << uid.error();
}
}
@ -60,7 +60,7 @@ Result<void> check_chown(const BuiltinArguments& args) {
// GID is optional and pushes the index of path out by one if specified.
if (args.size() == 4 && !args[2].empty()) {
auto gid = DecodeUid(args[2]);
if (!gid) {
if (!gid.ok()) {
return Error() << "Unable to decode GID for '" << args[2] << "': " << gid.error();
}
}
@ -72,7 +72,7 @@ Result<void> check_exec(const BuiltinArguments& args) {
ReturnIfAnyArgsEmpty();
auto result = Service::MakeTemporaryOneshotService(args.args);
if (!result) {
if (!result.ok()) {
return result.error();
}
@ -93,7 +93,7 @@ Result<void> check_exec_reboot_on_failure(const BuiltinArguments& args) {
}
Result<void> check_interface_restart(const BuiltinArguments& args) {
if (auto result = IsKnownInterface(args[1]); !result) {
if (auto result = IsKnownInterface(args[1]); !result.ok()) {
return result.error();
}
return {};
@ -124,7 +124,7 @@ Result<void> check_loglevel(const BuiltinArguments& args) {
Result<void> check_mkdir(const BuiltinArguments& args) {
auto options = ParseMkdir(args.args);
if (!options) {
if (!options.ok()) {
return options.error();
}
return {};
@ -134,7 +134,7 @@ Result<void> check_restorecon(const BuiltinArguments& args) {
ReturnIfAnyArgsEmpty();
auto restorecon_info = ParseRestorecon(args.args);
if (!restorecon_info) {
if (!restorecon_info.ok()) {
return restorecon_info.error();
}
@ -157,7 +157,7 @@ Result<void> check_setprop(const BuiltinArguments& args) {
}
if (!value.empty()) {
if (auto result = IsLegalPropertyValue(name, value); !result) {
if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
return result.error();
}
}
@ -189,7 +189,7 @@ Result<void> check_setrlimit(const BuiltinArguments& args) {
ReturnIfAnyArgsEmpty();
auto rlimit = ParseRlimit(args.args);
if (!rlimit) return rlimit.error();
if (!rlimit.ok()) return rlimit.error();
return {};
}

View file

@ -165,7 +165,7 @@ std::string FirmwareHandler::GetFirmwarePath(const Uevent& uevent) const {
auto result =
RunExternalHandler(external_handler.handler_path, external_handler.uid, uevent);
if (!result) {
if (!result.ok()) {
LOG(ERROR) << "Using default firmware; External firmware handler failed: "
<< result.error();
return uevent.firmware;

View file

@ -248,7 +248,7 @@ int main(int argc, char** argv) {
}
auto interface_inheritance_hierarchy_map = ReadInterfaceInheritanceHierarchy();
if (!interface_inheritance_hierarchy_map) {
if (!interface_inheritance_hierarchy_map.ok()) {
LOG(ERROR) << interface_inheritance_hierarchy_map.error();
return EXIT_FAILURE;
}

View file

@ -30,7 +30,7 @@ Result<void> ImportParser::ParseSection(std::vector<std::string>&& args,
}
auto conf_file = ExpandProps(args[1]);
if (!conf_file) {
if (!conf_file.ok()) {
return Error() << "Could not expand import: " << conf_file.error();
}

View file

@ -237,7 +237,7 @@ static std::optional<boot_clock::time_point> HandleProcessActions() {
auto restart_time = s->time_started() + s->restart_period();
if (boot_clock::now() > restart_time) {
if (auto result = s->Start(); !result) {
if (auto result = s->Start(); !result.ok()) {
LOG(ERROR) << "Could not restart process '" << s->name() << "': " << result.error();
}
} else {
@ -333,7 +333,7 @@ bool HandleControlMessage(const std::string& msg, const std::string& name, pid_t
return false;
}
if (auto result = function.action(svc); !result) {
if (auto result = function.action(svc); !result.ok()) {
LOG(ERROR) << "Control message: Could not ctl." << msg << " for '" << name
<< "' from pid: " << pid << " (" << process_cmdline << "): " << result.error();
return false;
@ -478,7 +478,7 @@ static void InstallSignalFdHandler(Epoll* epoll) {
PLOG(FATAL) << "failed to create signalfd";
}
if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result) {
if (auto result = epoll->RegisterHandler(signal_fd, HandleSignalFd); !result.ok()) {
LOG(FATAL) << result.error();
}
}
@ -499,7 +499,7 @@ void HandleKeychord(const std::vector<int>& keycodes) {
found = true;
LOG(INFO) << "Starting service '" << svc->name() << "' from keychord "
<< android::base::Join(keycodes, ' ');
if (auto result = svc->Start(); !result) {
if (auto result = svc->Start(); !result.ok()) {
LOG(ERROR) << "Could not start service '" << svc->name() << "' from keychord "
<< android::base::Join(keycodes, ' ') << ": " << result.error();
}
@ -558,7 +558,7 @@ static void RecordStageBoottimes(const boot_clock::time_point& second_stage_star
void SendLoadPersistentPropertiesMessage() {
auto init_message = InitMessage{};
init_message.set_load_persistent_properties(true);
if (auto result = SendMessage(property_fd, init_message); !result) {
if (auto result = SendMessage(property_fd, init_message); !result.ok()) {
LOG(ERROR) << "Failed to send load persistent properties message: " << result.error();
}
}
@ -566,7 +566,7 @@ void SendLoadPersistentPropertiesMessage() {
void SendStopSendingMessagesMessage() {
auto init_message = InitMessage{};
init_message.set_stop_sending_messages(true);
if (auto result = SendMessage(property_fd, init_message); !result) {
if (auto result = SendMessage(property_fd, init_message); !result.ok()) {
LOG(ERROR) << "Failed to send 'stop sending messages' message: " << result.error();
}
}
@ -574,14 +574,14 @@ void SendStopSendingMessagesMessage() {
void SendStartSendingMessagesMessage() {
auto init_message = InitMessage{};
init_message.set_start_sending_messages(true);
if (auto result = SendMessage(property_fd, init_message); !result) {
if (auto result = SendMessage(property_fd, init_message); !result.ok()) {
LOG(ERROR) << "Failed to send 'start sending messages' message: " << result.error();
}
}
static void HandlePropertyFd() {
auto message = ReadMessage(property_fd);
if (!message) {
if (!message.ok()) {
LOG(ERROR) << "Could not read message from property service: " << message.error();
return;
}
@ -636,7 +636,7 @@ int SecondStageMain(int argc, char** argv) {
// Set init and its forked children's oom_adj.
if (auto result =
WriteFile("/proc/1/oom_score_adj", StringPrintf("%d", DEFAULT_OOM_SCORE_ADJUST));
!result) {
!result.ok()) {
LOG(ERROR) << "Unable to write " << DEFAULT_OOM_SCORE_ADJUST
<< " to /proc/1/oom_score_adj: " << result.error();
}
@ -679,14 +679,14 @@ int SecondStageMain(int argc, char** argv) {
SelinuxRestoreContext();
Epoll epoll;
if (auto result = epoll.Open(); !result) {
if (auto result = epoll.Open(); !result.ok()) {
PLOG(FATAL) << result.error();
}
InstallSignalFdHandler(&epoll);
StartPropertyService(&property_fd);
if (auto result = epoll.RegisterHandler(property_fd, HandlePropertyFd); !result) {
if (auto result = epoll.RegisterHandler(property_fd, HandlePropertyFd); !result.ok()) {
LOG(FATAL) << "Could not register epoll handler for property fd: " << result.error();
}
@ -797,7 +797,7 @@ int SecondStageMain(int argc, char** argv) {
}
auto pending_functions = epoll.Wait(epoll_timeout);
if (!pending_functions) {
if (!pending_functions.ok()) {
LOG(ERROR) << pending_functions.error();
} else if (!pending_functions->empty()) {
// We always reap children before responding to the other pending functions. This is to

View file

@ -204,9 +204,9 @@ TEST(init, EventTriggerOrderMultipleFiles) {
"execute 3";
// clang-format on
// WriteFile() ensures the right mode is set
ASSERT_TRUE(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/a.rc", dir_a_script));
ASSERT_TRUE(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
ASSERT_RESULT_OK(WriteFile(std::string(dir.path) + "/b.rc", "on boot\nexecute 5"));
// clang-format off
std::string start_script = "import " + std::string(first_import.path) + "\n"

View file

@ -187,7 +187,7 @@ bool Keychords::GeteventEnable(int fd) {
LambdaCheck();
}
if (auto result = epoll_->RegisterHandler(fd, [this, fd]() { this->LambdaHandler(fd); });
!result) {
!result.ok()) {
LOG(WARNING) << "Could not register keychord epoll handler: " << result.error();
return false;
}
@ -272,7 +272,7 @@ void Keychords::GeteventOpenDevice() {
if (inotify_fd_ >= 0) {
if (auto result =
epoll_->RegisterHandler(inotify_fd_, [this]() { this->InotifyHandler(); });
!result) {
!result.ok()) {
LOG(WARNING) << "Could not register keychord epoll handler: " << result.error();
}
}

View file

@ -204,7 +204,7 @@ class TestFrame {
TestFrame::TestFrame(const std::vector<const std::vector<int>>& chords, EventHandler* ev)
: ev_(ev) {
if (!epoll_.Open()) return;
if (!epoll_.Open().ok()) return;
for (const auto& keycodes : chords) keychords_.Register(keycodes);
keychords_.Start(&epoll_, [this](const std::vector<int>& keycodes) {
this->keycodes_.emplace_back(keycodes);
@ -213,7 +213,7 @@ TestFrame::TestFrame(const std::vector<const std::vector<int>>& chords, EventHan
void TestFrame::RelaxForMs(std::chrono::milliseconds wait) {
auto pending_functions = epoll_.Wait(wait);
ASSERT_TRUE(pending_functions) << pending_functions.error();
ASSERT_RESULT_OK(pending_functions);
for (const auto& function : *pending_functions) {
(*function)();
}

View file

@ -116,7 +116,7 @@ MountHandler::MountHandler(Epoll* epoll) : epoll_(epoll), fp_(fopen("/proc/mount
if (!fp_) PLOG(FATAL) << "Could not open /proc/mounts";
auto result = epoll->RegisterHandler(
fileno(fp_.get()), [this]() { this->MountHandlerFunction(); }, EPOLLERR | EPOLLPRI);
if (!result) LOG(FATAL) << result.error();
if (!result.ok()) LOG(FATAL) << result.error();
}
MountHandler::~MountHandler() {

View file

@ -141,12 +141,12 @@ static Result<void> ActivateFlattenedApexesFrom(const std::string& from_dir,
if (entry->d_type == DT_DIR) {
const std::string apex_path = from_dir + "/" + entry->d_name;
const auto apex_name = GetApexName(apex_path);
if (!apex_name) {
if (!apex_name.ok()) {
LOG(ERROR) << apex_path << " is not an APEX directory: " << apex_name.error();
continue;
}
const std::string mount_path = to_dir + "/" + (*apex_name);
if (auto result = MountDir(apex_path, mount_path); !result) {
if (auto result = MountDir(apex_path, mount_path); !result.ok()) {
return result;
}
}
@ -168,7 +168,7 @@ static bool ActivateFlattenedApexesIfPossible() {
};
for (const auto& dir : kBuiltinDirsForApexes) {
if (auto result = ActivateFlattenedApexesFrom(dir, kApexTop); !result) {
if (auto result = ActivateFlattenedApexesFrom(dir, kApexTop); !result.ok()) {
LOG(ERROR) << result.error();
return false;
}
@ -295,7 +295,7 @@ bool SwitchToDefaultMountNamespace() {
return false;
}
if (auto result = MountLinkerConfigForDefaultNamespace(); !result) {
if (auto result = MountLinkerConfigForDefaultNamespace(); !result.ok()) {
LOG(ERROR) << result.error();
return false;
}

View file

@ -61,7 +61,7 @@ void Parser::ParseData(const std::string& filename, std::string* data) {
bad_section_found = false;
if (section_parser == nullptr) return;
if (auto result = section_parser->EndSection(); !result) {
if (auto result = section_parser->EndSection(); !result.ok()) {
parse_error_count_++;
LOG(ERROR) << filename << ": " << section_start_line << ": " << result.error();
}
@ -92,7 +92,7 @@ void Parser::ParseData(const std::string& filename, std::string* data) {
if (line_callback != line_callbacks_.end()) {
end_section();
if (auto result = line_callback->second(std::move(args)); !result) {
if (auto result = line_callback->second(std::move(args)); !result.ok()) {
parse_error_count_++;
LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
}
@ -101,8 +101,8 @@ void Parser::ParseData(const std::string& filename, std::string* data) {
section_parser = section_parsers_[args[0]].get();
section_start_line = state.line;
if (auto result =
section_parser->ParseSection(std::move(args), filename, state.line);
!result) {
section_parser->ParseSection(std::move(args), filename, state.line);
!result.ok()) {
parse_error_count_++;
LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
section_parser = nullptr;
@ -110,7 +110,7 @@ void Parser::ParseData(const std::string& filename, std::string* data) {
}
} else if (section_parser) {
if (auto result = section_parser->ParseLineSection(std::move(args), state.line);
!result) {
!result.ok()) {
parse_error_count_++;
LOG(ERROR) << filename << ": " << state.line << ": " << result.error();
}
@ -143,7 +143,7 @@ bool Parser::ParseConfigFile(const std::string& path) {
LOG(INFO) << "Parsing file " << path << "...";
android::base::Timer t;
auto config_contents = ReadFile(path);
if (!config_contents) {
if (!config_contents.ok()) {
LOG(INFO) << "Unable to read config file '" << path << "': " << config_contents.error();
return false;
}

View file

@ -149,7 +149,7 @@ Result<std::string> ReadPersistentPropertyFile() {
unlink(temp_filename.c_str());
}
auto file_contents = ReadFile(persistent_property_filename);
if (!file_contents) {
if (!file_contents.ok()) {
return Error() << "Unable to read persistent property file: " << file_contents.error();
}
return *file_contents;
@ -159,7 +159,7 @@ Result<std::string> ReadPersistentPropertyFile() {
Result<PersistentProperties> LoadPersistentPropertyFile() {
auto file_contents = ReadPersistentPropertyFile();
if (!file_contents) return file_contents.error();
if (!file_contents.ok()) return file_contents.error();
PersistentProperties persistent_properties;
if (persistent_properties.ParseFromString(*file_contents)) return persistent_properties;
@ -212,7 +212,7 @@ Result<void> WritePersistentPropertyFile(const PersistentProperties& persistent_
void WritePersistentProperty(const std::string& name, const std::string& value) {
auto persistent_properties = LoadPersistentPropertyFile();
if (!persistent_properties) {
if (!persistent_properties.ok()) {
LOG(ERROR) << "Recovering persistent properties from memory: "
<< persistent_properties.error();
persistent_properties = LoadPersistentPropertiesFromMemory();
@ -227,7 +227,7 @@ void WritePersistentProperty(const std::string& name, const std::string& value)
AddPersistentProperty(name, value, &persistent_properties.value());
}
if (auto result = WritePersistentPropertyFile(*persistent_properties); !result) {
if (auto result = WritePersistentPropertyFile(*persistent_properties); !result.ok()) {
LOG(ERROR) << "Could not store persistent property: " << result.error();
}
}
@ -235,16 +235,16 @@ void WritePersistentProperty(const std::string& name, const std::string& value)
PersistentProperties LoadPersistentProperties() {
auto persistent_properties = LoadPersistentPropertyFile();
if (!persistent_properties) {
if (!persistent_properties.ok()) {
LOG(ERROR) << "Could not load single persistent property file, trying legacy directory: "
<< persistent_properties.error();
persistent_properties = LoadLegacyPersistentProperties();
if (!persistent_properties) {
if (!persistent_properties.ok()) {
LOG(ERROR) << "Unable to load legacy persistent properties: "
<< persistent_properties.error();
return {};
}
if (auto result = WritePersistentPropertyFile(*persistent_properties); result) {
if (auto result = WritePersistentPropertyFile(*persistent_properties); result.ok()) {
RemoveLegacyPersistentPropertyFiles();
} else {
LOG(ERROR) << "Unable to write single persistent property file: " << result.error();

View file

@ -83,7 +83,8 @@ TEST(persistent_properties, EndToEnd) {
{"persist.\x00\x01\x02\xFF\xFE\xFD\x7F\x8F\x9F", "non-ascii-name"},
};
ASSERT_TRUE(WritePersistentPropertyFile(VectorToPersistentProperties(persistent_properties)));
ASSERT_RESULT_OK(
WritePersistentPropertyFile(VectorToPersistentProperties(persistent_properties)));
auto read_back_properties = LoadPersistentProperties();
CheckPropertiesEqual(persistent_properties, read_back_properties);
@ -97,7 +98,8 @@ TEST(persistent_properties, AddProperty) {
std::vector<std::pair<std::string, std::string>> persistent_properties = {
{"persist.sys.timezone", "America/Los_Angeles"},
};
ASSERT_TRUE(WritePersistentPropertyFile(VectorToPersistentProperties(persistent_properties)));
ASSERT_RESULT_OK(
WritePersistentPropertyFile(VectorToPersistentProperties(persistent_properties)));
WritePersistentProperty("persist.sys.locale", "pt-BR");
@ -119,7 +121,8 @@ TEST(persistent_properties, UpdateProperty) {
{"persist.sys.locale", "en-US"},
{"persist.sys.timezone", "America/Los_Angeles"},
};
ASSERT_TRUE(WritePersistentPropertyFile(VectorToPersistentProperties(persistent_properties)));
ASSERT_RESULT_OK(
WritePersistentPropertyFile(VectorToPersistentProperties(persistent_properties)));
WritePersistentProperty("persist.sys.locale", "pt-BR");
@ -137,7 +140,7 @@ TEST(persistent_properties, UpdatePropertyBadParse) {
ASSERT_TRUE(tf.fd != -1);
persistent_property_filename = tf.path;
ASSERT_TRUE(WriteFile(tf.path, "ab"));
ASSERT_RESULT_OK(WriteFile(tf.path, "ab"));
WritePersistentProperty("persist.sys.locale", "pt-BR");

View file

@ -153,7 +153,7 @@ static void SendPropertyChanged(const std::string& name, const std::string& valu
changed_message->set_name(name);
changed_message->set_value(value);
if (auto result = SendMessage(init_socket, property_msg); !result) {
if (auto result = SendMessage(init_socket, property_msg); !result.ok()) {
LOG(ERROR) << "Failed to send property changed message: " << result.error();
}
}
@ -166,7 +166,7 @@ static uint32_t PropertySet(const std::string& name, const std::string& value, s
return PROP_ERROR_INVALID_NAME;
}
if (auto result = IsLegalPropertyValue(name, value); !result) {
if (auto result = IsLegalPropertyValue(name, value); !result.ok()) {
*error = result.error().message();
return PROP_ERROR_INVALID_VALUE;
}
@ -392,7 +392,7 @@ static uint32_t SendControlMessage(const std::string& msg, const std::string& na
control_message->set_fd(fd);
}
if (auto result = SendMessage(init_socket, property_msg); !result) {
if (auto result = SendMessage(init_socket, property_msg); !result.ok()) {
// We've already released the fd above, so if we fail to send the message to init, we need
// to manually free it here.
if (fd != -1) {
@ -670,7 +670,7 @@ static void LoadProperties(char* data, const char* filter, const char* filename,
std::string raw_filename(fn);
auto expanded_filename = ExpandProps(raw_filename);
if (!expanded_filename) {
if (!expanded_filename.ok()) {
LOG(ERROR) << "Could not expand filename ': " << expanded_filename.error();
continue;
}
@ -726,7 +726,7 @@ static bool load_properties_from_file(const char* filename, const char* filter,
std::map<std::string, std::string>* properties) {
Timer t;
auto file_contents = ReadFile(filename);
if (!file_contents) {
if (!file_contents.ok()) {
PLOG(WARNING) << "Couldn't load property file '" << filename
<< "': " << file_contents.error();
return false;
@ -1084,7 +1084,7 @@ void PropertyInit() {
static void HandleInitSocket() {
auto message = ReadMessage(init_socket);
if (!message) {
if (!message.ok()) {
LOG(ERROR) << "Could not read message from init_dedicated_recv_socket: " << message.error();
return;
}
@ -1123,21 +1123,22 @@ static void HandleInitSocket() {
static void PropertyServiceThread() {
Epoll epoll;
if (auto result = epoll.Open(); !result) {
if (auto result = epoll.Open(); !result.ok()) {
LOG(FATAL) << result.error();
}
if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd); !result) {
if (auto result = epoll.RegisterHandler(property_set_fd, handle_property_set_fd);
!result.ok()) {
LOG(FATAL) << result.error();
}
if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result) {
if (auto result = epoll.RegisterHandler(init_socket, HandleInitSocket); !result.ok()) {
LOG(FATAL) << result.error();
}
while (true) {
auto pending_functions = epoll.Wait(std::nullopt);
if (!pending_functions) {
if (!pending_functions.ok()) {
LOG(ERROR) << pending_functions.error();
} else {
for (const auto& function : *pending_functions) {
@ -1159,7 +1160,8 @@ void StartPropertyService(int* epoll_socket) {
accept_messages = true;
if (auto result = CreateSocket(PROP_SERVICE_NAME, SOCK_STREAM | SOCK_CLOEXEC | SOCK_NONBLOCK,
false, 0666, 0, 0, {})) {
false, 0666, 0, 0, {});
result.ok()) {
property_set_fd = *result;
} else {
LOG(FATAL) << "start_property_service socket creation failed: " << result.error();

View file

@ -180,7 +180,7 @@ static void TurnOffBacklight() {
LOG(WARNING) << "cannot find blank_screen in TurnOffBacklight";
return;
}
if (auto result = service->Start(); !result) {
if (auto result = service->Start(); !result.ok()) {
LOG(WARNING) << "Could not start blank_screen service: " << result.error();
}
}
@ -591,14 +591,14 @@ static void DoReboot(unsigned int cmd, const std::string& reason, const std::str
// keep debugging tools until non critical ones are all gone.
s->SetShutdownCritical();
} else if (to_starts.count(s->name())) {
if (auto result = s->Start(); !result) {
if (auto result = s->Start(); !result.ok()) {
LOG(ERROR) << "Could not start shutdown 'to_start' service '" << s->name()
<< "': " << result.error();
}
s->SetShutdownCritical();
} else if (s->IsShutdownCritical()) {
// Start shutdown critical service if not started.
if (auto result = s->Start(); !result) {
if (auto result = s->Start(); !result.ok()) {
LOG(ERROR) << "Could not start shutdown critical service '" << s->name()
<< "': " << result.error();
}
@ -776,10 +776,10 @@ static Result<void> DoUserspaceReboot() {
// TODO(b/135984674): store information about offending services for debugging.
return Error() << r << " post-data services are still running";
}
if (auto result = KillZramBackingDevice(); !result) {
if (auto result = KillZramBackingDevice(); !result.ok()) {
return result;
}
if (auto result = CallVdc("volume", "reset"); !result) {
if (auto result = CallVdc("volume", "reset"); !result.ok()) {
return result;
}
if (int r = StopServicesAndLogViolations(GetDebuggingServices(true /* only_post_data */), 5s,
@ -794,7 +794,7 @@ static Result<void> DoUserspaceReboot() {
sync();
LOG(INFO) << "sync() took " << sync_timer;
}
if (auto result = UnmountAllApexes(); !result) {
if (auto result = UnmountAllApexes(); !result.ok()) {
return result;
}
if (!SwitchToBootstrapMountNamespaceIfNeeded()) {

View file

@ -29,7 +29,7 @@ void TestRlimitSuccess(std::vector<std::string> input,
ASSERT_EQ(4U, input.size());
auto result = ParseRlimit(input);
ASSERT_TRUE(result) << "input: " << input[1];
ASSERT_TRUE(result.ok()) << "input: " << input[1];
const auto& [resource, rlimit] = *result;
const auto& [expected_resource, expected_rlimit] = expected_result;
EXPECT_EQ(expected_resource, resource);
@ -42,7 +42,7 @@ void TestRlimitFailure(std::vector<std::string> input, const std::string& expect
ASSERT_EQ(4U, input.size());
auto result = ParseRlimit(input);
ASSERT_FALSE(result) << "input: " << input[1];
ASSERT_FALSE(result.ok()) << "input: " << input[1];
EXPECT_EQ(expected_result, result.error().message());
EXPECT_EQ(0, result.error().code());
}

View file

@ -477,7 +477,7 @@ void SelinuxInitialize() {
}
}
if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result) {
if (auto result = WriteFile("/sys/fs/selinux/checkreqprot", "0"); !result.ok()) {
LOG(FATAL) << "Unable to write to /sys/fs/selinux/checkreqprot: " << result.error();
}
}

View file

@ -106,7 +106,7 @@ static bool ExpandArgsAndExecv(const std::vector<std::string>& args, bool sigsto
c_strings.push_back(const_cast<char*>(args[0].data()));
for (std::size_t i = 1; i < args.size(); ++i) {
auto expanded_arg = ExpandProps(args[i]);
if (!expanded_arg) {
if (!expanded_arg.ok()) {
LOG(FATAL) << args[0] << ": cannot expand arguments': " << expanded_arg.error();
}
expanded_args[i] = *expanded_arg;
@ -232,7 +232,7 @@ void Service::SetProcessAttributesAndCaps() {
}
}
if (auto result = SetProcessAttributes(proc_attr_); !result) {
if (auto result = SetProcessAttributes(proc_attr_); !result.ok()) {
LOG(FATAL) << "cannot set attribute for " << name_ << ": " << result.error();
}
@ -374,7 +374,7 @@ Result<void> Service::ExecStart() {
flags_ |= SVC_ONESHOT;
if (auto result = Start(); !result) {
if (auto result = Start(); !result.ok()) {
return result;
}
@ -449,7 +449,7 @@ Result<void> Service::Start() {
scon = seclabel_;
} else {
auto result = ComputeContextFromExecutable(args_[0]);
if (!result) {
if (!result.ok()) {
return result.error();
}
scon = *result;
@ -469,7 +469,7 @@ Result<void> Service::Start() {
std::vector<Descriptor> descriptors;
for (const auto& socket : sockets_) {
if (auto result = socket.Create(scon)) {
if (auto result = socket.Create(scon); result.ok()) {
descriptors.emplace_back(std::move(*result));
} else {
LOG(INFO) << "Could not create socket '" << socket.name << "': " << result.error();
@ -477,7 +477,7 @@ Result<void> Service::Start() {
}
for (const auto& file : files_) {
if (auto result = file.Create()) {
if (auto result = file.Create(); result.ok()) {
descriptors.emplace_back(std::move(*result));
} else {
LOG(INFO) << "Could not open file '" << file.name << "': " << result.error();
@ -494,7 +494,7 @@ Result<void> Service::Start() {
if (pid == 0) {
umask(077);
if (auto result = EnterNamespaces(namespaces_, name_, pre_apexd_); !result) {
if (auto result = EnterNamespaces(namespaces_, name_, pre_apexd_); !result.ok()) {
LOG(FATAL) << "Service '" << name_
<< "' failed to set up namespaces: " << result.error();
}
@ -507,7 +507,7 @@ Result<void> Service::Start() {
descriptor.Publish();
}
if (auto result = WritePidToFiles(&writepid_files_); !result) {
if (auto result = WritePidToFiles(&writepid_files_); !result.ok()) {
LOG(ERROR) << "failed to write pid to files: " << result.error();
}
@ -669,7 +669,7 @@ void Service::Restart() {
StopOrReset(SVC_RESTART);
} else if (!(flags_ & SVC_RESTARTING)) {
/* Just start the service since it's not running. */
if (auto result = Start(); !result) {
if (auto result = Start(); !result.ok()) {
LOG(ERROR) << "Could not restart '" << name_ << "': " << result.error();
}
} /* else: Service is restarting anyways. */
@ -742,7 +742,7 @@ Result<std::unique_ptr<Service>> Service::MakeTemporaryOneshotService(
Result<uid_t> uid = 0;
if (command_arg > 3) {
uid = DecodeUid(args[2]);
if (!uid) {
if (!uid.ok()) {
return Error() << "Unable to decode UID for '" << args[2] << "': " << uid.error();
}
}
@ -750,13 +750,13 @@ Result<std::unique_ptr<Service>> Service::MakeTemporaryOneshotService(
std::vector<gid_t> supp_gids;
if (command_arg > 4) {
gid = DecodeUid(args[3]);
if (!gid) {
if (!gid.ok()) {
return Error() << "Unable to decode GID for '" << args[3] << "': " << gid.error();
}
std::size_t nr_supp_gids = command_arg - 1 /* -- */ - 4 /* exec SECLABEL UID GID */;
for (size_t i = 0; i < nr_supp_gids; ++i) {
auto supp_gid = DecodeUid(args[4 + i]);
if (!supp_gid) {
if (!supp_gid.ok()) {
return Error() << "Unable to decode GID for '" << args[4 + i]
<< "': " << supp_gid.error();
}

View file

@ -86,7 +86,7 @@ void ServiceList::MarkServicesUpdate() {
LOG(ERROR) << "delayed service '" << name << "' could not be found.";
continue;
}
if (auto result = service->Start(); !result) {
if (auto result = service->Start(); !result.ok()) {
LOG(ERROR) << result.error().message();
}
}

View file

@ -119,14 +119,14 @@ Result<void> ServiceParser::ParseEnterNamespace(std::vector<std::string>&& args)
Result<void> ServiceParser::ParseGroup(std::vector<std::string>&& args) {
auto gid = DecodeUid(args[1]);
if (!gid) {
if (!gid.ok()) {
return Error() << "Unable to decode GID for '" << args[1] << "': " << gid.error();
}
service_->proc_attr_.gid = *gid;
for (std::size_t n = 2; n < args.size(); n++) {
gid = DecodeUid(args[n]);
if (!gid) {
if (!gid.ok()) {
return Error() << "Unable to decode GID for '" << args[n] << "': " << gid.error();
}
service_->proc_attr_.supp_gids.emplace_back(*gid);
@ -202,7 +202,7 @@ Result<void> ServiceParser::ParseKeycodes(std::vector<std::string>&& args) {
auto it = args.begin() + 1;
if (args.size() == 2 && StartsWith(args[1], "$")) {
auto expanded = ExpandProps(args[1]);
if (!expanded) {
if (!expanded.ok()) {
return expanded.error();
}
@ -240,7 +240,7 @@ Result<void> ServiceParser::ParseOneshot(std::vector<std::string>&& args) {
Result<void> ServiceParser::ParseOnrestart(std::vector<std::string>&& args) {
args.erase(args.begin());
int line = service_->onrestart_.NumCommands() + 1;
if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result) {
if (auto result = service_->onrestart_.AddCommand(std::move(args), line); !result.ok()) {
return Error() << "cannot add Onrestart command: " << result.error();
}
return {};
@ -310,7 +310,7 @@ Result<void> ServiceParser::ParseMemcgSoftLimitInBytes(std::vector<std::string>&
Result<void> ServiceParser::ParseProcessRlimit(std::vector<std::string>&& args) {
auto rlimit = ParseRlimit(args);
if (!rlimit) return rlimit.error();
if (!rlimit.ok()) return rlimit.error();
service_->proc_attr_.rlimits.emplace_back(*rlimit);
return {};
@ -407,7 +407,7 @@ Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
if (args.size() > 4) {
auto uid = DecodeUid(args[4]);
if (!uid) {
if (!uid.ok()) {
return Error() << "Unable to find UID for '" << args[4] << "': " << uid.error();
}
socket.uid = *uid;
@ -415,7 +415,7 @@ Result<void> ServiceParser::ParseSocket(std::vector<std::string>&& args) {
if (args.size() > 5) {
auto gid = DecodeUid(args[5]);
if (!gid) {
if (!gid.ok()) {
return Error() << "Unable to find GID for '" << args[5] << "': " << gid.error();
}
socket.gid = *gid;
@ -453,7 +453,7 @@ Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
file.type = args[2];
auto file_name = ExpandProps(args[1]);
if (!file_name) {
if (!file_name.ok()) {
return Error() << "Could not expand file path ': " << file_name.error();
}
file.name = *file_name;
@ -475,7 +475,7 @@ Result<void> ServiceParser::ParseFile(std::vector<std::string>&& args) {
Result<void> ServiceParser::ParseUser(std::vector<std::string>&& args) {
auto uid = DecodeUid(args[1]);
if (!uid) {
if (!uid.ok()) {
return Error() << "Unable to find UID for '" << args[1] << "': " << uid.error();
}
service_->proc_attr_.uid = *uid;
@ -580,7 +580,7 @@ Result<void> ServiceParser::ParseLineSection(std::vector<std::string>&& args, in
auto parser = GetParserMap().Find(args);
if (!parser) return parser.error();
if (!parser.ok()) return parser.error();
return std::invoke(*parser, this, std::move(args));
}
@ -593,7 +593,7 @@ Result<void> ServiceParser::EndSection() {
if (interface_inheritance_hierarchy_) {
if (const auto& check_hierarchy_result = CheckInterfaceInheritanceHierarchy(
service_->interfaces(), *interface_inheritance_hierarchy_);
!check_hierarchy_result) {
!check_hierarchy_result.ok()) {
return Error() << check_hierarchy_result.error();
}
}

View file

@ -76,15 +76,15 @@ TEST(service, pod_initialized) {
TEST(service, make_temporary_oneshot_service_invalid_syntax) {
std::vector<std::string> args;
// Nothing.
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args));
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args).ok());
// No arguments to 'exec'.
args.push_back("exec");
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args));
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args).ok());
// No command in "exec --".
args.push_back("--");
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args));
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args).ok());
}
TEST(service, make_temporary_oneshot_service_too_many_supplementary_gids) {
@ -98,7 +98,7 @@ TEST(service, make_temporary_oneshot_service_too_many_supplementary_gids) {
}
args.push_back("--");
args.push_back("/system/bin/id");
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args));
ASSERT_FALSE(Service::MakeTemporaryOneshotService(args).ok());
}
static void Test_make_temporary_oneshot_service(bool dash_dash, bool seclabel, bool uid, bool gid,
@ -124,7 +124,7 @@ static void Test_make_temporary_oneshot_service(bool dash_dash, bool seclabel, b
args.push_back("/system/bin/toybox");
args.push_back("id");
auto service_ret = Service::MakeTemporaryOneshotService(args);
ASSERT_TRUE(service_ret);
ASSERT_RESULT_OK(service_ret);
auto svc = std::move(*service_ret);
if (seclabel) {
@ -134,14 +134,14 @@ static void Test_make_temporary_oneshot_service(bool dash_dash, bool seclabel, b
}
if (uid) {
auto decoded_uid = DecodeUid("log");
ASSERT_TRUE(decoded_uid);
ASSERT_RESULT_OK(decoded_uid);
ASSERT_EQ(*decoded_uid, svc->uid());
} else {
ASSERT_EQ(0U, svc->uid());
}
if (gid) {
auto decoded_uid = DecodeUid("shell");
ASSERT_TRUE(decoded_uid);
ASSERT_RESULT_OK(decoded_uid);
ASSERT_EQ(*decoded_uid, svc->gid());
} else {
ASSERT_EQ(0U, svc->gid());
@ -150,11 +150,11 @@ static void Test_make_temporary_oneshot_service(bool dash_dash, bool seclabel, b
ASSERT_EQ(2U, svc->supp_gids().size());
auto decoded_uid = DecodeUid("system");
ASSERT_TRUE(decoded_uid);
ASSERT_RESULT_OK(decoded_uid);
ASSERT_EQ(*decoded_uid, svc->supp_gids()[0]);
decoded_uid = DecodeUid("adb");
ASSERT_TRUE(decoded_uid);
ASSERT_RESULT_OK(decoded_uid);
ASSERT_EQ(*decoded_uid, svc->supp_gids()[1]);
} else {
ASSERT_EQ(0U, svc->supp_gids().size());

View file

@ -167,7 +167,7 @@ void Descriptor::Publish() const {
Result<Descriptor> SocketDescriptor::Create(const std::string& global_context) const {
const auto& socket_context = context.empty() ? global_context : context;
auto result = CreateSocket(name, type | SOCK_CLOEXEC, passcred, perm, uid, gid, socket_context);
if (!result) {
if (!result.ok()) {
return result.error();
}
@ -196,7 +196,7 @@ Result<Descriptor> FileDescriptor::Create() const {
Result<void> EnterNamespaces(const NamespaceInfo& info, const std::string& name, bool pre_apexd) {
for (const auto& [nstype, path] : info.namespaces_to_enter) {
if (auto result = EnterNamespace(nstype, path.c_str()); !result) {
if (auto result = EnterNamespace(nstype, path.c_str()); !result.ok()) {
return result;
}
}
@ -214,14 +214,14 @@ Result<void> EnterNamespaces(const NamespaceInfo& info, const std::string& name,
bool remount_sys =
std::any_of(info.namespaces_to_enter.begin(), info.namespaces_to_enter.end(),
[](const auto& entry) { return entry.first == CLONE_NEWNET; });
if (auto result = SetUpMountNamespace(remount_proc, remount_sys); !result) {
if (auto result = SetUpMountNamespace(remount_proc, remount_sys); !result.ok()) {
return result;
}
}
if (info.flags & CLONE_NEWPID) {
// This will fork again to run an init process inside the PID namespace.
if (auto result = SetUpPidNamespace(name.c_str()); !result) {
if (auto result = SetUpPidNamespace(name.c_str()); !result.ok()) {
return result;
}
}

View file

@ -80,13 +80,13 @@ void SubcontextProcess::RunCommand(const SubcontextCommand::ExecuteCommand& exec
auto map_result = function_map_->Find(args);
Result<void> result;
if (!map_result) {
if (!map_result.ok()) {
result = Error() << "Cannot find command: " << map_result.error();
} else {
result = RunBuiltinFunction(map_result->function, args, context_);
}
if (result) {
if (result.ok()) {
reply->set_success(true);
} else {
auto* failure = reply->mutable_failure();
@ -99,7 +99,7 @@ void SubcontextProcess::ExpandArgs(const SubcontextCommand::ExpandArgsCommand& e
SubcontextReply* reply) const {
for (const auto& arg : expand_args_command.args()) {
auto expanded_arg = ExpandProps(arg);
if (!expanded_arg) {
if (!expanded_arg.ok()) {
auto* failure = reply->mutable_failure();
failure->set_error_string(expanded_arg.error().message());
failure->set_error_errno(0);
@ -125,7 +125,7 @@ void SubcontextProcess::MainLoop() {
}
auto init_message = ReadMessage(init_fd_);
if (!init_message) {
if (!init_message.ok()) {
if (init_message.error().code() == 0) {
// If the init file descriptor was closed, let's exit quietly. If
// this was accidental, init will restart us. If init died, this
@ -160,7 +160,7 @@ void SubcontextProcess::MainLoop() {
shutdown_command.clear();
}
if (auto result = SendMessage(init_fd_, reply); !result) {
if (auto result = SendMessage(init_fd_, reply); !result.ok()) {
LOG(FATAL) << "Failed to send message to init: " << result.error();
}
}
@ -246,13 +246,13 @@ bool Subcontext::PathMatchesSubcontext(const std::string& path) {
}
Result<SubcontextReply> Subcontext::TransmitMessage(const SubcontextCommand& subcontext_command) {
if (auto result = SendMessage(socket_, subcontext_command); !result) {
if (auto result = SendMessage(socket_, subcontext_command); !result.ok()) {
Restart();
return ErrnoError() << "Failed to send message to subcontext";
}
auto subcontext_message = ReadMessage(socket_);
if (!subcontext_message) {
if (!subcontext_message.ok()) {
Restart();
return Error() << "Failed to receive result from subcontext: " << subcontext_message.error();
}
@ -277,7 +277,7 @@ Result<void> Subcontext::Execute(const std::vector<std::string>& args) {
RepeatedPtrFieldBackInserter(subcontext_command.mutable_execute_command()->mutable_args()));
auto subcontext_reply = TransmitMessage(subcontext_command);
if (!subcontext_reply) {
if (!subcontext_reply.ok()) {
return subcontext_reply.error();
}
@ -301,7 +301,7 @@ Result<std::vector<std::string>> Subcontext::ExpandArgs(const std::vector<std::s
subcontext_command.mutable_expand_args_command()->mutable_args()));
auto subcontext_reply = TransmitMessage(subcontext_command);
if (!subcontext_reply) {
if (!subcontext_reply.ok()) {
return subcontext_reply.error();
}

View file

@ -55,7 +55,7 @@ void RunTest(F&& test_function) {
TEST(subcontext, CheckDifferentPid) {
RunTest([](auto& subcontext) {
auto result = subcontext.Execute(std::vector<std::string>{"return_pids_as_error"});
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
auto pids = Split(result.error().message(), " ");
ASSERT_EQ(2U, pids.size());
@ -81,7 +81,7 @@ TEST(subcontext, SetProp) {
"success",
};
auto result = subcontext.Execute(args);
ASSERT_TRUE(result) << result.error();
ASSERT_RESULT_OK(result);
EXPECT_TRUE(WaitForProperty("init.test.subcontext", "success", 10s));
});
@ -104,11 +104,11 @@ TEST(subcontext, MultipleCommands) {
word,
};
auto result = subcontext.Execute(args);
ASSERT_TRUE(result) << result.error();
ASSERT_RESULT_OK(result);
}
auto result = subcontext.Execute(std::vector<std::string>{"return_words_as_error"});
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
EXPECT_EQ(Join(expected_words, " "), result.error().message());
EXPECT_EQ(first_pid, subcontext.pid());
});
@ -119,10 +119,10 @@ TEST(subcontext, RecoverAfterAbort) {
auto first_pid = subcontext.pid();
auto result = subcontext.Execute(std::vector<std::string>{"cause_log_fatal"});
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
auto result2 = subcontext.Execute(std::vector<std::string>{"generate_sane_error"});
ASSERT_FALSE(result2);
ASSERT_FALSE(result2.ok());
EXPECT_EQ("Sane error!", result2.error().message());
EXPECT_NE(subcontext.pid(), first_pid);
});
@ -131,7 +131,7 @@ TEST(subcontext, RecoverAfterAbort) {
TEST(subcontext, ContextString) {
RunTest([](auto& subcontext) {
auto result = subcontext.Execute(std::vector<std::string>{"return_context_as_error"});
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
ASSERT_EQ(kTestContext, result.error().message());
});
}
@ -143,7 +143,7 @@ TEST(subcontext, TriggerShutdown) {
RunTest([](auto& subcontext) {
auto result = subcontext.Execute(
std::vector<std::string>{"trigger_shutdown", kTestShutdownCommand});
ASSERT_TRUE(result);
ASSERT_RESULT_OK(result);
});
EXPECT_EQ(kTestShutdownCommand, trigger_shutdown_command);
}
@ -156,7 +156,7 @@ TEST(subcontext, ExpandArgs) {
"$$third",
};
auto result = subcontext.ExpandArgs(args);
ASSERT_TRUE(result) << result.error();
ASSERT_RESULT_OK(result);
ASSERT_EQ(3U, result->size());
EXPECT_EQ(args[0], result->at(0));
EXPECT_EQ(GetProperty("ro.hardware", ""), result->at(1));
@ -171,7 +171,7 @@ TEST(subcontext, ExpandArgsFailure) {
"${",
};
auto result = subcontext.ExpandArgs(args);
ASSERT_FALSE(result);
ASSERT_FALSE(result.ok());
EXPECT_EQ("unexpected end of string in '" + args[1] + "', looking for }",
result.error().message());
});

View file

@ -209,7 +209,7 @@ Result<void> SubsystemParser::ParseLineSection(std::vector<std::string>&& args,
auto parser = parser_map.Find(args);
if (!parser) return Error() << parser.error();
if (!parser.ok()) return Error() << parser.error();
return std::invoke(*parser, this, std::move(args));
}

View file

@ -497,14 +497,14 @@ Result<MkdirOptions> ParseMkdir(const std::vector<std::string>& args) {
break;
case 3:
uid = DecodeUid(args[3]);
if (!uid) {
if (!uid.ok()) {
return Error()
<< "Unable to decode UID for '" << args[3] << "': " << uid.error();
}
break;
case 4:
gid = DecodeUid(args[4]);
if (!gid) {
if (!gid.ok()) {
return Error()
<< "Unable to decode GID for '" << args[4] << "': " << gid.error();
}

View file

@ -33,7 +33,7 @@ TEST(util, ReadFile_ENOENT) {
errno = 0;
auto file_contents = ReadFile("/proc/does-not-exist");
EXPECT_EQ(ENOENT, errno);
ASSERT_FALSE(file_contents);
ASSERT_FALSE(file_contents.ok());
EXPECT_EQ("open() failed: No such file or directory", file_contents.error().message());
}
@ -41,10 +41,10 @@ TEST(util, ReadFileGroupWriteable) {
std::string s("hello");
TemporaryFile tf;
ASSERT_TRUE(tf.fd != -1);
EXPECT_TRUE(WriteFile(tf.path, s)) << strerror(errno);
EXPECT_RESULT_OK(WriteFile(tf.path, s));
EXPECT_NE(-1, fchmodat(AT_FDCWD, tf.path, 0620, AT_SYMLINK_NOFOLLOW)) << strerror(errno);
auto file_contents = ReadFile(tf.path);
ASSERT_FALSE(file_contents) << strerror(errno);
ASSERT_FALSE(file_contents.ok()) << strerror(errno);
EXPECT_EQ("Skipping insecure file", file_contents.error().message());
}
@ -52,10 +52,10 @@ TEST(util, ReadFileWorldWiteable) {
std::string s("hello");
TemporaryFile tf;
ASSERT_TRUE(tf.fd != -1);
EXPECT_TRUE(WriteFile(tf.path, s)) << strerror(errno);
EXPECT_RESULT_OK(WriteFile(tf.path, s));
EXPECT_NE(-1, fchmodat(AT_FDCWD, tf.path, 0602, AT_SYMLINK_NOFOLLOW)) << strerror(errno);
auto file_contents = ReadFile(tf.path);
ASSERT_FALSE(file_contents) << strerror(errno);
ASSERT_FALSE(file_contents.ok());
EXPECT_EQ("Skipping insecure file", file_contents.error().message());
}
@ -64,14 +64,14 @@ TEST(util, ReadFileSymbolicLink) {
// lrw------- 1 root root 23 2008-12-31 19:00 default.prop -> system/etc/prop.default
auto file_contents = ReadFile("/default.prop");
EXPECT_EQ(ELOOP, errno);
ASSERT_FALSE(file_contents);
ASSERT_FALSE(file_contents.ok());
EXPECT_EQ("open() failed: Too many symbolic links encountered",
file_contents.error().message());
}
TEST(util, ReadFileSuccess) {
auto file_contents = ReadFile("/proc/version");
ASSERT_TRUE(file_contents);
ASSERT_TRUE(file_contents.ok());
EXPECT_GT(file_contents->length(), 6U);
EXPECT_EQ('\n', file_contents->at(file_contents->length() - 1));
(*file_contents)[5] = 0;
@ -87,10 +87,10 @@ TEST(util, WriteFileBinary) {
TemporaryFile tf;
ASSERT_TRUE(tf.fd != -1);
EXPECT_TRUE(WriteFile(tf.path, contents)) << strerror(errno);
EXPECT_RESULT_OK(WriteFile(tf.path, contents));
auto read_back_contents = ReadFile(tf.path);
ASSERT_TRUE(read_back_contents) << strerror(errno);
ASSERT_RESULT_OK(read_back_contents);
EXPECT_EQ(contents, *read_back_contents);
EXPECT_EQ(10u, read_back_contents->size());
}
@ -99,14 +99,15 @@ TEST(util, WriteFileNotExist) {
std::string s("hello");
TemporaryDir test_dir;
std::string path = android::base::StringPrintf("%s/does-not-exist", test_dir.path);
EXPECT_TRUE(WriteFile(path, s));
EXPECT_RESULT_OK(WriteFile(path, s));
auto file_contents = ReadFile(path);
ASSERT_TRUE(file_contents);
ASSERT_RESULT_OK(file_contents);
EXPECT_EQ(s, *file_contents);
struct stat sb;
int fd = open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);
EXPECT_NE(-1, fd);
EXPECT_EQ(0, fstat(fd, &sb));
EXPECT_EQ(0, close(fd));
EXPECT_EQ((const unsigned int)(S_IRUSR | S_IWUSR), sb.st_mode & 0777);
EXPECT_EQ(0, unlink(path.c_str()));
}
@ -114,27 +115,27 @@ TEST(util, WriteFileNotExist) {
TEST(util, WriteFileExist) {
TemporaryFile tf;
ASSERT_TRUE(tf.fd != -1);
EXPECT_TRUE(WriteFile(tf.path, "1hello1")) << strerror(errno);
EXPECT_RESULT_OK(WriteFile(tf.path, "1hello1"));
auto file_contents = ReadFile(tf.path);
ASSERT_TRUE(file_contents);
ASSERT_RESULT_OK(file_contents);
EXPECT_EQ("1hello1", *file_contents);
EXPECT_TRUE(WriteFile(tf.path, "2ll2"));
EXPECT_RESULT_OK(WriteFile(tf.path, "2ll2"));
file_contents = ReadFile(tf.path);
ASSERT_TRUE(file_contents);
ASSERT_RESULT_OK(file_contents);
EXPECT_EQ("2ll2", *file_contents);
}
TEST(util, DecodeUid) {
auto decoded_uid = DecodeUid("root");
EXPECT_TRUE(decoded_uid);
EXPECT_TRUE(decoded_uid.ok());
EXPECT_EQ(0U, *decoded_uid);
decoded_uid = DecodeUid("toot");
EXPECT_FALSE(decoded_uid);
EXPECT_FALSE(decoded_uid.ok());
EXPECT_EQ("getpwnam failed: No such file or directory", decoded_uid.error().message());
decoded_uid = DecodeUid("123");
EXPECT_TRUE(decoded_uid);
EXPECT_RESULT_OK(decoded_uid);
EXPECT_EQ(123U, *decoded_uid);
}