From 3479483f4debddc67aca0c3edec2a8d06ed03911 Mon Sep 17 00:00:00 2001 From: Lukasz Kostyra Date: Tue, 7 Apr 2015 10:54:00 +0200 Subject: [PATCH] Optimize launchAsRoot when UID is 0 [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 --- common/utils/environment.cpp | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/common/utils/environment.cpp b/common/utils/environment.cpp index fc45321..511fcda 100644 --- a/common/utils/environment.cpp +++ b/common/utils/environment.cpp @@ -177,18 +177,22 @@ bool dropRoot(uid_t uid, gid_t gid, const std::vector& caps) bool launchAsRoot(const std::function& 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) -- 2.7.4