loadlib.c 21 KB

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