[Feature] Optimization in launchAsRoot function
[Cause] There is no need to fork when we are already launched as root
[Solution] Call func directly when UID is 0
[Verification] Build, install, run tests
Change-Id: I25453b18329d1c5f353e4303d82836943d19528b
bool launchAsRoot(const std::function<bool()>& func)
{
- // TODO optimize if getuid() == 0
- return executeAndWait([&func]() {
- if (::setuid(0) < 0) {
- LOGW("Failed to become root: " << getSystemErrorMessage());
- _exit(EXIT_FAILURE);
- }
-
- if (!func()) {
- LOGE("Failed to successfully execute func");
- _exit(EXIT_FAILURE);
- }
- });
+ if (::getuid() == 0) {
+ // we are already root, no need to fork
+ return func();
+ } else {
+ return executeAndWait([&func]() {
+ if (::setuid(0) < 0) {
+ LOGW("Failed to become root: " << getSystemErrorMessage());
+ _exit(EXIT_FAILURE);
+ }
+
+ if (!func()) {
+ LOGE("Failed to successfully execute func");
+ _exit(EXIT_FAILURE);
+ }
+ });
+ }
}
bool joinToNs(int nsPid, int ns)