9
3

loadlib.c 22 KB

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