fastboot: Mount /metadata before overlayfs teardown.

fs_mgr_overlayfs needs access to /metadata to tell whether or not the
scratch partition exists on /data.

Bug: 134949511
Test: adb remount, fastboot flash system
Change-Id: I3a09aae495d691e9c1a1e25a8fb3514e355ecd05
diff --git a/fastboot/device/utility.cpp b/fastboot/device/utility.cpp
index b3f2d5f..7c6ac89 100644
--- a/fastboot/device/utility.cpp
+++ b/fastboot/device/utility.cpp
@@ -26,6 +26,7 @@
 #include <android-base/properties.h>
 #include <android-base/strings.h>
 #include <fs_mgr.h>
+#include <fs_mgr/roots.h>
 #include <fs_mgr_dm_linear.h>
 #include <liblp/builder.h>
 #include <liblp/liblp.h>
@@ -240,3 +241,29 @@
     }
     return current_slot_suffix;
 }
+
+AutoMountMetadata::AutoMountMetadata() {
+    android::fs_mgr::Fstab proc_mounts;
+    if (!ReadFstabFromFile("/proc/mounts", &proc_mounts)) {
+        LOG(ERROR) << "Could not read /proc/mounts";
+        return;
+    }
+
+    if (GetEntryForMountPoint(&proc_mounts, "/metadata")) {
+        mounted_ = true;
+        return;
+    }
+
+    if (!ReadDefaultFstab(&fstab_)) {
+        LOG(ERROR) << "Could not read default fstab";
+        return;
+    }
+    mounted_ = EnsurePathMounted(&fstab_, "/metadata");
+    should_unmount_ = true;
+}
+
+AutoMountMetadata::~AutoMountMetadata() {
+    if (mounted_ && should_unmount_) {
+        EnsurePathUnmounted(&fstab_, "/metadata");
+    }
+}