3 ** Copyright (C) 2005-2023 Mike Pall. See Copyright Notice in luajit.h
5 ** Major portions taken verbatim or adapted from the Lua interpreter.
6 ** Copyright (C) 1994-2012 Lua.org, PUC-Rio. See Copyright Notice in lua.h
20 /* ------------------------------------------------------------------------ */
22 /* Error codes for ll_loadfunc. */
23 #define PACKAGE_ERR_LIB 1
24 #define PACKAGE_ERR_FUNC 2
25 #define PACKAGE_ERR_LOAD 3
27 /* Redefined in platform specific part. */
28 #define PACKAGE_LIB_FAIL "open"
29 #define setprogdir(L) ((void)0)
31 /* Symbol name prefixes. */
32 #define SYMPREFIX_CF "luaopen_%s"
33 #define SYMPREFIX_BC "luaJIT_BC_%s"
39 static void ll_unloadlib(void *lib
)
44 static void *ll_load(lua_State
*L
, const char *path
, int gl
)
46 void *lib
= dlopen(path
, RTLD_NOW
| (gl
? RTLD_GLOBAL
: RTLD_LOCAL
));
47 if (lib
== NULL
) lua_pushstring(L
, dlerror());
51 static lua_CFunction
ll_sym(lua_State
*L
, void *lib
, const char *sym
)
53 lua_CFunction f
= (lua_CFunction
)dlsym(lib
, sym
);
54 if (f
== NULL
) lua_pushstring(L
, dlerror());
58 static const char *ll_bcsym(void *lib
, const char *sym
)
60 #if defined(RTLD_DEFAULT) && !defined(NO_RTLD_DEFAULT)
61 if (lib
== NULL
) lib
= RTLD_DEFAULT
;
62 #elif LJ_TARGET_OSX || LJ_TARGET_BSD
63 if (lib
== NULL
) lib
= (void *)(intptr_t)-2;
65 return (const char *)dlsym(lib
, sym
);
68 #elif LJ_TARGET_WINDOWS
70 #define WIN32_LEAN_AND_MEAN
73 #ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
74 #define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
75 #define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
76 BOOL WINAPI
GetModuleHandleExA(DWORD
, LPCSTR
, HMODULE
*);
81 static void setprogdir(lua_State
*L
)
83 char buff
[MAX_PATH
+ 1];
85 DWORD nsize
= sizeof(buff
);
86 DWORD n
= GetModuleFileNameA(NULL
, buff
, nsize
);
87 if (n
== 0 || n
== nsize
|| (lb
= strrchr(buff
, '\\')) == NULL
) {
88 luaL_error(L
, "unable to get ModuleFileName");
91 luaL_gsub(L
, lua_tostring(L
, -1), LUA_EXECDIR
, buff
);
92 lua_remove(L
, -2); /* remove original string */
96 static void pusherror(lua_State
*L
)
98 DWORD error
= GetLastError();
100 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS
| FORMAT_MESSAGE_FROM_SYSTEM
,
101 NULL
, error
, 0, buffer
, sizeof(buffer
), NULL
))
102 lua_pushstring(L
, buffer
);
104 lua_pushfstring(L
, "system error %d\n", error
);
107 static void ll_unloadlib(void *lib
)
109 FreeLibrary((HINSTANCE
)lib
);
112 static void *ll_load(lua_State
*L
, const char *path
, int gl
)
114 HINSTANCE lib
= LoadLibraryA(path
);
115 if (lib
== NULL
) pusherror(L
);
120 static lua_CFunction
ll_sym(lua_State
*L
, void *lib
, const char *sym
)
122 lua_CFunction f
= (lua_CFunction
)GetProcAddress((HINSTANCE
)lib
, sym
);
123 if (f
== NULL
) pusherror(L
);
127 static const char *ll_bcsym(void *lib
, const char *sym
)
130 return (const char *)GetProcAddress((HINSTANCE
)lib
, sym
);
132 HINSTANCE h
= GetModuleHandleA(NULL
);
133 const char *p
= (const char *)GetProcAddress(h
, sym
);
134 if (p
== NULL
&& GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT
,
135 (const char *)ll_bcsym
, &h
))
136 p
= (const char *)GetProcAddress(h
, sym
);
143 #undef PACKAGE_LIB_FAIL
144 #define PACKAGE_LIB_FAIL "absent"
146 #define DLMSG "dynamic libraries not enabled; no support for target OS"
148 static void ll_unloadlib(void *lib
)
153 static void *ll_load(lua_State
*L
, const char *path
, int gl
)
155 UNUSED(path
); UNUSED(gl
);
156 lua_pushliteral(L
, DLMSG
);
160 static lua_CFunction
ll_sym(lua_State
*L
, void *lib
, const char *sym
)
162 UNUSED(lib
); UNUSED(sym
);
163 lua_pushliteral(L
, DLMSG
);
167 static const char *ll_bcsym(void *lib
, const char *sym
)
169 UNUSED(lib
); UNUSED(sym
);
175 /* ------------------------------------------------------------------------ */
177 static void **ll_register(lua_State
*L
, const char *path
)
180 lua_pushfstring(L
, "LOADLIB: %s", path
);
181 lua_gettable(L
, LUA_REGISTRYINDEX
); /* check library in registry? */
182 if (!lua_isnil(L
, -1)) { /* is there an entry? */
183 plib
= (void **)lua_touserdata(L
, -1);
184 } else { /* no entry yet; create one */
186 plib
= (void **)lua_newuserdata(L
, sizeof(void *));
188 luaL_getmetatable(L
, "_LOADLIB");
189 lua_setmetatable(L
, -2);
190 lua_pushfstring(L
, "LOADLIB: %s", path
);
191 lua_pushvalue(L
, -2);
192 lua_settable(L
, LUA_REGISTRYINDEX
);
197 static const char *mksymname(lua_State
*L
, const char *modname
,
200 const char *funcname
;
201 const char *mark
= strchr(modname
, *LUA_IGMARK
);
202 if (mark
) modname
= mark
+ 1;
203 funcname
= luaL_gsub(L
, modname
, ".", "_");
204 funcname
= lua_pushfstring(L
, prefix
, funcname
);
205 lua_remove(L
, -2); /* remove 'gsub' result */
209 static int ll_loadfunc(lua_State
*L
, const char *path
, const char *name
, int r
)
212 if (strlen(path
) >= 4096) {
213 lua_pushliteral(L
, "path too long");
214 return PACKAGE_ERR_LIB
;
216 reg
= ll_register(L
, path
);
217 if (*reg
== NULL
) *reg
= ll_load(L
, path
, (*name
== '*'));
219 return PACKAGE_ERR_LIB
; /* Unable to load library. */
220 } else if (*name
== '*') { /* Only load library into global namespace. */
221 lua_pushboolean(L
, 1);
224 const char *sym
= r
? name
: mksymname(L
, name
, SYMPREFIX_CF
);
225 lua_CFunction f
= ll_sym(L
, *reg
, sym
);
227 lua_pushcfunction(L
, f
);
231 const char *bcdata
= ll_bcsym(*reg
, mksymname(L
, name
, SYMPREFIX_BC
));
234 if (luaL_loadbuffer(L
, bcdata
, ~(size_t)0, name
) != 0)
235 return PACKAGE_ERR_LOAD
;
239 return PACKAGE_ERR_FUNC
; /* Unable to find function. */
243 static int lj_cf_package_loadlib(lua_State
*L
)
245 const char *path
= luaL_checkstring(L
, 1);
246 const char *init
= luaL_checkstring(L
, 2);
247 int st
= ll_loadfunc(L
, path
, init
, 1);
248 if (st
== 0) { /* no errors? */
249 return 1; /* return the loaded function */
250 } else { /* error; error message is on stack top */
253 lua_pushstring(L
, (st
== PACKAGE_ERR_LIB
) ? PACKAGE_LIB_FAIL
: "init");
254 return 3; /* return nil, error message, and where */
258 static int lj_cf_package_unloadlib(lua_State
*L
)
260 void **lib
= (void **)luaL_checkudata(L
, 1, "_LOADLIB");
261 if (*lib
) ll_unloadlib(*lib
);
262 *lib
= NULL
; /* mark library as closed */
266 /* ------------------------------------------------------------------------ */
268 static int readable(const char *filename
)
270 FILE *f
= fopen(filename
, "r"); /* try to open file */
271 if (f
== NULL
) return 0; /* open failed */
276 static const char *pushnexttemplate(lua_State
*L
, const char *path
)
279 while (*path
== *LUA_PATHSEP
) path
++; /* skip separators */
280 if (*path
== '\0') return NULL
; /* no more templates */
281 l
= strchr(path
, *LUA_PATHSEP
); /* find next separator */
282 if (l
== NULL
) l
= path
+ strlen(path
);
283 lua_pushlstring(L
, path
, (size_t)(l
- path
)); /* template */
287 static const char *searchpath (lua_State
*L
, const char *name
,
288 const char *path
, const char *sep
,
291 luaL_Buffer msg
; /* to build error message */
292 luaL_buffinit(L
, &msg
);
293 if (*sep
!= '\0') /* non-empty separator? */
294 name
= luaL_gsub(L
, name
, sep
, dirsep
); /* replace it by 'dirsep' */
295 while ((path
= pushnexttemplate(L
, path
)) != NULL
) {
296 const char *filename
= luaL_gsub(L
, lua_tostring(L
, -1),
297 LUA_PATH_MARK
, name
);
298 lua_remove(L
, -2); /* remove path template */
299 if (readable(filename
)) /* does file exist and is readable? */
300 return filename
; /* return that file name */
301 lua_pushfstring(L
, "\n\tno file " LUA_QS
, filename
);
302 lua_remove(L
, -2); /* remove file name */
303 luaL_addvalue(&msg
); /* concatenate error msg. entry */
305 luaL_pushresult(&msg
); /* create error message */
306 return NULL
; /* not found */
309 static int lj_cf_package_searchpath(lua_State
*L
)
311 const char *f
= searchpath(L
, luaL_checkstring(L
, 1),
312 luaL_checkstring(L
, 2),
313 luaL_optstring(L
, 3, "."),
314 luaL_optstring(L
, 4, LUA_DIRSEP
));
317 } else { /* error message is on top of the stack */
320 return 2; /* return nil + error message */
324 static const char *findfile(lua_State
*L
, const char *name
,
328 lua_getfield(L
, LUA_ENVIRONINDEX
, pname
);
329 path
= lua_tostring(L
, -1);
331 luaL_error(L
, LUA_QL("package.%s") " must be a string", pname
);
332 return searchpath(L
, name
, path
, ".", LUA_DIRSEP
);
335 static void loaderror(lua_State
*L
, const char *filename
)
337 luaL_error(L
, "error loading module " LUA_QS
" from file " LUA_QS
":\n\t%s",
338 lua_tostring(L
, 1), filename
, lua_tostring(L
, -1));
341 static int lj_cf_package_loader_lua(lua_State
*L
)
343 const char *filename
;
344 const char *name
= luaL_checkstring(L
, 1);
345 filename
= findfile(L
, name
, "path");
346 if (filename
== NULL
) return 1; /* library not found in this path */
347 if (luaL_loadfile(L
, filename
) != 0)
348 loaderror(L
, filename
);
349 return 1; /* library loaded successfully */
352 static int lj_cf_package_loader_c(lua_State
*L
)
354 const char *name
= luaL_checkstring(L
, 1);
355 const char *filename
= findfile(L
, name
, "cpath");
356 if (filename
== NULL
) return 1; /* library not found in this path */
357 if (ll_loadfunc(L
, filename
, name
, 0) != 0)
358 loaderror(L
, filename
);
359 return 1; /* library loaded successfully */
362 static int lj_cf_package_loader_croot(lua_State
*L
)
364 const char *filename
;
365 const char *name
= luaL_checkstring(L
, 1);
366 const char *p
= strchr(name
, '.');
368 if (p
== NULL
) return 0; /* is root */
369 lua_pushlstring(L
, name
, (size_t)(p
- name
));
370 filename
= findfile(L
, lua_tostring(L
, -1), "cpath");
371 if (filename
== NULL
) return 1; /* root not found */
372 if ((st
= ll_loadfunc(L
, filename
, name
, 0)) != 0) {
373 if (st
!= PACKAGE_ERR_FUNC
) loaderror(L
, filename
); /* real error */
374 lua_pushfstring(L
, "\n\tno module " LUA_QS
" in file " LUA_QS
,
376 return 1; /* function not found */
381 static int lj_cf_package_loader_preload(lua_State
*L
)
383 const char *name
= luaL_checkstring(L
, 1);
384 lua_getfield(L
, LUA_ENVIRONINDEX
, "preload");
385 if (!lua_istable(L
, -1))
386 luaL_error(L
, LUA_QL("package.preload") " must be a table");
387 lua_getfield(L
, -1, name
);
388 if (lua_isnil(L
, -1)) { /* Not found? */
389 const char *bcname
= mksymname(L
, name
, SYMPREFIX_BC
);
390 const char *bcdata
= ll_bcsym(NULL
, bcname
);
391 if (bcdata
== NULL
|| luaL_loadbuffer(L
, bcdata
, ~(size_t)0, name
) != 0)
392 lua_pushfstring(L
, "\n\tno field package.preload['%s']", name
);
397 /* ------------------------------------------------------------------------ */
399 static const int sentinel_
= 0;
400 #define sentinel ((void *)&sentinel_)
402 static int lj_cf_package_require(lua_State
*L
)
404 const char *name
= luaL_checkstring(L
, 1);
406 lua_settop(L
, 1); /* _LOADED table will be at index 2 */
407 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
408 lua_getfield(L
, 2, name
);
409 if (lua_toboolean(L
, -1)) { /* is it there? */
410 if (lua_touserdata(L
, -1) == sentinel
) /* check loops */
411 luaL_error(L
, "loop or previous error loading module " LUA_QS
, name
);
412 return 1; /* package is already loaded */
414 /* else must load it; iterate over available loaders */
415 lua_getfield(L
, LUA_ENVIRONINDEX
, "loaders");
416 if (!lua_istable(L
, -1))
417 luaL_error(L
, LUA_QL("package.loaders") " must be a table");
418 lua_pushliteral(L
, ""); /* error message accumulator */
420 lua_rawgeti(L
, -2, i
); /* get a loader */
421 if (lua_isnil(L
, -1))
422 luaL_error(L
, "module " LUA_QS
" not found:%s",
423 name
, lua_tostring(L
, -2));
424 lua_pushstring(L
, name
);
425 lua_call(L
, 1, 1); /* call it */
426 if (lua_isfunction(L
, -1)) /* did it find module? */
427 break; /* module loaded successfully */
428 else if (lua_isstring(L
, -1)) /* loader returned error message? */
429 lua_concat(L
, 2); /* accumulate it */
433 lua_pushlightuserdata(L
, sentinel
);
434 lua_setfield(L
, 2, name
); /* _LOADED[name] = sentinel */
435 lua_pushstring(L
, name
); /* pass name as argument to module */
436 lua_call(L
, 1, 1); /* run loaded module */
437 if (!lua_isnil(L
, -1)) /* non-nil return? */
438 lua_setfield(L
, 2, name
); /* _LOADED[name] = returned value */
439 lua_getfield(L
, 2, name
);
440 if (lua_touserdata(L
, -1) == sentinel
) { /* module did not set a value? */
441 lua_pushboolean(L
, 1); /* use true as result */
442 lua_pushvalue(L
, -1); /* extra copy to be returned */
443 lua_setfield(L
, 2, name
); /* _LOADED[name] = true */
449 /* ------------------------------------------------------------------------ */
451 static void setfenv(lua_State
*L
)
454 if (lua_getstack(L
, 1, &ar
) == 0 ||
455 lua_getinfo(L
, "f", &ar
) == 0 || /* get calling function */
456 lua_iscfunction(L
, -1))
457 luaL_error(L
, LUA_QL("module") " not called from a Lua function");
458 lua_pushvalue(L
, -2);
463 static void dooptions(lua_State
*L
, int n
)
466 for (i
= 2; i
<= n
; i
++) {
467 lua_pushvalue(L
, i
); /* get option (a function) */
468 lua_pushvalue(L
, -2); /* module */
473 static void modinit(lua_State
*L
, const char *modname
)
476 lua_pushvalue(L
, -1);
477 lua_setfield(L
, -2, "_M"); /* module._M = module */
478 lua_pushstring(L
, modname
);
479 lua_setfield(L
, -2, "_NAME");
480 dot
= strrchr(modname
, '.'); /* look for last dot in module name */
481 if (dot
== NULL
) dot
= modname
; else dot
++;
482 /* set _PACKAGE as package name (full module name minus last part) */
483 lua_pushlstring(L
, modname
, (size_t)(dot
- modname
));
484 lua_setfield(L
, -2, "_PACKAGE");
487 static int lj_cf_package_module(lua_State
*L
)
489 const char *modname
= luaL_checkstring(L
, 1);
490 int loaded
= lua_gettop(L
) + 1; /* index of _LOADED table */
491 lua_getfield(L
, LUA_REGISTRYINDEX
, "_LOADED");
492 lua_getfield(L
, loaded
, modname
); /* get _LOADED[modname] */
493 if (!lua_istable(L
, -1)) { /* not found? */
494 lua_pop(L
, 1); /* remove previous result */
495 /* try global variable (and create one if it does not exist) */
496 if (luaL_findtable(L
, LUA_GLOBALSINDEX
, modname
, 1) != NULL
)
497 lj_err_callerv(L
, LJ_ERR_BADMODN
, modname
);
498 lua_pushvalue(L
, -1);
499 lua_setfield(L
, loaded
, modname
); /* _LOADED[modname] = new table */
501 /* check whether table already has a _NAME field */
502 lua_getfield(L
, -1, "_NAME");
503 if (!lua_isnil(L
, -1)) { /* is table an initialized module? */
505 } else { /* no; initialize it */
509 lua_pushvalue(L
, -1);
511 dooptions(L
, loaded
- 1);
515 static int lj_cf_package_seeall(lua_State
*L
)
517 luaL_checktype(L
, 1, LUA_TTABLE
);
518 if (!lua_getmetatable(L
, 1)) {
519 lua_createtable(L
, 0, 1); /* create new metatable */
520 lua_pushvalue(L
, -1);
521 lua_setmetatable(L
, 1);
523 lua_pushvalue(L
, LUA_GLOBALSINDEX
);
524 lua_setfield(L
, -2, "__index"); /* mt.__index = _G */
528 /* ------------------------------------------------------------------------ */
532 static void setpath(lua_State
*L
, const char *fieldname
, const char *envname
,
533 const char *def
, int noenv
)
535 #if LJ_TARGET_CONSOLE
536 const char *path
= NULL
;
539 const char *path
= getenv(envname
);
541 if (path
== NULL
|| noenv
) {
542 lua_pushstring(L
, def
);
544 path
= luaL_gsub(L
, path
, LUA_PATHSEP LUA_PATHSEP
,
545 LUA_PATHSEP AUXMARK LUA_PATHSEP
);
546 luaL_gsub(L
, path
, AUXMARK
, def
);
550 lua_setfield(L
, -2, fieldname
);
553 static const luaL_Reg package_lib
[] = {
554 { "loadlib", lj_cf_package_loadlib
},
555 { "searchpath", lj_cf_package_searchpath
},
556 { "seeall", lj_cf_package_seeall
},
560 static const luaL_Reg package_global
[] = {
561 { "module", lj_cf_package_module
},
562 { "require", lj_cf_package_require
},
566 static const lua_CFunction package_loaders
[] =
568 lj_cf_package_loader_preload
,
569 lj_cf_package_loader_lua
,
570 lj_cf_package_loader_c
,
571 lj_cf_package_loader_croot
,
575 LUALIB_API
int luaopen_package(lua_State
*L
)
579 luaL_newmetatable(L
, "_LOADLIB");
580 lj_lib_pushcf(L
, lj_cf_package_unloadlib
, 1);
581 lua_setfield(L
, -2, "__gc");
582 luaL_register(L
, LUA_LOADLIBNAME
, package_lib
);
583 lua_pushvalue(L
, -1);
584 lua_replace(L
, LUA_ENVIRONINDEX
);
585 lua_createtable(L
, sizeof(package_loaders
)/sizeof(package_loaders
[0])-1, 0);
586 for (i
= 0; package_loaders
[i
] != NULL
; i
++) {
587 lj_lib_pushcf(L
, package_loaders
[i
], 1);
588 lua_rawseti(L
, -2, i
+1);
590 lua_setfield(L
, -2, "loaders");
591 lua_getfield(L
, LUA_REGISTRYINDEX
, "LUA_NOENV");
592 noenv
= lua_toboolean(L
, -1);
594 setpath(L
, "path", LUA_PATH
, LUA_PATH_DEFAULT
, noenv
);
595 setpath(L
, "cpath", LUA_CPATH
, LUA_CPATH_DEFAULT
, noenv
);
596 lua_pushliteral(L
, LUA_PATH_CONFIG
);
597 lua_setfield(L
, -2, "config");
598 luaL_findtable(L
, LUA_REGISTRYINDEX
, "_LOADED", 16);
599 lua_setfield(L
, -2, "loaded");
600 luaL_findtable(L
, LUA_REGISTRYINDEX
, "_PRELOAD", 4);
601 lua_setfield(L
, -2, "preload");
602 lua_pushvalue(L
, LUA_GLOBALSINDEX
);
603 luaL_register(L
, NULL
, package_global
);