tools: io: add ppcMemFd cleanup

The destructor may try to double-close because the ppcMemFd was not
being set to -1.

Signed-off-by: Patrick Venture <venture@google.com>
Change-Id: I3423ae874d551b39f3deb761c5572078b07a0349
diff --git a/tools/io.cpp b/tools/io.cpp
index 991507b..9af8ace 100644
--- a/tools/io.cpp
+++ b/tools/io.cpp
@@ -94,9 +94,15 @@
 PpcMemDevice::~PpcMemDevice()
 {
     // Attempt to close in case reads or writes didn't close themselves
+    close();
+}
+
+void PpcMemDevice::close()
+{
     if (ppcMemFd >= 0)
     {
         sys->close(ppcMemFd);
+        ppcMemFd = -1;
     }
 }
 
@@ -116,11 +122,11 @@
     {
         std::fprintf(stderr, "IO read failed at offset: 0x%zx, length: %zu\n",
                      offset, length);
-        sys->close(ppcMemFd);
+        close();
         return false;
     }
 
-    sys->close(ppcMemFd);
+    close();
     return true;
 }
 
@@ -140,11 +146,11 @@
     {
         std::fprintf(stderr, "IO write failed at offset: 0x%zx, length: %zu\n",
                      offset, length);
-        sys->close(ppcMemFd);
+        close();
         return false;
     }
 
-    sys->close(ppcMemFd);
+    close();
     return true;
 }
 
diff --git a/tools/io.hpp b/tools/io.hpp
index 1476c5c..b3b2c79 100644
--- a/tools/io.hpp
+++ b/tools/io.hpp
@@ -91,6 +91,8 @@
                const void* const source) override;
 
   private:
+    void close();
+
     int ppcMemFd = -1;
     const std::string ppcMemPath;
     const internal::Sys* sys;