blob: b8da0ef9389c7e4db2e776312973084cd16bcc27 [file] [log] [blame]
Patrick Venture030b1a82019-01-18 08:33:02 -08001#pragma once
2
3#include "internal/sys.hpp"
4
5#include <cstdint>
6#include <string>
7
8namespace host_tool
9{
10
11class HostIoInterface
12{
13 public:
14 virtual ~HostIoInterface() = default;
15
16 /**
17 * Attempt to write bytes from source to offset into the host memory device.
18 *
19 * @param[in] offset - offset into the host memory device.
20 * @param[in] length - the number of bytes to copy from source.
21 * @param[in] source - the souce of the bytes to copy to the memory device.
22 * @return true on success, false on failure (such as unable to initialize
23 * device).
24 */
25 virtual bool write(const std::size_t offset, const std::size_t length,
26 const void* const source) = 0;
27};
28
29class DevMemDevice : public HostIoInterface
30{
31 public:
32 explicit DevMemDevice(const internal::Sys* sys = &internal::sys_impl) :
33 sys(sys)
34 {
35 }
36
37 /* On destruction, close /dev/mem if it was open. */
38 ~DevMemDevice()
39 {
40 if (opened)
41 {
42 sys->close(devMemFd);
43 }
44 }
45
46 /* Don't allow copying or assignment, only moving. */
47 DevMemDevice(const DevMemDevice&) = delete;
48 DevMemDevice& operator=(const DevMemDevice&) = delete;
49 DevMemDevice(DevMemDevice&&) = default;
50 DevMemDevice& operator=(DevMemDevice&&) = default;
51
52 bool write(const std::size_t offset, const std::size_t length,
53 const void* const source) override;
54
55 private:
56 static const std::string devMemPath;
57 bool opened = false;
58 int devMemFd = -1;
59 void* devMemMapped = nullptr;
60 const internal::Sys* sys;
61};
62
63} // namespace host_tool