Merge "Call fsync after init writes to install_status."
diff --git a/libgsi.cpp b/libgsi.cpp
index 13a18fe..fdb147e 100644
--- a/libgsi.cpp
+++ b/libgsi.cpp
@@ -23,6 +23,7 @@
 
 #include <android-base/file.h>
 #include <android-base/parseint.h>
+#include <android-base/unique_fd.h>
 
 #include "file_paths.h"
 #include "libgsi_private.h"
@@ -31,6 +32,7 @@
 namespace gsi {
 
 using namespace std::literals;
+using android::base::unique_fd;
 
 bool IsGsiRunning() {
     return !access(kGsiBootedIndicatorFile, F_OK);
@@ -44,6 +46,17 @@
 // will bring the device back to its normal system image.
 static constexpr bool kOnlyAllowSingleBoot = true;
 
+static bool WriteAndSyncFile(const std::string& data, const std::string& file) {
+    unique_fd fd(open(file.c_str(), O_WRONLY | O_NOFOLLOW | O_CLOEXEC));
+    if (fd < 0) {
+        return false;
+    }
+    if (!android::base::WriteFully(fd, data.c_str(), data.size())) {
+        return false;
+    }
+    return fsync(fd) == 0;
+}
+
 static bool CanBootIntoGsi(std::string* error) {
     if (!IsGsiInstalled()) {
         *error = "not detected";
@@ -72,7 +85,7 @@
         } else {
             new_key = std::to_string(attempts + 1);
         }
-        if (!android::base::WriteStringToFile(new_key, kGsiInstallStatusFile)) {
+        if (!WriteAndSyncFile(new_key, kGsiInstallStatusFile)) {
             *error = "error ("s + strerror(errno) + ")";
             return false;
         }