blob: e25216e5ce9c0f71ba22cb8bdfa85844feb3f91d [file] [log] [blame]
Patrick Venture030b1a82019-01-18 08:33:02 -08001#include "io.hpp"
2
3#include "internal/sys.hpp"
4
5#include <fcntl.h>
6
7#include <cstdint>
8#include <cstring>
9#include <string>
10
11namespace host_tool
12{
13
14const std::string DevMemDevice::devMemPath = "/dev/mem";
15
16bool DevMemDevice::write(const std::size_t offset, const std::size_t length,
17 const void* const source)
18{
19 if (!opened)
20 {
21 devMemFd = sys->open(devMemPath.c_str(), O_RDWR);
22 if (devMemFd < 0)
23 {
24 return false;
25 }
26
27 opened = true;
28 }
29
30 // addr, length, prot, flags, fd, offset
31 devMemMapped =
32 sys->mmap(0, length, PROT_WRITE, MAP_SHARED, devMemFd, offset);
33 if (devMemMapped == MAP_FAILED)
34 {
35 return false; /* but leave the file open. */
36 }
37
38 /* Copy the bytes. */
39 std::memcpy(devMemMapped, source, length);
40
41 /* Close the map between writes for now. */
42 sys->munmap(devMemMapped, length);
43
44 return true;
45}
46
47} // namespace host_tool