Debian Codegraph @

lib/3rdparty/cdl.c

raw
1 #include <stdlib.h>
2 #include <string.h>
3 #include <assert.h>
4
5 #ifndef size_t
6 # include <stddef.h>
7 #endif
8
9 #if defined(_WIN32) || defined(_WIN64)
10 # include <windows.h>
11 #elif defined(__posix__) || defined(__unix__) || defined(__linux__) || defined(__APPLE__)
12 # include <dlfcn.h>
13 #else
14 # warning "cdl: unsupported os"
15 #endif
16
17 void* chckDlLoad(const char *file, const char **outError)
18 {
19 assert(file);
20 void *handle = NULL;
21 const char *error = NULL;
22
23 #if defined(_WIN32) || defined(_WIN64)
24 #if defined(__WINRT__)
25 /**
26 * WinRT only publically supports LoadPackagedLibrary() for loading .dll
27 * files. LoadLibrary() is a private API, and not available for apps
28 * (that can be published to MS' Windows Store.)
29 */
30 handle = (void*)LoadPackagedLibrary(file, 0);
31 #else
32 handle = (void*)LoadLibrary(file);
33 #endif
34
35 if (!handle)
36 error = "Failed to load dll file.";
37 #elif defined(__posix__) || defined(__unix__) || defined(__linux__) || defined(__APPLE__)
38 if (!(handle = dlopen(file, RTLD_NOW | RTLD_LOCAL)))
39 error = dlerror();
40 #else
41 error = "cdl: unsupported os";
42 #endif
43
44 if (outError)
45 *outError = error;
46
47 return handle;
48 }
49
50 void* chckDlLoadSymbol(void *handle, const char *name, const char **outError)
51 {
52 assert(handle);
53 void *symbol = NULL;
54 const char *error = NULL;
55
56 #if defined(_WIN32) || defined(_WIN64)
57 if (!(symbol = (void*)GetProcAddress((HMODULE)handle, name)))
58 error = "Failed to load symbol.";
59 #elif defined(__posix__) || defined(__unix__) || defined(__linux__) || defined(__APPLE__)
60 if (!(symbol = dlsym(handle, name))) {
61 size_t len = strlen(name) + 1;
62 char *nname = calloc(1, len + 1);
63
64 if (nname) {
65 /* append an underscore for platforms that need that. */
66 nname[0] = '_';
67 memcpy(nname + 1, name, len);
68 symbol = dlsym(handle, nname);
69 free(nname);
70 }
71 }
72
73 if (!symbol)
74 error = dlerror();
75 #else
76 error = "cdl: unsupported os";
77 #endif
78
79 if (outError)
80 *outError = error;
81
82 return symbol;
83 }
84
85 void chckDlUnload(void *handle)
86 {
87 assert(handle);
88
89 #if defined(_WIN32) || defined(_WIN64)
90 FreeLibrary((HMODULE)handle);
91 #elif defined(__posix__) || defined(__unix__) || defined(__linux__) || defined(__APPLE__)
92 dlclose(handle);
93 #endif
94 }
95
96 /* vim: set ts=8 sw=3 tw=0 :*/