Enable cppcoreguidelines-avoid-goto checks
We've been pretty good about this one, the only usages seem to be in
nvme sensor and added recently. To move to more RAII compliant
containers, this commit creates a FileHandle class, which accepts either
a file path and a mode, or a direct file handle, to be handled via RAII.
Ideally we wouldn't have to create this ourselves, and could rely on
some library, but the alternatives all have compromises that are worse.
boost::asio::random_access_file requires iouring to be enabled, and
isn't available until boost 0.78, which we haven't rebased to yet.
https://www.boost.org/doc/libs/develop/doc/html/boost_asio/reference/random_access_file.html
Once available, this is what I would hope that a bunch of the nvme stuff
evolves into to be much simpler.
boost::iostream::file_descriptor requires linking against
boost::iostream, which would bloat our binary size for a lot of things
we don't use. There is a file_descriptor.cpp that we could compile
directly to solve this, but the existing yocto boost project (nor any
other distro project) installs these files for use, which would
complicate this solution
std::fstream doesn't allow direct access to the file handle, which would
be required for streaming operations.
https://www.boost.org/doc/libs/1_35_0/libs/iostreams/doc/installation.html
https://www.boost.org/doc/libs/1_78_0/libs/iostreams/doc/classes/file_descriptor.html#file_descriptor
A very similar class exists within ipmid here:
https://github.com/openbmc/phosphor-host-ipmid/blob/master/user_channel/file.hpp
This class differs in a couple minor ways, in that it throws exceptions
on open failures (similar to the boost classes), accepts the input by
std::filesystem::path, instead of string, and supports std::move, which
is required for the pipe usage.
Signed-off-by: Ed Tanous <edtanous@google.com>
Change-Id: I8be2419783e41e8f529030bb3d05c2e7aa890307
diff --git a/include/FileHandle.hpp b/include/FileHandle.hpp
new file mode 100644
index 0000000..46e5539
--- /dev/null
+++ b/include/FileHandle.hpp
@@ -0,0 +1,27 @@
+#pragma once
+
+#include <filesystem>
+#include <ios>
+
+// An RAII compliant object for holding a posix file descriptor
+class FileHandle
+{
+ private:
+ int fd;
+
+ public:
+ FileHandle() = delete;
+ FileHandle(const FileHandle&) = delete;
+ FileHandle& operator=(const FileHandle&) = delete;
+ FileHandle(FileHandle&&) noexcept;
+ FileHandle& operator=(FileHandle&&) noexcept;
+
+ explicit FileHandle(const std::filesystem::path& name,
+ std::ios_base::openmode mode = std::ios_base::in |
+ std::ios_base::out);
+
+ explicit FileHandle(int fd);
+
+ ~FileHandle();
+ int handle();
+};
\ No newline at end of file