-
-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
dlfcn.cpp
80 lines (71 loc) · 2.04 KB
/
dlfcn.cpp
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
/*
* Copyright (c) 2021, Gunnar Beutner <[email protected]>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/ByteString.h>
#include <AK/Result.h>
#include <AK/Types.h>
#include <bits/dlfcn_integration.h>
#include <dlfcn.h>
#include <string.h>
[[gnu::weak]] Result<void, DlErrorMessage> __dlclose(void*) asm("__dlclose");
[[gnu::weak]] Result<void*, DlErrorMessage> __dlopen(char const*, int) asm("__dlopen");
[[gnu::weak]] Result<void*, DlErrorMessage> __dlsym(void*, char const*) asm("__dlsym");
[[gnu::weak]] Result<void, DlErrorMessage> __dladdr(void const*, Dl_info*) asm("__dladdr");
// FIXME: use thread_local and a String once TLS works
__thread char* s_dlerror_text = NULL;
__thread bool s_dlerror_retrieved = false;
static void store_error(ByteString const& error)
{
free(s_dlerror_text);
s_dlerror_text = strdup(error.characters());
s_dlerror_retrieved = false;
}
int dlclose(void* handle)
{
auto result = __dlclose(handle);
if (result.is_error()) {
store_error(result.error().text);
return -1;
}
return 0;
}
char* dlerror()
{
if (s_dlerror_retrieved) {
free(s_dlerror_text);
s_dlerror_text = nullptr;
}
s_dlerror_retrieved = true;
return const_cast<char*>(s_dlerror_text);
}
void* dlopen(char const* filename, int flags)
{
auto result = __dlopen(filename, flags);
if (result.is_error()) {
store_error(result.error().text);
return nullptr;
}
return result.value();
}
void* dlsym(void* handle, char const* symbol_name)
{
auto result = __dlsym(handle, symbol_name);
if (result.is_error()) {
store_error(result.error().text);
return nullptr;
}
return result.value();
}
int dladdr(void const* addr, Dl_info* info)
{
auto result = __dladdr(addr, info);
if (result.is_error()) {
// FIXME: According to the man page glibc does _not_ make the error
// available via dlerror(), however we do. Does this break anything?
store_error(result.error().text);
return 0;
}
return 1;
}