loadlib.c 22 KB

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