loadlib.c 13 KB

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