loadlib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428
  1. /*
  2. ** $Id: loadlib.c,v 1.9 2004/11/11 15:42:57 roberto Exp roberto $
  3. ** Dynamic library loader for Lua
  4. ** See Copyright Notice in lua.h
  5. *
  6. * This Lua library exports a single function, called loadlib, which
  7. * is called from Lua as loadlib(lib,init), where lib is the full
  8. * name of the library to be loaded (including the complete path) and
  9. * init is the name of a function to be called after the library is
  10. * loaded. Typically, this function will register other functions, thus
  11. * making the complete library available to Lua. The init function is
  12. * *not* automatically called by loadlib. Instead, loadlib returns the
  13. * init function as a Lua function that the client can call when it
  14. * thinks is appropriate. In the case of errors, loadlib returns nil and
  15. * two strings describing the error. The first string is supplied by
  16. * the operating system; it should be informative and useful for error
  17. * messages. The second string is "open", "init", or "absent" to identify
  18. * the error and is meant to be used for making decisions without having
  19. * to look into the first string (whose format is system-dependent).
  20. * This module contains an implementation of loadlib for Unix systems
  21. * that have dlfcn, an implementation for Darwin (Mac OS X), an
  22. * implementation for Windows, and a stub for other systems. See
  23. * the list at the end of this file for some links to available
  24. * implementations of dlfcn and interfaces to other native dynamic
  25. * loaders on top of which loadlib could be implemented.
  26. */
  27. #include <string.h>
  28. #define loadlib_c
  29. #define LUA_LIB
  30. #include "lua.h"
  31. #include "lauxlib.h"
  32. #include "lualib.h"
  33. #define ERR_OPEN 1
  34. #define ERR_FUNCTION 2
  35. static void registerlib (lua_State *L, const void *lib);
  36. #if defined(USE_DLOPEN)
  37. /*
  38. * This is an implementation of loadlib based on the dlfcn interface.
  39. * The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  40. * NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  41. * as an emulation layer on top of native functions.
  42. */
  43. #include <dlfcn.h>
  44. #define freelib dlclose
  45. static int loadlib(lua_State *L, const char *path, const char *init)
  46. {
  47. void *lib=dlopen(path,RTLD_NOW);
  48. if (lib!=NULL)
  49. {
  50. lua_CFunction f=(lua_CFunction) dlsym(lib,init);
  51. if (f!=NULL)
  52. {
  53. registerlib(L, lib);
  54. lua_pushcfunction(L,f);
  55. return 0;
  56. }
  57. }
  58. /* else return appropriate error message */
  59. lua_pushstring(L,dlerror());
  60. if (lib!=NULL) {
  61. dlclose(lib);
  62. return ERR_FUNCTION; /* error loading function */
  63. }
  64. else return ERR_OPEN; /* error loading library */
  65. }
  66. #elif defined(USE_DLL)
  67. /*
  68. * This is an implementation of loadlib for Windows using native functions.
  69. */
  70. #include <windows.h>
  71. #define freelib(lib) FreeLibrary((HINSTANCE)lib)
  72. static void pusherror(lua_State *L)
  73. {
  74. int error=GetLastError();
  75. char buffer[128];
  76. if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  77. 0, error, 0, buffer, sizeof(buffer), 0))
  78. lua_pushstring(L,buffer);
  79. else
  80. lua_pushfstring(L,"system error %d\n",error);
  81. }
  82. static int loadlib(lua_State *L, const char *path, const char *init)
  83. {
  84. HINSTANCE lib=LoadLibrary(path);
  85. if (lib!=NULL)
  86. {
  87. lua_CFunction f=(lua_CFunction) GetProcAddress(lib,init);
  88. if (f!=NULL)
  89. {
  90. registerlib(L, lib);
  91. lua_pushcfunction(L,f);
  92. return 1;
  93. }
  94. }
  95. pusherror(L);
  96. if (lib!=NULL) {
  97. FreeLibrary(lib);
  98. return ERR_OPEN;
  99. }
  100. else return ERR_FUNCTION;
  101. }
  102. /* Native Mac OS X / Darwin Implementation */
  103. #elif defined(USE_DYLD)
  104. #include <mach-o/dyld.h>
  105. /* Mach cannot unload images (?) */
  106. #define freelib(lib) ((void)lib)
  107. static void pusherror (lua_State *L)
  108. {
  109. const char *err_str;
  110. const char *err_file;
  111. NSLinkEditErrors err;
  112. int err_num;
  113. NSLinkEditError(&err, &err_num, &err_file, &err_str);
  114. lua_pushstring(L, err_str);
  115. }
  116. static int loadlib (lua_State *L, const char *path, const char *init) {
  117. const struct mach_header *lib;
  118. /* this would be a rare case, but prevents crashing if it happens */
  119. if(!_dyld_present()) {
  120. lua_pushstring(L,"dyld not present.");
  121. return ERR_OPEN;
  122. }
  123. lib = NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
  124. if(lib != NULL) {
  125. NSSymbol init_sym = NSLookupSymbolInImage(lib, init,
  126. NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
  127. NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
  128. if(init_sym != NULL) {
  129. lua_CFunction f = (lua_CFunction)NSAddressOfSymbol(init_sym);
  130. registerlib(L, lib);
  131. lua_pushcfunction(L,f);
  132. return 0;
  133. }
  134. }
  135. /* else an error ocurred */
  136. pusherror(L);
  137. /* Can't unload image */
  138. return (lib != NULL) ? ERR_FUNCTION : ERR_OPEN;
  139. }
  140. #else
  141. /* Fallback for other systems */
  142. #define freelib(lib) ((void)lib)
  143. static int loadlib(lua_State *L)
  144. {
  145. registerlib(L, NULL); /* to avoid warnings */
  146. lua_pushnil(L);
  147. lua_pushliteral(L,"`loadlib' not supported");
  148. lua_pushliteral(L,"absent");
  149. return 3;
  150. }
  151. #endif
  152. /*
  153. ** common code for all implementations: put a library into the registry
  154. ** so that, when Lua closes its state, the library's __gc metamethod
  155. ** will be called to unload the library.
  156. */
  157. static void registerlib (lua_State *L, const void *lib)
  158. {
  159. const void **plib = (const void **)lua_newuserdata(L, sizeof(const void *));
  160. *plib = lib;
  161. luaL_getmetatable(L, "_LOADLIB");
  162. lua_setmetatable(L, -2);
  163. lua_pushboolean(L, 1);
  164. lua_settable(L, LUA_REGISTRYINDEX); /* registry[lib] = true */
  165. }
  166. /*
  167. ** __gc tag method: calls library's `freelib' function with the lib
  168. ** handle
  169. */
  170. static int gctm (lua_State *L)
  171. {
  172. void *lib = *(void **)luaL_checkudata(L, 1, "_LOADLIB");
  173. freelib(lib);
  174. return 0;
  175. }
  176. static int loadlib1 (lua_State *L) {
  177. const char *path=luaL_checkstring(L,1);
  178. const char *init=luaL_checkstring(L,2);
  179. int res = loadlib(L,path,init);
  180. if (res == 0) /* no error? */
  181. return 1; /* function is at stack top */
  182. else { /* error */
  183. lua_pushnil(L);
  184. lua_insert(L,-2); /* insert nil before error message */
  185. lua_pushstring(L, (res==ERR_OPEN)?"open":"init");
  186. return 3;
  187. }
  188. }
  189. /*
  190. ** {======================================================
  191. ** `require' and `module' functions
  192. ** =======================================================
  193. */
  194. static const char *loadLua (lua_State *L, const char *fname, const char *name) {
  195. const char *path;
  196. /* try first `LUA_PATH' for compatibility */
  197. lua_getglobal(L, "LUA_PATH");
  198. path = lua_tostring(L, -1);
  199. if (!path) {
  200. lua_pop(L, 1);
  201. luaL_getfield(L, LUA_GLOBALSINDEX, "package.path");
  202. path = lua_tostring(L, -1);
  203. }
  204. if (path == NULL)
  205. luaL_error(L, "`package.path' must be a string");
  206. fname = luaL_searchpath(L, fname, path);
  207. if (fname == NULL) return path; /* library not found in this path */
  208. if (luaL_loadfile(L, fname) != 0)
  209. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -1));
  210. return NULL; /* library loaded successfully */
  211. }
  212. static const char *loadC (lua_State *L, const char *fname, const char *name) {
  213. const char *path;
  214. const char *funcname;
  215. luaL_getfield(L, LUA_GLOBALSINDEX, "package.cpath");
  216. path = lua_tostring(L, -1);
  217. if (path == NULL)
  218. luaL_error(L, "global _CPATH must be a string");
  219. fname = luaL_searchpath(L, fname, path);
  220. if (fname == NULL) return path; /* library not found in this path */
  221. funcname = luaL_gsub(L, name, ".", "");
  222. funcname = lua_pushfstring(L, "%s%s", LUA_POF, funcname);
  223. if (loadlib(L, fname, funcname) != 0)
  224. luaL_error(L, "error loading package `%s' (%s)", name, lua_tostring(L, -1));
  225. return NULL; /* library loaded successfully */
  226. }
  227. static int ll_require (lua_State *L) {
  228. const char *name = luaL_checkstring(L, 1);
  229. lua_settop(L, 1);
  230. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  231. lua_getfield(L, 2, name);
  232. if (lua_toboolean(L, -1)) /* is it there? */
  233. return 1; /* package is already loaded; return its result */
  234. /* else must load it; first mark it as loaded */
  235. lua_pushboolean(L, 1);
  236. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  237. /* check whether it is preloaded */
  238. lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
  239. lua_getfield(L, -1, name);
  240. if (lua_isnil(L, -1)) { /* no preload function for that module? */
  241. const char *fname = luaL_gsub(L, name, ".", LUA_DIRSEP);
  242. const char *cpath = loadC(L, fname, name); /* try a C module */
  243. if (cpath) { /* not found? */
  244. const char *path = loadLua(L, fname, name); /* try a Lua module */
  245. if (path) { /* yet not found? */
  246. lua_pushnil(L);
  247. lua_setfield(L, 2, name); /* unmark _LOADED[name] */
  248. return luaL_error(L, "package `%s' not found\n"
  249. " cpath: %s\n path: %s",
  250. name, cpath, path);
  251. }
  252. }
  253. }
  254. lua_pushvalue(L, 1); /* pass name as argument to module */
  255. lua_call(L, 1, 1); /* run loaded module */
  256. if (!lua_isnil(L, -1)) /* non-nil return? */
  257. lua_setfield(L, 2, name); /* update _LOADED[name] with returned value */
  258. lua_getfield(L, 2, name); /* return _LOADED[name] */
  259. return 1;
  260. }
  261. static void setfenv (lua_State *L) {
  262. lua_Debug ar;
  263. lua_getstack(L, 1, &ar);
  264. lua_getinfo(L, "f", &ar);
  265. lua_pushvalue(L, -2);
  266. lua_setfenv(L, -2);
  267. }
  268. static int ll_module (lua_State *L) {
  269. const char *modname = luaL_checkstring(L, 1);
  270. const char *dot;
  271. lua_settop(L, 1);
  272. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  273. /* try to find given table */
  274. luaL_getfield(L, LUA_GLOBALSINDEX, modname);
  275. if (lua_isnil(L, -1)) { /* not found? */
  276. lua_pop(L, 1); /* remove previous result */
  277. lua_newtable(L); /* create it */
  278. /* register it with given name */
  279. lua_pushvalue(L, -1);
  280. luaL_setfield(L, LUA_GLOBALSINDEX, modname);
  281. }
  282. else if (!lua_istable(L, -1))
  283. return luaL_error(L, "name conflict for module `%s'", modname);
  284. /* check whether table already has a _NAME field */
  285. lua_getfield(L, -1, "_NAME");
  286. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  287. lua_pop(L, 1);
  288. else { /* no; initialize it */
  289. lua_pop(L, 1);
  290. lua_newtable(L); /* create new metatable */
  291. lua_pushvalue(L, LUA_GLOBALSINDEX);
  292. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  293. lua_setmetatable(L, -2);
  294. lua_pushstring(L, modname);
  295. lua_setfield(L, -2, "_NAME");
  296. dot = strrchr(modname, '.'); /* look for last dot in module name */
  297. if (dot == NULL) dot = modname;
  298. else dot++;
  299. /* set _PACKAGE as package name (full module name minus last part) */
  300. lua_pushlstring(L, modname, dot - modname);
  301. lua_setfield(L, -2, "_PACKAGE");
  302. }
  303. lua_pushvalue(L, -1);
  304. lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
  305. setfenv(L);
  306. return 0;
  307. }
  308. /* }====================================================== */
  309. static const luaL_reg ll_funcs[] = {
  310. {"loadlib", loadlib1},
  311. {"require", ll_require},
  312. {"module", ll_module},
  313. {NULL, NULL}
  314. };
  315. LUALIB_API int luaopen_loadlib (lua_State *L) {
  316. const char *path;
  317. /* create new type _LOADLIB */
  318. luaL_newmetatable(L, "_LOADLIB");
  319. lua_pushcfunction(L, gctm);
  320. lua_setfield(L, -2, "__gc");
  321. /* create `package' table */
  322. lua_newtable(L);
  323. lua_pushvalue(L, -1);
  324. lua_setglobal(L, "package");
  325. /* set field `path' */
  326. path = getenv(LUA_PATH);
  327. if (path == NULL) path = LUA_PATH_DEFAULT;
  328. lua_pushstring(L, path);
  329. lua_setfield(L, -2, "path");
  330. /* set field `cpath' */
  331. path = getenv(LUA_CPATH);
  332. if (path == NULL) path = LUA_CPATH_DEFAULT;
  333. lua_pushstring(L, path);
  334. lua_setfield(L, -2, "cpath");
  335. /* set field `loaded' */
  336. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  337. lua_setfield(L, -2, "loaded");
  338. /* set field `preload' */
  339. lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
  340. lua_setfield(L, -2, "preload");
  341. lua_pushvalue(L, LUA_GLOBALSINDEX);
  342. luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
  343. return 1;
  344. }
  345. /*
  346. * Here are some links to available implementations of dlfcn and
  347. * interfaces to other native dynamic loaders on top of which loadlib
  348. * could be implemented. Please send contributions and corrections to us.
  349. *
  350. * AIX
  351. * Starting with AIX 4.2, dlfcn is included in the base OS.
  352. * There is also an emulation package available.
  353. * http://www.faqs.org/faqs/aix-faq/part4/section-21.html
  354. *
  355. * HPUX
  356. * HPUX 11 has dlfcn. For HPUX 10 use shl_*.
  357. * http://www.geda.seul.org/mailinglist/geda-dev37/msg00094.html
  358. * http://www.stat.umn.edu/~luke/xls/projects/dlbasics/dlbasics.html
  359. *
  360. * Macintosh, Windows
  361. * http://www.stat.umn.edu/~luke/xls/projects/dlbasics/dlbasics.html
  362. *
  363. * GLIB has wrapper code for BeOS, OS2, Unix and Windows
  364. * http://cvs.gnome.org/lxr/source/glib/gmodule/
  365. *
  366. */