MimIR 0.1
MimIR is my Intermediate Representation
Loading...
Searching...
No Matches
dl.cpp
Go to the documentation of this file.
1#include "mim/util/dl.h"
2
3#include <cstdlib>
4
5#include <sstream>
6
7#include "mim/util/print.h"
8
9#ifdef _WIN32
10# include <windows.h>
11#else
12# include <dlfcn.h>
13#endif
14
15namespace mim::dl {
16
17void* open(const char* file) {
18#ifdef _WIN32
19 if (HMODULE handle = LoadLibraryA(file)) {
20 return static_cast<void*>(handle);
21 } else {
22 error("could not load plugin '{}' due to error '{}'\n"
23 "see https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes\n",
24 file, GetLastError());
25 }
26#else
27 if (void* handle = dlopen(file, RTLD_NOW))
28 return handle;
29 else if (auto err = dlerror())
30 error("could not load plugin '{}' due to error '{}'\n", file, err);
31 else
32 error("could not load plugin '{}'\n", file);
33#endif
34}
35
36void* get(void* handle, const char* symbol) {
37#ifdef _WIN32
38 if (auto addr = GetProcAddress(static_cast<HMODULE>(handle), symbol)) {
39 return reinterpret_cast<void*>(addr);
40 } else {
41 error("could not find symbol '{}' in plugin due to error '{}'\n"
42 "see (https://docs.microsoft.com/en-us/windows/win32/debug/system-error-codes)\n",
43 symbol, GetLastError());
44 }
45#else
46 dlerror(); // clear error state
47 void* addr = dlsym(handle, symbol);
48 if (auto err = dlerror())
49 error("could not find symbol '{}' in plugin due to error '{}' \n", symbol, err);
50 else
51 return addr;
52#endif
53}
54
55void close(void* handle) {
56#ifdef _WIN32
57 if (!FreeLibrary(static_cast<HMODULE>(handle))) error("FreeLibrary() failed\n");
58#else
59 if (auto err = dlclose(handle)) error("dlclose() failed with error code '{}'\n", err);
60#endif
61}
62
63} // namespace mim::dl
Definition dl.h:6
void * get(void *handle, const char *symbol_name)
Definition dl.cpp:36
void close(void *handle)
Definition dl.cpp:55
void * open(const char *filename)
Definition dl.cpp:17
void error(Loc loc, const char *f, Args &&... args)
Definition dbg.h:122