loadlib.c 18 KB

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