beta-0.89.2
[luatex.git] / source / libs / luajit / LuaJIT-src / src / lib_package.c
blobf8d69bfea82f698fceffac9bf43663fdf8da5673
1 /*
2 ** Package library.
3 ** Copyright (C) 2005-2015 Mike Pall. See Copyright Notice in luajit.h
4 **
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
7 */
9 #define lib_package_c
10 #define LUA_LIB
12 #include "lua.h"
13 #include "lauxlib.h"
14 #include "lualib.h"
16 #include "lj_obj.h"
17 #include "lj_err.h"
18 #include "lj_lib.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"
35 #if LJ_TARGET_DLOPEN
37 #include <dlfcn.h>
39 static void ll_unloadlib(void *lib)
41 dlclose(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());
48 return lib;
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());
55 return f;
58 static const char *ll_bcsym(void *lib, const char *sym)
60 #if defined(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;
64 #endif
65 return (const char *)dlsym(lib, sym);
68 #elif LJ_TARGET_WINDOWS
70 #define WIN32_LEAN_AND_MEAN
71 #include <windows.h>
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*);
77 #endif
79 #undef setprogdir
81 static void setprogdir(lua_State *L)
83 char buff[MAX_PATH + 1];
84 char *lb;
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");
89 } else {
90 *lb = '\0';
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();
99 #if LJ_TARGET_XBOXONE
100 wchar_t wbuffer[128];
101 char buffer[128*2];
102 if (FormatMessageW(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
103 NULL, error, 0, wbuffer, sizeof(wbuffer)/sizeof(wchar_t), NULL) &&
104 WideCharToMultiByte(CP_ACP, 0, wbuffer, 128, buffer, 128*2, NULL, NULL))
105 #else
106 char buffer[128];
107 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
108 NULL, error, 0, buffer, sizeof(buffer), NULL))
109 #endif
110 lua_pushstring(L, buffer);
111 else
112 lua_pushfstring(L, "system error %d\n", error);
115 static void ll_unloadlib(void *lib)
117 FreeLibrary((HINSTANCE)lib);
120 static void *ll_load(lua_State *L, const char *path, int gl)
122 HINSTANCE lib = LoadLibraryExA(path, NULL, 0);
123 if (lib == NULL) pusherror(L);
124 UNUSED(gl);
125 return lib;
128 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
130 lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
131 if (f == NULL) pusherror(L);
132 return f;
135 static const char *ll_bcsym(void *lib, const char *sym)
137 if (lib) {
138 return (const char *)GetProcAddress((HINSTANCE)lib, sym);
139 } else {
140 HINSTANCE h = GetModuleHandleA(NULL);
141 const char *p = (const char *)GetProcAddress(h, sym);
142 if (p == NULL && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
143 (const char *)ll_bcsym, &h))
144 p = (const char *)GetProcAddress(h, sym);
145 return p;
149 #else
151 #undef PACKAGE_LIB_FAIL
152 #define PACKAGE_LIB_FAIL "absent"
154 #define DLMSG "dynamic libraries not enabled; no support for target OS"
156 static void ll_unloadlib(void *lib)
158 UNUSED(lib);
161 static void *ll_load(lua_State *L, const char *path, int gl)
163 UNUSED(path); UNUSED(gl);
164 lua_pushliteral(L, DLMSG);
165 return NULL;
168 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
170 UNUSED(lib); UNUSED(sym);
171 lua_pushliteral(L, DLMSG);
172 return NULL;
175 static const char *ll_bcsym(void *lib, const char *sym)
177 UNUSED(lib); UNUSED(sym);
178 return NULL;
181 #endif
183 /* ------------------------------------------------------------------------ */
185 static void **ll_register(lua_State *L, const char *path)
187 void **plib;
188 lua_pushfstring(L, "LOADLIB: %s", path);
189 lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
190 if (!lua_isnil(L, -1)) { /* is there an entry? */
191 plib = (void **)lua_touserdata(L, -1);
192 } else { /* no entry yet; create one */
193 lua_pop(L, 1);
194 plib = (void **)lua_newuserdata(L, sizeof(void *));
195 *plib = NULL;
196 luaL_getmetatable(L, "_LOADLIB");
197 lua_setmetatable(L, -2);
198 lua_pushfstring(L, "LOADLIB: %s", path);
199 lua_pushvalue(L, -2);
200 lua_settable(L, LUA_REGISTRYINDEX);
202 return plib;
205 static const char *mksymname(lua_State *L, const char *modname,
206 const char *prefix)
208 const char *funcname;
209 const char *mark = strchr(modname, *LUA_IGMARK);
210 if (mark) modname = mark + 1;
211 funcname = luaL_gsub(L, modname, ".", "_");
212 funcname = lua_pushfstring(L, prefix, funcname);
213 lua_remove(L, -2); /* remove 'gsub' result */
214 return funcname;
217 static int ll_loadfunc(lua_State *L, const char *path, const char *name, int r)
219 void **reg = ll_register(L, path);
220 if (*reg == NULL) *reg = ll_load(L, path, (*name == '*'));
221 if (*reg == NULL) {
222 return PACKAGE_ERR_LIB; /* Unable to load library. */
223 } else if (*name == '*') { /* Only load library into global namespace. */
224 lua_pushboolean(L, 1);
225 return 0;
226 } else {
227 const char *sym = r ? name : mksymname(L, name, SYMPREFIX_CF);
228 lua_CFunction f = ll_sym(L, *reg, sym);
229 if (f) {
230 lua_pushcfunction(L, f);
231 return 0;
233 if (!r) {
234 const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC));
235 lua_pop(L, 1);
236 if (bcdata) {
237 if (luaL_loadbuffer(L, bcdata, LJ_MAX_BUF, name) != 0)
238 return PACKAGE_ERR_LOAD;
239 return 0;
242 return PACKAGE_ERR_FUNC; /* Unable to find function. */
246 static int lj_cf_package_loadlib(lua_State *L)
248 const char *path = luaL_checkstring(L, 1);
249 const char *init = luaL_checkstring(L, 2);
250 int st = ll_loadfunc(L, path, init, 1);
251 if (st == 0) { /* no errors? */
252 return 1; /* return the loaded function */
253 } else { /* error; error message is on stack top */
254 lua_pushnil(L);
255 lua_insert(L, -2);
256 lua_pushstring(L, (st == PACKAGE_ERR_LIB) ? PACKAGE_LIB_FAIL : "init");
257 return 3; /* return nil, error message, and where */
261 static int lj_cf_package_unloadlib(lua_State *L)
263 void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
264 if (*lib) ll_unloadlib(*lib);
265 *lib = NULL; /* mark library as closed */
266 return 0;
269 /* ------------------------------------------------------------------------ */
271 static int readable(const char *filename)
273 FILE *f = fopen(filename, "r"); /* try to open file */
274 if (f == NULL) return 0; /* open failed */
275 fclose(f);
276 return 1;
279 static const char *pushnexttemplate(lua_State *L, const char *path)
281 const char *l;
282 while (*path == *LUA_PATHSEP) path++; /* skip separators */
283 if (*path == '\0') return NULL; /* no more templates */
284 l = strchr(path, *LUA_PATHSEP); /* find next separator */
285 if (l == NULL) l = path + strlen(path);
286 lua_pushlstring(L, path, (size_t)(l - path)); /* template */
287 return l;
290 static const char *searchpath (lua_State *L, const char *name,
291 const char *path, const char *sep,
292 const char *dirsep)
294 luaL_Buffer msg; /* to build error message */
295 luaL_buffinit(L, &msg);
296 if (*sep != '\0') /* non-empty separator? */
297 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
298 while ((path = pushnexttemplate(L, path)) != NULL) {
299 const char *filename = luaL_gsub(L, lua_tostring(L, -1),
300 LUA_PATH_MARK, name);
301 lua_remove(L, -2); /* remove path template */
302 if (readable(filename)) /* does file exist and is readable? */
303 return filename; /* return that file name */
304 lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
305 lua_remove(L, -2); /* remove file name */
306 luaL_addvalue(&msg); /* concatenate error msg. entry */
308 luaL_pushresult(&msg); /* create error message */
309 return NULL; /* not found */
312 static int lj_cf_package_searchpath(lua_State *L)
314 const char *f = searchpath(L, luaL_checkstring(L, 1),
315 luaL_checkstring(L, 2),
316 luaL_optstring(L, 3, "."),
317 luaL_optstring(L, 4, LUA_DIRSEP));
318 if (f != NULL) {
319 return 1;
320 } else { /* error message is on top of the stack */
321 lua_pushnil(L);
322 lua_insert(L, -2);
323 return 2; /* return nil + error message */
327 static const char *findfile(lua_State *L, const char *name,
328 const char *pname)
330 const char *path;
331 lua_getfield(L, LUA_ENVIRONINDEX, pname);
332 path = lua_tostring(L, -1);
333 if (path == NULL)
334 luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
335 return searchpath(L, name, path, ".", LUA_DIRSEP);
338 static void loaderror(lua_State *L, const char *filename)
340 luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
341 lua_tostring(L, 1), filename, lua_tostring(L, -1));
344 static int lj_cf_package_loader_lua(lua_State *L)
346 const char *filename;
347 const char *name = luaL_checkstring(L, 1);
348 filename = findfile(L, name, "path");
349 if (filename == NULL) return 1; /* library not found in this path */
350 if (luaL_loadfile(L, filename) != 0)
351 loaderror(L, filename);
352 return 1; /* library loaded successfully */
355 static int lj_cf_package_loader_c(lua_State *L)
357 const char *name = luaL_checkstring(L, 1);
358 const char *filename = findfile(L, name, "cpath");
359 if (filename == NULL) return 1; /* library not found in this path */
360 if (ll_loadfunc(L, filename, name, 0) != 0)
361 loaderror(L, filename);
362 return 1; /* library loaded successfully */
365 #define LUA_POF "luaopen_"
366 #define LUA_OFSEP "_"
367 #define POF LUA_POF
369 static const char *mkfuncname (lua_State *L, const char *modname) {
370 const char *funcname;
371 const char *mark = strchr(modname, *LUA_IGMARK);
372 if (mark) modname = mark + 1;
373 funcname = luaL_gsub(L, modname, ".", LUA_OFSEP);
374 funcname = lua_pushfstring(L, POF"%s", funcname);
375 lua_remove(L, -2); /* remove 'gsub' result */
376 return funcname;
380 int loader_C_luatex (lua_State *L, const char *name, const char *filename) {
381 const char *funcname;
382 funcname = mkfuncname(L, name);
383 if (ll_loadfunc(L, filename, funcname,0) != 0)
384 loaderror(L, filename);
385 return 1; /* library loaded successfully */
388 static int lj_cf_package_loader_croot(lua_State *L)
390 const char *filename;
391 const char *name = luaL_checkstring(L, 1);
392 const char *p = strchr(name, '.');
393 int st;
394 if (p == NULL) return 0; /* is root */
395 lua_pushlstring(L, name, (size_t)(p - name));
396 filename = findfile(L, lua_tostring(L, -1), "cpath");
397 if (filename == NULL) return 1; /* root not found */
398 if ((st = ll_loadfunc(L, filename, name, 0)) != 0) {
399 if (st != PACKAGE_ERR_FUNC) loaderror(L, filename); /* real error */
400 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
401 name, filename);
402 return 1; /* function not found */
404 return 1;
407 int loader_Call_luatex (lua_State *L, const char *name, const char *filename) {
408 const char *funcname;
409 int stat;
410 if (filename == NULL) return 1; /* root not found */
411 funcname = mkfuncname(L, name);
412 if ((stat = ll_loadfunc(L, filename, funcname,0)) != 0) {
413 if (stat != PACKAGE_ERR_FUNC) loaderror(L, filename); /* real error */
414 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
415 name, filename);
416 return 1; /* function not found */
418 return 1; /* library loaded successfully */
422 static int lj_cf_package_loader_preload(lua_State *L)
424 const char *name = luaL_checkstring(L, 1);
425 lua_getfield(L, LUA_ENVIRONINDEX, "preload");
426 if (!lua_istable(L, -1))
427 luaL_error(L, LUA_QL("package.preload") " must be a table");
428 lua_getfield(L, -1, name);
429 if (lua_isnil(L, -1)) { /* Not found? */
430 const char *bcname = mksymname(L, name, SYMPREFIX_BC);
431 const char *bcdata = ll_bcsym(NULL, bcname);
432 if (bcdata == NULL || luaL_loadbuffer(L, bcdata, LJ_MAX_BUF, name) != 0)
433 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
435 return 1;
438 /* ------------------------------------------------------------------------ */
440 static const int sentinel_ = 0;
441 #define sentinel ((void *)&sentinel_)
443 static int lj_cf_package_require(lua_State *L)
445 const char *name = luaL_checkstring(L, 1);
446 int i;
447 lua_settop(L, 1); /* _LOADED table will be at index 2 */
448 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
449 lua_getfield(L, 2, name);
450 if (lua_toboolean(L, -1)) { /* is it there? */
451 if (lua_touserdata(L, -1) == sentinel) /* check loops */
452 luaL_error(L, "loop or previous error loading module " LUA_QS, name);
453 return 1; /* package is already loaded */
455 /* else must load it; iterate over available loaders */
456 lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
457 if (!lua_istable(L, -1))
458 luaL_error(L, LUA_QL("package.loaders") " must be a table");
459 lua_pushliteral(L, ""); /* error message accumulator */
460 for (i = 1; ; i++) {
461 lua_rawgeti(L, -2, i); /* get a loader */
462 if (lua_isnil(L, -1))
463 luaL_error(L, "module " LUA_QS " not found:%s",
464 name, lua_tostring(L, -2));
465 lua_pushstring(L, name);
466 lua_call(L, 1, 1); /* call it */
467 if (lua_isfunction(L, -1)) /* did it find module? */
468 break; /* module loaded successfully */
469 else if (lua_isstring(L, -1)) /* loader returned error message? */
470 lua_concat(L, 2); /* accumulate it */
471 else
472 lua_pop(L, 1);
474 lua_pushlightuserdata(L, sentinel);
475 lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
476 lua_pushstring(L, name); /* pass name as argument to module */
477 lua_call(L, 1, 1); /* run loaded module */
478 if (!lua_isnil(L, -1)) /* non-nil return? */
479 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
480 lua_getfield(L, 2, name);
481 if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */
482 lua_pushboolean(L, 1); /* use true as result */
483 lua_pushvalue(L, -1); /* extra copy to be returned */
484 lua_setfield(L, 2, name); /* _LOADED[name] = true */
486 lj_lib_checkfpu(L);
487 return 1;
490 /* ------------------------------------------------------------------------ */
492 static void setfenv(lua_State *L)
494 lua_Debug ar;
495 if (lua_getstack(L, 1, &ar) == 0 ||
496 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
497 lua_iscfunction(L, -1))
498 luaL_error(L, LUA_QL("module") " not called from a Lua function");
499 lua_pushvalue(L, -2);
500 lua_setfenv(L, -2);
501 lua_pop(L, 1);
504 static void dooptions(lua_State *L, int n)
506 int i;
507 for (i = 2; i <= n; i++) {
508 lua_pushvalue(L, i); /* get option (a function) */
509 lua_pushvalue(L, -2); /* module */
510 lua_call(L, 1, 0);
514 static void modinit(lua_State *L, const char *modname)
516 const char *dot;
517 lua_pushvalue(L, -1);
518 lua_setfield(L, -2, "_M"); /* module._M = module */
519 lua_pushstring(L, modname);
520 lua_setfield(L, -2, "_NAME");
521 dot = strrchr(modname, '.'); /* look for last dot in module name */
522 if (dot == NULL) dot = modname; else dot++;
523 /* set _PACKAGE as package name (full module name minus last part) */
524 lua_pushlstring(L, modname, (size_t)(dot - modname));
525 lua_setfield(L, -2, "_PACKAGE");
528 static int lj_cf_package_module(lua_State *L)
530 const char *modname = luaL_checkstring(L, 1);
531 int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
532 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
533 lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
534 if (!lua_istable(L, -1)) { /* not found? */
535 lua_pop(L, 1); /* remove previous result */
536 /* try global variable (and create one if it does not exist) */
537 if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL)
538 lj_err_callerv(L, LJ_ERR_BADMODN, modname);
539 lua_pushvalue(L, -1);
540 lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
542 /* check whether table already has a _NAME field */
543 lua_getfield(L, -1, "_NAME");
544 if (!lua_isnil(L, -1)) { /* is table an initialized module? */
545 lua_pop(L, 1);
546 } else { /* no; initialize it */
547 lua_pop(L, 1);
548 modinit(L, modname);
550 lua_pushvalue(L, -1);
551 setfenv(L);
552 dooptions(L, loaded - 1);
553 return 0;
556 static int lj_cf_package_seeall(lua_State *L)
558 luaL_checktype(L, 1, LUA_TTABLE);
559 if (!lua_getmetatable(L, 1)) {
560 lua_createtable(L, 0, 1); /* create new metatable */
561 lua_pushvalue(L, -1);
562 lua_setmetatable(L, 1);
564 lua_pushvalue(L, LUA_GLOBALSINDEX);
565 lua_setfield(L, -2, "__index"); /* mt.__index = _G */
566 return 0;
569 /* ------------------------------------------------------------------------ */
571 #define AUXMARK "\1"
573 static void setpath(lua_State *L, const char *fieldname, const char *envname,
574 const char *def, int noenv)
576 #if LJ_TARGET_CONSOLE
577 const char *path = NULL;
578 UNUSED(envname);
579 #else
580 const char *path = getenv(envname);
581 #endif
582 if (path == NULL || noenv) {
583 lua_pushstring(L, def);
584 } else {
585 path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
586 LUA_PATHSEP AUXMARK LUA_PATHSEP);
587 luaL_gsub(L, path, AUXMARK, def);
588 lua_remove(L, -2);
590 setprogdir(L);
591 lua_setfield(L, -2, fieldname);
594 static const luaL_Reg package_lib[] = {
595 { "loadlib", lj_cf_package_loadlib },
596 { "searchpath", lj_cf_package_searchpath },
597 { "seeall", lj_cf_package_seeall },
598 { NULL, NULL }
601 static const luaL_Reg package_global[] = {
602 { "module", lj_cf_package_module },
603 { "require", lj_cf_package_require },
604 { NULL, NULL }
607 static const lua_CFunction package_loaders[] =
609 lj_cf_package_loader_preload,
610 lj_cf_package_loader_lua,
611 lj_cf_package_loader_c,
612 lj_cf_package_loader_croot,
613 NULL
616 LUALIB_API int luaopen_package(lua_State *L)
618 int i;
619 int noenv;
620 luaL_newmetatable(L, "_LOADLIB");
621 lj_lib_pushcf(L, lj_cf_package_unloadlib, 1);
622 lua_setfield(L, -2, "__gc");
623 luaL_register(L, LUA_LOADLIBNAME, package_lib);
624 lua_pushvalue(L, -1);
625 lua_replace(L, LUA_ENVIRONINDEX);
626 lua_createtable(L, sizeof(package_loaders)/sizeof(package_loaders[0])-1, 0);
627 for (i = 0; package_loaders[i] != NULL; i++) {
628 lj_lib_pushcf(L, package_loaders[i], 1);
629 lua_rawseti(L, -2, i+1);
631 lua_setfield(L, -2, "loaders");
632 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
633 noenv = lua_toboolean(L, -1);
634 lua_pop(L, 1);
635 setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT, noenv);
636 setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT, noenv);
637 lua_pushliteral(L, LUA_PATH_CONFIG);
638 lua_setfield(L, -2, "config");
639 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16);
640 lua_setfield(L, -2, "loaded");
641 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 4);
642 lua_setfield(L, -2, "preload");
643 lua_pushvalue(L, LUA_GLOBALSINDEX);
644 luaL_register(L, NULL, package_global);
645 lua_pop(L, 1);
646 return 1;