aboutsummaryrefslogtreecommitdiff
path: root/src/memory/memory.cc
blob: 59fb50f88572d67b61acff1bc2aa83f15edefb84 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include "memory/memory.hh"

namespace memory {

buffer_t read_buffer(const std::size_t num_bytes, const pid_t& pid,
                     const void* const address) {
    buffer_t buffer{num_bytes};
    const struct iovec local {
        .iov_base = std::data(buffer), .iov_len = std::size(buffer)
    };
    const struct iovec remote {
        .iov_base = const_cast<void* const>(address), .iov_len = num_bytes
    };

    if (const auto read = process_vm_readv(pid, &local, 1, &remote, 1, 0);
        static_cast<unsigned long>(read) != num_bytes) {

        if (read == -1) {
            throw std::runtime_error{"read fail - " +
                                     std::string{strerror(errno)}};
        }
        throw std::runtime_error("read fail - not enough bytes read (" +
                                 std::to_string(num_bytes) + " wanted, " +
                                 std::to_string(read) + " read)");
    }

    return buffer;
}

void write_buffer(const buffer_t& buffer, const pid_t& pid,
                  const void* const address) {
    const struct iovec local {
        .iov_base = (void*)std::data(buffer), .iov_len = std::size(buffer)
    };
    const struct iovec remote {
        .iov_base = const_cast<void* const>(address),
        .iov_len = std::size(buffer)
    };

    if (const auto written = process_vm_writev(pid, &local, 1, &remote, 1, 0);
        static_cast<unsigned long>(written) != std::size(buffer)) {

        if (written == -1) {
            throw std::runtime_error{"write fail - " +
                                     std::string{strerror(errno)}};
        }
        throw std::runtime_error("read fail - not enough bytes written (" +
                                 std::to_string(std::size(buffer)) +
                                 " wanted, " + std::to_string(written) +
                                 " written)");
    }
}

} // namespace memory