blob: 0712694aaa5bfb274ef4fceabca4d6cd2a54d115 [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 /**
Patrick Ventureac4ff972019-05-03 17:35:00 -070017 * Attempt to read bytes from offset to the destination from the host
18 * memory device.
19 *
20 * @param[in] offset - offset into the host memory device.
21 * @param[in] length - the number of bytes to copy from source.
22 * @param[in] destination - where to write the bytes.
23 * @return true on success, false on failure (such as unable to initialize
24 * device).
25 */
26 virtual bool read(const std::size_t offset, const std::size_t length,
27 void* const destination) = 0;
28
29 /**
Patrick Venture030b1a82019-01-18 08:33:02 -080030 * Attempt to write bytes from source to offset into the host memory device.
31 *
32 * @param[in] offset - offset into the host memory device.
33 * @param[in] length - the number of bytes to copy from source.
34 * @param[in] source - the souce of the bytes to copy to the memory device.
35 * @return true on success, false on failure (such as unable to initialize
36 * device).
37 */
38 virtual bool write(const std::size_t offset, const std::size_t length,
39 const void* const source) = 0;
40};
41
42class DevMemDevice : public HostIoInterface
43{
44 public:
45 explicit DevMemDevice(const internal::Sys* sys = &internal::sys_impl) :
46 sys(sys)
47 {
48 }
49
50 /* On destruction, close /dev/mem if it was open. */
51 ~DevMemDevice()
52 {
53 if (opened)
54 {
55 sys->close(devMemFd);
56 }
57 }
58
59 /* Don't allow copying or assignment, only moving. */
60 DevMemDevice(const DevMemDevice&) = delete;
61 DevMemDevice& operator=(const DevMemDevice&) = delete;
62 DevMemDevice(DevMemDevice&&) = default;
63 DevMemDevice& operator=(DevMemDevice&&) = default;
64
Patrick Ventureac4ff972019-05-03 17:35:00 -070065 bool read(const std::size_t offset, const std::size_t length,
66 void* const destination) override;
67
Patrick Venture030b1a82019-01-18 08:33:02 -080068 bool write(const std::size_t offset, const std::size_t length,
69 const void* const source) override;
70
71 private:
72 static const std::string devMemPath;
73 bool opened = false;
74 int devMemFd = -1;
75 void* devMemMapped = nullptr;
76 const internal::Sys* sys;
77};
78
79} // namespace host_tool