loadlib.c 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518
  1. /*
  2. ** $Id: loadlib.c,v 1.25 2005/03/30 19:50:29 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 `%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. #if defined(__ELF__) || defined(__sun) || defined(sgi) || defined(__hpux)
  157. #define DLMSG "`loadlib' not enabled; check your Lua installation"
  158. #else
  159. #define DLMSG "`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 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, "`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 `%s' (%s)", name, lua_tostring(L, -1));
  256. return 1; /* library loaded successfully */
  257. }
  258. static int loader_C (lua_State *L) {
  259. const char *name = luaL_checkstring(L, 1);
  260. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  261. const char *path;
  262. const char *funcname;
  263. lua_getfield(L, LUA_ENVIRONINDEX, "cpath");
  264. path = lua_tostring(L, -1);
  265. if (path == NULL)
  266. luaL_error(L, "`package.cpath' must be a string");
  267. fname = luaL_searchpath(L, fname, path);
  268. if (fname == NULL) return 0; /* library not found in this path */
  269. funcname = luaL_gsub(L, name, ".", LUA_OFSEP);
  270. funcname = lua_pushfstring(L, "%s%s", POF, funcname);
  271. if (ll_loadfunc(L, fname, funcname) != 1)
  272. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -2));
  273. return 1; /* library loaded successfully */
  274. }
  275. static int loader_preload (lua_State *L) {
  276. lua_getfield(L, LUA_ENVIRONINDEX, "preload");
  277. if (!lua_istable(L, -1))
  278. luaL_error(L, "`package.preload' must be a table");
  279. lua_getfield(L, -1, luaL_checkstring(L, 1));
  280. return 1;
  281. }
  282. static int ll_require (lua_State *L) {
  283. const char *name = luaL_checkstring(L, 1);
  284. int i;
  285. lua_settop(L, 1);
  286. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  287. lua_getfield(L, 2, name);
  288. if (lua_toboolean(L, -1)) /* is it there? */
  289. return 1; /* package is already loaded; return its result */
  290. /* else must load it; first mark it as loaded */
  291. lua_pushboolean(L, 1);
  292. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  293. /* iterate over available loaders */
  294. lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  295. if (!lua_istable(L, -1))
  296. luaL_error(L, "`package.loaders' must be a table");
  297. for (i=1;; i++) {
  298. lua_rawgeti(L, -1, i); /* get a loader */
  299. if (lua_isnil(L, -1))
  300. return luaL_error(L, "package `%s' not found", name);
  301. lua_pushstring(L, name);
  302. lua_call(L, 1, 1); /* call it */
  303. if (lua_isnil(L, -1)) lua_pop(L, 1);
  304. else break; /* module loaded successfully */
  305. }
  306. lua_pushvalue(L, 1); /* pass name as argument to module */
  307. lua_call(L, 1, 1); /* run loaded module */
  308. if (!lua_isnil(L, -1)) /* non-nil return? */
  309. lua_setfield(L, 2, name); /* update _LOADED[name] with returned value */
  310. lua_getfield(L, 2, name); /* return _LOADED[name] */
  311. return 1;
  312. }
  313. static void setfenv (lua_State *L) {
  314. lua_Debug ar;
  315. lua_getstack(L, 1, &ar);
  316. lua_getinfo(L, "f", &ar);
  317. lua_pushvalue(L, -2);
  318. lua_setfenv(L, -2);
  319. }
  320. static int ll_module (lua_State *L) {
  321. const char *modname = luaL_checkstring(L, 1);
  322. const char *dot;
  323. lua_settop(L, 1);
  324. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  325. /* try to find given table */
  326. luaL_getfield(L, LUA_GLOBALSINDEX, modname);
  327. if (lua_isnil(L, -1)) { /* not found? */
  328. lua_pop(L, 1); /* remove previous result */
  329. lua_newtable(L); /* create it */
  330. /* register it with given name */
  331. lua_pushvalue(L, -1);
  332. luaL_setfield(L, LUA_GLOBALSINDEX, modname);
  333. }
  334. else if (!lua_istable(L, -1))
  335. return luaL_error(L, "name conflict for module `%s'", modname);
  336. /* check whether table already has a _NAME field */
  337. lua_getfield(L, -1, "_NAME");
  338. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  339. lua_pop(L, 1);
  340. else { /* no; initialize it */
  341. lua_pop(L, 1);
  342. lua_newtable(L); /* create new metatable */
  343. lua_pushvalue(L, LUA_GLOBALSINDEX);
  344. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  345. lua_setmetatable(L, -2);
  346. lua_pushvalue(L, -1);
  347. lua_setfield(L, -2, "_M"); /* module._M = module */
  348. lua_pushstring(L, modname);
  349. lua_setfield(L, -2, "_NAME");
  350. dot = strrchr(modname, '.'); /* look for last dot in module name */
  351. if (dot == NULL) dot = modname;
  352. else dot++;
  353. /* set _PACKAGE as package name (full module name minus last part) */
  354. lua_pushlstring(L, modname, dot - modname);
  355. lua_setfield(L, -2, "_PACKAGE");
  356. }
  357. lua_pushvalue(L, -1);
  358. lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
  359. setfenv(L);
  360. return 0;
  361. }
  362. /* }====================================================== */
  363. static const luaL_reg ll_funcs[] = {
  364. {"require", ll_require},
  365. {"module", ll_module},
  366. {NULL, NULL}
  367. };
  368. static const lua_CFunction loaders[] =
  369. {loader_preload, loader_C, loader_Lua, NULL};
  370. LUALIB_API int luaopen_loadlib (lua_State *L) {
  371. const char *path;
  372. int i;
  373. /* create new type _LOADLIB */
  374. luaL_newmetatable(L, "_LOADLIB");
  375. lua_pushcfunction(L, gctm);
  376. lua_setfield(L, -2, "__gc");
  377. /* create `package' table */
  378. lua_newtable(L);
  379. lua_pushvalue(L, -1);
  380. lua_setglobal(L, LUA_LOADLIBNAME);
  381. lua_pushvalue(L, -1);
  382. lua_setfield(L, LUA_REGISTRYINDEX, "_PACKAGE");
  383. lua_pushvalue(L, -1);
  384. lua_replace(L, LUA_ENVIRONINDEX);
  385. /* create `loaders' table */
  386. lua_newtable(L);
  387. /* fill it with pre-defined loaders */
  388. for (i=0; loaders[i] != NULL; i++) {
  389. lua_pushcfunction(L, loaders[i]);
  390. lua_rawseti(L, -2, i+1);
  391. }
  392. /* put it in field `loaders' */
  393. lua_setfield(L, -2, "loaders");
  394. /* set field `path' */
  395. path = getenv(LUA_PATH);
  396. if (path == NULL) path = LUA_PATH_DEFAULT;
  397. lua_pushstring(L, path);
  398. lua_setfield(L, -2, "path");
  399. /* set field `cpath' */
  400. path = getenv(LUA_CPATH);
  401. if (path == NULL) path = LUA_CPATH_DEFAULT;
  402. lua_pushstring(L, path);
  403. lua_setfield(L, -2, "cpath");
  404. /* set field `loaded' */
  405. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  406. lua_setfield(L, -2, "loaded");
  407. /* set field `preload' */
  408. lua_newtable(L);
  409. lua_setfield(L, -2, "preload");
  410. /* create `loadlib' function */
  411. lua_pushcfunction(L, ll_loadlib);
  412. #if LUA_COMPAT_LOADLIB
  413. lua_pushvalue(L, -1);
  414. lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
  415. #endif
  416. lua_setfield(L, -2, "loadlib");
  417. lua_pushvalue(L, LUA_GLOBALSINDEX);
  418. luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
  419. return 1;
  420. }