summaryrefslogtreecommitdiff
path: root/foreign_unix.c
blob: bb5dfb696d830449f16b995788344629483fead6 (plain)
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
#include <dlfcn.h>
typedef struct {
	void *handle;
} Library;

static FnPtr foreign_get_fn_ptr(ForeignFnManager *ffmgr, FnExpr *fn, Location call_where) {
	FnPtr fn_ptr = fn->foreign.fn_ptr;
	if (!fn_ptr) {
		assert(fn->flags & FN_EXPR_FOREIGN);
		const char *libname = fn->foreign.lib;
		if (!libname) {
			err_print(call_where, "Attempt to call function at compile time which does not have an associated library.");
			info_print(fn->where, "Function was declared here.");
			return NULL;
		}
		Library *lib = str_hash_table_get(&ffmgr->libs_loaded, libname, strlen(libname));
		if (!lib) {
			void *handle = dlopen(libname, RTLD_LAZY);
			if (!handle) {
				err_print(call_where, "Could not open dynamic library: %s.", libname);
				return NULL;
			}
			lib = str_hash_table_insert(&ffmgr->libs_loaded, libname, strlen(libname));
			lib->handle = handle;
		}
		const char *name = fn->foreign.name;
#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
		fn_ptr = dlsym(lib->handle, name);
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
		
		if (!fn_ptr) {
			err_print(call_where, "Could not get function from dynamic library: %s.", name);
			return NULL;
		}
		fn->foreign.fn_ptr = fn_ptr;
	}
	return fn_ptr;
}

#ifdef FOREIGN_USE_AVCALL
#include "foreign_avcall.c"
#elif defined __x86_64__
#include "foreign64.c"
#else
#include "foreign_avcall.c"
#endif