loadlib.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. /*
  2. ** $Id: loadlib.c,v 1.31 2005/07/05 19:29:03 roberto Exp roberto $
  3. ** Dynamic library loader for Lua
  4. ** See Copyright Notice in lua.h
  5. **
  6. ** This module contains an implementation of loadlib for Unix systems
  7. ** that have dlfcn, an implementation for Darwin (Mac OS X), an
  8. ** implementation for Windows, and a stub for other systems.
  9. */
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #define loadlib_c
  13. #define LUA_LIB
  14. #include "lua.h"
  15. #include "lauxlib.h"
  16. #include "lualib.h"
  17. /* environment variables that hold the search path for packages */
  18. #define LUA_PATH "LUA_PATH"
  19. #define LUA_CPATH "LUA_CPATH"
  20. /* prefix for open functions in C libraries */
  21. #define LUA_POF "luaopen_"
  22. /* separator for open functions in C libraries */
  23. #define LUA_OFSEP "_"
  24. #define LIBPREFIX "LOADLIB: "
  25. #define POF LUA_POF
  26. #define LIB_FAIL "open"
  27. #define setprogdir(L) ((void)0)
  28. static void ll_unloadlib (void *lib);
  29. static void *ll_load (lua_State *L, const char *path);
  30. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
  31. #if defined(LUA_DL_DLOPEN)
  32. /*
  33. ** {========================================================================
  34. ** This is an implementation of loadlib based on the dlfcn interface.
  35. ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  36. ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  37. ** as an emulation layer on top of native functions.
  38. ** =========================================================================
  39. */
  40. #include <dlfcn.h>
  41. static void ll_unloadlib (void *lib) {
  42. dlclose(lib);
  43. }
  44. static void *ll_load (lua_State *L, const char *path) {
  45. void *lib = dlopen(path, RTLD_NOW);
  46. if (lib == NULL) lua_pushstring(L, dlerror());
  47. return lib;
  48. }
  49. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  50. lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
  51. if (f == NULL) lua_pushstring(L, dlerror());
  52. return f;
  53. }
  54. /* }====================================================== */
  55. #elif defined(LUA_DL_DLL)
  56. /*
  57. ** {======================================================================
  58. ** This is an implementation of loadlib for Windows using native functions.
  59. ** =======================================================================
  60. */
  61. #include <windows.h>
  62. #include "Shlwapi.h"
  63. #undef setprogdir
  64. void setprogdir (lua_State *L) {
  65. char buff[MAX_PATH + 1];
  66. DWORD nsize = sizeof(buff)/sizeof(char);
  67. DWORD n = GetModuleFileName(NULL, buff, nsize);
  68. if (n == 0 || n == nsize)
  69. luaL_error(L, "unable to get ModuleFileName");
  70. PathRemoveFileSpec(buff);
  71. luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
  72. lua_remove(L, -2); /* remove original string */
  73. }
  74. static void pusherror (lua_State *L) {
  75. int error = GetLastError();
  76. char buffer[128];
  77. if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  78. NULL, error, 0, buffer, sizeof(buffer), NULL))
  79. lua_pushstring(L, buffer);
  80. else
  81. lua_pushfstring(L, "system error %d\n", error);
  82. }
  83. static void ll_unloadlib (void *lib) {
  84. FreeLibrary((HINSTANCE)lib);
  85. }
  86. static void *ll_load (lua_State *L, const char *path) {
  87. HINSTANCE lib = LoadLibrary(path);
  88. if (lib == NULL) pusherror(L);
  89. return lib;
  90. }
  91. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  92. lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
  93. if (f == NULL) pusherror(L);
  94. return f;
  95. }
  96. /* }====================================================== */
  97. #elif defined(LUA_DL_DYLD)
  98. /*
  99. ** {======================================================================
  100. ** Native Mac OS X / Darwin Implementation
  101. ** =======================================================================
  102. */
  103. #include <mach-o/dyld.h>
  104. /* Mac appends a `_' before C function names */
  105. #undef POF
  106. #define POF "_" LUA_POF
  107. static void pusherror (lua_State *L) {
  108. const char *err_str;
  109. const char *err_file;
  110. NSLinkEditErrors err;
  111. int err_num;
  112. NSLinkEditError(&err, &err_num, &err_file, &err_str);
  113. lua_pushstring(L, err_str);
  114. }
  115. static const char *errorfromcode (NSObjectFileImageReturnCode ret) {
  116. switch (ret) {
  117. case NSObjectFileImageInappropriateFile:
  118. return "file is not a bundle";
  119. case NSObjectFileImageArch:
  120. return "library is for wrong CPU type";
  121. case NSObjectFileImageFormat:
  122. return "bad format";
  123. case NSObjectFileImageAccess:
  124. return "cannot access file";
  125. case NSObjectFileImageFailure:
  126. default:
  127. return "unable to load library";
  128. }
  129. }
  130. static void ll_unloadlib (void *lib) {
  131. NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
  132. }
  133. static void *ll_load (lua_State *L, const char *path) {
  134. NSObjectFileImage img;
  135. NSObjectFileImageReturnCode ret;
  136. /* this would be a rare case, but prevents crashing if it happens */
  137. if(!_dyld_present()) {
  138. lua_pushliteral(L, "dyld not present");
  139. return NULL;
  140. }
  141. ret = NSCreateObjectFileImageFromFile(path, &img);
  142. if (ret == NSObjectFileImageSuccess) {
  143. NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE |
  144. NSLINKMODULE_OPTION_RETURN_ON_ERROR);
  145. NSDestroyObjectFileImage(img);
  146. if (mod == NULL) pusherror(L);
  147. return mod;
  148. }
  149. lua_pushstring(L, errorfromcode(ret));
  150. return NULL;
  151. }
  152. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  153. NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
  154. if (nss == NULL) {
  155. lua_pushfstring(L, "symbol " LUA_QS " not found", sym);
  156. return NULL;
  157. }
  158. return (lua_CFunction)NSAddressOfSymbol(nss);
  159. }
  160. /* }====================================================== */
  161. #else
  162. /*
  163. ** {======================================================
  164. ** Fallback for other systems
  165. ** =======================================================
  166. */
  167. #undef LIB_FAIL
  168. #define LIB_FAIL "absent"
  169. #if defined(__ELF__) || defined(__sun) || defined(sgi) || defined(__hpux)
  170. #define DLMSG LUA_QL("loadlib") " not enabled; check your Lua installation"
  171. #else
  172. #define DLMSG LUA_QL("loadlib") " not supported"
  173. #endif
  174. static void ll_unloadlib (void *lib) {
  175. (void)lib; /* to avoid warnings */
  176. }
  177. static void *ll_load (lua_State *L, const char *path) {
  178. (void)path; /* to avoid warnings */
  179. lua_pushliteral(L, DLMSG);
  180. return NULL;
  181. }
  182. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  183. (void)lib; (void)sym; /* to avoid warnings */
  184. lua_pushliteral(L, DLMSG);
  185. return NULL;
  186. }
  187. /* }====================================================== */
  188. #endif
  189. static void **ll_register (lua_State *L, const char *path) {
  190. void **plib;
  191. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  192. lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
  193. if (!lua_isnil(L, -1)) /* is there an entry? */
  194. plib = (void **)lua_touserdata(L, -1);
  195. else { /* no entry yet; create one */
  196. lua_pop(L, 1);
  197. plib = (void **)lua_newuserdata(L, sizeof(const void *));
  198. *plib = NULL;
  199. luaL_getmetatable(L, "_LOADLIB");
  200. lua_setmetatable(L, -2);
  201. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  202. lua_pushvalue(L, -2);
  203. lua_settable(L, LUA_REGISTRYINDEX);
  204. }
  205. return plib;
  206. }
  207. /*
  208. ** __gc tag method: calls library's `ll_unloadlib' function with the lib
  209. ** handle
  210. */
  211. static int gctm (lua_State *L) {
  212. void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
  213. if (lib) {
  214. if (*lib) ll_unloadlib(*lib);
  215. *lib = NULL; /* mark library as closed */
  216. }
  217. return 0;
  218. }
  219. static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
  220. const char *reason;
  221. void **reg = ll_register(L, path);
  222. if (*reg == NULL) *reg = ll_load(L, path);
  223. if (*reg == NULL)
  224. reason = LIB_FAIL;
  225. else {
  226. lua_CFunction f = ll_sym(L, *reg, sym);
  227. if (f) {
  228. lua_pushcfunction(L, f);
  229. return 1; /* return function */
  230. }
  231. reason = "init";
  232. }
  233. lua_pushnil(L);
  234. lua_insert(L, -2);
  235. lua_pushstring(L, reason);
  236. return 3; /* return nil, ll_error, reason */
  237. }
  238. static int ll_loadlib (lua_State *L) {
  239. const char *path = luaL_checkstring(L, 1);
  240. const char *init = luaL_checkstring(L, 2);
  241. return ll_loadfunc(L, path, init);
  242. }
  243. /*
  244. ** {======================================================
  245. ** `require' and `module' functions
  246. ** =======================================================
  247. */
  248. static int loader_Lua (lua_State *L) {
  249. const char *name = luaL_checkstring(L, 1);
  250. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  251. const char *path = NULL;
  252. #if defined(LUA_COMPAT_PATH)
  253. /* try first `LUA_PATH' for compatibility */
  254. lua_pushstring(L, "LUA_PATH");
  255. lua_rawget(L, LUA_GLOBALSINDEX);
  256. path = lua_tostring(L, -1);
  257. #endif
  258. if (!path) {
  259. lua_pop(L, 1);
  260. lua_getfield(L, LUA_ENVIRONINDEX, "path");
  261. path = lua_tostring(L, -1);
  262. }
  263. if (path == NULL)
  264. luaL_error(L, LUA_QL("package.path") " must be a string");
  265. fname = luaL_searchpath(L, fname, path);
  266. if (fname == NULL) return 0; /* library not found in this path */
  267. if (luaL_loadfile(L, fname) != 0)
  268. luaL_error(L, "error loading package " LUA_QS " (%s)",
  269. name, lua_tostring(L, -1));
  270. return 1; /* library loaded successfully */
  271. }
  272. static int loader_C (lua_State *L) {
  273. const char *name = luaL_checkstring(L, 1);
  274. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  275. const char *path;
  276. const char *funcname;
  277. lua_getfield(L, LUA_ENVIRONINDEX, "cpath");
  278. path = lua_tostring(L, -1);
  279. if (path == NULL)
  280. luaL_error(L, LUA_QL("package.cpath") " must be a string");
  281. fname = luaL_searchpath(L, fname, path);
  282. if (fname == NULL) return 0; /* library not found in this path */
  283. funcname = luaL_gsub(L, name, ".", LUA_OFSEP);
  284. funcname = lua_pushfstring(L, "%s%s", POF, funcname);
  285. if (ll_loadfunc(L, fname, funcname) != 1)
  286. luaL_error(L, "error loading package " LUA_QS " (%s)",
  287. name, lua_tostring(L, -2));
  288. return 1; /* library loaded successfully */
  289. }
  290. static int loader_preload (lua_State *L) {
  291. lua_getfield(L, LUA_ENVIRONINDEX, "preload");
  292. if (!lua_istable(L, -1))
  293. luaL_error(L, LUA_QL("package.preload") " must be a table");
  294. lua_getfield(L, -1, luaL_checkstring(L, 1));
  295. return 1;
  296. }
  297. static void require_aux (lua_State *L, const char *name) {
  298. int i;
  299. int loadedtable = lua_gettop(L) + 1;
  300. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  301. lua_getfield(L, loadedtable, name);
  302. if (lua_toboolean(L, -1)) /* is it there? */
  303. return; /* package is already loaded; return its result */
  304. /* else must load it; iterate over available loaders */
  305. lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  306. if (!lua_istable(L, -1))
  307. luaL_error(L, LUA_QL("package.loaders") " must be a table");
  308. for (i=1; ; i++) {
  309. lua_rawgeti(L, -1, i); /* get a loader */
  310. if (lua_isnil(L, -1))
  311. luaL_error(L, "package " LUA_QS " not found", name);
  312. lua_pushstring(L, name);
  313. lua_call(L, 1, 1); /* call it */
  314. if (lua_isnil(L, -1)) lua_pop(L, 1); /* did not found module */
  315. else break; /* module loaded successfully */
  316. }
  317. lua_pushboolean(L, 1);
  318. lua_setfield(L, loadedtable, name); /* _LOADED[name] = true */
  319. lua_pushstring(L, name); /* pass name as argument to module */
  320. if (lua_pcall(L, 1, 1, 0) != 0) { /* run loaded module */
  321. lua_pushnil(L); /* in case of errors... */
  322. lua_setfield(L, loadedtable, name); /* ...clear _LOADED[name] */
  323. luaL_error(L, "error loading package " LUA_QS " (%s)",
  324. name, lua_tostring(L, -1)); /* propagate error */
  325. }
  326. if (!lua_isnil(L, -1)) /* non-nil return? */
  327. lua_setfield(L, loadedtable, name); /* _LOADED[name] = returned value */
  328. lua_getfield(L, loadedtable, name); /* return _LOADED[name] */
  329. return;
  330. }
  331. static int ll_require (lua_State *L) {
  332. const char *name = luaL_checkstring(L, 1);
  333. const char *pt;
  334. /* load all parent modules */
  335. for (pt = name; (pt = strchr(pt, '.')) != NULL; pt++) {
  336. lua_settop(L, 1);
  337. lua_pushlstring(L, name, pt - name);
  338. require_aux(L, lua_tostring(L, -1));
  339. }
  340. require_aux(L, name); /* load module itself */
  341. return 1;
  342. }
  343. static void setfenv (lua_State *L) {
  344. lua_Debug ar;
  345. lua_getstack(L, 1, &ar);
  346. lua_getinfo(L, "f", &ar);
  347. lua_pushvalue(L, -2);
  348. lua_setfenv(L, -2);
  349. }
  350. static int ll_module (lua_State *L) {
  351. const char *modname = luaL_checkstring(L, 1);
  352. const char *dot;
  353. lua_settop(L, 1);
  354. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  355. /* try to find given table */
  356. luaL_getfield(L, LUA_GLOBALSINDEX, modname);
  357. if (lua_isnil(L, -1)) { /* not found? */
  358. lua_pop(L, 1); /* remove previous result */
  359. lua_newtable(L); /* create it */
  360. /* register it with given name */
  361. lua_pushvalue(L, -1);
  362. luaL_setfield(L, LUA_GLOBALSINDEX, modname);
  363. }
  364. else if (!lua_istable(L, -1))
  365. return luaL_error(L, "name conflict for module " LUA_QS, modname);
  366. /* check whether table already has a _NAME field */
  367. lua_getfield(L, -1, "_NAME");
  368. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  369. lua_pop(L, 1);
  370. else { /* no; initialize it */
  371. lua_pop(L, 1);
  372. lua_newtable(L); /* create new metatable */
  373. lua_pushvalue(L, LUA_GLOBALSINDEX);
  374. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  375. lua_setmetatable(L, -2);
  376. lua_pushvalue(L, -1);
  377. lua_setfield(L, -2, "_M"); /* module._M = module */
  378. lua_pushstring(L, modname);
  379. lua_setfield(L, -2, "_NAME");
  380. dot = strrchr(modname, '.'); /* look for last dot in module name */
  381. if (dot == NULL) dot = modname;
  382. else dot++;
  383. /* set _PACKAGE as package name (full module name minus last part) */
  384. lua_pushlstring(L, modname, dot - modname);
  385. lua_setfield(L, -2, "_PACKAGE");
  386. }
  387. lua_pushvalue(L, -1);
  388. lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
  389. setfenv(L);
  390. return 0;
  391. }
  392. /* }====================================================== */
  393. static void setpath (lua_State *L, const char *fname, const char *envname,
  394. const char *def) {
  395. const char *path = getenv(envname);
  396. if (path == NULL) lua_pushstring(L, def);
  397. else {
  398. /* replace ";;" by default path */
  399. path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
  400. LUA_PATHSEP"\1"LUA_PATHSEP);
  401. luaL_gsub(L, path, "\1", def);
  402. lua_remove(L, -2);
  403. }
  404. setprogdir(L);
  405. lua_setfield(L, -2, fname);
  406. }
  407. static const luaL_reg ll_funcs[] = {
  408. {"require", ll_require},
  409. {"module", ll_module},
  410. {NULL, NULL}
  411. };
  412. static const lua_CFunction loaders[] =
  413. {loader_preload, loader_Lua, loader_C, NULL};
  414. LUALIB_API int luaopen_loadlib (lua_State *L) {
  415. int i;
  416. /* create new type _LOADLIB */
  417. luaL_newmetatable(L, "_LOADLIB");
  418. lua_pushcfunction(L, gctm);
  419. lua_setfield(L, -2, "__gc");
  420. /* create `package' table */
  421. lua_newtable(L);
  422. lua_pushvalue(L, -1);
  423. lua_setglobal(L, LUA_LOADLIBNAME);
  424. lua_pushvalue(L, -1);
  425. lua_setfield(L, LUA_REGISTRYINDEX, "_PACKAGE");
  426. lua_pushvalue(L, -1);
  427. lua_replace(L, LUA_ENVIRONINDEX);
  428. /* create `loaders' table */
  429. lua_newtable(L);
  430. /* fill it with pre-defined loaders */
  431. for (i=0; loaders[i] != NULL; i++) {
  432. lua_pushcfunction(L, loaders[i]);
  433. lua_rawseti(L, -2, i+1);
  434. }
  435. lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
  436. setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT); /* set field `path' */
  437. setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */
  438. /* set field `loaded' */
  439. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  440. lua_setfield(L, -2, "loaded");
  441. /* set field `preload' */
  442. lua_newtable(L);
  443. lua_setfield(L, -2, "preload");
  444. /* create `loadlib' function */
  445. lua_pushcfunction(L, ll_loadlib);
  446. #if defined(LUA_COMPAT_LOADLIB)
  447. lua_pushvalue(L, -1);
  448. lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
  449. #endif
  450. lua_setfield(L, -2, "loadlib");
  451. lua_pushvalue(L, LUA_GLOBALSINDEX);
  452. luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
  453. return 1;
  454. }