loadlib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. /*
  2. ** $Id: loadlib.c,v 1.21 2005/03/09 16:28:07 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_USE_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_USE_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_USE_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 `%s' 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. static void ll_unloadlib (void *lib) {
  157. (void)lib; /* to avoid warnings */
  158. }
  159. static void *ll_load (lua_State *L, const char *path) {
  160. (void)path; /* to avoid warnings */
  161. lua_pushliteral(L,"`loadlib' not supported");
  162. return NULL;
  163. }
  164. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  165. (void)lib; (void)sym; /* to avoid warnings */
  166. lua_pushliteral(L,"`loadlib' not supported");
  167. return NULL;
  168. }
  169. /* }====================================================== */
  170. #endif
  171. static void **ll_register (lua_State *L, const char *path) {
  172. void **plib;
  173. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  174. lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
  175. if (!lua_isnil(L, -1)) /* is there an entry? */
  176. plib = (void **)lua_touserdata(L, -1);
  177. else { /* no entry yet; create one */
  178. lua_pop(L, 1);
  179. plib = (void **)lua_newuserdata(L, sizeof(const void *));
  180. *plib = NULL;
  181. luaL_getmetatable(L, "_LOADLIB");
  182. lua_setmetatable(L, -2);
  183. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  184. lua_pushvalue(L, -2);
  185. lua_settable(L, LUA_REGISTRYINDEX);
  186. }
  187. return plib;
  188. }
  189. /*
  190. ** __gc tag method: calls library's `ll_unloadlib' function with the lib
  191. ** handle
  192. */
  193. static int gctm (lua_State *L) {
  194. void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
  195. if (lib) {
  196. if (*lib) ll_unloadlib(*lib);
  197. *lib = NULL; /* mark library as closed */
  198. }
  199. return 0;
  200. }
  201. static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
  202. const char *reason;
  203. void **reg = ll_register(L, path);
  204. if (*reg == NULL) *reg = ll_load(L, path);
  205. if (*reg == NULL)
  206. reason = LIB_FAIL;
  207. else {
  208. lua_CFunction f = ll_sym(L, *reg, sym);
  209. if (f) {
  210. lua_pushcfunction(L, f);
  211. return 1; /* return function */
  212. }
  213. reason = "init";
  214. }
  215. lua_pushnil(L);
  216. lua_insert(L, -2);
  217. lua_pushstring(L, reason);
  218. return 3; /* return nil, ll_error, reason */
  219. }
  220. static int ll_loadlib (lua_State *L) {
  221. const char *path = luaL_checkstring(L, 1);
  222. const char *init = luaL_checkstring(L, 2);
  223. return ll_loadfunc(L, path, init);
  224. }
  225. /*
  226. ** {======================================================
  227. ** `require' and `module' functions
  228. ** =======================================================
  229. */
  230. static int loader_Lua (lua_State *L) {
  231. const char *name = luaL_checkstring(L, 1);
  232. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  233. const char *path;
  234. /* try first `LUA_PATH' for compatibility */
  235. lua_pushstring(L, "LUA_PATH");
  236. lua_rawget(L, LUA_GLOBALSINDEX);
  237. path = lua_tostring(L, -1);
  238. if (!path) {
  239. lua_pop(L, 1);
  240. lua_getfield(L, LUA_ENVIRONINDEX, "path");
  241. path = lua_tostring(L, -1);
  242. }
  243. if (path == NULL)
  244. luaL_error(L, "`package.path' must be a string");
  245. fname = luaL_searchpath(L, fname, path);
  246. if (fname == NULL) return 0; /* library not found in this path */
  247. if (luaL_loadfile(L, fname) != 0)
  248. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -1));
  249. return 1; /* library loaded successfully */
  250. }
  251. static int loader_C (lua_State *L) {
  252. const char *name = luaL_checkstring(L, 1);
  253. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  254. const char *path;
  255. const char *funcname;
  256. lua_getfield(L, LUA_ENVIRONINDEX, "cpath");
  257. path = lua_tostring(L, -1);
  258. if (path == NULL)
  259. luaL_error(L, "`package.cpath' must be a string");
  260. fname = luaL_searchpath(L, fname, path);
  261. if (fname == NULL) return 0; /* library not found in this path */
  262. funcname = luaL_gsub(L, name, ".", LUA_OFSEP);
  263. funcname = lua_pushfstring(L, "%s%s", POF, funcname);
  264. if (ll_loadfunc(L, fname, funcname) != 1)
  265. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -2));
  266. return 1; /* library loaded successfully */
  267. }
  268. static int loader_preload (lua_State *L) {
  269. lua_getfield(L, LUA_ENVIRONINDEX, "preload");
  270. if (!lua_istable(L, -1))
  271. luaL_error(L, "`package.preload' must be a table");
  272. lua_getfield(L, -1, luaL_checkstring(L, 1));
  273. return 1;
  274. }
  275. static int ll_require (lua_State *L) {
  276. const char *name = luaL_checkstring(L, 1);
  277. int i;
  278. lua_settop(L, 1);
  279. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  280. lua_getfield(L, 2, name);
  281. if (lua_toboolean(L, -1)) /* is it there? */
  282. return 1; /* package is already loaded; return its result */
  283. /* else must load it; first mark it as loaded */
  284. lua_pushboolean(L, 1);
  285. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  286. /* iterate over available loaders */
  287. lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  288. if (!lua_istable(L, -1))
  289. luaL_error(L, "`package.loaders' must be a table");
  290. for (i=1;; i++) {
  291. lua_rawgeti(L, -1, i); /* get a loader */
  292. if (lua_isnil(L, -1))
  293. return luaL_error(L, "package `%s' not found", name);
  294. lua_pushstring(L, name);
  295. lua_call(L, 1, 1); /* call it */
  296. if (lua_isnil(L, -1)) lua_pop(L, 1);
  297. else break; /* module loaded successfully */
  298. }
  299. lua_pushvalue(L, 1); /* pass name as argument to module */
  300. lua_call(L, 1, 1); /* run loaded module */
  301. if (!lua_isnil(L, -1)) /* non-nil return? */
  302. lua_setfield(L, 2, name); /* update _LOADED[name] with returned value */
  303. lua_getfield(L, 2, name); /* return _LOADED[name] */
  304. return 1;
  305. }
  306. static void setfenv (lua_State *L) {
  307. lua_Debug ar;
  308. lua_getstack(L, 1, &ar);
  309. lua_getinfo(L, "f", &ar);
  310. lua_pushvalue(L, -2);
  311. lua_setfenv(L, -2);
  312. }
  313. static int ll_module (lua_State *L) {
  314. const char *modname = luaL_checkstring(L, 1);
  315. const char *dot;
  316. lua_settop(L, 1);
  317. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  318. /* try to find given table */
  319. luaL_getfield(L, LUA_GLOBALSINDEX, modname);
  320. if (lua_isnil(L, -1)) { /* not found? */
  321. lua_pop(L, 1); /* remove previous result */
  322. lua_newtable(L); /* create it */
  323. /* register it with given name */
  324. lua_pushvalue(L, -1);
  325. luaL_setfield(L, LUA_GLOBALSINDEX, modname);
  326. }
  327. else if (!lua_istable(L, -1))
  328. return luaL_error(L, "name conflict for module `%s'", modname);
  329. /* check whether table already has a _NAME field */
  330. lua_getfield(L, -1, "_NAME");
  331. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  332. lua_pop(L, 1);
  333. else { /* no; initialize it */
  334. lua_pop(L, 1);
  335. lua_newtable(L); /* create new metatable */
  336. lua_pushvalue(L, LUA_GLOBALSINDEX);
  337. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  338. lua_setmetatable(L, -2);
  339. lua_pushvalue(L, -1);
  340. lua_setfield(L, -2, "_M"); /* module._M = module */
  341. lua_pushstring(L, modname);
  342. lua_setfield(L, -2, "_NAME");
  343. dot = strrchr(modname, '.'); /* look for last dot in module name */
  344. if (dot == NULL) dot = modname;
  345. else dot++;
  346. /* set _PACKAGE as package name (full module name minus last part) */
  347. lua_pushlstring(L, modname, dot - modname);
  348. lua_setfield(L, -2, "_PACKAGE");
  349. }
  350. lua_pushvalue(L, -1);
  351. lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
  352. setfenv(L);
  353. return 0;
  354. }
  355. /* }====================================================== */
  356. static const luaL_reg ll_funcs[] = {
  357. {"require", ll_require},
  358. {"module", ll_module},
  359. {NULL, NULL}
  360. };
  361. static const lua_CFunction loaders[] =
  362. {loader_preload, loader_C, loader_Lua, NULL};
  363. LUALIB_API int luaopen_loadlib (lua_State *L) {
  364. const char *path;
  365. int i;
  366. /* create new type _LOADLIB */
  367. luaL_newmetatable(L, "_LOADLIB");
  368. lua_pushcfunction(L, gctm);
  369. lua_setfield(L, -2, "__gc");
  370. /* create `package' table */
  371. lua_newtable(L);
  372. lua_pushvalue(L, -1);
  373. lua_setglobal(L, "package");
  374. lua_pushvalue(L, -1);
  375. lua_setfield(L, LUA_REGISTRYINDEX, "_PACKAGE");
  376. lua_pushvalue(L, -1);
  377. lua_replace(L, LUA_ENVIRONINDEX);
  378. /* create `loaders' table */
  379. lua_newtable(L);
  380. /* fill it with pre-defined loaders */
  381. for (i=0; loaders[i] != NULL; i++) {
  382. lua_pushcfunction(L, loaders[i]);
  383. lua_rawseti(L, -2, i+1);
  384. }
  385. /* put it in field `loaders' */
  386. lua_setfield(L, -2, "loaders");
  387. /* set field `path' */
  388. path = getenv(LUA_PATH);
  389. if (path == NULL) path = LUA_PATH_DEFAULT;
  390. lua_pushstring(L, path);
  391. lua_setfield(L, -2, "path");
  392. /* set field `cpath' */
  393. path = getenv(LUA_CPATH);
  394. if (path == NULL) path = LUA_CPATH_DEFAULT;
  395. lua_pushstring(L, path);
  396. lua_setfield(L, -2, "cpath");
  397. /* set field `loaded' */
  398. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  399. lua_setfield(L, -2, "loaded");
  400. /* set field `preload' */
  401. lua_newtable(L);
  402. lua_setfield(L, -2, "preload");
  403. /* create `loadlib' function */
  404. lua_pushcfunction(L, ll_loadlib);
  405. lua_pushvalue(L, -1);
  406. lua_setfield(L, LUA_GLOBALSINDEX, "loadlib"); /* COMPATIBILITY ONLY!! */
  407. lua_setfield(L, -2, "loadlib");
  408. lua_pushvalue(L, LUA_GLOBALSINDEX);
  409. luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
  410. return 1;
  411. }