Snap for 4448085 from 7ce9f66723ff5f2fd2704ee2fd37e56b72e19bea to oc-m3-release

Change-Id: I8870e695f59155fa1584a8fc0ae71d275227ed74
diff --git a/EmulatedVolume.cpp b/EmulatedVolume.cpp
index df91904..21b290a 100644
--- a/EmulatedVolume.cpp
+++ b/EmulatedVolume.cpp
@@ -84,6 +84,7 @@
                 "-g", "1023", // AID_MEDIA_RW
                 "-m",
                 "-w",
+                "-G",
                 mRawPath.c_str(),
                 label.c_str(),
                 NULL)) {
diff --git a/KeyStorage.cpp b/KeyStorage.cpp
index 9d61555..20b2391 100644
--- a/KeyStorage.cpp
+++ b/KeyStorage.cpp
@@ -35,6 +35,7 @@
 
 #include <android-base/file.h>
 #include <android-base/logging.h>
+#include <android-base/unique_fd.h>
 
 #include <cutils/properties.h>
 
@@ -153,10 +154,29 @@
 }
 
 static bool writeStringToFile(const std::string& payload, const std::string& filename) {
-    if (!android::base::WriteStringToFile(payload, filename)) {
-        PLOG(ERROR) << "Failed to write to " << filename;
+    android::base::unique_fd fd(TEMP_FAILURE_RETRY(
+        open(filename.c_str(), O_WRONLY | O_CREAT | O_NOFOLLOW | O_TRUNC | O_CLOEXEC, 0666)));
+    if (fd == -1) {
+        PLOG(ERROR) << "Failed to open " << filename;
         return false;
     }
+    if (!android::base::WriteStringToFd(payload, fd)) {
+        PLOG(ERROR) << "Failed to write to " << filename;
+        unlink(filename.c_str());
+        return false;
+    }
+    // fsync as close won't guarantee flush data
+    // see close(2), fsync(2) and b/68901441
+    if (fsync(fd) == -1) {
+        if (errno == EROFS || errno == EINVAL) {
+            PLOG(WARNING) << "Skip fsync " << filename
+                          << " on a file system does not support synchronization";
+        } else {
+            PLOG(ERROR) << "Failed to fsync " << filename;
+            unlink(filename.c_str());
+            return false;
+        }
+    }
     return true;
 }
 
diff --git a/KeyUtil.cpp b/KeyUtil.cpp
index 7bbbf01..dbc73c1 100644
--- a/KeyUtil.cpp
+++ b/KeyUtil.cpp
@@ -98,7 +98,7 @@
 static std::string keyname(const std::string& prefix, const std::string& raw_ref) {
     std::ostringstream o;
     o << prefix << ":";
-    for (auto i : raw_ref) {
+    for (unsigned char i : raw_ref) {
         o << std::hex << std::setw(2) << std::setfill('0') << (int)i;
     }
     return o.str();