loadlib.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. /*
  2. ** $Id: loadlib.c,v 1.70 2009/12/17 13:06:47 roberto Exp roberto $
  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 Darwin (Mac OS X), an
  8. ** implementation for Windows, and a stub for other systems.
  9. */
  10. #include <stdlib.h>
  11. #include <string.h>
  12. #define loadlib_c
  13. #define LUA_LIB
  14. #include "lua.h"
  15. #include "lauxlib.h"
  16. #include "lualib.h"
  17. /*
  18. ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
  19. ** variables that Lua check to set its paths.
  20. */
  21. #if !defined(LUA_PATH_VAR)
  22. #define LUA_PATH_VAR "LUA_PATH"
  23. #endif
  24. #if !defined(LUA_CPATH_VAR)
  25. #define LUA_CPATH_VAR "LUA_CPATH"
  26. #endif
  27. /*
  28. ** LUA_PATH_SEP is the character that separates templates in a path.
  29. ** LUA_PATH_MARK is the string that marks the substitution points in a
  30. ** template.
  31. ** LUA_EXEC_DIR in a Windows path is replaced by the executable's
  32. ** directory.
  33. ** LUA_IGMARK is a mark to ignore all before it when building the
  34. ** luaopen_ function name.
  35. */
  36. #if !defined (LUA_PATH_SEP)
  37. #define LUA_PATH_SEP ";"
  38. #endif
  39. #if !defined (LUA_PATH_MARK)
  40. #define LUA_PATH_MARK "?"
  41. #endif
  42. #if !defined (LUA_EXEC_DIR)
  43. #define LUA_EXEC_DIR "!"
  44. #endif
  45. #if !defined (LUA_IGMARK)
  46. #define LUA_IGMARK "-"
  47. #endif
  48. /* prefix for open functions in C libraries */
  49. #define LUA_POF "luaopen_"
  50. /* separator for open functions in C libraries */
  51. #define LUA_OFSEP "_"
  52. #define LIBPREFIX "LOADLIB: "
  53. #define POF LUA_POF
  54. #define LIB_FAIL "open"
  55. /* error codes for ll_loadfunc */
  56. #define ERRLIB 1
  57. #define ERRFUNC 2
  58. #define setprogdir(L) ((void)0)
  59. static void ll_unloadlib (void *lib);
  60. static void *ll_load (lua_State *L, const char *path, int seeglb);
  61. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym);
  62. #if defined(LUA_DL_DLOPEN)
  63. /*
  64. ** {========================================================================
  65. ** This is an implementation of loadlib based on the dlfcn interface.
  66. ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
  67. ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
  68. ** as an emulation layer on top of native functions.
  69. ** =========================================================================
  70. */
  71. #include <dlfcn.h>
  72. static void ll_unloadlib (void *lib) {
  73. dlclose(lib);
  74. }
  75. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  76. void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : 0));
  77. if (lib == NULL) lua_pushstring(L, dlerror());
  78. return lib;
  79. }
  80. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  81. lua_CFunction f = (lua_CFunction)dlsym(lib, sym);
  82. if (f == NULL) lua_pushstring(L, dlerror());
  83. return f;
  84. }
  85. /* }====================================================== */
  86. #elif defined(LUA_DL_DLL)
  87. /*
  88. ** {======================================================================
  89. ** This is an implementation of loadlib for Windows using native functions.
  90. ** =======================================================================
  91. */
  92. #undef setprogdir
  93. static void setprogdir (lua_State *L) {
  94. char buff[MAX_PATH + 1];
  95. char *lb;
  96. DWORD nsize = sizeof(buff)/sizeof(char);
  97. DWORD n = GetModuleFileName(NULL, buff, nsize);
  98. if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
  99. luaL_error(L, "unable to get ModuleFileName");
  100. else {
  101. *lb = '\0';
  102. luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
  103. lua_remove(L, -2); /* remove original string */
  104. }
  105. }
  106. static void pusherror (lua_State *L) {
  107. int error = GetLastError();
  108. char buffer[128];
  109. if (FormatMessage(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
  110. NULL, error, 0, buffer, sizeof(buffer), NULL))
  111. lua_pushstring(L, buffer);
  112. else
  113. lua_pushfstring(L, "system error %d\n", error);
  114. }
  115. static void ll_unloadlib (void *lib) {
  116. FreeLibrary((HINSTANCE)lib);
  117. }
  118. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  119. HINSTANCE lib = LoadLibrary(path);
  120. (void)(seeglb); /* symbols are 'global' by default? */
  121. if (lib == NULL) pusherror(L);
  122. return lib;
  123. }
  124. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  125. lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
  126. if (f == NULL) pusherror(L);
  127. return f;
  128. }
  129. /* }====================================================== */
  130. #elif defined(LUA_DL_DYLD)
  131. /*
  132. ** {======================================================================
  133. ** Native Mac OS X / Darwin Implementation
  134. ** =======================================================================
  135. */
  136. #include <mach-o/dyld.h>
  137. /* Mac appends a `_' before C function names */
  138. #undef POF
  139. #define POF "_" LUA_POF
  140. static void pusherror (lua_State *L) {
  141. const char *err_str;
  142. const char *err_file;
  143. NSLinkEditErrors err;
  144. int err_num;
  145. NSLinkEditError(&err, &err_num, &err_file, &err_str);
  146. lua_pushstring(L, err_str);
  147. }
  148. static const char *errorfromcode (NSObjectFileImageReturnCode ret) {
  149. switch (ret) {
  150. case NSObjectFileImageInappropriateFile:
  151. return "file is not a bundle";
  152. case NSObjectFileImageArch:
  153. return "library is for wrong CPU type";
  154. case NSObjectFileImageFormat:
  155. return "bad format";
  156. case NSObjectFileImageAccess:
  157. return "cannot access file";
  158. case NSObjectFileImageFailure:
  159. default:
  160. return "unable to load library";
  161. }
  162. }
  163. static void ll_unloadlib (void *lib) {
  164. NSUnLinkModule((NSModule)lib, NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES);
  165. }
  166. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  167. NSObjectFileImage img;
  168. NSObjectFileImageReturnCode ret;
  169. /* this would be a rare case, but prevents crashing if it happens */
  170. if(!_dyld_present()) {
  171. lua_pushliteral(L, "dyld not present");
  172. return NULL;
  173. }
  174. ret = NSCreateObjectFileImageFromFile(path, &img);
  175. if (ret == NSObjectFileImageSuccess) {
  176. NSModule mod = NSLinkModule(img,
  177. path,
  178. NSLINKMODULE_OPTION_RETURN_ON_ERROR |
  179. (seeglb ? 0 : NSLINKMODULE_OPTION_PRIVATE));
  180. NSDestroyObjectFileImage(img);
  181. if (mod == NULL) pusherror(L);
  182. return mod;
  183. }
  184. lua_pushstring(L, errorfromcode(ret));
  185. return NULL;
  186. }
  187. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  188. NSSymbol nss = NSLookupSymbolInModule((NSModule)lib, sym);
  189. if (nss == NULL) {
  190. lua_pushfstring(L, "symbol " LUA_QS " not found", sym);
  191. return NULL;
  192. }
  193. return (lua_CFunction)NSAddressOfSymbol(nss);
  194. }
  195. /* }====================================================== */
  196. #else
  197. /*
  198. ** {======================================================
  199. ** Fallback for other systems
  200. ** =======================================================
  201. */
  202. #undef LIB_FAIL
  203. #define LIB_FAIL "absent"
  204. #define DLMSG "dynamic libraries not enabled; check your Lua installation"
  205. static void ll_unloadlib (void *lib) {
  206. (void)(lib); /* to avoid warnings */
  207. }
  208. static void *ll_load (lua_State *L, const char *path, int seeglb) {
  209. (void)(path); /* to avoid warnings */
  210. lua_pushliteral(L, DLMSG);
  211. return NULL;
  212. }
  213. static lua_CFunction ll_sym (lua_State *L, void *lib, const char *sym) {
  214. (void)(lib); (void)(sym); /* to avoid warnings */
  215. lua_pushliteral(L, DLMSG);
  216. return NULL;
  217. }
  218. /* }====================================================== */
  219. #endif
  220. static void **ll_register (lua_State *L, const char *path) {
  221. void **plib;
  222. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  223. lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
  224. if (!lua_isnil(L, -1)) /* is there an entry? */
  225. plib = (void **)lua_touserdata(L, -1);
  226. else { /* no entry yet; create one */
  227. lua_pop(L, 1);
  228. plib = (void **)lua_newuserdata(L, sizeof(const void *));
  229. *plib = NULL;
  230. luaL_getmetatable(L, "_LOADLIB");
  231. lua_setmetatable(L, -2);
  232. lua_pushfstring(L, "%s%s", LIBPREFIX, path);
  233. lua_pushvalue(L, -2);
  234. lua_settable(L, LUA_REGISTRYINDEX);
  235. }
  236. return plib;
  237. }
  238. /*
  239. ** __gc tag method: calls library's `ll_unloadlib' function with the lib
  240. ** handle
  241. */
  242. static int gctm (lua_State *L) {
  243. void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
  244. if (*lib) ll_unloadlib(*lib);
  245. *lib = NULL; /* mark library as closed */
  246. return 0;
  247. }
  248. static int ll_loadfunc (lua_State *L, const char *path, const char *sym) {
  249. void **reg = ll_register(L, path);
  250. if (*reg == NULL) *reg = ll_load(L, path, *sym == '*');
  251. if (*reg == NULL)
  252. return ERRLIB; /* unable to load library */
  253. else if (*sym == '*') { /* loading only library (no function)? */
  254. lua_pushboolean(L, 1); /* return 'true' */
  255. return 0;
  256. }
  257. else {
  258. lua_CFunction f = ll_sym(L, *reg, sym);
  259. if (f == NULL)
  260. return ERRFUNC; /* unable to find function */
  261. lua_pushcfunction(L, f);
  262. return 0; /* return function */
  263. }
  264. }
  265. static int ll_loadlib (lua_State *L) {
  266. const char *path = luaL_checkstring(L, 1);
  267. const char *init = luaL_checkstring(L, 2);
  268. int stat = ll_loadfunc(L, path, init);
  269. if (stat == 0) /* no errors? */
  270. return 1; /* return the loaded function */
  271. else { /* error; error message is on stack top */
  272. lua_pushnil(L);
  273. lua_insert(L, -2);
  274. lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
  275. return 3; /* return nil, error message, and where */
  276. }
  277. }
  278. /*
  279. ** {======================================================
  280. ** 'require' function
  281. ** =======================================================
  282. */
  283. static int readable (const char *filename) {
  284. FILE *f = fopen(filename, "r"); /* try to open file */
  285. if (f == NULL) return 0; /* open failed */
  286. fclose(f);
  287. return 1;
  288. }
  289. static const char *pushnexttemplate (lua_State *L, const char *path) {
  290. const char *l;
  291. while (*path == *LUA_PATH_SEP) path++; /* skip separators */
  292. if (*path == '\0') return NULL; /* no more templates */
  293. l = strchr(path, *LUA_PATH_SEP); /* find next separator */
  294. if (l == NULL) l = path + strlen(path);
  295. lua_pushlstring(L, path, l - path); /* template */
  296. return l;
  297. }
  298. static const char *searchpath (lua_State *L, const char *name,
  299. const char *path) {
  300. lua_pushliteral(L, ""); /* error accumulator */
  301. while ((path = pushnexttemplate(L, path)) != NULL) {
  302. const char *filename = luaL_gsub(L, lua_tostring(L, -1),
  303. LUA_PATH_MARK, name);
  304. lua_remove(L, -2); /* remove path template */
  305. if (readable(filename)) /* does file exist and is readable? */
  306. return filename; /* return that file name */
  307. lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
  308. lua_remove(L, -2); /* remove file name */
  309. lua_concat(L, 2); /* add entry to possible error message */
  310. }
  311. return NULL; /* not found */
  312. }
  313. static int ll_searchpath (lua_State *L) {
  314. const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2));
  315. if (f != NULL) return 1;
  316. else { /* error message is on top of the stack */
  317. lua_pushnil(L);
  318. lua_insert(L, -2);
  319. return 2; /* return nil + error message */
  320. }
  321. }
  322. static const char *findfile (lua_State *L, const char *name,
  323. const char *pname) {
  324. const char *path;
  325. name = luaL_gsub(L, name, ".", LUA_DIRSEP);
  326. lua_getfield(L, LUA_ENVIRONINDEX, pname);
  327. path = lua_tostring(L, -1);
  328. if (path == NULL)
  329. luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
  330. return searchpath(L, name, path);
  331. }
  332. static void loaderror (lua_State *L, const char *filename) {
  333. luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
  334. lua_tostring(L, 1), filename, lua_tostring(L, -1));
  335. }
  336. static int loader_Lua (lua_State *L) {
  337. const char *filename;
  338. const char *name = luaL_checkstring(L, 1);
  339. filename = findfile(L, name, "path");
  340. if (filename == NULL) return 1; /* library not found in this path */
  341. if (luaL_loadfile(L, filename) != LUA_OK)
  342. loaderror(L, filename);
  343. return 1; /* library loaded successfully */
  344. }
  345. static const char *mkfuncname (lua_State *L, const char *modname) {
  346. const char *funcname;
  347. const char *mark = strchr(modname, *LUA_IGMARK);
  348. if (mark) modname = mark + 1;
  349. funcname = luaL_gsub(L, modname, ".", LUA_OFSEP);
  350. funcname = lua_pushfstring(L, POF"%s", funcname);
  351. lua_remove(L, -2); /* remove 'gsub' result */
  352. return funcname;
  353. }
  354. static int loader_C (lua_State *L) {
  355. const char *funcname;
  356. const char *name = luaL_checkstring(L, 1);
  357. const char *filename = findfile(L, name, "cpath");
  358. if (filename == NULL) return 1; /* library not found in this path */
  359. funcname = mkfuncname(L, name);
  360. if (ll_loadfunc(L, filename, funcname) != 0)
  361. loaderror(L, filename);
  362. return 1; /* library loaded successfully */
  363. }
  364. static int loader_Croot (lua_State *L) {
  365. const char *funcname;
  366. const char *filename;
  367. const char *name = luaL_checkstring(L, 1);
  368. const char *p = strchr(name, '.');
  369. int stat;
  370. if (p == NULL) return 0; /* is root */
  371. lua_pushlstring(L, name, p - name);
  372. filename = findfile(L, lua_tostring(L, -1), "cpath");
  373. if (filename == NULL) return 1; /* root not found */
  374. funcname = mkfuncname(L, name);
  375. if ((stat = ll_loadfunc(L, filename, funcname)) != 0) {
  376. if (stat != ERRFUNC) loaderror(L, filename); /* real error */
  377. lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
  378. name, filename);
  379. return 1; /* function not found */
  380. }
  381. return 1;
  382. }
  383. static int loader_preload (lua_State *L) {
  384. const char *name = luaL_checkstring(L, 1);
  385. lua_getfield(L, LUA_ENVIRONINDEX, "preload");
  386. if (!lua_istable(L, -1))
  387. luaL_error(L, LUA_QL("package.preload") " must be a table");
  388. lua_getfield(L, -1, name);
  389. if (lua_isnil(L, -1)) /* not found? */
  390. lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
  391. return 1;
  392. }
  393. static const int sentinel_ = 0;
  394. #define sentinel ((void *)&sentinel_)
  395. static int ll_require (lua_State *L) {
  396. const char *name = luaL_checkstring(L, 1);
  397. int i;
  398. lua_settop(L, 1); /* _LOADED table will be at index 2 */
  399. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  400. lua_getfield(L, 2, name);
  401. if (lua_toboolean(L, -1)) { /* is it there? */
  402. if (lua_touserdata(L, -1) == sentinel) /* check loops */
  403. luaL_error(L, "loop or previous error loading module " LUA_QS, name);
  404. return 1; /* package is already loaded */
  405. }
  406. /* else must load it; iterate over available loaders */
  407. lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
  408. if (!lua_istable(L, -1))
  409. luaL_error(L, LUA_QL("package.loaders") " must be a table");
  410. lua_pushliteral(L, ""); /* error message accumulator */
  411. for (i=1; ; i++) {
  412. lua_rawgeti(L, -2, i); /* get a loader */
  413. if (lua_isnil(L, -1))
  414. luaL_error(L, "module " LUA_QS " not found:%s",
  415. name, lua_tostring(L, -2));
  416. lua_pushstring(L, name);
  417. lua_call(L, 1, 1); /* call it */
  418. if (lua_isfunction(L, -1)) /* did it find module? */
  419. break; /* module loaded successfully */
  420. else if (lua_isstring(L, -1)) /* loader returned error message? */
  421. lua_concat(L, 2); /* accumulate it */
  422. else
  423. lua_pop(L, 1);
  424. }
  425. lua_pushlightuserdata(L, sentinel);
  426. lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
  427. lua_pushstring(L, name); /* pass name as argument to module */
  428. lua_call(L, 1, 1); /* run loaded module */
  429. if (!lua_isnil(L, -1)) /* non-nil return? */
  430. lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
  431. lua_getfield(L, 2, name);
  432. if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */
  433. lua_pushboolean(L, 1); /* use true as result */
  434. lua_pushvalue(L, -1); /* extra copy to be returned */
  435. lua_setfield(L, 2, name); /* _LOADED[name] = true */
  436. }
  437. return 1;
  438. }
  439. /* }====================================================== */
  440. /*
  441. ** {======================================================
  442. ** 'module' function
  443. ** =======================================================
  444. */
  445. static void setfenv (lua_State *L) {
  446. lua_Debug ar;
  447. if (lua_getstack(L, 1, &ar) == 0 ||
  448. lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
  449. lua_iscfunction(L, -1))
  450. luaL_error(L, LUA_QL("module") " not called from a Lua function");
  451. lua_pushvalue(L, -2); /* copy new environment table to top */
  452. lua_setfenv(L, -2);
  453. lua_pop(L, 1); /* remove function */
  454. }
  455. static void dooptions (lua_State *L, int n) {
  456. int i;
  457. for (i = 2; i <= n; i++) {
  458. lua_pushvalue(L, i); /* get option (a function) */
  459. lua_pushvalue(L, -2); /* module */
  460. lua_call(L, 1, 0);
  461. }
  462. }
  463. static void modinit (lua_State *L, const char *modname) {
  464. const char *dot;
  465. lua_pushvalue(L, -1);
  466. lua_setfield(L, -2, "_M"); /* module._M = module */
  467. lua_pushstring(L, modname);
  468. lua_setfield(L, -2, "_NAME");
  469. dot = strrchr(modname, '.'); /* look for last dot in module name */
  470. if (dot == NULL) dot = modname;
  471. else dot++;
  472. /* set _PACKAGE as package name (full module name minus last part) */
  473. lua_pushlstring(L, modname, dot - modname);
  474. lua_setfield(L, -2, "_PACKAGE");
  475. }
  476. static int ll_module (lua_State *L) {
  477. const char *modname = luaL_checkstring(L, 1);
  478. int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
  479. lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
  480. lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
  481. if (!lua_istable(L, -1)) { /* not found? */
  482. lua_pop(L, 1); /* remove previous result */
  483. /* try global variable (and create one if it does not exist) */
  484. lua_pushglobaltable(L);
  485. if (luaL_findtable(L, 0, modname, 1) != NULL)
  486. return luaL_error(L, "name conflict for module " LUA_QS, modname);
  487. lua_pushvalue(L, -1);
  488. lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
  489. }
  490. /* check whether table already has a _NAME field */
  491. lua_getfield(L, -1, "_NAME");
  492. if (!lua_isnil(L, -1)) /* is table an initialized module? */
  493. lua_pop(L, 1);
  494. else { /* no; initialize it */
  495. lua_pop(L, 1);
  496. modinit(L, modname);
  497. }
  498. lua_pushvalue(L, -1);
  499. setfenv(L);
  500. dooptions(L, loaded - 1);
  501. return 1;
  502. }
  503. static int ll_seeall (lua_State *L) {
  504. luaL_checktype(L, 1, LUA_TTABLE);
  505. if (!lua_getmetatable(L, 1)) {
  506. lua_createtable(L, 0, 1); /* create new metatable */
  507. lua_pushvalue(L, -1);
  508. lua_setmetatable(L, 1);
  509. }
  510. lua_pushglobaltable(L);
  511. lua_setfield(L, -2, "__index"); /* mt.__index = _G */
  512. return 0;
  513. }
  514. /* }====================================================== */
  515. /* auxiliary mark (for internal use) */
  516. #define AUXMARK "\1"
  517. static void setpath (lua_State *L, const char *fieldname, const char *envname,
  518. const char *def) {
  519. const char *path = getenv(envname);
  520. if (path == NULL) /* no environment variable? */
  521. lua_pushstring(L, def); /* use default */
  522. else {
  523. /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
  524. path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP,
  525. LUA_PATH_SEP AUXMARK LUA_PATH_SEP);
  526. luaL_gsub(L, path, AUXMARK, def);
  527. lua_remove(L, -2);
  528. }
  529. setprogdir(L);
  530. lua_setfield(L, -2, fieldname);
  531. }
  532. static const luaL_Reg pk_funcs[] = {
  533. {"loadlib", ll_loadlib},
  534. {"searchpath", ll_searchpath},
  535. {"seeall", ll_seeall},
  536. {NULL, NULL}
  537. };
  538. static const luaL_Reg ll_funcs[] = {
  539. {"module", ll_module},
  540. {"require", ll_require},
  541. {NULL, NULL}
  542. };
  543. static const lua_CFunction loaders[] =
  544. {loader_preload, loader_Lua, loader_C, loader_Croot, NULL};
  545. LUAMOD_API int luaopen_package (lua_State *L) {
  546. int i;
  547. /* create new type _LOADLIB */
  548. luaL_newmetatable(L, "_LOADLIB");
  549. lua_pushcfunction(L, gctm);
  550. lua_setfield(L, -2, "__gc");
  551. /* create `package' table */
  552. luaL_register(L, LUA_LOADLIBNAME, pk_funcs);
  553. lua_copy(L, -1, LUA_ENVIRONINDEX);
  554. /* create `loaders' table */
  555. lua_createtable(L, sizeof(loaders)/sizeof(loaders[0]) - 1, 0);
  556. /* fill it with pre-defined loaders */
  557. for (i=0; loaders[i] != NULL; i++) {
  558. lua_pushcfunction(L, loaders[i]);
  559. lua_rawseti(L, -2, i+1);
  560. }
  561. lua_setfield(L, -2, "loaders"); /* put it in field `loaders' */
  562. setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); /* set field `path' */
  563. setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); /* set field `cpath' */
  564. /* store config information */
  565. lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
  566. LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
  567. lua_setfield(L, -2, "config");
  568. /* set field `loaded' */
  569. luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 2);
  570. lua_setfield(L, -2, "loaded");
  571. /* set field `preload' */
  572. lua_newtable(L);
  573. lua_setfield(L, -2, "preload");
  574. lua_pushglobaltable(L);
  575. luaL_register(L, NULL, ll_funcs); /* open lib into global table */
  576. lua_pop(L, 1);
  577. return 1; /* return 'package' table */
  578. }