loadlib.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. /*
  2. ** $Id: loadlib.c,v 1.33 2005/07/12 21:17:46 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. /* environment variables that hold the search path for packages */
  18. #define LUA_PATH "LUA_PATH"
  19. #define LUA_CPATH "LUA_CPATH"
  20. /* prefix for open functions in C libraries */
  21. #define LUA_POF "luaopen_"
  22. /* separator for open functions in C libraries */
  23. #define LUA_OFSEP "_"
  24. #define LIBPREFIX "LOADLIB: "
  25. #define POF LUA_POF
  26. #define LIB_FAIL "open"
  27. #define setprogdir(L) ((void)0)
  28. static void ll_unloadlib (void *lib);
  29. static void *ll_load (lua_State *L, const char *path);
  30. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
  31. #if defined(LUA_DL_DLOPEN)
  32. /*
  33. ** {========================================================================
  34. ** This is an implementation of loadlib based on the dlfcn interface.
  35. ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  36. ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  37. ** as an emulation layer on top of native functions.
  38. ** =========================================================================
  39. */
  40. #include <dlfcn.h>
  41. static void ll_unloadlib (void *lib) {
  42. dlclose(lib);
  43. }
  44. static void *ll_load (lua_State *L, const char *path) {
  45. void *lib = dlopen(path, RTLD_NOW);
  46. if (lib == NULL) lua_pushstring(L, dlerror());
  47. return lib;
  48. }
  49. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  50. lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
  51. if (f == NULL) lua_pushstring(L, dlerror());
  52. return f;
  53. }
  54. /* }====================================================== */
  55. #elif defined(LUA_DL_DLL)
  56. /*
  57. ** {======================================================================
  58. ** This is an implementation of loadlib for Windows using native functions.
  59. ** =======================================================================
  60. */
  61. #include <windows.h>
  62. #include "Shlwapi.h"
  63. #undef setprogdir
  64. void setprogdir (lua_State *L) {
  65. char buff[MAX_PATH + 1];
  66. DWORD nsize = sizeof(buff)/sizeof(char);
  67. DWORD n = GetModuleFileName(NULL, buff, nsize);
  68. if (n == 0 || n == nsize)
  69. luaL_error(L, "unable to get ModuleFileName");
  70. PathRemoveFileSpec(buff);
  71. luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
  72. lua_remove(L, -2); /* remove original string */
  73. }
  74. static void pusherror (lua_State *L) {
  75. int error = GetLastError();
  76. char buffer[128];
  77. if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  78. NULL, error, 0, buffer, sizeof(buffer), NULL))
  79. lua_pushstring(L, buffer);
  80. else
  81. lua_pushfstring(L, "system error %d\n", error);
  82. }
  83. static void ll_unloadlib (void *lib) {
  84. FreeLibrary((HINSTANCE)lib);
  85. }
  86. static void *ll_load (lua_State *L, const char *path) {
  87. HINSTANCE lib = LoadLibrary(path);
  88. if (lib == NULL) pusherror(L);
  89. return lib;
  90. }
  91. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  92. lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
  93. if (f == NULL) pusherror(L);
  94. return f;
  95. }
  96. /* }====================================================== */
  97. #elif defined(LUA_DL_DYLD)
  98. /*
  99. ** {======================================================================
  100. ** Native Mac OS X / Darwin Implementation
  101. ** =======================================================================
  102. */
  103. #include <mach-o/dyld.h>
  104. /* Mac appends a `_' before C function names */
  105. #undef POF
  106. #define POF "_" LUA_POF
  107. static void pusherror (lua_State *L) {
  108. const char *err_str;
  109. const char *err_file;
  110. NSLinkEditErrors err;
  111. int err_num;
  112. NSLinkEditError(&err, &err_num, &err_file, &err_str);
  113. lua_pushstring(L, err_str);
  114. }
  115. static const char *errorfromcode (NSObjectFileImageReturnCode ret) {
  116. switch (ret) {
  117. case NSObjectFileImageInappropriateFile:
  118. return "file is not a bundle";
  119. case NSObjectFileImageArch:
  120. return "library is for wrong CPU type";
  121. case NSObjectFileImageFormat:
  122. return "bad format";
  123. case NSObjectFileImageAccess:
  124. return "cannot access file";
  125. case NSObjectFileImageFailure:
  126. default:
  127. return "unable to load library";
  128. }
  129. }
  130. static void ll_unloadlib (void *lib) {
  131. NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
  132. }
  133. static void *ll_load (lua_State *L, const char *path) {
  134. NSObjectFileImage img;
  135. NSObjectFileImageReturnCode ret;
  136. /* this would be a rare case, but prevents crashing if it happens */
  137. if(!_dyld_present()) {
  138. lua_pushliteral(L, "dyld not present");
  139. return NULL;
  140. }
  141. ret = NSCreateObjectFileImageFromFile(path, &img);
  142. if (ret == NSObjectFileImageSuccess) {
  143. NSModule mod = NSLinkModule(img, path, NSLINKMODULE_OPTION_PRIVATE |
  144. NSLINKMODULE_OPTION_RETURN_ON_ERROR);
  145. NSDestroyObjectFileImage(img);
  146. if (mod == NULL) pusherror(L);
  147. return mod;
  148. }
  149. lua_pushstring(L, errorfromcode(ret));
  150. return NULL;
  151. }
  152. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  153. NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
  154. if (nss == NULL) {
  155. lua_pushfstring(L, "symbol " LUA_QS " not found", sym);
  156. return NULL;
  157. }
  158. return (lua_CFunction)NSAddressOfSymbol(nss);
  159. }
  160. /* }====================================================== */
  161. #else
  162. /*
  163. ** {======================================================
  164. ** Fallback for other systems
  165. ** =======================================================
  166. */
  167. #undef LIB_FAIL
  168. #define LIB_FAIL "absent"
  169. #if defined(__ELF__) || defined(__sun) || defined(sgi) || defined(__hpux)
  170. #define DLMSG LUA_QL("loadlib") " not enabled; check your Lua installation"
  171. #else
  172. #define DLMSG LUA_QL("loadlib") " not supported"
  173. #endif
  174. static void ll_unloadlib (void *lib) {
  175. (void)lib; /* to avoid warnings */
  176. }
  177. static void *ll_load (lua_State *L, const char *path) {
  178. (void)path; /* to avoid warnings */
  179. lua_pushliteral(L, DLMSG);
  180. return NULL;
  181. }
  182. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  183. (void)lib; (void)sym; /* to avoid warnings */
  184. lua_pushliteral(L, DLMSG);
  185. return NULL;
  186. }
  187. /* }====================================================== */
  188. #endif
  189. static void **ll_register (lua_State *L, const char *path) {
  190. void **plib;
  191. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  192. lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
  193. if (!lua_isnil(L, -1)) /* is there an entry? */
  194. plib = (void **)lua_touserdata(L, -1);
  195. else { /* no entry yet; create one */
  196. lua_pop(L, 1);
  197. plib = (void **)lua_newuserdata(L, sizeof(const void *));
  198. *plib = NULL;
  199. luaL_getmetatable(L, "_LOADLIB");
  200. lua_setmetatable(L, -2);
  201. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  202. lua_pushvalue(L, -2);
  203. lua_settable(L, LUA_REGISTRYINDEX);
  204. }
  205. return plib;
  206. }
  207. /*
  208. ** __gc tag method: calls library's `ll_unloadlib' function with the lib
  209. ** handle
  210. */
  211. static int gctm (lua_State *L) {
  212. void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
  213. if (lib) {
  214. if (*lib) ll_unloadlib(*lib);
  215. *lib = NULL; /* mark library as closed */
  216. }
  217. return 0;
  218. }
  219. static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
  220. const char *reason;
  221. void **reg = ll_register(L, path);
  222. if (*reg == NULL) *reg = ll_load(L, path);
  223. if (*reg == NULL)
  224. reason = LIB_FAIL;
  225. else {
  226. lua_CFunction f = ll_sym(L, *reg, sym);
  227. if (f) {
  228. lua_pushcfunction(L, f);
  229. return 1; /* return function */
  230. }
  231. reason = "init";
  232. }
  233. lua_pushnil(L);
  234. lua_insert(L, -2);
  235. lua_pushstring(L, reason);
  236. return 3; /* return nil, ll_error, reason */
  237. }
  238. static int ll_loadlib (lua_State *L) {
  239. const char *path = luaL_checkstring(L, 1);
  240. const char *init = luaL_checkstring(L, 2);
  241. return ll_loadfunc(L, path, init);
  242. }
  243. /*
  244. ** {======================================================
  245. ** `require' and `module' functions
  246. ** =======================================================
  247. */
  248. static int readable (const char *fname) {
  249. FILE *f = fopen(fname, "r"); /* try to open file */
  250. if (f == NULL) return 0; /* open failed */
  251. fclose(f);
  252. return 1;
  253. }
  254. static const char *pushnexttemplate (lua_State *L, const char *path) {
  255. const char *l;
  256. while (*path == *LUA_PATHSEP) path++; /* skip separators */
  257. if (*path == '\0') return NULL; /* no more templates */
  258. l = strchr(path, *LUA_PATHSEP); /* find next separator */
  259. if (l == NULL) l = path + strlen(path);
  260. lua_pushlstring(L, path, l - path); /* template */
  261. return l;
  262. }
  263. static const char *findfile (lua_State *L, const char *pname) {
  264. const char *path;
  265. const char *name = luaL_checkstring(L, 1);
  266. name = luaL_gsub(L, name, ".", LUA_DIRSEP);
  267. lua_getfield(L, LUA_ENVIRONINDEX, pname);
  268. path = lua_tostring(L, -1);
  269. if (path == NULL)
  270. luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
  271. while ((path = pushnexttemplate(L, path)) != NULL) {
  272. const char *fname;
  273. fname = luaL_gsub(L, lua_tostring(L, -1), LUA_PATH_MARK, name);
  274. if (readable(fname)) /* does file exist and is readable? */
  275. return fname; /* return that file name */
  276. lua_pop(L, 2); /* remove path template and file name */
  277. }
  278. return NULL; /* not found */
  279. }
  280. static void loaderror (lua_State *L, const char *msg) {
  281. luaL_error(L, "error loading package " LUA_QS " (%s)",
  282. lua_tostring(L, 1), msg);
  283. }
  284. static int loader_Lua (lua_State *L) {
  285. const char *fname;
  286. fname = findfile(L, "path");
  287. if (fname == NULL) return 0; /* library not found in this path */
  288. if (luaL_loadfile(L, fname) != 0)
  289. loaderror(L, lua_tostring(L, -1));
  290. return 1; /* library loaded successfully */
  291. }
  292. static int loader_C (lua_State *L) {
  293. const char *funcname;
  294. const char *fname = findfile(L, "cpath");
  295. if (fname == NULL) return 0; /* library not found in this path */
  296. funcname = luaL_gsub(L, lua_tostring(L, 1), ".", LUA_OFSEP);
  297. funcname = lua_pushfstring(L, POF"%s", funcname);
  298. if (ll_loadfunc(L, fname, funcname) != 1)
  299. loaderror(L, lua_tostring(L, -2));
  300. return 1; /* library loaded successfully */
  301. }
  302. static int loader_preload (lua_State *L) {
  303. lua_getfield(L, LUA_ENVIRONINDEX, "preload");
  304. if (!lua_istable(L, -1))
  305. luaL_error(L, LUA_QL("package.preload") " must be a table");
  306. lua_getfield(L, -1, luaL_checkstring(L, 1));
  307. return 1;
  308. }
  309. static int require_aux (lua_State *L, const char *name) {
  310. int i;
  311. int loadedtable = lua_gettop(L) + 1;
  312. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  313. lua_getfield(L, loadedtable, name);
  314. if (lua_toboolean(L, -1)) /* is it there? */
  315. return 1; /* package is already loaded */
  316. /* else must load it; iterate over available loaders */
  317. lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  318. if (!lua_istable(L, -1))
  319. luaL_error(L, LUA_QL("package.loaders") " must be a table");
  320. for (i=1; ; i++) {
  321. lua_rawgeti(L, -1, i); /* get a loader */
  322. if (lua_isnil(L, -1))
  323. return 0; /* package not found */
  324. lua_pushstring(L, name);
  325. lua_call(L, 1, 1); /* call it */
  326. if (lua_isnil(L, -1)) lua_pop(L, 1); /* did not found module */
  327. else break; /* module loaded successfully */
  328. }
  329. lua_pushboolean(L, 1);
  330. lua_setfield(L, loadedtable, name); /* _LOADED[name] = true */
  331. lua_pushstring(L, name); /* pass name as argument to module */
  332. if (lua_pcall(L, 1, 1, 0) != 0) { /* run loaded module */
  333. lua_pushnil(L); /* in case of errors... */
  334. lua_setfield(L, loadedtable, name); /* ...clear _LOADED[name] */
  335. luaL_error(L, "error loading package " LUA_QS " (%s)",
  336. name, lua_tostring(L, -1)); /* propagate error */
  337. }
  338. if (!lua_isnil(L, -1)) /* non-nil return? */
  339. lua_setfield(L, loadedtable, name); /* _LOADED[name] = returned value */
  340. lua_getfield(L, loadedtable, name); /* return _LOADED[name] */
  341. return 1;
  342. }
  343. static void require_check (lua_State *L, const char *name) {
  344. if (!require_aux(L, name)) { /* error? */
  345. /* build and show error message */
  346. const char *msg;
  347. lua_settop(L, 1);
  348. lua_getfield(L, LUA_ENVIRONINDEX, "path");
  349. lua_getfield(L, LUA_ENVIRONINDEX, "cpath");
  350. msg = lua_pushfstring(L,
  351. "package " LUA_QS " not found in following paths:\n"
  352. " Lua path: %s\n"
  353. " C path: %s\n", name,
  354. lua_tostring(L, -2), lua_tostring(L, -1));
  355. msg = luaL_gsub(L, msg, LUA_PATHSEP, "\n ");
  356. luaL_error(L, msg);
  357. }
  358. }
  359. static int ll_require (lua_State *L) {
  360. const char *name = luaL_checkstring(L, 1);
  361. const char *pt;
  362. /* load all parent modules */
  363. for (pt = name; (pt = strchr(pt, '.')) != NULL; pt++) {
  364. lua_settop(L, 1);
  365. lua_pushlstring(L, name, pt - name);
  366. require_aux(L, lua_tostring(L, -1));
  367. }
  368. require_check(L, name); /* load module itself */
  369. return 1;
  370. }
  371. static void setfenv (lua_State *L) {
  372. lua_Debug ar;
  373. lua_getstack(L, 1, &ar);
  374. lua_getinfo(L, "f", &ar);
  375. lua_pushvalue(L, -2);
  376. lua_setfenv(L, -2);
  377. }
  378. static int ll_module (lua_State *L) {
  379. const char *modname = luaL_checkstring(L, 1);
  380. const char *dot;
  381. lua_settop(L, 1);
  382. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  383. /* try to find given table */
  384. luaL_getfield(L, LUA_GLOBALSINDEX, modname);
  385. if (lua_isnil(L, -1)) { /* not found? */
  386. lua_pop(L, 1); /* remove previous result */
  387. lua_newtable(L); /* create it */
  388. /* register it with given name */
  389. lua_pushvalue(L, -1);
  390. luaL_setfield(L, LUA_GLOBALSINDEX, modname);
  391. }
  392. else if (!lua_istable(L, -1))
  393. return luaL_error(L, "name conflict for module " LUA_QS, modname);
  394. /* check whether table already has a _NAME field */
  395. lua_getfield(L, -1, "_NAME");
  396. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  397. lua_pop(L, 1);
  398. else { /* no; initialize it */
  399. lua_pop(L, 1);
  400. lua_newtable(L); /* create new metatable */
  401. lua_pushvalue(L, LUA_GLOBALSINDEX);
  402. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  403. lua_setmetatable(L, -2);
  404. lua_pushvalue(L, -1);
  405. lua_setfield(L, -2, "_M"); /* module._M = module */
  406. lua_pushstring(L, modname);
  407. lua_setfield(L, -2, "_NAME");
  408. dot = strrchr(modname, '.'); /* look for last dot in module name */
  409. if (dot == NULL) dot = modname;
  410. else dot++;
  411. /* set _PACKAGE as package name (full module name minus last part) */
  412. lua_pushlstring(L, modname, dot - modname);
  413. lua_setfield(L, -2, "_PACKAGE");
  414. }
  415. lua_pushvalue(L, -1);
  416. lua_setfield(L, 2, modname); /* _LOADED[modname] = new table */
  417. setfenv(L);
  418. return 0;
  419. }
  420. /* }====================================================== */
  421. /* auxiliary mark (for internal use) */
  422. #define AUXMARK "\1"
  423. static void setpath (lua_State *L, const char *fname, const char *envname,
  424. const char *def) {
  425. const char *path = getenv(envname);
  426. if (path == NULL) /* no environment variable? */
  427. lua_pushstring(L, def); /* use default */
  428. else {
  429. /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
  430. path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
  431. LUA_PATHSEP AUXMARK LUA_PATHSEP);
  432. luaL_gsub(L, path, AUXMARK, def);
  433. lua_remove(L, -2);
  434. }
  435. setprogdir(L);
  436. lua_setfield(L, -2, fname);
  437. }
  438. static const luaL_reg ll_funcs[] = {
  439. {"module", ll_module},
  440. {"require", ll_require},
  441. {NULL, NULL}
  442. };
  443. static const lua_CFunction loaders[] =
  444. {loader_preload, loader_Lua, loader_C, NULL};
  445. LUALIB_API int luaopen_loadlib (lua_State *L) {
  446. int i;
  447. /* create new type _LOADLIB */
  448. luaL_newmetatable(L, "_LOADLIB");
  449. lua_pushcfunction(L, gctm);
  450. lua_setfield(L, -2, "__gc");
  451. /* create `package' table */
  452. lua_newtable(L);
  453. lua_pushvalue(L, -1);
  454. lua_setglobal(L, LUA_LOADLIBNAME);
  455. lua_pushvalue(L, -1);
  456. lua_setfield(L, LUA_REGISTRYINDEX, "_PACKAGE");
  457. lua_pushvalue(L, -1);
  458. lua_replace(L, LUA_ENVIRONINDEX);
  459. /* create `loaders' table */
  460. lua_newtable(L);
  461. /* fill it with pre-defined loaders */
  462. for (i=0; loaders[i] != NULL; i++) {
  463. lua_pushcfunction(L, loaders[i]);
  464. lua_rawseti(L, -2, i+1);
  465. }
  466. lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
  467. setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT); /* set field `path' */
  468. setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT); /* set field `cpath' */
  469. /* set field `loaded' */
  470. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  471. lua_setfield(L, -2, "loaded");
  472. /* set field `preload' */
  473. lua_newtable(L);
  474. lua_setfield(L, -2, "preload");
  475. /* create `loadlib' function */
  476. lua_pushcfunction(L, ll_loadlib);
  477. #if defined(LUA_COMPAT_LOADLIB)
  478. lua_pushvalue(L, -1);
  479. lua_setfield(L, LUA_GLOBALSINDEX, "loadlib");
  480. #endif
  481. lua_setfield(L, -2, "loadlib");
  482. lua_pushvalue(L, LUA_GLOBALSINDEX);
  483. luaL_openlib(L, NULL, ll_funcs, 0); /* open lib into global table */
  484. return 1;
  485. }