Close profile before leaving android::installd::clear_profile.

The profile file descriptor used to be kept open and to
produce SElinux denials when installd ran dex2oat, as that
file descriptor was passed accross security domains.

Bug: 27943553
Change-Id: Ie025082f97c2736156bd5069d7a22aacde86f039
diff --git a/cmds/installd/commands.cpp b/cmds/installd/commands.cpp
index 95bc4b9..2bfea63 100644
--- a/cmds/installd/commands.cpp
+++ b/cmds/installd/commands.cpp
@@ -30,6 +30,7 @@
 
 #include <android-base/stringprintf.h>
 #include <android-base/logging.h>
+#include <android-base/unique_fd.h>
 #include <cutils/fs.h>
 #include <cutils/log.h>               // TODO: Move everything to base/logging.
 #include <cutils/sched_policy.h>
@@ -162,8 +163,8 @@
 }
 
 static bool clear_profile(const std::string& profile) {
-    fd_t fd = open(profile.c_str(), O_WRONLY | O_NOFOLLOW);
-    if (fd < 0) {
+    base::unique_fd ufd(open(profile.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
+    if (ufd.get() < 0) {
         if (errno != ENOENT) {
             PLOG(WARNING) << "Could not open profile " << profile;
             return false;
@@ -173,7 +174,7 @@
         }
     }
 
-    if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
+    if (flock(ufd.get(), LOCK_EX | LOCK_NB) != 0) {
         if (errno != EWOULDBLOCK) {
             PLOG(WARNING) << "Error locking profile " << profile;
         }
@@ -195,11 +196,11 @@
         return false;
     }
 
-    bool truncated = ftruncate(fd, 0) == 0;
+    bool truncated = ftruncate(ufd.get(), 0) == 0;
     if (!truncated) {
         PLOG(WARNING) << "Could not truncate " << profile;
     }
-    if (flock(fd, LOCK_UN) != 0) {
+    if (flock(ufd.get(), LOCK_UN) != 0) {
         PLOG(WARNING) << "Error unlocking profile " << profile;
     }
     return truncated;