loadlib.c 14 KB

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