2 ** $Id: loadlib.c,v 1.127 2015/11/23 11:30:45 roberto Exp $
3 ** Dynamic library loader for Lua
4 ** See Copyright Notice in lua.h
6 ** This module contains an implementation of loadlib for Unix systems
7 ** that have dlfcn, an implementation for Windows, and a stub for other
28 ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
29 ** variables that Lua check to set its paths.
31 #if !defined(LUA_PATH_VAR)
32 #define LUA_PATH_VAR "LUA_PATH"
35 #if !defined(LUA_CPATH_VAR)
36 #define LUA_CPATH_VAR "LUA_CPATH"
39 #define LUA_PATHSUFFIX "_" LUA_VERSION_MAJOR "_" LUA_VERSION_MINOR
41 #define LUA_PATHVARVERSION LUA_PATH_VAR LUA_PATHSUFFIX
42 #define LUA_CPATHVARVERSION LUA_CPATH_VAR LUA_PATHSUFFIX
45 ** LUA_PATH_SEP is the character that separates templates in a path.
46 ** LUA_PATH_MARK is the string that marks the substitution points in a
48 ** LUA_EXEC_DIR in a Windows path is replaced by the executable's
50 ** LUA_IGMARK is a mark to ignore all before it when building the
51 ** luaopen_ function name.
53 #if !defined (LUA_PATH_SEP)
54 #define LUA_PATH_SEP ";"
56 #if !defined (LUA_PATH_MARK)
57 #define LUA_PATH_MARK "?"
59 #if !defined (LUA_EXEC_DIR)
60 #define LUA_EXEC_DIR "!"
62 #if !defined (LUA_IGMARK)
63 #define LUA_IGMARK "-"
68 ** LUA_CSUBSEP is the character that replaces dots in submodule names
69 ** when searching for a C loader.
70 ** LUA_LSUBSEP is the character that replaces dots in submodule names
71 ** when searching for a Lua loader.
73 #if !defined(LUA_CSUBSEP)
74 #define LUA_CSUBSEP LUA_DIRSEP
77 #if !defined(LUA_LSUBSEP)
78 #define LUA_LSUBSEP LUA_DIRSEP
82 /* prefix for open functions in C libraries */
83 #define LUA_POF "luaopen_"
85 /* separator for open functions in C libraries */
90 ** unique key for table in the registry that keeps handles
91 ** for all loaded C libraries
93 static const int CLIBS = 0;
95 #define LIB_FAIL "open"
97 #define setprogdir(L) ((void)0)
101 ** system-dependent functions
105 ** unload library 'lib'
107 static void lsys_unloadlib (void *lib);
110 ** load C library in file 'path'. If 'seeglb', load with all names in
111 ** the library global.
112 ** Returns the library; in case of error, returns NULL plus an
113 ** error string in the stack.
115 static void *lsys_load (lua_State *L, const char *path, int seeglb);
118 ** Try to find a function named 'sym' in library 'lib'.
119 ** Returns the function; in case of error, returns NULL plus an
120 ** error string in the stack.
122 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
127 #if defined(LUA_USE_DLOPEN) /* { */
129 ** {========================================================================
130 ** This is an implementation of loadlib based on the dlfcn interface.
131 ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
132 ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
133 ** as an emulation layer on top of native functions.
134 ** =========================================================================
140 ** Macro to convert pointer-to-void* to pointer-to-function. This cast
141 ** is undefined according to ISO C, but POSIX assumes that it works.
142 ** (The '__extension__' in gnu compilers is only to avoid warnings.)
144 #if defined(__GNUC__)
145 #define cast_func(p) (__extension__ (lua_CFunction)(p))
147 #define cast_func(p) ((lua_CFunction)(p))
151 static void lsys_unloadlib (void *lib) {
156 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
157 void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
158 if (lib == NULL) lua_pushstring(L, dlerror());
163 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
164 lua_CFunction f = cast_func(dlsym(lib, sym));
165 if (f == NULL) lua_pushstring(L, dlerror());
169 /* }====================================================== */
173 #elif defined(LUA_DL_DLL) /* }{ */
175 ** {======================================================================
176 ** This is an implementation of loadlib for Windows using native functions.
177 ** =======================================================================
185 ** optional flags for LoadLibraryEx
187 #if !defined(LUA_LLE_FLAGS)
188 #define LUA_LLE_FLAGS 0
192 static void setprogdir (lua_State *L) {
193 char buff[MAX_PATH + 1];
195 DWORD nsize = sizeof(buff)/sizeof(char);
196 DWORD n = GetModuleFileNameA(NULL, buff, nsize);
197 if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
198 luaL_error(L, "unable to get ModuleFileName");
201 luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
202 lua_remove(L, -2); /* remove original string */
207 static void pusherror (lua_State *L) {
208 int error = GetLastError();
210 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
211 NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
212 lua_pushstring(L, buffer);
214 lua_pushfstring(L, "system error %d\n", error);
217 static void lsys_unloadlib (void *lib) {
218 FreeLibrary((HMODULE)lib);
222 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
223 HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
224 (void)(seeglb); /* not used: symbols are 'global' by default */
225 if (lib == NULL) pusherror(L);
230 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
231 lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym);
232 if (f == NULL) pusherror(L);
236 /* }====================================================== */
241 ** {======================================================
242 ** Fallback for other systems
243 ** =======================================================
247 #define LIB_FAIL "absent"
250 #define DLMSG "dynamic libraries not enabled; check your Lua installation"
253 static void lsys_unloadlib (void *lib) {
254 (void)(lib); /* not used */
258 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
259 (void)(path); (void)(seeglb); /* not used */
260 lua_pushliteral(L, DLMSG);
265 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
266 (void)(lib); (void)(sym); /* not used */
267 lua_pushliteral(L, DLMSG);
271 /* }====================================================== */
276 ** return registry.CLIBS[path]
278 static void *checkclib (lua_State *L, const char *path) {
280 lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
281 lua_getfield(L, -1, path);
282 plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
283 lua_pop(L, 2); /* pop CLIBS table and 'plib' */
289 ** registry.CLIBS[path] = plib -- for queries
290 ** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries
292 static void addtoclib (lua_State *L, const char *path, void *plib) {
293 lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS);
294 lua_pushlightuserdata(L, plib);
295 lua_pushvalue(L, -1);
296 lua_setfield(L, -3, path); /* CLIBS[path] = plib */
297 lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */
298 lua_pop(L, 1); /* pop CLIBS table */
303 ** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
304 ** handles in list CLIBS
306 static int gctm (lua_State *L) {
307 lua_Integer n = luaL_len(L, 1);
308 for (; n >= 1; n--) { /* for each handle, in reverse order */
309 lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
310 lsys_unloadlib(lua_touserdata(L, -1));
311 lua_pop(L, 1); /* pop handle */
318 /* error codes for 'lookforfunc' */
323 ** Look for a C function named 'sym' in a dynamically loaded library
325 ** First, check whether the library is already loaded; if not, try
327 ** Then, if 'sym' is '*', return true (as library has been loaded).
328 ** Otherwise, look for symbol 'sym' in the library and push a
329 ** C function with that symbol.
330 ** Return 0 and 'true' or a function in the stack; in case of
331 ** errors, return an error code and an error message in the stack.
333 static int lookforfunc (lua_State *L, const char *path, const char *sym) {
334 void *reg = checkclib(L, path); /* check loaded C libraries */
335 if (reg == NULL) { /* must load library? */
336 reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */
337 if (reg == NULL) return ERRLIB; /* unable to load library */
338 addtoclib(L, path, reg);
340 if (*sym == '*') { /* loading only library (no function)? */
341 lua_pushboolean(L, 1); /* return 'true' */
342 return 0; /* no errors */
345 lua_CFunction f = lsys_sym(L, reg, sym);
347 return ERRFUNC; /* unable to find function */
348 lua_pushcfunction(L, f); /* else create new function */
349 return 0; /* no errors */
354 static int ll_loadlib (lua_State *L) {
355 const char *path = luaL_checkstring(L, 1);
356 const char *init = luaL_checkstring(L, 2);
357 int stat = lookforfunc(L, path, init);
358 if (stat == 0) /* no errors? */
359 return 1; /* return the loaded function */
360 else { /* error; error message is on stack top */
363 lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
364 return 3; /* return nil, error message, and where */
371 ** {======================================================
372 ** 'require' function
373 ** =======================================================
377 static int readable (const char *filename) {
378 FILE *f = fopen(filename, "r"); /* try to open file */
379 if (f == NULL) return 0; /* open failed */
385 static const char *pushnexttemplate (lua_State *L, const char *path) {
387 while (*path == *LUA_PATH_SEP) path++; /* skip separators */
388 if (*path == '\0') return NULL; /* no more templates */
389 l = strchr(path, *LUA_PATH_SEP); /* find next separator */
390 if (l == NULL) l = path + strlen(path);
391 lua_pushlstring(L, path, l - path); /* template */
396 static const char *searchpath (lua_State *L, const char *name,
399 const char *dirsep) {
400 luaL_Buffer msg; /* to build error message */
401 luaL_buffinit(L, &msg);
402 if (*sep != '\0') /* non-empty separator? */
403 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
404 while ((path = pushnexttemplate(L, path)) != NULL) {
405 const char *filename = luaL_gsub(L, lua_tostring(L, -1),
406 LUA_PATH_MARK, name);
407 lua_remove(L, -2); /* remove path template */
408 if (readable(filename)) /* does file exist and is readable? */
409 return filename; /* return that file name */
410 lua_pushfstring(L, "\n\tno file '%s'", filename);
411 lua_remove(L, -2); /* remove file name */
412 luaL_addvalue(&msg); /* concatenate error msg. entry */
414 luaL_pushresult(&msg); /* create error message */
415 return NULL; /* not found */
419 static int ll_searchpath (lua_State *L) {
420 const char *f = searchpath(L, luaL_checkstring(L, 1),
421 luaL_checkstring(L, 2),
422 luaL_optstring(L, 3, "."),
423 luaL_optstring(L, 4, LUA_DIRSEP));
424 if (f != NULL) return 1;
425 else { /* error message is on top of the stack */
428 return 2; /* return nil + error message */
433 static const char *findfile (lua_State *L, const char *name,
435 const char *dirsep) {
437 lua_getfield(L, lua_upvalueindex(1), pname);
438 path = lua_tostring(L, -1);
440 luaL_error(L, "'package.%s' must be a string", pname);
441 return searchpath(L, name, path, ".", dirsep);
445 static int checkload (lua_State *L, int stat, const char *filename) {
446 if (stat) { /* module loaded successfully? */
447 lua_pushstring(L, filename); /* will be 2nd argument to module */
448 return 2; /* return open function and file name */
451 return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
452 lua_tostring(L, 1), filename, lua_tostring(L, -1));
456 static int searcher_Lua (lua_State *L) {
457 const char *filename;
458 const char *name = luaL_checkstring(L, 1);
459 filename = findfile(L, name, "path", LUA_LSUBSEP);
460 if (filename == NULL) return 1; /* module not found in this path */
461 return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
466 ** Try to find a load function for module 'modname' at file 'filename'.
467 ** First, change '.' to '_' in 'modname'; then, if 'modname' has
468 ** the form X-Y (that is, it has an "ignore mark"), build a function
469 ** name "luaopen_X" and look for it. (For compatibility, if that
470 ** fails, it also tries "luaopen_Y".) If there is no ignore mark,
471 ** look for a function named "luaopen_modname".
473 static int loadfunc (lua_State *L, const char *filename, const char *modname) {
474 const char *openfunc;
476 modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
477 mark = strchr(modname, *LUA_IGMARK);
480 openfunc = lua_pushlstring(L, modname, mark - modname);
481 openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
482 stat = lookforfunc(L, filename, openfunc);
483 if (stat != ERRFUNC) return stat;
484 modname = mark + 1; /* else go ahead and try old-style name */
486 openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
487 return lookforfunc(L, filename, openfunc);
491 static int searcher_C (lua_State *L) {
492 const char *name = luaL_checkstring(L, 1);
493 const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
494 if (filename == NULL) return 1; /* module not found in this path */
495 return checkload(L, (loadfunc(L, filename, name) == 0), filename);
499 static int searcher_Croot (lua_State *L) {
500 const char *filename;
501 const char *name = luaL_checkstring(L, 1);
502 const char *p = strchr(name, '.');
504 if (p == NULL) return 0; /* is root */
505 lua_pushlstring(L, name, p - name);
506 filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
507 if (filename == NULL) return 1; /* root not found */
508 if ((stat = loadfunc(L, filename, name)) != 0) {
510 return checkload(L, 0, filename); /* real error */
511 else { /* open function not found */
512 lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename);
516 lua_pushstring(L, filename); /* will be 2nd argument to module */
521 static int searcher_preload (lua_State *L) {
522 const char *name = luaL_checkstring(L, 1);
523 lua_getfield(L, LUA_REGISTRYINDEX, "_PRELOAD");
524 if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */
525 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
530 static void findloader (lua_State *L, const char *name) {
532 luaL_Buffer msg; /* to build error message */
533 luaL_buffinit(L, &msg);
534 /* push 'package.searchers' to index 3 in the stack */
535 if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE)
536 luaL_error(L, "'package.searchers' must be a table");
537 /* iterate over available searchers to find a loader */
539 if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */
540 lua_pop(L, 1); /* remove nil */
541 luaL_pushresult(&msg); /* create error message */
542 luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
544 lua_pushstring(L, name);
545 lua_call(L, 1, 2); /* call it */
546 if (lua_isfunction(L, -2)) /* did it find a loader? */
547 return; /* module loader found */
548 else if (lua_isstring(L, -2)) { /* searcher returned error message? */
549 lua_pop(L, 1); /* remove extra return */
550 luaL_addvalue(&msg); /* concatenate error message */
553 lua_pop(L, 2); /* remove both returns */
558 static int ll_require (lua_State *L) {
559 const char *name = luaL_checkstring(L, 1);
560 lua_settop(L, 1); /* _LOADED table will be at index 2 */
561 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
562 lua_getfield(L, 2, name); /* _LOADED[name] */
563 if (lua_toboolean(L, -1)) /* is it there? */
564 return 1; /* package is already loaded */
565 /* else must load package */
566 lua_pop(L, 1); /* remove 'getfield' result */
568 lua_pushstring(L, name); /* pass name as argument to module loader */
569 lua_insert(L, -2); /* name is 1st argument (before search data) */
570 lua_call(L, 2, 1); /* run loader to load module */
571 if (!lua_isnil(L, -1)) /* non-nil return? */
572 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
573 if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
574 lua_pushboolean(L, 1); /* use true as result */
575 lua_pushvalue(L, -1); /* extra copy to be returned */
576 lua_setfield(L, 2, name); /* _LOADED[name] = true */
581 /* }====================================================== */
586 ** {======================================================
588 ** =======================================================
590 #if defined(LUA_COMPAT_MODULE)
593 ** changes the environment variable of calling function
595 static void set_env (lua_State *L) {
597 if (lua_getstack(L, 1, &ar) == 0 ||
598 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
599 lua_iscfunction(L, -1))
600 luaL_error(L, "'module' not called from a Lua function");
601 lua_pushvalue(L, -2); /* copy new environment table to top */
602 lua_setupvalue(L, -2, 1);
603 lua_pop(L, 1); /* remove function */
607 static void dooptions (lua_State *L, int n) {
609 for (i = 2; i <= n; i++) {
610 if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */
611 lua_pushvalue(L, i); /* get option (a function) */
612 lua_pushvalue(L, -2); /* module */
619 static void modinit (lua_State *L, const char *modname) {
621 lua_pushvalue(L, -1);
622 lua_setfield(L, -2, "_M"); /* module._M = module */
623 lua_pushstring(L, modname);
624 lua_setfield(L, -2, "_NAME");
625 dot = strrchr(modname, '.'); /* look for last dot in module name */
626 if (dot == NULL) dot = modname;
628 /* set _PACKAGE as package name (full module name minus last part) */
629 lua_pushlstring(L, modname, dot - modname);
630 lua_setfield(L, -2, "_PACKAGE");
634 static int ll_module (lua_State *L) {
635 const char *modname = luaL_checkstring(L, 1);
636 int lastarg = lua_gettop(L); /* last parameter */
637 luaL_pushmodule(L, modname, 1); /* get/create module table */
638 /* check whether table already has a _NAME field */
639 if (lua_getfield(L, -1, "_NAME") != LUA_TNIL)
640 lua_pop(L, 1); /* table is an initialized module */
641 else { /* no; initialize it */
645 lua_pushvalue(L, -1);
647 dooptions(L, lastarg);
652 static int ll_seeall (lua_State *L) {
653 luaL_checktype(L, 1, LUA_TTABLE);
654 if (!lua_getmetatable(L, 1)) {
655 lua_createtable(L, 0, 1); /* create new metatable */
656 lua_pushvalue(L, -1);
657 lua_setmetatable(L, 1);
659 lua_pushglobaltable(L);
660 lua_setfield(L, -2, "__index"); /* mt.__index = _G */
665 /* }====================================================== */
669 /* auxiliary mark (for internal use) */
674 ** return registry.LUA_NOENV as a boolean
676 static int noenv (lua_State *L) {
678 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
679 b = lua_toboolean(L, -1);
680 lua_pop(L, 1); /* remove value */
685 static void setpath (lua_State *L, const char *fieldname, const char *envname1,
686 const char *envname2, const char *def) {
687 const char *path = getenv(envname1);
688 if (path == NULL) /* no environment variable? */
689 path = getenv(envname2); /* try alternative name */
690 if (path == NULL || noenv(L)) /* no environment variable? */
691 lua_pushstring(L, def); /* use default */
693 /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */
694 path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP,
695 LUA_PATH_SEP AUXMARK LUA_PATH_SEP);
696 luaL_gsub(L, path, AUXMARK, def);
700 lua_setfield(L, -2, fieldname);
704 static const luaL_Reg pk_funcs[] = {
705 {"loadlib", ll_loadlib},
706 {"searchpath", ll_searchpath},
707 #if defined(LUA_COMPAT_MODULE)
708 {"seeall", ll_seeall},
720 static const luaL_Reg ll_funcs[] = {
721 #if defined(LUA_COMPAT_MODULE)
722 {"module", ll_module},
724 {"require", ll_require},
729 static void createsearcherstable (lua_State *L) {
730 static const lua_CFunction searchers[] =
731 {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL};
733 /* create 'searchers' table */
734 lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
735 /* fill it with predefined searchers */
736 for (i=0; searchers[i] != NULL; i++) {
737 lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
738 lua_pushcclosure(L, searchers[i], 1);
739 lua_rawseti(L, -2, i+1);
741 #if defined(LUA_COMPAT_LOADERS)
742 lua_pushvalue(L, -1); /* make a copy of 'searchers' table */
743 lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */
745 lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
750 ** create table CLIBS to keep track of loaded C libraries,
751 ** setting a finalizer to close all libraries when closing state.
753 static void createclibstable (lua_State *L) {
754 lua_newtable(L); /* create CLIBS table */
755 lua_createtable(L, 0, 1); /* create metatable for CLIBS */
756 lua_pushcfunction(L, gctm);
757 lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
758 lua_setmetatable(L, -2);
759 lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */
763 LUAMOD_API int luaopen_package (lua_State *L) {
765 luaL_newlib(L, pk_funcs); /* create 'package' table */
766 createsearcherstable(L);
767 /* set field 'path' */
768 setpath(L, "path", LUA_PATHVARVERSION, LUA_PATH_VAR, LUA_PATH_DEFAULT);
769 /* set field 'cpath' */
770 setpath(L, "cpath", LUA_CPATHVARVERSION, LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
771 /* store config information */
772 lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
773 LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
774 lua_setfield(L, -2, "config");
775 /* set field 'loaded' */
776 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_LOADED");
777 lua_setfield(L, -2, "loaded");
778 /* set field 'preload' */
779 luaL_getsubtable(L, LUA_REGISTRYINDEX, "_PRELOAD");
780 lua_setfield(L, -2, "preload");
781 lua_pushglobaltable(L);
782 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
783 luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */
784 lua_pop(L, 1); /* pop global table */
785 return 1; /* return 'package' table */