loadlib.c 21 KB

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