loadlib.c 12 KB

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