aboutsummaryrefslogtreecommitdiff
path: root/pal/posix.h
diff options
context:
space:
mode:
Diffstat (limited to 'pal/posix.h')
-rwxr-xr-xpal/posix.h91
1 files changed, 91 insertions, 0 deletions
diff --git a/pal/posix.h b/pal/posix.h
new file mode 100755
index 0000000..8ac9775
--- /dev/null
+++ b/pal/posix.h
@@ -0,0 +1,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