loadlib.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. /*
  2. ** $Id: loadlib.c,v 1.122 2014/11/10 14:28:31 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 Windows, and a stub for other
  8. ** systems.
  9. */
  10. #define loadlib_c
  11. #define LUA_LIB
  12. #include "lprefix.h"
  13. #include <stdlib.h>
  14. #include <string.h>
  15. #include "lua.h"
  16. #include "lauxlib.h"
  17. #include "lualib.h"
  18. /*
  19. ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
  20. ** variables that Lua check to set its paths.
  21. */
  22. #if !defined(LUA_PATH_VAR)
  23. #define LUA_PATH_VAR "LUA_PATH"
  24. #endif
  25. #if !defined(LUA_CPATH_VAR)
  26. #define LUA_CPATH_VAR "LUA_CPATH"
  27. #endif
  28. #define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
  29. #define LUA_PATHVARVERSION LUA_PATH_VAR LUA_PATHSUFFIX
  30. #define LUA_CPATHVARVERSION LUA_CPATH_VAR LUA_PATHSUFFIX
  31. /*
  32. ** LUA_PATH_SEP is the character that separates templates in a path.
  33. ** LUA_PATH_MARK is the string that marks the substitution points in a
  34. ** template.
  35. ** LUA_EXEC_DIR in a Windows path is replaced by the executable's
  36. ** directory.
  37. ** LUA_IGMARK is a mark to ignore all before it when building the
  38. ** luaopen_ function name.
  39. */
  40. #if !defined (LUA_PATH_SEP)
  41. #define LUA_PATH_SEP ";"
  42. #endif
  43. #if !defined (LUA_PATH_MARK)
  44. #define LUA_PATH_MARK "?"
  45. #endif
  46. #if !defined (LUA_EXEC_DIR)
  47. #define LUA_EXEC_DIR "!"
  48. #endif
  49. #if !defined (LUA_IGMARK)
  50. #define LUA_IGMARK "-"
  51. #endif
  52. /*
  53. ** LUA_CSUBSEP is the character that replaces dots in submodule names
  54. ** when searching for a C loader.
  55. ** LUA_LSUBSEP is the character that replaces dots in submodule names
  56. ** when searching for a Lua loader.
  57. */
  58. #if !defined(LUA_CSUBSEP)
  59. #define LUA_CSUBSEP LUA_DIRSEP
  60. #endif
  61. #if !defined(LUA_LSUBSEP)
  62. #define LUA_LSUBSEP LUA_DIRSEP
  63. #endif
  64. /* prefix for open functions in C libraries */
  65. #define LUA_POF "luaopen_"
  66. /* separator for open functions in C libraries */
  67. #define LUA_OFSEP "_"
  68. /*
  69. ** unique key for table in the registry that keeps handles
  70. ** for all loaded C libraries
  71. */
  72. static const int CLIBS = 0;
  73. #define LIB_FAIL "open"
  74. #define setprogdir(L) ((void)0)
  75. /*
  76. ** system-dependent functions
  77. */
  78. /*
  79. ** unload library 'lib'
  80. */
  81. static void lsys_unloadlib (void *lib);
  82. /*
  83. ** load C library in file 'path'. If 'seeglb', load with all names in
  84. ** the library global.
  85. ** Returns the library; in case of error, returns NULL plus an
  86. ** error string in the stack.
  87. */
  88. static void *lsys_load (lua_State *L, const char *path, int seeglb);
  89. /*
  90. ** Try to find a function named 'sym' in library 'lib'.
  91. ** Returns the function; in case of error, returns NULL plus an
  92. ** error string in the stack.
  93. */
  94. static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
  95. #if defined(LUA_USE_DLOPEN) /* { */
  96. /*
  97. ** {========================================================================
  98. ** This is an implementation of loadlib based on the dlfcn interface.
  99. ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  100. ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  101. ** as an emulation layer on top of native functions.
  102. ** =========================================================================
  103. */
  104. #include <dlfcn.h>
  105. static void lsys_unloadlib (void *lib) {
  106. dlclose(lib);
  107. }
  108. static void *lsys_load (lua_State *L, const char *path, int seeglb) {
  109. void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
  110. if (lib == NULL) lua_pushstring(L, dlerror());
  111. return lib;
  112. }
  113. static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
  114. lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
  115. if (f == NULL) lua_pushstring(L, dlerror());
  116. return f;
  117. }
  118. /* }====================================================== */
  119. #elif defined(LUA_DL_DLL) /* }{ */
  120. /*
  121. ** {======================================================================
  122. ** This is an implementation of loadlib for Windows using native functions.
  123. ** =======================================================================
  124. */
  125. #include <windows.h>
  126. #undef setprogdir
  127. /*
  128. ** optional flags for LoadLibraryEx
  129. */
  130. #if !defined(LUA_LLE_FLAGS)
  131. #define LUA_LLE_FLAGS 0
  132. #endif
  133. static void setprogdir (lua_State *L) {
  134. char buff[MAX_PATH + 1];
  135. char *lb;
  136. DWORD nsize = sizeof(buff)/sizeof(char);
  137. DWORD n = GetModuleFileNameA(NULL, buff, nsize);
  138. if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
  139. luaL_error(L, "unable to get ModuleFileName");
  140. else {
  141. *lb = '\0';
  142. luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
  143. lua_remove(L, -2); /* remove original string */
  144. }
  145. }
  146. static void pusherror (lua_State *L) {
  147. int error = GetLastError();
  148. char buffer[128];
  149. if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  150. NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
  151. lua_pushstring(L, buffer);
  152. else
  153. lua_pushfstring(L, "system error %d\n", error);
  154. }
  155. static void lsys_unloadlib (void *lib) {
  156. FreeLibrary((HMODULE)lib);
  157. }
  158. static void *lsys_load (lua_State *L, const char *path, int seeglb) {
  159. HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
  160. (void)(seeglb); /* not used: symbols are 'global' by default */
  161. if (lib == NULL) pusherror(L);
  162. return lib;
  163. }
  164. static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
  165. lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
  166. if (f == NULL) pusherror(L);
  167. return f;
  168. }
  169. /* }====================================================== */
  170. #else /* }{ */
  171. /*
  172. ** {======================================================
  173. ** Fallback for other systems
  174. ** =======================================================
  175. */
  176. #undef LIB_FAIL
  177. #define LIB_FAIL "absent"
  178. #define DLMSG "dynamic libraries not enabled; check your Lua installation"
  179. static void lsys_unloadlib (void *lib) {
  180. (void)(lib); /* not used */
  181. }
  182. static void *lsys_load (lua_State *L, const char *path, int seeglb) {
  183. (void)(path); (void)(seeglb); /* not used */
  184. lua_pushliteral(L, DLMSG);
  185. return NULL;
  186. }
  187. static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
  188. (void)(lib); (void)(sym); /* not used */
  189. lua_pushliteral(L, DLMSG);
  190. return NULL;
  191. }
  192. /* }====================================================== */
  193. #endif /* } */
  194. /*
  195. ** return registry.CLIBS[path]
  196. */
  197. static void *checkclib (lua_State *L, const char *path) {
  198. void *plib;
  199. lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
  200. lua_getfield(L, -1, path);
  201. plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
  202. lua_pop(L, 2); /* pop CLIBS table and 'plib' */
  203. return plib;
  204. }
  205. /*
  206. ** registry.CLIBS[path] = plib -- for queries
  207. ** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries
  208. */
  209. static void addtoclib (lua_State *L, const char *path, void *plib) {
  210. lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
  211. lua_pushlightuserdata(L, plib);
  212. lua_pushvalue(L, -1);
  213. lua_setfield(L, -3, path); /* CLIBS[path] = plib */
  214. lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */
  215. lua_pop(L, 1); /* pop CLIBS table */
  216. }
  217. /*
  218. ** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
  219. ** handles in list CLIBS
  220. */
  221. static int gctm (lua_State *L) {
  222. lua_Integer n = luaL_len(L, 1);
  223. for (; n >= 1; n--) { /* for each handle, in reverse order */
  224. lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
  225. lsys_unloadlib(lua_touserdata(L, -1));
  226. lua_pop(L, 1); /* pop handle */
  227. }
  228. return 0;
  229. }
  230. /* error codes for 'lookforfunc' */
  231. #define ERRLIB 1
  232. #define ERRFUNC 2
  233. /*
  234. ** Look for a C function named 'sym' in a dynamically loaded library
  235. ** 'path'.
  236. ** First, check whether the library is already loaded; if not, try
  237. ** to load it.
  238. ** Then, if 'sym' is '*', return true (as library has been loaded).
  239. ** Otherwise, look for symbol 'sym' in the library and push a
  240. ** C function with that symbol.
  241. ** Return 0 and 'true' or a function in the stack; in case of
  242. ** errors, return an error code and an error message in the stack.
  243. */
  244. static int lookforfunc (lua_State *L, const char *path, const char *sym) {
  245. void *reg = checkclib(L, path); /* check loaded C libraries */
  246. if (reg == NULL) { /* must load library? */
  247. reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */
  248. if (reg == NULL) return ERRLIB; /* unable to load library */
  249. addtoclib(L, path, reg);
  250. }
  251. if (*sym == '*') { /* loading only library (no function)? */
  252. lua_pushboolean(L, 1); /* return 'true' */
  253. return 0; /* no errors */
  254. }
  255. else {
  256. lua_CFunction f = lsys_sym(L, reg, sym);
  257. if (f == NULL)
  258. return ERRFUNC; /* unable to find function */
  259. lua_pushcfunction(L, f); /* else create new function */
  260. return 0; /* no errors */
  261. }
  262. }
  263. static int ll_loadlib (lua_State *L) {
  264. const char *path = luaL_checkstring(L, 1);
  265. const char *init = luaL_checkstring(L, 2);
  266. int stat = lookforfunc(L, path, init);
  267. if (stat == 0) /* no errors? */
  268. return 1; /* return the loaded function */
  269. else { /* error; error message is on stack top */
  270. lua_pushnil(L);
  271. lua_insert(L, -2);
  272. lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
  273. return 3; /* return nil, error message, and where */
  274. }
  275. }
  276. /*
  277. ** {======================================================
  278. ** 'require' function
  279. ** =======================================================
  280. */
  281. static int readable (const char *filename) {
  282. FILE *f = fopen(filename, "r"); /* try to open file */
  283. if (f == NULL) return 0; /* open failed */
  284. fclose(f);
  285. return 1;
  286. }
  287. static const char *pushnexttemplate (lua_State *L, const char *path) {
  288. const char *l;
  289. while (*path == *LUA_PATH_SEP) path++; /* skip separators */
  290. if (*path == '\0') return NULL; /* no more templates */
  291. l = strchr(path, *LUA_PATH_SEP); /* find next separator */
  292. if (l == NULL) l = path + strlen(path);
  293. lua_pushlstring(L, path, l - path); /* template */
  294. return l;
  295. }
  296. static const char *searchpath (lua_State *L, const char *name,
  297. const char *path,
  298. const char *sep,
  299. const char *dirsep) {
  300. luaL_Buffer msg; /* to build error message */
  301. luaL_buffinit(L, &msg);
  302. if (*sep != '\0') /* non-empty separator? */
  303. name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
  304. while ((path = pushnexttemplate(L, path)) != NULL) {
  305. const char *filename = luaL_gsub(L, lua_tostring(L, -1),
  306. LUA_PATH_MARK, name);
  307. lua_remove(L, -2); /* remove path template */
  308. if (readable(filename)) /* does file exist and is readable? */
  309. return filename; /* return that file name */
  310. lua_pushfstring(L, "\n\tno file '%s'", filename);
  311. lua_remove(L, -2); /* remove file name */
  312. luaL_addvalue(&msg); /* concatenate error msg. entry */
  313. }
  314. luaL_pushresult(&msg); /* create error message */
  315. return NULL; /* not found */
  316. }
  317. static int ll_searchpath (lua_State *L) {
  318. const char *f = searchpath(L, luaL_checkstring(L, 1),
  319. luaL_checkstring(L, 2),
  320. luaL_optstring(L, 3, "."),
  321. luaL_optstring(L, 4, LUA_DIRSEP));
  322. if (f != NULL) return 1;
  323. else { /* error message is on top of the stack */
  324. lua_pushnil(L);
  325. lua_insert(L, -2);
  326. return 2; /* return nil + error message */
  327. }
  328. }
  329. static const char *findfile (lua_State *L, const char *name,
  330. const char *pname,
  331. const char *dirsep) {
  332. const char *path;
  333. lua_getfield(L, lua_upvalueindex(1), pname);
  334. path = lua_tostring(L, -1);
  335. if (path == NULL)
  336. luaL_error(L, "'package.%s' must be a string", pname);
  337. return searchpath(L, name, path, ".", dirsep);
  338. }
  339. static int checkload (lua_State *L, int stat, const char *filename) {
  340. if (stat) { /* module loaded successfully? */
  341. lua_pushstring(L, filename); /* will be 2nd argument to module */
  342. return 2; /* return open function and file name */
  343. }
  344. else
  345. return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
  346. lua_tostring(L, 1), filename, lua_tostring(L, -1));
  347. }
  348. static int searcher_Lua (lua_State *L) {
  349. const char *filename;
  350. const char *name = luaL_checkstring(L, 1);
  351. filename = findfile(L, name, "path", LUA_LSUBSEP);
  352. if (filename == NULL) return 1; /* module not found in this path */
  353. return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
  354. }
  355. /*
  356. ** Try to find a load function for module 'modname' at file 'filename'.
  357. ** First, change '.' to '_' in 'modname'; then, if 'modname' has
  358. ** the form X-Y (that is, it has an "ignore mark"), build a function
  359. ** name "luaopen_X" and look for it. (For compatibility, if that
  360. ** fails, it also tries "luaopen_Y".) If there is no ignore mark,
  361. ** look for a function named "luaopen_modname".
  362. */
  363. static int loadfunc (lua_State *L, const char *filename, const char *modname) {
  364. const char *openfunc;
  365. const char *mark;
  366. modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
  367. mark = strchr(modname, *LUA_IGMARK);
  368. if (mark) {
  369. int stat;
  370. openfunc = lua_pushlstring(L, modname, mark - modname);
  371. openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
  372. stat = lookforfunc(L, filename, openfunc);
  373. if (stat != ERRFUNC) return stat;
  374. modname = mark + 1; /* else go ahead and try old-style name */
  375. }
  376. openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
  377. return lookforfunc(L, filename, openfunc);
  378. }
  379. static int searcher_C (lua_State *L) {
  380. const char *name = luaL_checkstring(L, 1);
  381. const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
  382. if (filename == NULL) return 1; /* module not found in this path */
  383. return checkload(L, (loadfunc(L, filename, name) == 0), filename);
  384. }
  385. static int searcher_Croot (lua_State *L) {
  386. const char *filename;
  387. const char *name = luaL_checkstring(L, 1);
  388. const char *p = strchr(name, '.');
  389. int stat;
  390. if (p == NULL) return 0; /* is root */
  391. lua_pushlstring(L, name, p - name);
  392. filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
  393. if (filename == NULL) return 1; /* root not found */
  394. if ((stat = loadfunc(L, filename, name)) != 0) {
  395. if (stat != ERRFUNC)
  396. return checkload(L, 0, filename); /* real error */
  397. else { /* open function not found */
  398. lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
  399. return 1;
  400. }
  401. }
  402. lua_pushstring(L, filename); /* will be 2nd argument to module */
  403. return 2;
  404. }
  405. static int searcher_preload (lua_State *L) {
  406. const char *name = luaL_checkstring(L, 1);
  407. lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
  408. if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */
  409. lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
  410. return 1;
  411. }
  412. static void findloader (lua_State *L, const char *name) {
  413. int i;
  414. luaL_Buffer msg; /* to build error message */
  415. luaL_buffinit(L, &msg);
  416. /* push 'package.searchers' to index 3 in the stack */
  417. if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)
  418. luaL_error(L, "'package.searchers' must be a table");
  419. /* iterate over available searchers to find a loader */
  420. for (i = 1; ; i++) {
  421. if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
  422. lua_pop(L, 1); /* remove nil */
  423. luaL_pushresult(&msg); /* create error message */
  424. luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
  425. }
  426. lua_pushstring(L, name);
  427. lua_call(L, 1, 2); /* call it */
  428. if (lua_isfunction(L, -2)) /* did it find a loader? */
  429. return; /* module loader found */
  430. else if (lua_isstring(L, -2)) { /* searcher returned error message? */
  431. lua_pop(L, 1); /* remove extra return */
  432. luaL_addvalue(&msg); /* concatenate error message */
  433. }
  434. else
  435. lua_pop(L, 2); /* remove both returns */
  436. }
  437. }
  438. static int ll_require (lua_State *L) {
  439. const char *name = luaL_checkstring(L, 1);
  440. lua_settop(L, 1); /* _LOADED table will be at index 2 */
  441. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  442. lua_getfield(L, 2, name); /* _LOADED[name] */
  443. if (lua_toboolean(L, -1)) /* is it there? */
  444. return 1; /* package is already loaded */
  445. /* else must load package */
  446. lua_pop(L, 1); /* remove 'getfield' result */
  447. findloader(L, name);
  448. lua_pushstring(L, name); /* pass name as argument to module loader */
  449. lua_insert(L, -2); /* name is 1st argument (before search data) */
  450. lua_call(L, 2, 1); /* run loader to load module */
  451. if (!lua_isnil(L, -1)) /* non-nil return? */
  452. lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
  453. if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
  454. lua_pushboolean(L, 1); /* use true as result */
  455. lua_pushvalue(L, -1); /* extra copy to be returned */
  456. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  457. }
  458. return 1;
  459. }
  460. /* }====================================================== */
  461. /*
  462. ** {======================================================
  463. ** 'module' function
  464. ** =======================================================
  465. */
  466. #if defined(LUA_COMPAT_MODULE)
  467. /*
  468. ** changes the environment variable of calling function
  469. */
  470. static void set_env (lua_State *L) {
  471. lua_Debug ar;
  472. if (lua_getstack(L, 1, &ar) == 0 ||
  473. lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
  474. lua_iscfunction(L, -1))
  475. luaL_error(L, "'module' not called from a Lua function");
  476. lua_pushvalue(L, -2); /* copy new environment table to top */
  477. lua_setupvalue(L, -2, 1);
  478. lua_pop(L, 1); /* remove function */
  479. }
  480. static void dooptions (lua_State *L, int n) {
  481. int i;
  482. for (i = 2; i <= n; i++) {
  483. if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */
  484. lua_pushvalue(L, i); /* get option (a function) */
  485. lua_pushvalue(L, -2); /* module */
  486. lua_call(L, 1, 0);
  487. }
  488. }
  489. }
  490. static void modinit (lua_State *L, const char *modname) {
  491. const char *dot;
  492. lua_pushvalue(L, -1);
  493. lua_setfield(L, -2, "_M"); /* module._M = module */
  494. lua_pushstring(L, modname);
  495. lua_setfield(L, -2, "_NAME");
  496. dot = strrchr(modname, '.'); /* look for last dot in module name */
  497. if (dot == NULL) dot = modname;
  498. else dot++;
  499. /* set _PACKAGE as package name (full module name minus last part) */
  500. lua_pushlstring(L, modname, dot - modname);
  501. lua_setfield(L, -2, "_PACKAGE");
  502. }
  503. static int ll_module (lua_State *L) {
  504. const char *modname = luaL_checkstring(L, 1);
  505. int lastarg = lua_gettop(L); /* last parameter */
  506. luaL_pushmodule(L, modname, 1); /* get/create module table */
  507. /* check whether table already has a _NAME field */
  508. if (lua_getfield(L, -1, "_NAME") != LUA_TNIL)
  509. lua_pop(L, 1); /* table is an initialized module */
  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, lastarg);
  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. #endif
  531. /* }====================================================== */
  532. /* auxiliary mark (for internal use) */
  533. #define AUXMARK "\1"
  534. /*
  535. ** return registry.LUA_NOENV as a boolean
  536. */
  537. static int noenv (lua_State *L) {
  538. int b;
  539. lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
  540. b = lua_toboolean(L, -1);
  541. lua_pop(L, 1); /* remove value */
  542. return b;
  543. }
  544. static void setpath (lua_State *L, const char *fieldname, const char *envname1,
  545. const char *envname2, const char *def) {
  546. const char *path = getenv(envname1);
  547. if (path == NULL) /* no environment variable? */
  548. path = getenv(envname2); /* try alternative name */
  549. if (path == NULL || noenv(L)) /* no environment variable? */
  550. lua_pushstring(L, def); /* use default */
  551. else {
  552. /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
  553. path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP,
  554. LUA_PATH_SEP AUXMARK LUA_PATH_SEP);
  555. luaL_gsub(L, path, AUXMARK, def);
  556. lua_remove(L, -2);
  557. }
  558. setprogdir(L);
  559. lua_setfield(L, -2, fieldname);
  560. }
  561. static const luaL_Reg pk_funcs[] = {
  562. {"loadlib", ll_loadlib},
  563. {"searchpath", ll_searchpath},
  564. #if defined(LUA_COMPAT_MODULE)
  565. {"seeall", ll_seeall},
  566. #endif
  567. /* placeholders */
  568. {"preload", NULL},
  569. {"cpath", NULL},
  570. {"path", NULL},
  571. {"searchers", NULL},
  572. {"loaded", NULL},
  573. {NULL, NULL}
  574. };
  575. static const luaL_Reg ll_funcs[] = {
  576. #if defined(LUA_COMPAT_MODULE)
  577. {"module", ll_module},
  578. #endif
  579. {"require", ll_require},
  580. {NULL, NULL}
  581. };
  582. static void createsearcherstable (lua_State *L) {
  583. static const lua_CFunction searchers[] =
  584. {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL};
  585. int i;
  586. /* create 'searchers' table */
  587. lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
  588. /* fill it with pre-defined searchers */
  589. for (i=0; searchers[i] != NULL; i++) {
  590. lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
  591. lua_pushcclosure(L, searchers[i], 1);
  592. lua_rawseti(L, -2, i+1);
  593. }
  594. #if defined(LUA_COMPAT_LOADERS)
  595. lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
  596. lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */
  597. #endif
  598. lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
  599. }
  600. /*
  601. ** create table CLIBS to keep track of loaded C libraries,
  602. ** setting a finalizer to close all libraries when closing state.
  603. */
  604. static void createclibstable (lua_State *L) {
  605. lua_newtable(L); /* create CLIBS table */
  606. lua_createtable(L, 0, 1); /* create metatable for CLIBS */
  607. lua_pushcfunction(L, gctm);
  608. lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
  609. lua_setmetatable(L, -2);
  610. lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */
  611. }
  612. LUAMOD_API int luaopen_package (lua_State *L) {
  613. createclibstable(L);
  614. luaL_newlib(L, pk_funcs); /* create 'package' table */
  615. createsearcherstable(L);
  616. /* set field 'path' */
  617. setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
  618. /* set field 'cpath' */
  619. setpath(L, "cpath", LUA_CPATHVARVERSION, LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
  620. /* store config information */
  621. lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
  622. LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
  623. lua_setfield(L, -2, "config");
  624. /* set field 'loaded' */
  625. luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
  626. lua_setfield(L, -2, "loaded");
  627. /* set field 'preload' */
  628. luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
  629. lua_setfield(L, -2, "preload");
  630. lua_pushglobaltable(L);
  631. lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
  632. luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */
  633. lua_pop(L, 1); /* pop global table */
  634. return 1; /* return 'package' table */
  635. }