vpnor: partition: Fix file descriptor leaks

In the face of errors we were leaking the partition file descriptor when
throwing exceptions.

Change-Id: I257a491460062384928d8dda6bbf178da662f3b3
Signed-off-by: Andrew Jeffery <andrew@aj.id.au>
diff --git a/vpnor/partition.cpp b/vpnor/partition.cpp
index 90156f7..cfefc0a 100644
--- a/vpnor/partition.cpp
+++ b/vpnor/partition.cpp
@@ -147,20 +147,24 @@
         int rc = lseek(fd, offset, SEEK_SET);
         if (rc < 0)
         {
+            int lerrno = errno;
+            close(fd);
             MSG_ERR("Failed to seek to %zu in %s (%zu bytes): %d\n", offset,
-                    path.c_str(), fileSize, errno);
-            throw std::system_error(errno, std::system_category());
+                    path.c_str(), fileSize, lerrno);
+            throw std::system_error(lerrno, std::system_category());
         }
 
         access_len = std::min(len, fileSize - offset);
         rc = fd_process_all(::read, fd, dst, access_len);
         if (rc < 0)
         {
+            int lerrno = errno;
+            close(fd);
             MSG_ERR(
                 "Requested %zu bytes but failed to read %zu from %s (%zu) at "
                 "%zu: %d\n",
-                len, access_len, path.c_str(), fileSize, offset, errno);
-            throw std::system_error(errno, std::system_category());
+                len, access_len, path.c_str(), fileSize, offset, lerrno);
+            throw std::system_error(lerrno, std::system_category());
         }
 
         close(fd);
@@ -201,17 +205,21 @@
     int rc = lseek(fd, offset, SEEK_SET);
     if (rc < 0)
     {
+        int lerrno = errno;
+        close(fd);
         MSG_ERR("Failed to seek to %zu in %s: %d\n", offset, path.c_str(),
-                errno);
-        throw std::system_error(errno, std::system_category());
+                lerrno);
+        throw std::system_error(lerrno, std::system_category());
     }
 
     rc = fd_process_all(::write, fd, dst, len);
     if (rc < 0)
     {
+        int lerrno = errno;
+        close(fd);
         MSG_ERR("Failed to write %zu bytes to %s at %zu: %d\n", len,
-                path.c_str(), offset, errno);
-        throw std::system_error(errno, std::system_category());
+                path.c_str(), offset, lerrno);
+        throw std::system_error(lerrno, std::system_category());
     }
     backend_set_bytemap(backend, base + offset, len, FLASH_DIRTY);