loadlib.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730
  1. /*
  2. ** $Id: loadlib.c,v 1.76 2010/01/11 17:11:24 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. /*
  18. ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
  19. ** variables that Lua check to set its paths.
  20. */
  21. #if !defined(LUA_PATH_VAR)
  22. #define LUA_PATH_VAR "LUA_PATH"
  23. #endif
  24. #if !defined(LUA_CPATH_VAR)
  25. #define LUA_CPATH_VAR "LUA_CPATH"
  26. #endif
  27. /*
  28. ** LUA_PATH_SEP is the character that separates templates in a path.
  29. ** LUA_PATH_MARK is the string that marks the substitution points in a
  30. ** template.
  31. ** LUA_EXEC_DIR in a Windows path is replaced by the executable's
  32. ** directory.
  33. ** LUA_IGMARK is a mark to ignore all before it when building the
  34. ** luaopen_ function name.
  35. */
  36. #if !defined (LUA_PATH_SEP)
  37. #define LUA_PATH_SEP ";"
  38. #endif
  39. #if !defined (LUA_PATH_MARK)
  40. #define LUA_PATH_MARK "?"
  41. #endif
  42. #if !defined (LUA_EXEC_DIR)
  43. #define LUA_EXEC_DIR "!"
  44. #endif
  45. #if !defined (LUA_IGMARK)
  46. #define LUA_IGMARK "-"
  47. #endif
  48. /* prefix for open functions in C libraries */
  49. #define LUA_POF "luaopen_"
  50. /* separator for open functions in C libraries */
  51. #define LUA_OFSEP "_"
  52. #define LIBPREFIX "LOADLIB: "
  53. #define POF LUA_POF
  54. #define LIB_FAIL "open"
  55. /* error codes for ll_loadfunc */
  56. #define ERRLIB 1
  57. #define ERRFUNC 2
  58. #define setprogdir(L) ((void)0)
  59. /*
  60. ** system-dependent functions
  61. */
  62. static void ll_unloadlib (void *lib);
  63. static void *ll_load (lua_State *L, const char *path, int seeglb);
  64. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
  65. #if defined(LUA_USE_DLOPEN)
  66. /*
  67. ** {========================================================================
  68. ** This is an implementation of loadlib based on the dlfcn interface.
  69. ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  70. ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  71. ** as an emulation layer on top of native functions.
  72. ** =========================================================================
  73. */
  74. #include <dlfcn.h>
  75. static void ll_unloadlib (void *lib) {
  76. dlclose(lib);
  77. }
  78. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  79. void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : 0));
  80. if (lib == NULL) lua_pushstring(L, dlerror());
  81. return lib;
  82. }
  83. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  84. lua_CFunction f = (lua_CFunction)(unsigned long)dlsym(lib, sym);
  85. if (f == NULL) lua_pushstring(L, dlerror());
  86. return f;
  87. }
  88. /* }====================================================== */
  89. #elif defined(LUA_DL_DLL)
  90. /*
  91. ** {======================================================================
  92. ** This is an implementation of loadlib for Windows using native functions.
  93. ** =======================================================================
  94. */
  95. #include <windows.h>
  96. #undef setprogdir
  97. static void setprogdir (lua_State *L) {
  98. char buff[MAX_PATH + 1];
  99. char *lb;
  100. DWORD nsize = sizeof(buff)/sizeof(char);
  101. DWORD n = GetModuleFileName(NULL, buff, nsize);
  102. if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
  103. luaL_error(L, "unable to get ModuleFileName");
  104. else {
  105. *lb = '\0';
  106. luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
  107. lua_remove(L, -2); /* remove original string */
  108. }
  109. }
  110. static void pusherror (lua_State *L) {
  111. int error = GetLastError();
  112. char buffer[128];
  113. if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  114. NULL, error, 0, buffer, sizeof(buffer), NULL))
  115. lua_pushstring(L, buffer);
  116. else
  117. lua_pushfstring(L, "system error %d\n", error);
  118. }
  119. static void ll_unloadlib (void *lib) {
  120. FreeLibrary((HINSTANCE)lib);
  121. }
  122. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  123. HINSTANCE lib = LoadLibrary(path);
  124. (void)(seeglb); /* symbols are 'global' by default? */
  125. if (lib == NULL) pusherror(L);
  126. return lib;
  127. }
  128. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  129. lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
  130. if (f == NULL) pusherror(L);
  131. return f;
  132. }
  133. /* }====================================================== */
  134. #elif defined(LUA_DL_DYLD)
  135. /*
  136. ** {======================================================================
  137. ** Old native Mac OS X - only for old versions of Mac OS (< 10.3)
  138. ** =======================================================================
  139. */
  140. #include <mach-o/dyld.h>
  141. /* Mac appends a `_' before C function names */
  142. #undef POF
  143. #define POF "_" LUA_POF
  144. static void pusherror (lua_State *L) {
  145. const char *err_str;
  146. const char *err_file;
  147. NSLinkEditErrors err;
  148. int err_num;
  149. NSLinkEditError(&err, &err_num, &err_file, &err_str);
  150. lua_pushstring(L, err_str);
  151. }
  152. static const char *errorfromcode (NSObjectFileImageReturnCode ret) {
  153. switch (ret) {
  154. case NSObjectFileImageInappropriateFile:
  155. return "file is not a bundle";
  156. case NSObjectFileImageArch:
  157. return "library is for wrong CPU type";
  158. case NSObjectFileImageFormat:
  159. return "bad format";
  160. case NSObjectFileImageAccess:
  161. return "cannot access file";
  162. case NSObjectFileImageFailure:
  163. default:
  164. return "unable to load library";
  165. }
  166. }
  167. static void ll_unloadlib (void *lib) {
  168. NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
  169. }
  170. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  171. NSObjectFileImage img;
  172. NSObjectFileImageReturnCode ret;
  173. /* this would be a rare case, but prevents crashing if it happens */
  174. if(!_dyld_present()) {
  175. lua_pushliteral(L, "dyld not present");
  176. return NULL;
  177. }
  178. ret = NSCreateObjectFileImageFromFile(path, &img);
  179. if (ret == NSObjectFileImageSuccess) {
  180. NSModule mod = NSLinkModule(img,
  181. path,
  182. NSLINKMODULE_OPTION_RETURN_ON_ERROR |
  183. (seeglb ? 0 : NSLINKMODULE_OPTION_PRIVATE));
  184. NSDestroyObjectFileImage(img);
  185. if (mod == NULL) pusherror(L);
  186. return mod;
  187. }
  188. lua_pushstring(L, errorfromcode(ret));
  189. return NULL;
  190. }
  191. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  192. NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
  193. if (nss == NULL) {
  194. lua_pushfstring(L, "symbol " LUA_QS " not found", sym);
  195. return NULL;
  196. }
  197. return (lua_CFunction)NSAddressOfSymbol(nss);
  198. }
  199. /* }====================================================== */
  200. #else
  201. /*
  202. ** {======================================================
  203. ** Fallback for other systems
  204. ** =======================================================
  205. */
  206. #undef LIB_FAIL
  207. #define LIB_FAIL "absent"
  208. #define DLMSG "dynamic libraries not enabled; check your Lua installation"
  209. static void ll_unloadlib (void *lib) {
  210. (void)(lib); /* to avoid warnings */
  211. }
  212. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  213. (void)(path); /* to avoid warnings */
  214. lua_pushliteral(L, DLMSG);
  215. return NULL;
  216. }
  217. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  218. (void)(lib); (void)(sym); /* to avoid warnings */
  219. lua_pushliteral(L, DLMSG);
  220. return NULL;
  221. }
  222. /* }====================================================== */
  223. #endif
  224. static void **ll_register (lua_State *L, const char *path) {
  225. void **plib;
  226. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  227. lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
  228. if (!lua_isnil(L, -1)) /* is there an entry? */
  229. plib = (void **)lua_touserdata(L, -1);
  230. else { /* no entry yet; create one */
  231. lua_pop(L, 1); /* remove result from gettable */
  232. plib = (void **)lua_newuserdata(L, sizeof(const void *));
  233. *plib = NULL;
  234. luaL_getmetatable(L, "_LOADLIB");
  235. lua_setmetatable(L, -2);
  236. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  237. lua_pushvalue(L, -2);
  238. lua_settable(L, LUA_REGISTRYINDEX);
  239. }
  240. return plib;
  241. }
  242. /*
  243. ** __gc tag method: calls library's `ll_unloadlib' function with the lib
  244. ** handle
  245. */
  246. static int gctm (lua_State *L) {
  247. void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
  248. if (*lib) ll_unloadlib(*lib);
  249. *lib = NULL; /* mark library as closed */
  250. return 0;
  251. }
  252. static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
  253. void **reg = ll_register(L, path);
  254. if (*reg == NULL) *reg = ll_load(L, path, *sym == '*');
  255. if (*reg == NULL) return ERRLIB; /* unable to load library */
  256. if (*sym == '*') { /* loading only library (no function)? */
  257. lua_pushboolean(L, 1); /* return 'true' */
  258. return 0; /* no errors */
  259. }
  260. else {
  261. lua_CFunction f = ll_sym(L, *reg, sym);
  262. if (f == NULL)
  263. return ERRFUNC; /* unable to find function */
  264. lua_pushcfunction(L, f); /* else create new function... */
  265. lua_pushglobaltable(L); /* ... and set the standard global table... */
  266. lua_setfenv(L, -2); /* ... as its environment */
  267. return 0; /* no errors */
  268. }
  269. }
  270. static int ll_loadlib (lua_State *L) {
  271. const char *path = luaL_checkstring(L, 1);
  272. const char *init = luaL_checkstring(L, 2);
  273. int stat = ll_loadfunc(L, path, init);
  274. if (stat == 0) /* no errors? */
  275. return 1; /* return the loaded function */
  276. else { /* error; error message is on stack top */
  277. lua_pushnil(L);
  278. lua_insert(L, -2);
  279. lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
  280. return 3; /* return nil, error message, and where */
  281. }
  282. }
  283. /*
  284. ** {======================================================
  285. ** 'require' function
  286. ** =======================================================
  287. */
  288. static int readable (const char *filename) {
  289. FILE *f = fopen(filename, "r"); /* try to open file */
  290. if (f == NULL) return 0; /* open failed */
  291. fclose(f);
  292. return 1;
  293. }
  294. static const char *pushnexttemplate (lua_State *L, const char *path) {
  295. const char *l;
  296. while (*path == *LUA_PATH_SEP) path++; /* skip separators */
  297. if (*path == '\0') return NULL; /* no more templates */
  298. l = strchr(path, *LUA_PATH_SEP); /* find next separator */
  299. if (l == NULL) l = path + strlen(path);
  300. lua_pushlstring(L, path, l - path); /* template */
  301. return l;
  302. }
  303. static const char *searchpath (lua_State *L, const char *name,
  304. const char *path) {
  305. lua_pushliteral(L, ""); /* error accumulator */
  306. while ((path = pushnexttemplate(L, path)) != NULL) {
  307. const char *filename = luaL_gsub(L, lua_tostring(L, -1),
  308. LUA_PATH_MARK, name);
  309. lua_remove(L, -2); /* remove path template */
  310. if (readable(filename)) /* does file exist and is readable? */
  311. return filename; /* return that file name */
  312. lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
  313. lua_remove(L, -2); /* remove file name */
  314. lua_concat(L, 2); /* add entry to possible error message */
  315. }
  316. return NULL; /* not found */
  317. }
  318. static int ll_searchpath (lua_State *L) {
  319. const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2));
  320. if (f != NULL) return 1;
  321. else { /* error message is on top of the stack */
  322. lua_pushnil(L);
  323. lua_insert(L, -2);
  324. return 2; /* return nil + error message */
  325. }
  326. }
  327. static const char *findfile (lua_State *L, const char *name,
  328. const char *pname) {
  329. const char *path;
  330. name = luaL_gsub(L, name, ".", LUA_DIRSEP);
  331. lua_getfield(L, LUA_ENVIRONINDEX, pname);
  332. path = lua_tostring(L, -1);
  333. if (path == NULL)
  334. luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
  335. return searchpath(L, name, path);
  336. }
  337. static void loaderror (lua_State *L, const char *filename) {
  338. luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
  339. lua_tostring(L, 1), filename, lua_tostring(L, -1));
  340. }
  341. static int loader_Lua (lua_State *L) {
  342. const char *filename;
  343. const char *name = luaL_checkstring(L, 1);
  344. filename = findfile(L, name, "path");
  345. if (filename == NULL) return 1; /* library not found in this path */
  346. if (luaL_loadfile(L, filename) != LUA_OK)
  347. loaderror(L, filename);
  348. return 1; /* library loaded successfully */
  349. }
  350. static int loadfunc (lua_State *L, const char *filename, const char *modname) {
  351. const char *funcname;
  352. const char *mark;
  353. modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
  354. mark = strchr(modname, *LUA_IGMARK);
  355. if (mark) {
  356. int stat;
  357. funcname = lua_pushlstring(L, modname, mark - modname);
  358. funcname = lua_pushfstring(L, POF"%s", funcname);
  359. stat = ll_loadfunc(L, filename, funcname);
  360. if (stat != ERRFUNC) return stat;
  361. modname = mark + 1; /* else go ahead and try old-style name */
  362. }
  363. funcname = lua_pushfstring(L, POF"%s", modname);
  364. return ll_loadfunc(L, filename, funcname);
  365. }
  366. static int loader_C (lua_State *L) {
  367. const char *name = luaL_checkstring(L, 1);
  368. const char *filename = findfile(L, name, "cpath");
  369. if (filename == NULL) return 1; /* library not found in this path */
  370. if (loadfunc(L, filename, name) != 0)
  371. loaderror(L, filename);
  372. return 1; /* library loaded successfully */
  373. }
  374. static int loader_Croot (lua_State *L) {
  375. const char *filename;
  376. const char *name = luaL_checkstring(L, 1);
  377. const char *p = strchr(name, '.');
  378. int stat;
  379. if (p == NULL) return 0; /* is root */
  380. lua_pushlstring(L, name, p - name);
  381. filename = findfile(L, lua_tostring(L, -1), "cpath");
  382. if (filename == NULL) return 1; /* root not found */
  383. if ((stat = loadfunc(L, filename, name)) != 0) {
  384. if (stat != ERRFUNC) loaderror(L, filename); /* real error */
  385. lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
  386. name, filename);
  387. return 1; /* function not found */
  388. }
  389. return 1;
  390. }
  391. static int loader_preload (lua_State *L) {
  392. const char *name = luaL_checkstring(L, 1);
  393. lua_getfield(L, LUA_ENVIRONINDEX, "preload");
  394. if (!lua_istable(L, -1))
  395. luaL_error(L, LUA_QL("package.preload") " must be a table");
  396. lua_getfield(L, -1, name);
  397. if (lua_isnil(L, -1)) /* not found? */
  398. lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
  399. return 1;
  400. }
  401. static const int sentinel_ = 0;
  402. #define sentinel ((void *)&sentinel_)
  403. static int ll_require (lua_State *L) {
  404. const char *name = luaL_checkstring(L, 1);
  405. int i;
  406. lua_settop(L, 1); /* _LOADED table will be at index 2 */
  407. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  408. lua_getfield(L, 2, name);
  409. if (lua_toboolean(L, -1)) { /* is it there? */
  410. if (lua_touserdata(L, -1) == sentinel) /* check loops */
  411. luaL_error(L, "loop or previous error loading module " LUA_QS, name);
  412. return 1; /* package is already loaded */
  413. }
  414. /* else must load it; iterate over available loaders */
  415. lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  416. if (!lua_istable(L, -1))
  417. luaL_error(L, LUA_QL("package.loaders") " must be a table");
  418. lua_pushliteral(L, ""); /* error message accumulator */
  419. for (i=1; ; i++) {
  420. lua_rawgeti(L, -2, i); /* get a loader */
  421. if (lua_isnil(L, -1))
  422. luaL_error(L, "module " LUA_QS " not found:%s",
  423. name, lua_tostring(L, -2));
  424. lua_pushstring(L, name);
  425. lua_call(L, 1, 1); /* call it */
  426. if (lua_isfunction(L, -1)) /* did it find module? */
  427. break; /* module loaded successfully */
  428. else if (lua_isstring(L, -1)) /* loader returned error message? */
  429. lua_concat(L, 2); /* accumulate it */
  430. else
  431. lua_pop(L, 1);
  432. }
  433. lua_pushlightuserdata(L, sentinel);
  434. lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
  435. lua_pushstring(L, name); /* pass name as argument to module */
  436. lua_call(L, 1, 1); /* run loaded module */
  437. if (!lua_isnil(L, -1)) /* non-nil return? */
  438. lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
  439. lua_getfield(L, 2, name);
  440. if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */
  441. lua_pushboolean(L, 1); /* use true as result */
  442. lua_pushvalue(L, -1); /* extra copy to be returned */
  443. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  444. }
  445. return 1;
  446. }
  447. /* }====================================================== */
  448. /*
  449. ** {======================================================
  450. ** 'module' function
  451. ** =======================================================
  452. */
  453. static void setfenv (lua_State *L) {
  454. lua_Debug ar;
  455. if (lua_getstack(L, 1, &ar) == 0 ||
  456. lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
  457. lua_iscfunction(L, -1))
  458. luaL_error(L, LUA_QL("module") " not called from a Lua function");
  459. lua_pushvalue(L, -2); /* copy new environment table to top */
  460. lua_setfenv(L, -2);
  461. lua_pop(L, 1); /* remove function */
  462. }
  463. static void dooptions (lua_State *L, int n) {
  464. int i;
  465. for (i = 2; i <= n; i++) {
  466. lua_pushvalue(L, i); /* get option (a function) */
  467. lua_pushvalue(L, -2); /* module */
  468. lua_call(L, 1, 0);
  469. }
  470. }
  471. static void modinit (lua_State *L, const char *modname) {
  472. const char *dot;
  473. lua_pushvalue(L, -1);
  474. lua_setfield(L, -2, "_M"); /* module._M = module */
  475. lua_pushstring(L, modname);
  476. lua_setfield(L, -2, "_NAME");
  477. dot = strrchr(modname, '.'); /* look for last dot in module name */
  478. if (dot == NULL) dot = modname;
  479. else dot++;
  480. /* set _PACKAGE as package name (full module name minus last part) */
  481. lua_pushlstring(L, modname, dot - modname);
  482. lua_setfield(L, -2, "_PACKAGE");
  483. }
  484. static int ll_module (lua_State *L) {
  485. const char *modname = luaL_checkstring(L, 1);
  486. int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
  487. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  488. lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
  489. if (!lua_istable(L, -1)) { /* not found? */
  490. lua_pop(L, 1); /* remove previous result */
  491. /* try global variable (and create one if it does not exist) */
  492. lua_pushglobaltable(L);
  493. if (luaL_findtable(L, 0, modname, 1) != NULL)
  494. return luaL_error(L, "name conflict for module " LUA_QS, modname);
  495. lua_pushvalue(L, -1);
  496. lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
  497. }
  498. /* check whether table already has a _NAME field */
  499. lua_getfield(L, -1, "_NAME");
  500. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  501. lua_pop(L, 1);
  502. else { /* no; initialize it */
  503. lua_pop(L, 1);
  504. modinit(L, modname);
  505. }
  506. lua_pushvalue(L, -1);
  507. setfenv(L);
  508. dooptions(L, loaded - 1);
  509. return 1;
  510. }
  511. static int ll_seeall (lua_State *L) {
  512. luaL_checktype(L, 1, LUA_TTABLE);
  513. if (!lua_getmetatable(L, 1)) {
  514. lua_createtable(L, 0, 1); /* create new metatable */
  515. lua_pushvalue(L, -1);
  516. lua_setmetatable(L, 1);
  517. }
  518. lua_pushglobaltable(L);
  519. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  520. return 0;
  521. }
  522. /* }====================================================== */
  523. /* auxiliary mark (for internal use) */
  524. #define AUXMARK "\1"
  525. static void setpath (lua_State *L, const char *fieldname, const char *envname,
  526. const char *def) {
  527. const char *path = getenv(envname);
  528. if (path == NULL) /* no environment variable? */
  529. lua_pushstring(L, def); /* use default */
  530. else {
  531. /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
  532. path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP,
  533. LUA_PATH_SEP AUXMARK LUA_PATH_SEP);
  534. luaL_gsub(L, path, AUXMARK, def);
  535. lua_remove(L, -2);
  536. }
  537. setprogdir(L);
  538. lua_setfield(L, -2, fieldname);
  539. }
  540. static const luaL_Reg pk_funcs[] = {
  541. {"loadlib", ll_loadlib},
  542. {"searchpath", ll_searchpath},
  543. {"seeall", ll_seeall},
  544. {NULL, NULL}
  545. };
  546. static const luaL_Reg ll_funcs[] = {
  547. {"module", ll_module},
  548. {"require", ll_require},
  549. {NULL, NULL}
  550. };
  551. static const lua_CFunction loaders[] =
  552. {loader_preload, loader_Lua, loader_C, loader_Croot, NULL};
  553. LUAMOD_API int luaopen_package (lua_State *L) {
  554. int i;
  555. /* create new type _LOADLIB */
  556. luaL_newmetatable(L, "_LOADLIB");
  557. lua_pushcfunction(L, gctm);
  558. lua_setfield(L, -2, "__gc");
  559. /* create `package' table */
  560. luaL_register(L, LUA_LOADLIBNAME, pk_funcs);
  561. lua_copy(L, -1, LUA_ENVIRONINDEX);
  562. /* create `loaders' table */
  563. lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0);
  564. /* fill it with pre-defined loaders */
  565. for (i=0; loaders[i] != NULL; i++) {
  566. lua_pushcfunction(L, loaders[i]);
  567. lua_rawseti(L, -2, i+1);
  568. }
  569. lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
  570. setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); /* set field `path' */
  571. setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); /* set field `cpath' */
  572. /* store config information */
  573. lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
  574. LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
  575. lua_setfield(L, -2, "config");
  576. /* set field `loaded' */
  577. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2);
  578. lua_setfield(L, -2, "loaded");
  579. /* set field `preload' */
  580. lua_newtable(L);
  581. lua_setfield(L, -2, "preload");
  582. lua_pushglobaltable(L);
  583. luaL_register(L, NULL, ll_funcs); /* open lib into global table */
  584. lua_pop(L, 1);
  585. return 1; /* return 'package' table */
  586. }