loadlib.c 21 KB

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