loadlib.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  1. /*
  2. ** $Id: loadlib.c,v 1.11 2004/11/19 15:52:12 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. #define ERR_ABSENT 3
  37. static void registerlib (lua_State *L, const void *lib);
  38. #if defined(USE_DLOPEN)
  39. /*
  40. * This is an implementation of loadlib based on the dlfcn interface.
  41. * The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  42. * NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  43. * as an emulation layer on top of native functions.
  44. */
  45. #include <dlfcn.h>
  46. #define freelib dlclose
  47. static int loadlib(lua_State *L, const char *path, const char *init)
  48. {
  49. void *lib=dlopen(path,RTLD_NOW);
  50. if (lib!=NULL)
  51. {
  52. lua_CFunction f=(lua_CFunction) dlsym(lib,init);
  53. if (f!=NULL)
  54. {
  55. registerlib(L, lib);
  56. lua_pushcfunction(L,f);
  57. return 0;
  58. }
  59. }
  60. /* else return appropriate error message */
  61. lua_pushstring(L,dlerror());
  62. if (lib!=NULL) {
  63. dlclose(lib);
  64. return ERR_FUNCTION; /* error loading function */
  65. }
  66. else return ERR_OPEN; /* error loading library */
  67. }
  68. #elif defined(USE_DLL)
  69. /*
  70. * This is an implementation of loadlib for Windows using native functions.
  71. */
  72. #include <windows.h>
  73. #define freelib(lib) FreeLibrary((HINSTANCE)lib)
  74. static void pusherror(lua_State *L)
  75. {
  76. int error=GetLastError();
  77. char buffer[128];
  78. if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  79. 0, error, 0, buffer, sizeof(buffer), 0))
  80. lua_pushstring(L,buffer);
  81. else
  82. lua_pushfstring(L,"system error %d\n",error);
  83. }
  84. static int loadlib(lua_State *L, const char *path, const char *init)
  85. {
  86. HINSTANCE lib=LoadLibrary(path);
  87. if (lib!=NULL)
  88. {
  89. lua_CFunction f=(lua_CFunction) GetProcAddress(lib,init);
  90. if (f!=NULL)
  91. {
  92. registerlib(L, lib);
  93. lua_pushcfunction(L,f);
  94. return 1;
  95. }
  96. }
  97. pusherror(L);
  98. if (lib!=NULL) {
  99. FreeLibrary(lib);
  100. return ERR_OPEN;
  101. }
  102. else return ERR_FUNCTION;
  103. }
  104. /* Native Mac OS X / Darwin Implementation */
  105. #elif defined(USE_DYLD)
  106. #include <mach-o/dyld.h>
  107. /* Mach cannot unload images (?) */
  108. #define freelib(lib) ((void)lib)
  109. static void pusherror (lua_State *L)
  110. {
  111. const char *err_str;
  112. const char *err_file;
  113. NSLinkEditErrors err;
  114. int err_num;
  115. NSLinkEditError(&err, &err_num, &err_file, &err_str);
  116. lua_pushstring(L, err_str);
  117. }
  118. static int loadlib (lua_State *L, const char *path, const char *init) {
  119. const struct mach_header *lib;
  120. /* this would be a rare case, but prevents crashing if it happens */
  121. if(!_dyld_present()) {
  122. lua_pushstring(L,"dyld not present.");
  123. return ERR_OPEN;
  124. }
  125. lib = NSAddImage(path, NSADDIMAGE_OPTION_RETURN_ON_ERROR);
  126. if(lib != NULL) {
  127. NSSymbol init_sym = NSLookupSymbolInImage(lib, init,
  128. NSLOOKUPSYMBOLINIMAGE_OPTION_BIND |
  129. NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR);
  130. if(init_sym != NULL) {
  131. lua_CFunction f = (lua_CFunction)NSAddressOfSymbol(init_sym);
  132. registerlib(L, lib);
  133. lua_pushcfunction(L,f);
  134. return 0;
  135. }
  136. }
  137. /* else an error ocurred */
  138. pusherror(L);
  139. /* Can't unload image */
  140. return (lib != NULL) ? ERR_FUNCTION : ERR_OPEN;
  141. }
  142. #else
  143. /* Fallback for other systems */
  144. #define freelib(lib) ((void)lib)
  145. static int loadlib(lua_State *L, const char *path, const char *init)
  146. {
  147. (void)path; (void)init; (void)&registerlib; /* to avoid warnings */
  148. lua_pushliteral(L,"`loadlib' not supported");
  149. return ERR_ABSENT;
  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 ll_loadlib (lua_State *L) {
  177. static const char *const errcodes[] = {NULL, "open", "init", "absent"};
  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, errcodes[res]);
  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, ".", LUA_OFSEP);
  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", ll_loadlib},
  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. */