loadlib.c 15 KB

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