loadlib.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. /*
  2. ** $Id: loadlib.c,v 1.14 2004/12/27 15:58:15 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 const char *loadLua (lua_State *L, const char *fname, const char *name) {
  223. const char *path;
  224. /* try first `LUA_PATH' for compatibility */
  225. lua_getglobal(L, "LUA_PATH");
  226. path = lua_tostring(L, -1);
  227. if (!path) {
  228. lua_pop(L, 1);
  229. luaL_getfield(L, LUA_GLOBALSINDEX, "package.path");
  230. path = lua_tostring(L, -1);
  231. }
  232. if (path == NULL)
  233. luaL_error(L, "`package.path' must be a string");
  234. fname = luaL_searchpath(L, fname, path);
  235. if (fname == NULL) return path; /* library not found in this path */
  236. if (luaL_loadfile(L, fname) != 0)
  237. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -1));
  238. return NULL; /* library loaded successfully */
  239. }
  240. static const char *loadC (lua_State *L, const char *fname, const char *name) {
  241. const char *path;
  242. const char *funcname;
  243. luaL_getfield(L, LUA_GLOBALSINDEX, "package.cpath");
  244. path = lua_tostring(L, -1);
  245. if (path == NULL)
  246. luaL_error(L, "`package.cpath' must be a string");
  247. fname = luaL_searchpath(L, fname, path);
  248. if (fname == NULL) return path; /* library not found in this path */
  249. funcname = luaL_gsub(L, name, ".", LUA_OFSEP);
  250. funcname = lua_pushfstring(L, "%s%s", POF, funcname);
  251. if (ll_loadfunc(L, fname, funcname) != 1)
  252. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -2));
  253. return NULL; /* library loaded successfully */
  254. }
  255. static int ll_require (lua_State *L) {
  256. const char *name = luaL_checkstring(L, 1);
  257. lua_settop(L, 1);
  258. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  259. lua_getfield(L, 2, name);
  260. if (lua_toboolean(L, -1)) /* is it there? */
  261. return 1; /* package is already loaded; return its result */
  262. /* else must load it; first mark it as loaded */
  263. lua_pushboolean(L, 1);
  264. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  265. /* check whether it is preloaded */
  266. lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
  267. lua_getfield(L, -1, name);
  268. if (lua_isnil(L, -1)) { /* no preload function for that module? */
  269. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  270. const char *cpath = loadC(L, fname, name); /* try a C module */
  271. if (cpath) { /* not found? */
  272. const char *path = loadLua(L, fname, name); /* try a Lua module */
  273. if (path) { /* yet not found? */
  274. lua_pushnil(L);
  275. lua_setfield(L, 2, name); /* unmark _LOADED[name] */
  276. return luaL_error(L, "package `%s' not found\n"
  277. " cpath: %s\n path: %s",
  278. name, cpath, path);
  279. }
  280. }
  281. }
  282. lua_pushvalue(L, 1); /* pass name as argument to module */
  283. lua_call(L, 1, 1); /* run loaded module */
  284. if (!lua_isnil(L, -1)) /* non-nil return? */
  285. lua_setfield(L, 2, name); /* update _LOADED[name] with returned value */
  286. lua_getfield(L, 2, name); /* return _LOADED[name] */
  287. return 1;
  288. }
  289. static void setfenv (lua_State *L) {
  290. lua_Debug ar;
  291. lua_getstack(L, 1, &ar);
  292. lua_getinfo(L, "f", &ar);
  293. lua_pushvalue(L, -2);
  294. lua_setfenv(L, -2);
  295. }
  296. static int ll_module (lua_State *L) {
  297. const char *modname = luaL_checkstring(L, 1);
  298. const char *dot;
  299. lua_settop(L, 1);
  300. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  301. /* try to find given table */
  302. luaL_getfield(L, LUA_GLOBALSINDEX, modname);
  303. if (lua_isnil(L, -1)) { /* not found? */
  304. lua_pop(L, 1); /* remove previous result */
  305. lua_newtable(L); /* create it */
  306. /* register it with given name */
  307. lua_pushvalue(L, -1);
  308. luaL_setfield(L, LUA_GLOBALSINDEX, modname);
  309. }
  310. else if (!lua_istable(L, -1))
  311. return luaL_error(L, "name conflict for module `%s'", modname);
  312. /* check whether table already has a _NAME field */
  313. lua_getfield(L, -1, "_NAME");
  314. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  315. lua_pop(L, 1);
  316. else { /* no; initialize it */
  317. lua_pop(L, 1);
  318. lua_newtable(L); /* create new metatable */
  319. lua_pushvalue(L, LUA_GLOBALSINDEX);
  320. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  321. lua_setmetatable(L, -2);
  322. lua_pushvalue(L, -1);
  323. lua_setfield(L, -2, "_M"); /* module._M = module */
  324. lua_pushstring(L, modname);
  325. lua_setfield(L, -2, "_NAME");
  326. dot = strrchr(modname, '.'); /* look for last dot in module name */
  327. if (dot == NULL) dot = modname;
  328. else dot++;
  329. /* set _PACKAGE as package name (full module name minus last part) */
  330. lua_pushlstring(L, modname, dot - modname);
  331. lua_setfield(L, -2, "_PACKAGE");
  332. }
  333. lua_pushvalue(L, -1);
  334. lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
  335. setfenv(L);
  336. return 0;
  337. }
  338. /* }====================================================== */
  339. static const luaL_reg ll_funcs[] = {
  340. {"loadlib", ll_loadlib},
  341. {"require", ll_require},
  342. {"module", ll_module},
  343. {NULL, NULL}
  344. };
  345. LUALIB_API int luaopen_loadlib (lua_State *L) {
  346. const char *path;
  347. /* create new type _LOADLIB */
  348. luaL_newmetatable(L, "_LOADLIB");
  349. lua_pushcfunction(L, gctm);
  350. lua_setfield(L, -2, "__gc");
  351. /* create `package' table */
  352. lua_newtable(L);
  353. lua_pushvalue(L, -1);
  354. lua_setglobal(L, "package");
  355. /* set field `path' */
  356. path = getenv(LUA_PATH);
  357. if (path == NULL) path = LUA_PATH_DEFAULT;
  358. lua_pushstring(L, path);
  359. lua_setfield(L, -2, "path");
  360. /* set field `cpath' */
  361. path = getenv(LUA_CPATH);
  362. if (path == NULL) path = LUA_CPATH_DEFAULT;
  363. lua_pushstring(L, path);
  364. lua_setfield(L, -2, "cpath");
  365. /* set field `loaded' */
  366. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  367. lua_setfield(L, -2, "loaded");
  368. /* set field `preload' */
  369. lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
  370. lua_setfield(L, -2, "preload");
  371. lua_pushvalue(L, LUA_GLOBALSINDEX);
  372. luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
  373. return 1;
  374. }