loadlib.c 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748
  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. ** External strings created by DLLs may need the DLL code to be
  231. ** deallocated. This implies that a DLL can only be unloaded after all
  232. ** its strings were deallocated. To ensure that, we create a 'library
  233. ** string' to represent each DLL, and when this string is deallocated
  234. ** it closes its corresponding DLL.
  235. ** (The string itself is irrelevant; its userdata is the DLL pointer.)
  236. */
  237. /*
  238. ** return registry.CLIBS[path]
  239. */
  240. static void *checkclib (lua_State *L, const char *path) {
  241. void *plib;
  242. lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
  243. lua_getfield(L, -1, path);
  244. plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
  245. lua_pop(L, 2); /* pop CLIBS table and 'plib' */
  246. return plib;
  247. }
  248. /*
  249. ** Deallocate function for library strings.
  250. ** Unload the DLL associated with the string being deallocated.
  251. */
  252. static void *freelib (void *ud, void *ptr, size_t osize, size_t nsize) {
  253. /* string itself is irrelevant and static */
  254. (void)ptr; (void)osize; (void)nsize;
  255. lsys_unloadlib(ud); /* unload library represented by the string */
  256. return NULL;
  257. }
  258. /*
  259. ** Create a library string that, when deallocated, will unload 'plib'
  260. */
  261. static void createlibstr (lua_State *L, void *plib) {
  262. /* common content for all library strings */
  263. static const char dummy[] = "01234567890";
  264. lua_pushexternalstring(L, dummy, sizeof(dummy) - 1, freelib, plib);
  265. }
  266. /*
  267. ** registry.CLIBS[path] = plib -- for queries.
  268. ** Also create a reference to strlib, so that the library string will
  269. ** only be collected when registry.CLIBS is collected.
  270. */
  271. static void addtoclib (lua_State *L, const char *path, void *plib) {
  272. lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
  273. lua_pushlightuserdata(L, plib);
  274. lua_setfield(L, -2, path); /* CLIBS[path] = plib */
  275. createlibstr(L, plib);
  276. luaL_ref(L, -2); /* keep library string in CLIBS */
  277. lua_pop(L, 1); /* pop CLIBS table */
  278. }
  279. /* error codes for 'lookforfunc' */
  280. #define ERRLIB 1
  281. #define ERRFUNC 2
  282. /*
  283. ** Look for a C function named 'sym' in a dynamically loaded library
  284. ** 'path'.
  285. ** First, check whether the library is already loaded; if not, try
  286. ** to load it.
  287. ** Then, if 'sym' is '*', return true (as library has been loaded).
  288. ** Otherwise, look for symbol 'sym' in the library and push a
  289. ** C function with that symbol.
  290. ** Return 0 with 'true' or a function in the stack; in case of
  291. ** errors, return an error code with an error message in the stack.
  292. */
  293. static int lookforfunc (lua_State *L, const char *path, const char *sym) {
  294. void *reg = checkclib(L, path); /* check loaded C libraries */
  295. if (reg == NULL) { /* must load library? */
  296. reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */
  297. if (reg == NULL) return ERRLIB; /* unable to load library */
  298. addtoclib(L, path, reg);
  299. }
  300. if (*sym == '*') { /* loading only library (no function)? */
  301. lua_pushboolean(L, 1); /* return 'true' */
  302. return 0; /* no errors */
  303. }
  304. else {
  305. lua_CFunction f = lsys_sym(L, reg, sym);
  306. if (f == NULL)
  307. return ERRFUNC; /* unable to find function */
  308. lua_pushcfunction(L, f); /* else create new function */
  309. return 0; /* no errors */
  310. }
  311. }
  312. static int ll_loadlib (lua_State *L) {
  313. const char *path = luaL_checkstring(L, 1);
  314. const char *init = luaL_checkstring(L, 2);
  315. int stat = lookforfunc(L, path, init);
  316. if (l_likely(stat == 0)) /* no errors? */
  317. return 1; /* return the loaded function */
  318. else { /* error; error message is on stack top */
  319. luaL_pushfail(L);
  320. lua_insert(L, -2);
  321. lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
  322. return 3; /* return fail, error message, and where */
  323. }
  324. }
  325. /*
  326. ** {======================================================
  327. ** 'require' function
  328. ** =======================================================
  329. */
  330. static int readable (const char *filename) {
  331. FILE *f = fopen(filename, "r"); /* try to open file */
  332. if (f == NULL) return 0; /* open failed */
  333. fclose(f);
  334. return 1;
  335. }
  336. /*
  337. ** Get the next name in '*path' = 'name1;name2;name3;...', changing
  338. ** the ending ';' to '\0' to create a zero-terminated string. Return
  339. ** NULL when list ends.
  340. */
  341. static const char *getnextfilename (char **path, char *end) {
  342. char *sep;
  343. char *name = *path;
  344. if (name == end)
  345. return NULL; /* no more names */
  346. else if (*name == '\0') { /* from previous iteration? */
  347. *name = *LUA_PATH_SEP; /* restore separator */
  348. name++; /* skip it */
  349. }
  350. sep = strchr(name, *LUA_PATH_SEP); /* find next separator */
  351. if (sep == NULL) /* separator not found? */
  352. sep = end; /* name goes until the end */
  353. *sep = '\0'; /* finish file name */
  354. *path = sep; /* will start next search from here */
  355. return name;
  356. }
  357. /*
  358. ** Given a path such as ";blabla.so;blublu.so", pushes the string
  359. **
  360. ** no file 'blabla.so'
  361. ** no file 'blublu.so'
  362. */
  363. static void pusherrornotfound (lua_State *L, const char *path) {
  364. luaL_Buffer b;
  365. luaL_buffinit(L, &b);
  366. luaL_addstring(&b, "no file '");
  367. luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
  368. luaL_addstring(&b, "'");
  369. luaL_pushresult(&b);
  370. }
  371. static const char *searchpath (lua_State *L, const char *name,
  372. const char *path,
  373. const char *sep,
  374. const char *dirsep) {
  375. luaL_Buffer buff;
  376. char *pathname; /* path with name inserted */
  377. char *endpathname; /* its end */
  378. const char *filename;
  379. /* separator is non-empty and appears in 'name'? */
  380. if (*sep != '\0' && strchr(name, *sep) != NULL)
  381. name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
  382. luaL_buffinit(L, &buff);
  383. /* add path to the buffer, replacing marks ('?') with the file name */
  384. luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
  385. luaL_addchar(&buff, '\0');
  386. pathname = luaL_buffaddr(&buff); /* writable list of file names */
  387. endpathname = pathname + luaL_bufflen(&buff) - 1;
  388. while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
  389. if (readable(filename)) /* does file exist and is readable? */
  390. return lua_pushstring(L, filename); /* save and return name */
  391. }
  392. luaL_pushresult(&buff); /* push path to create error message */
  393. pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */
  394. return NULL; /* not found */
  395. }
  396. static int ll_searchpath (lua_State *L) {
  397. const char *f = searchpath(L, luaL_checkstring(L, 1),
  398. luaL_checkstring(L, 2),
  399. luaL_optstring(L, 3, "."),
  400. luaL_optstring(L, 4, LUA_DIRSEP));
  401. if (f != NULL) return 1;
  402. else { /* error message is on top of the stack */
  403. luaL_pushfail(L);
  404. lua_insert(L, -2);
  405. return 2; /* return fail + error message */
  406. }
  407. }
  408. static const char *findfile (lua_State *L, const char *name,
  409. const char *pname,
  410. const char *dirsep) {
  411. const char *path;
  412. lua_getfield(L, lua_upvalueindex(1), pname);
  413. path = lua_tostring(L, -1);
  414. if (l_unlikely(path == NULL))
  415. luaL_error(L, "'package.%s' must be a string", pname);
  416. return searchpath(L, name, path, ".", dirsep);
  417. }
  418. static int checkload (lua_State *L, int stat, const char *filename) {
  419. if (l_likely(stat)) { /* module loaded successfully? */
  420. lua_pushstring(L, filename); /* will be 2nd argument to module */
  421. return 2; /* return open function and file name */
  422. }
  423. else
  424. return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
  425. lua_tostring(L, 1), filename, lua_tostring(L, -1));
  426. }
  427. static int searcher_Lua (lua_State *L) {
  428. const char *filename;
  429. const char *name = luaL_checkstring(L, 1);
  430. filename = findfile(L, name, "path", LUA_LSUBSEP);
  431. if (filename == NULL) return 1; /* module not found in this path */
  432. return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
  433. }
  434. /*
  435. ** Try to find a load function for module 'modname' at file 'filename'.
  436. ** First, change '.' to '_' in 'modname'; then, if 'modname' has
  437. ** the form X-Y (that is, it has an "ignore mark"), build a function
  438. ** name "luaopen_X" and look for it. (For compatibility, if that
  439. ** fails, it also tries "luaopen_Y".) If there is no ignore mark,
  440. ** look for a function named "luaopen_modname".
  441. */
  442. static int loadfunc (lua_State *L, const char *filename, const char *modname) {
  443. const char *openfunc;
  444. const char *mark;
  445. modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
  446. mark = strchr(modname, *LUA_IGMARK);
  447. if (mark) {
  448. int stat;
  449. openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname));
  450. openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
  451. stat = lookforfunc(L, filename, openfunc);
  452. if (stat != ERRFUNC) return stat;
  453. modname = mark + 1; /* else go ahead and try old-style name */
  454. }
  455. openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
  456. return lookforfunc(L, filename, openfunc);
  457. }
  458. static int searcher_C (lua_State *L) {
  459. const char *name = luaL_checkstring(L, 1);
  460. const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
  461. if (filename == NULL) return 1; /* module not found in this path */
  462. return checkload(L, (loadfunc(L, filename, name) == 0), filename);
  463. }
  464. static int searcher_Croot (lua_State *L) {
  465. const char *filename;
  466. const char *name = luaL_checkstring(L, 1);
  467. const char *p = strchr(name, '.');
  468. int stat;
  469. if (p == NULL) return 0; /* is root */
  470. lua_pushlstring(L, name, ct_diff2sz(p - name));
  471. filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
  472. if (filename == NULL) return 1; /* root not found */
  473. if ((stat = loadfunc(L, filename, name)) != 0) {
  474. if (stat != ERRFUNC)
  475. return checkload(L, 0, filename); /* real error */
  476. else { /* open function not found */
  477. lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
  478. return 1;
  479. }
  480. }
  481. lua_pushstring(L, filename); /* will be 2nd argument to module */
  482. return 2;
  483. }
  484. static int searcher_preload (lua_State *L) {
  485. const char *name = luaL_checkstring(L, 1);
  486. lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
  487. if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */
  488. lua_pushfstring(L, "no field package.preload['%s']", name);
  489. return 1;
  490. }
  491. else {
  492. lua_pushliteral(L, ":preload:");
  493. return 2;
  494. }
  495. }
  496. static void findloader (lua_State *L, const char *name) {
  497. int i;
  498. luaL_Buffer msg; /* to build error message */
  499. /* push 'package.searchers' to index 3 in the stack */
  500. if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
  501. != LUA_TTABLE))
  502. luaL_error(L, "'package.searchers' must be a table");
  503. luaL_buffinit(L, &msg);
  504. luaL_addstring(&msg, "\n\t"); /* error-message prefix for first message */
  505. /* iterate over available searchers to find a loader */
  506. for (i = 1; ; i++) {
  507. if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */
  508. lua_pop(L, 1); /* remove nil */
  509. luaL_buffsub(&msg, 2); /* remove last prefix */
  510. luaL_pushresult(&msg); /* create error message */
  511. luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
  512. }
  513. lua_pushstring(L, name);
  514. lua_call(L, 1, 2); /* call it */
  515. if (lua_isfunction(L, -2)) /* did it find a loader? */
  516. return; /* module loader found */
  517. else if (lua_isstring(L, -2)) { /* searcher returned error message? */
  518. lua_pop(L, 1); /* remove extra return */
  519. luaL_addvalue(&msg); /* concatenate error message */
  520. luaL_addstring(&msg, "\n\t"); /* prefix for next message */
  521. }
  522. else /* no error message */
  523. lua_pop(L, 2); /* remove both returns */
  524. }
  525. }
  526. static int ll_require (lua_State *L) {
  527. const char *name = luaL_checkstring(L, 1);
  528. lua_settop(L, 1); /* LOADED table will be at index 2 */
  529. lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  530. lua_getfield(L, 2, name); /* LOADED[name] */
  531. if (lua_toboolean(L, -1)) /* is it there? */
  532. return 1; /* package is already loaded */
  533. /* else must load package */
  534. lua_pop(L, 1); /* remove 'getfield' result */
  535. findloader(L, name);
  536. lua_rotate(L, -2, 1); /* function <-> loader data */
  537. lua_pushvalue(L, 1); /* name is 1st argument to module loader */
  538. lua_pushvalue(L, -3); /* loader data is 2nd argument */
  539. /* stack: ...; loader data; loader function; mod. name; loader data */
  540. lua_call(L, 2, 1); /* run loader to load module */
  541. /* stack: ...; loader data; result from loader */
  542. if (!lua_isnil(L, -1)) /* non-nil return? */
  543. lua_setfield(L, 2, name); /* LOADED[name] = returned value */
  544. else
  545. lua_pop(L, 1); /* pop nil */
  546. if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
  547. lua_pushboolean(L, 1); /* use true as result */
  548. lua_copy(L, -1, -2); /* replace loader result */
  549. lua_setfield(L, 2, name); /* LOADED[name] = true */
  550. }
  551. lua_rotate(L, -2, 1); /* loader data <-> module result */
  552. return 2; /* return module result and loader data */
  553. }
  554. /* }====================================================== */
  555. static const luaL_Reg pk_funcs[] = {
  556. {"loadlib", ll_loadlib},
  557. {"searchpath", ll_searchpath},
  558. /* placeholders */
  559. {"preload", NULL},
  560. {"cpath", NULL},
  561. {"path", NULL},
  562. {"searchers", NULL},
  563. {"loaded", NULL},
  564. {NULL, NULL}
  565. };
  566. static const luaL_Reg ll_funcs[] = {
  567. {"require", ll_require},
  568. {NULL, NULL}
  569. };
  570. static void createsearcherstable (lua_State *L) {
  571. static const lua_CFunction searchers[] = {
  572. searcher_preload,
  573. searcher_Lua,
  574. searcher_C,
  575. searcher_Croot,
  576. NULL
  577. };
  578. int i;
  579. /* create 'searchers' table */
  580. lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
  581. /* fill it with predefined searchers */
  582. for (i=0; searchers[i] != NULL; i++) {
  583. lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
  584. lua_pushcclosure(L, searchers[i], 1);
  585. lua_rawseti(L, -2, i+1);
  586. }
  587. lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
  588. }
  589. LUAMOD_API int luaopen_package (lua_State *L) {
  590. luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */
  591. lua_pop(L, 1); /* will not use it now */
  592. luaL_newlib(L, pk_funcs); /* create 'package' table */
  593. createsearcherstable(L);
  594. /* set paths */
  595. setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT);
  596. setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
  597. /* store config information */
  598. lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
  599. LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
  600. lua_setfield(L, -2, "config");
  601. /* set field 'loaded' */
  602. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
  603. lua_setfield(L, -2, "loaded");
  604. /* set field 'preload' */
  605. luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
  606. lua_setfield(L, -2, "preload");
  607. lua_pushglobaltable(L);
  608. lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
  609. luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */
  610. lua_pop(L, 1); /* pop global table */
  611. return 1; /* return 'package' table */
  612. }