dumpstate: mount debugfs in non-user builds

This change will help non-user builds with keeping debugfs
disabled during run time. Instead, it will be mounted by dumpstate
for bug report generation and unmounted after. Access to debugfs
will be restricted to dumpstate HAL.

Test: adb shell am bug-report
Bug: 176936478
Change-Id: Icbe318399f50ca467f5ab9c414ddae5098826301
diff --git a/cmds/dumpstate/dumpstate.cpp b/cmds/dumpstate/dumpstate.cpp
index 9c5b883..59a7d8c 100644
--- a/cmds/dumpstate/dumpstate.cpp
+++ b/cmds/dumpstate/dumpstate.cpp
@@ -28,6 +28,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <sys/mount.h>
 #include <sys/poll.h>
 #include <sys/prctl.h>
 #include <sys/resource.h>
@@ -2156,6 +2157,22 @@
         return;
     }
 
+    /*
+     * mount debugfs for non-user builds which launch with S and unmount it
+     * after invoking dumpstateBoard_* methods. This is to enable debug builds
+     * to not have debugfs mounted during runtime. It will also ensure that
+     * debugfs is only accessed by the dumpstate HAL.
+     */
+    auto api_level = android::base::GetIntProperty("ro.product.first_api_level", 0);
+    bool mount_debugfs = !PropertiesHelper::IsUserBuild() && api_level >= 31;
+
+    if (mount_debugfs) {
+        RunCommand("mount debugfs", {"mount", "-t", "debugfs", "debugfs", "/sys/kernel/debug"},
+                   AS_ROOT_20);
+        RunCommand("chmod debugfs", {"chmod", "0755", "/sys/kernel/debug"},
+                   AS_ROOT_20);
+    }
+
     std::vector<std::string> paths;
     std::vector<android::base::ScopeGuard<std::function<void()>>> remover;
     for (int i = 0; i < NUM_OF_DUMPS; i++) {
@@ -2255,6 +2272,10 @@
                "there might be racing in content\n", killing_timeout_sec);
     }
 
+    if (mount_debugfs) {
+        RunCommand("unmount debugfs", {"umount", "/sys/kernel/debug"}, AS_ROOT_20);
+    }
+
     auto file_sizes = std::make_unique<ssize_t[]>(paths.size());
     for (size_t i = 0; i < paths.size(); i++) {
         struct stat s;