lj_clib.c 10 KB

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