loadlib.c 13 KB

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