Fix the core dump by using filesystem error_code

The currently used filesystem method will cause an exception if the
file system is damaged for some reason, resulting in a core dump of
the process.
So the overloaded method with the error_code parameter should be used
here to ensure that the process core dump will not be caused after an
exception is thrown.

Fixes: openbmc/phosphor-bmc-code-mgmt#12

Tested: built phosphor-bmc-code-mgmt successfully and CI passes.

Signed-off-by: George Liu <liuxiwei@inspur.com>
Change-Id: I329f78b481cb466e755bc1b78562583620f561c2
diff --git a/download_manager.cpp b/download_manager.cpp
index 972278b..fdffcb9 100644
--- a/download_manager.cpp
+++ b/download_manager.cpp
@@ -15,6 +15,7 @@
 #include <filesystem>
 #include <iostream>
 #include <string>
+#include <system_error>
 
 namespace phosphor
 {
@@ -61,9 +62,11 @@
 
     // Check if IMAGE DIR exists
     fs::path imgDirPath(IMG_UPLOAD_DIR);
-    if (!fs::is_directory(imgDirPath))
+    std::error_code ec;
+    if (!fs::is_directory(imgDirPath, ec))
     {
-        error("Image Dir {PATH} does not exist", "PATH", imgDirPath);
+        error("Image Dir {PATH} does not exist: {ERROR_MSG}", "PATH",
+              imgDirPath, "ERROR_MSG", ec.message());
         elog<InternalFailure>();
         return;
     }
diff --git a/image_manager.cpp b/image_manager.cpp
index eb4fec4..f998871 100644
--- a/image_manager.cpp
+++ b/image_manager.cpp
@@ -22,6 +22,7 @@
 #include <filesystem>
 #include <random>
 #include <string>
+#include <system_error>
 
 namespace phosphor
 {
@@ -76,9 +77,11 @@
 
 int Manager::processImage(const std::string& tarFilePath)
 {
-    if (!fs::is_regular_file(tarFilePath))
+    std::error_code ec;
+    if (!fs::is_regular_file(tarFilePath, ec))
     {
-        error("Tarball {PATH} does not exist", "PATH", tarFilePath);
+        error("Tarball {PATH} does not exist: {ERROR_MSG}", "PATH", tarFilePath,
+              "ERROR_MSG", ec.message());
         report<ManifestFileFailure>(ManifestFail::PATH(tarFilePath.c_str()));
         return -1;
     }
@@ -109,9 +112,10 @@
     }
 
     // Verify the manifest file
-    if (!fs::is_regular_file(manifestPath))
+    if (!fs::is_regular_file(manifestPath, ec))
     {
-        error("No manifest file {PATH}", "PATH", tarFilePath);
+        error("No manifest file {PATH}: {ERROR_MSG}", "PATH", tarFilePath,
+              "ERROR_MSG", ec.message());
         report<ManifestFileFailure>(ManifestFail::PATH(tarFilePath.c_str()));
         return -1;
     }
@@ -210,7 +214,7 @@
     if (versions.find(id) == versions.end() && it == allSoftwareObjs.end())
     {
         // Rename the temp dir to image dir
-        fs::rename(tmpDirPath, imageDirPath);
+        fs::rename(tmpDirPath, imageDirPath, ec);
         // Clear the path, so it does not attemp to remove a non-existing path
         tmpDirToRemove.path.clear();
 
@@ -242,9 +246,10 @@
 
     // Delete image dir
     fs::path imageDirPath = (*(it->second)).path();
-    if (fs::exists(imageDirPath))
+    std::error_code ec;
+    if (fs::exists(imageDirPath, ec))
     {
-        fs::remove_all(imageDirPath);
+        fs::remove_all(imageDirPath, ec);
     }
     this->versions.erase(entryId);
 }
diff --git a/image_verify.cpp b/image_verify.cpp
index 9551e4e..2b20340 100644
--- a/image_verify.cpp
+++ b/image_verify.cpp
@@ -18,6 +18,7 @@
 #include <cassert>
 #include <fstream>
 #include <set>
+#include <system_error>
 
 namespace phosphor
 {
@@ -57,9 +58,11 @@
     AvailableKeyTypes keyTypes{};
 
     // Find the path of all the files
-    if (!fs::is_directory(signedConfPath))
+    std::error_code ec;
+    if (!fs::is_directory(signedConfPath, ec))
     {
-        error("Signed configuration path not found in the system");
+        error("Signed configuration path not found in the system: {ERROR_MSG}",
+              "ERROR_MSG", ec.message());
         elog<InternalFailure>();
     }
 
@@ -129,7 +132,9 @@
     fs::path publicKeyFile(imageDirPath / PUBLICKEY_FILE_NAME);
 
     ret = verifyFile(pkeyFullFile, pkeyFullFileSig, publicKeyFile, hashType);
-    fs::remove(tmpFullFile);
+
+    std::error_code ec;
+    fs::remove(tmpFullFile, ec);
 #endif
 
     return ret;
@@ -186,7 +191,8 @@
             fs::path file(imageDirPath);
             file /= optionalImage;
 
-            if (fs::exists(file))
+            std::error_code ec;
+            if (fs::exists(file, ec))
             {
                 optionalFilesFound = true;
                 // Build Signature File name
@@ -297,10 +303,11 @@
 {
 
     // Check existence of the files in the system.
-    if (!(fs::exists(file) && fs::exists(sigFile)))
+    std::error_code ec;
+    if (!(fs::exists(file, ec) && fs::exists(sigFile, ec)))
     {
-        error("Failed to find the Data or signature file {PATH}.", "PATH",
-              file);
+        error("Failed to find the Data or signature file {PATH}: {ERROR_MSG}",
+              "PATH", file, "ERROR_MSG", ec.message());
         elog<InternalFailure>();
     }
 
@@ -338,7 +345,7 @@
     }
 
     // Hash the data file and update the verification context
-    auto size = fs::file_size(file);
+    auto size = fs::file_size(file, ec);
     auto dataPtr = mapFile(file, size);
 
     result = EVP_DigestVerifyUpdate(rsaVerifyCtx.get(), dataPtr(), size);
@@ -350,7 +357,7 @@
     }
 
     // Verify the data with signature.
-    size = fs::file_size(sigFile);
+    size = fs::file_size(sigFile, ec);
     auto signature = mapFile(sigFile, size);
 
     result = EVP_DigestVerifyFinal(
@@ -376,7 +383,8 @@
 
 inline EVP_PKEY_Ptr Signature::createPublicRSA(const fs::path& publicKey)
 {
-    auto size = fs::file_size(publicKey);
+    std::error_code ec;
+    auto size = fs::file_size(publicKey, ec);
 
     // Read public key file
     auto data = mapFile(publicKey, size);
@@ -414,7 +422,8 @@
         fs::path file(filePath);
         file /= bmcImage;
 
-        if (!fs::exists(file))
+        std::error_code ec;
+        if (!fs::exists(file, ec))
         {
             valid = false;
             break;
diff --git a/item_updater.cpp b/item_updater.cpp
index 2fdbc31..3ea954c 100644
--- a/item_updater.cpp
+++ b/item_updater.cpp
@@ -19,6 +19,7 @@
 #include <queue>
 #include <set>
 #include <string>
+#include <system_error>
 
 namespace phosphor
 {
@@ -194,7 +195,8 @@
 
     // Read os-release from folders under /media/ to get
     // BMC Software Versions.
-    for (const auto& iter : fs::directory_iterator(MEDIA_DIR))
+    std::error_code ec;
+    for (const auto& iter : fs::directory_iterator(MEDIA_DIR, ec))
     {
         auto activationState = server::Activation::Activations::Active;
         static const auto BMC_RO_PREFIX_LEN = strlen(BMC_ROFS_PREFIX);
@@ -206,14 +208,16 @@
             // Get the version to calculate the id
             fs::path releaseFile(OS_RELEASE_FILE);
             auto osRelease = iter.path() / releaseFile.relative_path();
-            if (!fs::is_regular_file(osRelease))
+            if (!fs::is_regular_file(osRelease, ec))
             {
 #ifdef BMC_STATIC_DUAL_IMAGE
                 // For dual image, it is possible that the secondary image is
                 // empty or contains invalid data, ignore such case.
-                info("Unable to find osRelease: {PATH}", "PATH", osRelease);
+                info("Unable to find osRelease: {PATH}: {ERROR_MSG}", "PATH",
+                     osRelease, "ERROR_MSG", ec.message());
 #else
-                error("Failed to read osRelease: {PATH}", "PATH", osRelease);
+                error("Failed to read osRelease: {PATH}: {ERROR_MSG}", "PATH",
+                      osRelease, "ERROR_MSG", ec.message());
 
                 // Try to get the version id from the mount directory name and
                 // call to delete it as this version may be corrupted. Dynamic
diff --git a/serialize.cpp b/serialize.cpp
index 8b7fca4..ff9e832 100644
--- a/serialize.cpp
+++ b/serialize.cpp
@@ -8,6 +8,7 @@
 
 #include <filesystem>
 #include <fstream>
+#include <system_error>
 
 namespace phosphor
 {
@@ -24,16 +25,17 @@
 
 void storePriority(const std::string& flashId, uint8_t priority)
 {
+    std::error_code ec;
     auto path = fs::path(PERSIST_DIR) / flashId;
-    if (!fs::is_directory(path))
+    if (!fs::is_directory(path, ec))
     {
-        if (fs::exists(path))
+        if (fs::exists(path, ec))
         {
             // Delete if it's a non-directory file
             warning("Removing non-directory file: {PATH}", "PATH", path);
-            fs::remove_all(path);
+            fs::remove_all(path, ec);
         }
-        fs::create_directories(path);
+        fs::create_directories(path, ec);
     }
     path = path / priorityName;
 
@@ -44,16 +46,17 @@
 
 void storePurpose(const std::string& flashId, VersionPurpose purpose)
 {
+    std::error_code ec;
     auto path = fs::path(PERSIST_DIR) / flashId;
-    if (!fs::is_directory(path))
+    if (!fs::is_directory(path, ec))
     {
-        if (fs::exists(path))
+        if (fs::exists(path, ec))
         {
             // Delete if it's a non-directory file
             warning("Removing non-directory file: {PATH}", "PATH", path);
-            fs::remove_all(path);
+            fs::remove_all(path, ec);
         }
-        fs::create_directories(path);
+        fs::create_directories(path, ec);
     }
     path = path / purposeName;
 
@@ -64,8 +67,9 @@
 
 bool restorePriority(const std::string& flashId, uint8_t& priority)
 {
+    std::error_code ec;
     auto path = fs::path(PERSIST_DIR) / flashId / priorityName;
-    if (fs::exists(path))
+    if (fs::exists(path, ec))
     {
         std::ifstream is(path.c_str(), std::ios::in);
         try
@@ -76,7 +80,7 @@
         }
         catch (const cereal::Exception& e)
         {
-            fs::remove_all(path);
+            fs::remove_all(path, ec);
         }
     }
 
@@ -124,8 +128,9 @@
 
 bool restorePurpose(const std::string& flashId, VersionPurpose& purpose)
 {
+    std::error_code ec;
     auto path = fs::path(PERSIST_DIR) / flashId / purposeName;
-    if (fs::exists(path))
+    if (fs::exists(path, ec))
     {
         std::ifstream is(path.c_str(), std::ios::in);
         try
@@ -136,7 +141,7 @@
         }
         catch (const cereal::Exception& e)
         {
-            fs::remove_all(path);
+            fs::remove_all(path, ec);
         }
     }
 
@@ -145,10 +150,11 @@
 
 void removePersistDataDirectory(const std::string& flashId)
 {
+    std::error_code ec;
     auto path = fs::path(PERSIST_DIR) / flashId;
-    if (fs::exists(path))
+    if (fs::exists(path, ec))
     {
-        fs::remove_all(path);
+        fs::remove_all(path, ec);
     }
 }
 
diff --git a/static/flash.cpp b/static/flash.cpp
index cdf0683..74316d1 100644
--- a/static/flash.cpp
+++ b/static/flash.cpp
@@ -9,6 +9,7 @@
 #include <phosphor-logging/lg2.hpp>
 
 #include <filesystem>
+#include <system_error>
 
 namespace
 {
@@ -52,8 +53,9 @@
 
     for (const auto& bmcImage : parent.imageUpdateList)
     {
+        std::error_code ec;
         fs::copy_file(uploadDir / versionId / bmcImage, toPath / bmcImage,
-                      fs::copy_options::overwrite_existing);
+                      fs::copy_options::overwrite_existing, ec);
     }
 }
 
diff --git a/sync_manager.cpp b/sync_manager.cpp
index 1a3e0dd..caafae0 100644
--- a/sync_manager.cpp
+++ b/sync_manager.cpp
@@ -9,6 +9,7 @@
 #include <phosphor-logging/lg2.hpp>
 
 #include <filesystem>
+#include <system_error>
 
 namespace phosphor
 {
@@ -34,18 +35,19 @@
         // so need to differentiate between the different file events.
         if (mask & IN_CLOSE_WRITE)
         {
-            if (!(fs::exists(dst)))
+            std::error_code ec;
+            if (!(fs::exists(dst, ec)))
             {
-                if (fs::is_directory(entryPath))
+                if (fs::is_directory(entryPath, ec))
                 {
                     // Source is a directory, create it at the destination.
-                    fs::create_directories(dst);
+                    fs::create_directories(dst, ec);
                 }
                 else
                 {
                     // Source is a file, create the directory where this file
                     // resides at the destination.
-                    fs::create_directories(dst.parent_path());
+                    fs::create_directories(dst.parent_path(), ec);
                 }
             }
 
diff --git a/sync_watch.cpp b/sync_watch.cpp
index e84d061..ecf6cef 100644
--- a/sync_watch.cpp
+++ b/sync_watch.cpp
@@ -9,6 +9,7 @@
 
 #include <filesystem>
 #include <fstream>
+#include <system_error>
 
 namespace phosphor
 {
@@ -53,8 +54,9 @@
         return;
     }
 
+    std::error_code ec;
     auto syncfile = fs::path(SYNC_LIST_DIR_PATH) / SYNC_LIST_FILE_NAME;
-    if (fs::exists(syncfile))
+    if (fs::exists(syncfile, ec))
     {
         std::string line;
         std::ifstream file(syncfile.c_str());
@@ -98,7 +100,8 @@
         // Watch was removed, re-add it if file still exists.
         if (event->mask & IN_IGNORED)
         {
-            if (fs::exists(syncWatch->fileMap[event->wd]))
+            std::error_code ec;
+            if (fs::exists(syncWatch->fileMap[event->wd], ec))
             {
                 syncWatch->addInotifyWatch(syncWatch->fileMap[event->wd]);
             }
diff --git a/usb/usb_manager.cpp b/usb/usb_manager.cpp
index 196ab42..226a578 100644
--- a/usb/usb_manager.cpp
+++ b/usb/usb_manager.cpp
@@ -4,6 +4,8 @@
 
 #include <sys/mount.h>
 
+#include <system_error>
+
 namespace phosphor
 {
 namespace usb
@@ -11,8 +13,9 @@
 
 bool USBManager::run()
 {
+    std::error_code ec;
     fs::path dir(usbPath);
-    fs::create_directories(dir);
+    fs::create_directories(dir, ec);
 
     auto rc = mount(devicePath.c_str(), usbPath.c_str(), "vfat", 0, NULL);
     if (rc)
@@ -27,7 +30,7 @@
         if (p.path().extension() == ".tar")
         {
             fs::path dstPath{IMG_UPLOAD_DIR / p.path().filename()};
-            if (fs::exists(dstPath))
+            if (fs::exists(dstPath, ec))
             {
                 lg2::info(
                     "{DSTPATH} already exists in the /tmp/images directory, exit the upgrade",
diff --git a/watch.cpp b/watch.cpp
index 38887d4..cabfd79 100644
--- a/watch.cpp
+++ b/watch.cpp
@@ -14,6 +14,7 @@
 #include <filesystem>
 #include <stdexcept>
 #include <string>
+#include <system_error>
 
 namespace phosphor
 {
@@ -30,10 +31,11 @@
     imageCallback(imageCallback)
 {
     // Check if IMAGE DIR exists.
+    std::error_code ec;
     fs::path imgDirPath(IMG_UPLOAD_DIR);
-    if (!fs::is_directory(imgDirPath))
+    if (!fs::is_directory(imgDirPath, ec))
     {
-        fs::create_directories(imgDirPath);
+        fs::create_directories(imgDirPath, ec);
     }
 
     fd = inotify_init1(IN_NONBLOCK);