loadlib.c 24 KB

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