Stopping the cvd should not delete all of the debug data

Delete any remaining data at startup instead

BUG: 110116203
Change-Id: If948e0d78c4f83135f5f71136018d5ae31375196
Merged-In: If948e0d78c4f83135f5f71136018d5ae31375196
Test: On GCE
(cherry picked from commit 98384ee858016e45a26d95d59bf82e38cd9a3f63)
diff --git a/host/commands/launch/main.cc b/host/commands/launch/main.cc
index d304d5e..691672a 100644
--- a/host/commands/launch/main.cc
+++ b/host/commands/launch/main.cc
@@ -611,9 +611,6 @@
   return true;
 }
 
-}  // anonymous namespace
-
-namespace launch_cvd {
 void ParseCommandLineFlags(int argc, char** argv) {
   // The config_file is created by the launcher, so the launcher is the only
   // host process that doesn't use the flag.
@@ -626,17 +623,43 @@
 
   ValidateAdbModeFlag();
 }
-}  // namespace launch_cvd
+
+bool CleanPriorFiles() {
+  auto config = vsoc::CuttlefishConfig::Get();
+  std::string run_files = config->PerInstancePath("*") + " " +
+                          config->mempath();
+  LOG(INFO) << "Assuming run files of " << run_files;
+  // TODO(b/78512938): Shouldn't need sudo here
+  std::string fuser_cmd = "sudo fuser " + run_files + " 2> /dev/null";
+  int rval = std::system(fuser_cmd.c_str());
+  // fuser returns 0 if any of the files are open
+  if (WEXITSTATUS(rval) == 0) {
+    LOG(ERROR) << "Clean aborted: files are in use";
+    return false;
+  }
+  std::string clean_command = "sudo rm -rf " + run_files;
+  rval = std::system(clean_command.c_str());
+  if (WEXITSTATUS(rval) != 0) {
+    LOG(ERROR) << "Remove of files failed";
+    return false;
+  }
+  return true;
+}
+}  // namespace
 
 int main(int argc, char** argv) {
   ::android::base::InitLogging(argv, android::base::StderrLogger);
-  launch_cvd::ParseCommandLineFlags(argc, argv);
+  ParseCommandLineFlags(argc, argv);
 
   // Do this early so that the config object is ready for anything that needs it
   if (!SetUpGlobalConfiguration()) {
     return -1;
   }
 
+  if (!CleanPriorFiles()) {
+    LOG(FATAL) << "Failed to clean prior files";
+  }
+
   auto& memory_layout = *vsoc::VSoCMemoryLayout::Get();
   // TODO(b/79170615) These values need to go to the config object/file and the
   // region resizing be done by the ivserver process (or maybe the config
diff --git a/host/commands/stop_cvd/main.cc b/host/commands/stop_cvd/main.cc
index 08648b1..441ec60 100644
--- a/host/commands/stop_cvd/main.cc
+++ b/host/commands/stop_cvd/main.cc
@@ -71,9 +71,4 @@
   fuser_cmd += " ";
   fuser_cmd += config->mempath();
   RunCommand(fuser_cmd.c_str());
-  std::string delete_cmd = "rm -f ";
-  delete_cmd += run_files;
-  RunCommand(delete_cmd.c_str());
-
-  return exit_code;
 }