1 //===-- safestack_platform.h ----------------------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements platform specific parts of SafeStack runtime.
11 //===----------------------------------------------------------------------===//
13 #ifndef SAFESTACK_PLATFORM_H
14 #define SAFESTACK_PLATFORM_H
16 #include "safestack_util.h"
17 #include "sanitizer_common/sanitizer_platform.h"
24 #include <sys/syscall.h>
25 #include <sys/types.h>
28 #if !(SANITIZER_NETBSD || SANITIZER_FREEBSD || SANITIZER_LINUX)
29 #error "Support for your platform has not been implemented"
35 extern "C" void *__mmap(void *, size_t, int, int, int, int, off_t
);
45 static void *GetRealLibcAddress(const char *symbol
) {
46 void *real
= dlsym(RTLD_NEXT
, symbol
);
48 real
= dlsym(RTLD_DEFAULT
, symbol
);
50 fprintf(stderr
, "safestack GetRealLibcAddress failed for symbol=%s",
57 #define _REAL(func, ...) real##_##func(__VA_ARGS__)
58 #define DEFINE__REAL(ret_type, func, ...) \
59 static ret_type (*real_##func)(__VA_ARGS__) = NULL; \
61 real_##func = (ret_type(*)(__VA_ARGS__))GetRealLibcAddress(#func); \
63 SFS_CHECK(real_##func);
66 using ThreadId
= uint64_t;
68 inline ThreadId
GetTid() {
70 DEFINE__REAL(int, _lwp_self
);
71 return _REAL(_lwp_self
);
72 #elif SANITIZER_FREEBSD
77 return syscall(SYS_gettid
);
81 inline int TgKill(pid_t pid
, ThreadId tid
, int sig
) {
83 DEFINE__REAL(int, _lwp_kill
, int a
, int b
);
85 return _REAL(_lwp_kill
, tid
, sig
);
86 #elif SANITIZER_FREEBSD
87 return syscall(SYS_thr_kill2
, pid
, tid
, sig
);
89 return syscall(SYS_tgkill
, pid
, tid
, sig
);
93 inline void *Mmap(void *addr
, size_t length
, int prot
, int flags
, int fd
,
96 return __mmap(addr
, length
, prot
, flags
, fd
, 0, offset
);
97 #elif SANITIZER_FREEBSD && (defined(__aarch64__) || defined(__x86_64__))
98 return (void *)__syscall(SYS_mmap
, addr
, length
, prot
, flags
, fd
, offset
);
100 return (void *)syscall(SYS_mmap
, addr
, length
, prot
, flags
, fd
, offset
);
104 inline int Munmap(void *addr
, size_t length
) {
106 DEFINE__REAL(int, munmap
, void *a
, size_t b
);
107 return _REAL(munmap
, addr
, length
);
109 return syscall(SYS_munmap
, addr
, length
);
113 inline int Mprotect(void *addr
, size_t length
, int prot
) {
115 DEFINE__REAL(int, mprotect
, void *a
, size_t b
, int c
);
116 return _REAL(mprotect
, addr
, length
, prot
);
118 return syscall(SYS_mprotect
, addr
, length
, prot
);
122 } // namespace safestack
124 #endif // SAFESTACK_PLATFORM_H