loadlib.c 21 KB

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