loadlib.c 23 KB

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