Optimize launchAsRoot when UID is 0 38/37838/2
authorLukasz Kostyra <l.kostyra@samsung.com>
Tue, 7 Apr 2015 08:54:00 +0000 (10:54 +0200)
committerDariusz Michaluk <d.michaluk@samsung.com>
Tue, 7 Apr 2015 11:28:22 +0000 (04:28 -0700)
[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

index fc45321..511fcda 100644 (file)
@@ -177,18 +177,22 @@ bool dropRoot(uid_t uid, gid_t gid, const std::vector<unsigned int>& caps)
 
 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)