loadlib.c 23 KB

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