aboutsummaryrefslogtreecommitdiff
path: root/pal/posix.h
blob: 8ac97758e0728a26b86777cbf762eba2bc30ae7b (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#pragma once

#include <iostream>
#include <sys/mman.h>
#include <sys/resource.h>

#define DECL_MAIN int main()

#define NOINLINE __attribute__((noinline))

namespace pal {

static constexpr size_t kPageSize =
    #if defined(__APPLE__) && defined(__aarch64__)
        0x4000
    #else
        0x1000
    #endif
    ;

inline void* MemReserve(size_t len) {
    int flags = MAP_PRIVATE | MAP_ANONYMOUS;

    #ifdef MAP_NORESERVE
        // On Linux, guarantee lazy commit even if /proc/sys/vm/overcommit_memory is set to `heuristic` (0).
        flags |= MAP_NORESERVE;
    #endif

    void* buf = mmap(nullptr, len, PROT_NONE, flags, -1, 0);
    if (buf == nullptr) {
        int saved_errno = errno;
        std::cerr << "Reserving memory with mmap failed. Exit code: " << saved_errno << std::endl;
        return nullptr;
    }

    return buf;
}

inline bool MemCommit(void* p, size_t len) {
    if (mprotect(p, len, PROT_READ | PROT_WRITE) != 0) {
        int saved_errno = errno;
        std::cerr << "Committing memory with mprotect failed. Exit code: " << saved_errno << std::endl;
        return false;
    }

    return true;
}

inline void MemFree(void* p, size_t len) {
    if (munmap(p, len) != 0) {
        int saved_errno = errno;
        std::cerr << "Failed to unmap memory. Exit code: " << saved_errno << std::endl;
    }
}

inline size_t GetPeakMemoryUse() {
    rusage r_usage;
    if (getrusage(RUSAGE_SELF, &r_usage) != 0) {
        int saved_errno = errno;
        std::cerr << "Failed to fetch memory use. Exit code: " << saved_errno << std::endl;
        return 0;
    }

    // On Mac, ru_maxrss is in bytes. On Linux and FreeBSD it's in kilobytes. So much for POSIX.
    #ifdef __APPLE__
    size_t multiplier = 1;
    #else
    size_t multiplier = 1000;
    #endif

    return r_usage.ru_maxrss * multiplier;
}

inline uint64_t ConvertTimevalToMicroseconds(timeval t) {
    return static_cast<uint64_t>(t.tv_sec) * 1000000ULL + static_cast<uint64_t>(t.tv_usec);
}

inline uint64_t GetCpuTime() {
    rusage r_usage;
    if (getrusage(RUSAGE_SELF, &r_usage) != 0) {
        int saved_errno = errno;
        std::cerr << "Failed to fetch memory use. Exit code: " << saved_errno << std::endl;
        return 0;
    }

    auto user_time = ConvertTimevalToMicroseconds(r_usage.ru_utime);
    auto kernel_time = ConvertTimevalToMicroseconds(r_usage.ru_stime);
    return user_time + kernel_time;
}

} // namespace pal