loadlib.c 23 KB

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