Merge branch 'master' into v2.1
[luajit-2.0.git] / src / lj_clib.c
blob70e1c8f32da27ffc9fbef981f188b474bd9917af
1 /*
2 ** FFI C library loader.
3 ** Copyright (C) 2005-2014 Mike Pall. See Copyright Notice in luajit.h
4 */
6 #include "lj_obj.h"
8 #if LJ_HASFFI
10 #include "lj_gc.h"
11 #include "lj_err.h"
12 #include "lj_tab.h"
13 #include "lj_str.h"
14 #include "lj_udata.h"
15 #include "lj_ctype.h"
16 #include "lj_cconv.h"
17 #include "lj_cdata.h"
18 #include "lj_clib.h"
19 #include "lj_strfmt.h"
21 /* -- OS-specific functions ----------------------------------------------- */
23 #if LJ_TARGET_DLOPEN
25 #include <dlfcn.h>
26 #include <stdio.h>
28 #if defined(RTLD_DEFAULT)
29 #define CLIB_DEFHANDLE RTLD_DEFAULT
30 #elif LJ_TARGET_OSX || LJ_TARGET_BSD
31 #define CLIB_DEFHANDLE ((void *)(intptr_t)-2)
32 #else
33 #define CLIB_DEFHANDLE NULL
34 #endif
36 LJ_NORET LJ_NOINLINE static void clib_error_(lua_State *L)
38 lj_err_callermsg(L, dlerror());
41 #define clib_error(L, fmt, name) clib_error_(L)
43 #if defined(__CYGWIN__)
44 #define CLIB_SOPREFIX "cyg"
45 #else
46 #define CLIB_SOPREFIX "lib"
47 #endif
49 #if LJ_TARGET_OSX
50 #define CLIB_SOEXT "%s.dylib"
51 #elif defined(__CYGWIN__)
52 #define CLIB_SOEXT "%s.dll"
53 #else
54 #define CLIB_SOEXT "%s.so"
55 #endif
57 static const char *clib_extname(lua_State *L, const char *name)
59 if (!strchr(name, '/')
60 #ifdef __CYGWIN__
61 && !strchr(name, '\\')
62 #endif
63 ) {
64 if (!strchr(name, '.')) {
65 name = lj_strfmt_pushf(L, CLIB_SOEXT, name);
66 L->top--;
67 #ifdef __CYGWIN__
68 } else {
69 return name;
70 #endif
72 if (!(name[0] == CLIB_SOPREFIX[0] && name[1] == CLIB_SOPREFIX[1] &&
73 name[2] == CLIB_SOPREFIX[2])) {
74 name = lj_strfmt_pushf(L, CLIB_SOPREFIX "%s", name);
75 L->top--;
78 return name;
81 /* Check for a recognized ld script line. */
82 static const char *clib_check_lds(lua_State *L, const char *buf)
84 char *p, *e;
85 if ((!strncmp(buf, "GROUP", 5) || !strncmp(buf, "INPUT", 5)) &&
86 (p = strchr(buf, '('))) {
87 while (*++p == ' ') ;
88 for (e = p; *e && *e != ' ' && *e != ')'; e++) ;
89 return strdata(lj_str_new(L, p, e-p));
91 return NULL;
94 /* Quick and dirty solution to resolve shared library name from ld script. */
95 static const char *clib_resolve_lds(lua_State *L, const char *name)
97 FILE *fp = fopen(name, "r");
98 const char *p = NULL;
99 if (fp) {
100 char buf[256];
101 if (fgets(buf, sizeof(buf), fp)) {
102 if (!strncmp(buf, "/* GNU ld script", 16)) { /* ld script magic? */
103 while (fgets(buf, sizeof(buf), fp)) { /* Check all lines. */
104 p = clib_check_lds(L, buf);
105 if (p) break;
107 } else { /* Otherwise check only the first line. */
108 p = clib_check_lds(L, buf);
111 fclose(fp);
113 return p;
116 static void *clib_loadlib(lua_State *L, const char *name, int global)
118 void *h = dlopen(clib_extname(L, name),
119 RTLD_LAZY | (global?RTLD_GLOBAL:RTLD_LOCAL));
120 if (!h) {
121 const char *e, *err = dlerror();
122 if (*err == '/' && (e = strchr(err, ':')) &&
123 (name = clib_resolve_lds(L, strdata(lj_str_new(L, err, e-err))))) {
124 h = dlopen(name, RTLD_LAZY | (global?RTLD_GLOBAL:RTLD_LOCAL));
125 if (h) return h;
126 err = dlerror();
128 lj_err_callermsg(L, err);
130 return h;
133 static void clib_unloadlib(CLibrary *cl)
135 if (cl->handle && cl->handle != CLIB_DEFHANDLE)
136 dlclose(cl->handle);
139 static void *clib_getsym(CLibrary *cl, const char *name)
141 void *p = dlsym(cl->handle, name);
142 return p;
145 #elif LJ_TARGET_WINDOWS
147 #define WIN32_LEAN_AND_MEAN
148 #include <windows.h>
150 #ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
151 #define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
152 #define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
153 BOOL WINAPI GetModuleHandleExA(DWORD, LPCSTR, HMODULE*);
154 #endif
156 #define CLIB_DEFHANDLE ((void *)-1)
158 /* Default libraries. */
159 enum {
160 CLIB_HANDLE_EXE,
161 CLIB_HANDLE_DLL,
162 CLIB_HANDLE_CRT,
163 CLIB_HANDLE_KERNEL32,
164 CLIB_HANDLE_USER32,
165 CLIB_HANDLE_GDI32,
166 CLIB_HANDLE_MAX
169 static void *clib_def_handle[CLIB_HANDLE_MAX];
171 LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt,
172 const char *name)
174 DWORD err = GetLastError();
175 char buf[128];
176 if (!FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS|FORMAT_MESSAGE_FROM_SYSTEM,
177 NULL, err, 0, buf, sizeof(buf), NULL))
178 buf[0] = '\0';
179 lj_err_callermsg(L, lj_strfmt_pushf(L, fmt, name, buf));
182 static int clib_needext(const char *s)
184 while (*s) {
185 if (*s == '/' || *s == '\\' || *s == '.') return 0;
186 s++;
188 return 1;
191 static const char *clib_extname(lua_State *L, const char *name)
193 if (clib_needext(name)) {
194 name = lj_strfmt_pushf(L, "%s.dll", name);
195 L->top--;
197 return name;
200 static void *clib_loadlib(lua_State *L, const char *name, int global)
202 DWORD oldwerr = GetLastError();
203 void *h = (void *)LoadLibraryA(clib_extname(L, name));
204 if (!h) clib_error(L, "cannot load module " LUA_QS ": %s", name);
205 SetLastError(oldwerr);
206 UNUSED(global);
207 return h;
210 static void clib_unloadlib(CLibrary *cl)
212 if (cl->handle == CLIB_DEFHANDLE) {
213 MSize i;
214 for (i = CLIB_HANDLE_KERNEL32; i < CLIB_HANDLE_MAX; i++) {
215 void *h = clib_def_handle[i];
216 if (h) {
217 clib_def_handle[i] = NULL;
218 FreeLibrary((HINSTANCE)h);
221 } else if (cl->handle) {
222 FreeLibrary((HINSTANCE)cl->handle);
226 static void *clib_getsym(CLibrary *cl, const char *name)
228 void *p = NULL;
229 if (cl->handle == CLIB_DEFHANDLE) { /* Search default libraries. */
230 MSize i;
231 for (i = 0; i < CLIB_HANDLE_MAX; i++) {
232 HINSTANCE h = (HINSTANCE)clib_def_handle[i];
233 if (!(void *)h) { /* Resolve default library handles (once). */
234 switch (i) {
235 case CLIB_HANDLE_EXE: GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, NULL, &h); break;
236 case CLIB_HANDLE_DLL:
237 GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
238 (const char *)clib_def_handle, &h);
239 break;
240 case CLIB_HANDLE_CRT:
241 GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
242 (const char *)&_fmode, &h);
243 break;
244 case CLIB_HANDLE_KERNEL32: h = LoadLibraryA("kernel32.dll"); break;
245 case CLIB_HANDLE_USER32: h = LoadLibraryA("user32.dll"); break;
246 case CLIB_HANDLE_GDI32: h = LoadLibraryA("gdi32.dll"); break;
248 if (!h) continue;
249 clib_def_handle[i] = (void *)h;
251 p = (void *)GetProcAddress(h, name);
252 if (p) break;
254 } else {
255 p = (void *)GetProcAddress((HINSTANCE)cl->handle, name);
257 return p;
260 #else
262 #define CLIB_DEFHANDLE NULL
264 LJ_NORET LJ_NOINLINE static void clib_error(lua_State *L, const char *fmt,
265 const char *name)
267 lj_err_callermsg(L, lj_strfmt_pushf(L, fmt, name, "no support for this OS"));
270 static void *clib_loadlib(lua_State *L, const char *name, int global)
272 lj_err_callermsg(L, "no support for loading dynamic libraries for this OS");
273 UNUSED(name); UNUSED(global);
274 return NULL;
277 static void clib_unloadlib(CLibrary *cl)
279 UNUSED(cl);
282 static void *clib_getsym(CLibrary *cl, const char *name)
284 UNUSED(cl); UNUSED(name);
285 return NULL;
288 #endif
290 /* -- C library indexing -------------------------------------------------- */
292 #if LJ_TARGET_X86 && LJ_ABI_WIN
293 /* Compute argument size for fastcall/stdcall functions. */
294 static CTSize clib_func_argsize(CTState *cts, CType *ct)
296 CTSize n = 0;
297 while (ct->sib) {
298 CType *d;
299 ct = ctype_get(cts, ct->sib);
300 if (ctype_isfield(ct->info)) {
301 d = ctype_rawchild(cts, ct);
302 n += ((d->size + 3) & ~3);
305 return n;
307 #endif
309 /* Get redirected or mangled external symbol. */
310 static const char *clib_extsym(CTState *cts, CType *ct, GCstr *name)
312 if (ct->sib) {
313 CType *ctf = ctype_get(cts, ct->sib);
314 if (ctype_isxattrib(ctf->info, CTA_REDIR))
315 return strdata(gco2str(gcref(ctf->name)));
317 return strdata(name);
320 /* Index a C library by name. */
321 TValue *lj_clib_index(lua_State *L, CLibrary *cl, GCstr *name)
323 TValue *tv = lj_tab_setstr(L, cl->cache, name);
324 if (LJ_UNLIKELY(tvisnil(tv))) {
325 CTState *cts = ctype_cts(L);
326 CType *ct;
327 CTypeID id = lj_ctype_getname(cts, &ct, name, CLNS_INDEX);
328 if (!id)
329 lj_err_callerv(L, LJ_ERR_FFI_NODECL, strdata(name));
330 if (ctype_isconstval(ct->info)) {
331 CType *ctt = ctype_child(cts, ct);
332 lua_assert(ctype_isinteger(ctt->info) && ctt->size <= 4);
333 if ((ctt->info & CTF_UNSIGNED) && (int32_t)ct->size < 0)
334 setnumV(tv, (lua_Number)(uint32_t)ct->size);
335 else
336 setintV(tv, (int32_t)ct->size);
337 } else {
338 const char *sym = clib_extsym(cts, ct, name);
339 #if LJ_TARGET_WINDOWS
340 DWORD oldwerr = GetLastError();
341 #endif
342 void *p = clib_getsym(cl, sym);
343 GCcdata *cd;
344 lua_assert(ctype_isfunc(ct->info) || ctype_isextern(ct->info));
345 #if LJ_TARGET_X86 && LJ_ABI_WIN
346 /* Retry with decorated name for fastcall/stdcall functions. */
347 if (!p && ctype_isfunc(ct->info)) {
348 CTInfo cconv = ctype_cconv(ct->info);
349 if (cconv == CTCC_FASTCALL || cconv == CTCC_STDCALL) {
350 CTSize sz = clib_func_argsize(cts, ct);
351 const char *symd = lj_strfmt_pushf(L,
352 cconv == CTCC_FASTCALL ? "@%s@%d" : "_%s@%d",
353 sym, sz);
354 L->top--;
355 p = clib_getsym(cl, symd);
358 #endif
359 if (!p)
360 clib_error(L, "cannot resolve symbol " LUA_QS ": %s", sym);
361 #if LJ_TARGET_WINDOWS
362 SetLastError(oldwerr);
363 #endif
364 cd = lj_cdata_new(cts, id, CTSIZE_PTR);
365 *(void **)cdataptr(cd) = p;
366 setcdataV(L, tv, cd);
369 return tv;
372 /* -- C library management ------------------------------------------------ */
374 /* Create a new CLibrary object and push it on the stack. */
375 static CLibrary *clib_new(lua_State *L, GCtab *mt)
377 GCtab *t = lj_tab_new(L, 0, 0);
378 GCudata *ud = lj_udata_new(L, sizeof(CLibrary), t);
379 CLibrary *cl = (CLibrary *)uddata(ud);
380 cl->cache = t;
381 ud->udtype = UDTYPE_FFI_CLIB;
382 /* NOBARRIER: The GCudata is new (marked white). */
383 setgcref(ud->metatable, obj2gco(mt));
384 setudataV(L, L->top++, ud);
385 return cl;
388 /* Load a C library. */
389 void lj_clib_load(lua_State *L, GCtab *mt, GCstr *name, int global)
391 void *handle = clib_loadlib(L, strdata(name), global);
392 CLibrary *cl = clib_new(L, mt);
393 cl->handle = handle;
396 /* Unload a C library. */
397 void lj_clib_unload(CLibrary *cl)
399 clib_unloadlib(cl);
400 cl->handle = NULL;
403 /* Create the default C library object. */
404 void lj_clib_default(lua_State *L, GCtab *mt)
406 CLibrary *cl = clib_new(L, mt);
407 cl->handle = CLIB_DEFHANDLE;
410 #endif