loadlib.c 21 KB

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