loadlib.c 22 KB

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