-
Notifications
You must be signed in to change notification settings - Fork 0
/
utpx.h
56 lines (46 loc) · 1.88 KB
/
utpx.h
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
#pragma once
#include <cstdio>
#include <cstdlib>
#include <dlfcn.h>
#include <unistd.h>
namespace utpx {
void log(const char *fmt, ...);
[[noreturn]] void fatal(const char *fmt, ...);
#ifndef NDEBUG
#define log(fmt, ...) fprintf(stderr, fmt "\n" __VA_OPT__(, ) __VA_ARGS__)
#define fatal(fmt, ...) \
do { \
fprintf(stderr, fmt "\n" __VA_OPT__(, ) __VA_ARGS__); \
std::abort(); \
} while (0)
#else
#define log(fmt, ...)
#define fatal(fmt, ...) std::abort()
#endif
template <typename T> T dlSymbol(const char *symbol_name, const char *so) {
static T fn;
if (!fn) {
fn = (T)dlsym(RTLD_NEXT, symbol_name);
if (fn) log("[DLSYM] Found %s at %p", symbol_name, (void *)fn);
else {
if (!so) {
log("[DLSYM] Missing original %s and no library is specified to find this symbol, terminating...", symbol_name);
std::abort();
}
log("[DLSYM] Missing original %s, trying to load directly from %s", symbol_name, so);
auto handle = dlopen(so, RTLD_LAZY);
if (!handle) {
log("[DLSYM] dlopen failed for %s when resolving for %s, reason=%s, terminating...", so, symbol_name, dlerror());
std::abort();
}
dlerror(); // clear existing errors
fn = (T)dlsym(handle, symbol_name);
if (auto e = dlerror(); e) {
log("[DLSYM] dlsym failed for %s, reason=%s, terminating...", symbol_name, e);
std::abort();
}
}
}
return fn;
}
} // namespace utpx