RELEASE LuaJIT-2.0.0-beta11
[luajit-2.0/celess22.git] / src / lib_package.c
blob1794a3d4f3096796979b1ddce99fac2c5a5e7e1c
1 /*
2 ** Package library.
3 ** Copyright (C) 2005-2012 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 #ifndef WINVER
72 #define WINVER 0x0500
73 #endif
74 #include <windows.h>
76 #ifndef GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS
77 #define GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS 4
78 #define GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT 2
79 BOOL WINAPI GetModuleHandleExA(DWORD, LPCSTR, HMODULE*);
80 #endif
82 #undef setprogdir
84 static void setprogdir(lua_State *L)
86 char buff[MAX_PATH + 1];
87 char *lb;
88 DWORD nsize = sizeof(buff);
89 DWORD n = GetModuleFileNameA(NULL, buff, nsize);
90 if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) {
91 luaL_error(L, "unable to get ModuleFileName");
92 } else {
93 *lb = '\0';
94 luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
95 lua_remove(L, -2); /* remove original string */
99 static void pusherror(lua_State *L)
101 DWORD error = GetLastError();
102 char buffer[128];
103 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
104 NULL, error, 0, buffer, sizeof(buffer), NULL))
105 lua_pushstring(L, buffer);
106 else
107 lua_pushfstring(L, "system error %d\n", error);
110 static void ll_unloadlib(void *lib)
112 FreeLibrary((HINSTANCE)lib);
115 static void *ll_load(lua_State *L, const char *path, int gl)
117 HINSTANCE lib = LoadLibraryA(path);
118 if (lib == NULL) pusherror(L);
119 UNUSED(gl);
120 return lib;
123 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;
130 static const char *ll_bcsym(void *lib, const char *sym)
132 if (lib) {
133 return (const char *)GetProcAddress((HINSTANCE)lib, sym);
134 } else {
135 HINSTANCE h = GetModuleHandleA(NULL);
136 const char *p = (const char *)GetProcAddress(h, sym);
137 if (p == NULL && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
138 (const char *)ll_bcsym, &h))
139 p = (const char *)GetProcAddress(h, sym);
140 return p;
144 #else
146 #undef PACKAGE_LIB_FAIL
147 #define PACKAGE_LIB_FAIL "absent"
149 #define DLMSG "dynamic libraries not enabled; no support for target OS"
151 static void ll_unloadlib(void *lib)
153 UNUSED(lib);
156 static void *ll_load(lua_State *L, const char *path, int gl)
158 UNUSED(path); UNUSED(gl);
159 lua_pushliteral(L, DLMSG);
160 return NULL;
163 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
165 UNUSED(lib); UNUSED(sym);
166 lua_pushliteral(L, DLMSG);
167 return NULL;
170 static const char *ll_bcsym(void *lib, const char *sym)
172 UNUSED(lib); UNUSED(sym);
173 return NULL;
176 #endif
178 /* ------------------------------------------------------------------------ */
180 static void **ll_register(lua_State *L, const char *path)
182 void **plib;
183 lua_pushfstring(L, "LOADLIB: %s", path);
184 lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
185 if (!lua_isnil(L, -1)) { /* is there an entry? */
186 plib = (void **)lua_touserdata(L, -1);
187 } else { /* no entry yet; create one */
188 lua_pop(L, 1);
189 plib = (void **)lua_newuserdata(L, sizeof(void *));
190 *plib = NULL;
191 luaL_getmetatable(L, "_LOADLIB");
192 lua_setmetatable(L, -2);
193 lua_pushfstring(L, "LOADLIB: %s", path);
194 lua_pushvalue(L, -2);
195 lua_settable(L, LUA_REGISTRYINDEX);
197 return plib;
200 static const char *mksymname(lua_State *L, const char *modname,
201 const char *prefix)
203 const char *funcname;
204 const char *mark = strchr(modname, *LUA_IGMARK);
205 if (mark) modname = mark + 1;
206 funcname = luaL_gsub(L, modname, ".", "_");
207 funcname = lua_pushfstring(L, prefix, funcname);
208 lua_remove(L, -2); /* remove 'gsub' result */
209 return funcname;
212 static int ll_loadfunc(lua_State *L, const char *path, const char *name, int r)
214 void **reg = ll_register(L, path);
215 if (*reg == NULL) *reg = ll_load(L, path, (*name == '*'));
216 if (*reg == NULL) {
217 return PACKAGE_ERR_LIB; /* Unable to load library. */
218 } else if (*name == '*') { /* Only load library into global namespace. */
219 lua_pushboolean(L, 1);
220 return 0;
221 } else {
222 const char *sym = r ? name : mksymname(L, name, SYMPREFIX_CF);
223 lua_CFunction f = ll_sym(L, *reg, sym);
224 if (f) {
225 lua_pushcfunction(L, f);
226 return 0;
228 if (!r) {
229 const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC));
230 lua_pop(L, 1);
231 if (bcdata) {
232 if (luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0)
233 return PACKAGE_ERR_LOAD;
234 return 0;
237 return PACKAGE_ERR_FUNC; /* Unable to find function. */
241 static int lj_cf_package_loadlib(lua_State *L)
243 const char *path = luaL_checkstring(L, 1);
244 const char *init = luaL_checkstring(L, 2);
245 int st = ll_loadfunc(L, path, init, 1);
246 if (st == 0) { /* no errors? */
247 return 1; /* return the loaded function */
248 } else { /* error; error message is on stack top */
249 lua_pushnil(L);
250 lua_insert(L, -2);
251 lua_pushstring(L, (st == PACKAGE_ERR_LIB) ? PACKAGE_LIB_FAIL : "init");
252 return 3; /* return nil, error message, and where */
256 static int lj_cf_package_unloadlib(lua_State *L)
258 void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
259 if (*lib) ll_unloadlib(*lib);
260 *lib = NULL; /* mark library as closed */
261 return 0;
264 /* ------------------------------------------------------------------------ */
266 static int readable(const char *filename)
268 FILE *f = fopen(filename, "r"); /* try to open file */
269 if (f == NULL) return 0; /* open failed */
270 fclose(f);
271 return 1;
274 static const char *pushnexttemplate(lua_State *L, const char *path)
276 const char *l;
277 while (*path == *LUA_PATHSEP) path++; /* skip separators */
278 if (*path == '\0') return NULL; /* no more templates */
279 l = strchr(path, *LUA_PATHSEP); /* find next separator */
280 if (l == NULL) l = path + strlen(path);
281 lua_pushlstring(L, path, (size_t)(l - path)); /* template */
282 return l;
285 static const char *searchpath (lua_State *L, const char *name,
286 const char *path, const char *sep,
287 const char *dirsep)
289 luaL_Buffer msg; /* to build error message */
290 luaL_buffinit(L, &msg);
291 if (*sep != '\0') /* non-empty separator? */
292 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
293 while ((path = pushnexttemplate(L, path)) != NULL) {
294 const char *filename = luaL_gsub(L, lua_tostring(L, -1),
295 LUA_PATH_MARK, name);
296 lua_remove(L, -2); /* remove path template */
297 if (readable(filename)) /* does file exist and is readable? */
298 return filename; /* return that file name */
299 lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
300 lua_remove(L, -2); /* remove file name */
301 luaL_addvalue(&msg); /* concatenate error msg. entry */
303 luaL_pushresult(&msg); /* create error message */
304 return NULL; /* not found */
307 static int lj_cf_package_searchpath(lua_State *L)
309 const char *f = searchpath(L, luaL_checkstring(L, 1),
310 luaL_checkstring(L, 2),
311 luaL_optstring(L, 3, "."),
312 luaL_optstring(L, 4, LUA_DIRSEP));
313 if (f != NULL) {
314 return 1;
315 } else { /* error message is on top of the stack */
316 lua_pushnil(L);
317 lua_insert(L, -2);
318 return 2; /* return nil + error message */
322 static const char *findfile(lua_State *L, const char *name,
323 const char *pname)
325 const char *path;
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, ".", LUA_DIRSEP);
333 static void loaderror(lua_State *L, const char *filename)
335 luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
336 lua_tostring(L, 1), filename, lua_tostring(L, -1));
339 static int lj_cf_package_loader_lua(lua_State *L)
341 const char *filename;
342 const char *name = luaL_checkstring(L, 1);
343 filename = findfile(L, name, "path");
344 if (filename == NULL) return 1; /* library not found in this path */
345 if (luaL_loadfile(L, filename) != 0)
346 loaderror(L, filename);
347 return 1; /* library loaded successfully */
350 static int lj_cf_package_loader_c(lua_State *L)
352 const char *name = luaL_checkstring(L, 1);
353 const char *filename = findfile(L, name, "cpath");
354 if (filename == NULL) return 1; /* library not found in this path */
355 if (ll_loadfunc(L, filename, name, 0) != 0)
356 loaderror(L, filename);
357 return 1; /* library loaded successfully */
360 static int lj_cf_package_loader_croot(lua_State *L)
362 const char *filename;
363 const char *name = luaL_checkstring(L, 1);
364 const char *p = strchr(name, '.');
365 int st;
366 if (p == NULL) return 0; /* is root */
367 lua_pushlstring(L, name, (size_t)(p - name));
368 filename = findfile(L, lua_tostring(L, -1), "cpath");
369 if (filename == NULL) return 1; /* root not found */
370 if ((st = ll_loadfunc(L, filename, name, 0)) != 0) {
371 if (st != PACKAGE_ERR_FUNC) loaderror(L, filename); /* real error */
372 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
373 name, filename);
374 return 1; /* function not found */
376 return 1;
379 static int lj_cf_package_loader_preload(lua_State *L)
381 const char *name = luaL_checkstring(L, 1);
382 lua_getfield(L, LUA_ENVIRONINDEX, "preload");
383 if (!lua_istable(L, -1))
384 luaL_error(L, LUA_QL("package.preload") " must be a table");
385 lua_getfield(L, -1, name);
386 if (lua_isnil(L, -1)) { /* Not found? */
387 const char *bcname = mksymname(L, name, SYMPREFIX_BC);
388 const char *bcdata = ll_bcsym(NULL, bcname);
389 if (bcdata == NULL || luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0)
390 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
392 return 1;
395 /* ------------------------------------------------------------------------ */
397 static const int sentinel_ = 0;
398 #define sentinel ((void *)&sentinel_)
400 static int lj_cf_package_require(lua_State *L)
402 const char *name = luaL_checkstring(L, 1);
403 int i;
404 lua_settop(L, 1); /* _LOADED table will be at index 2 */
405 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
406 lua_getfield(L, 2, name);
407 if (lua_toboolean(L, -1)) { /* is it there? */
408 if (lua_touserdata(L, -1) == sentinel) /* check loops */
409 luaL_error(L, "loop or previous error loading module " LUA_QS, name);
410 return 1; /* package is already loaded */
412 /* else must load it; iterate over available loaders */
413 lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
414 if (!lua_istable(L, -1))
415 luaL_error(L, LUA_QL("package.loaders") " must be a table");
416 lua_pushliteral(L, ""); /* error message accumulator */
417 for (i = 1; ; i++) {
418 lua_rawgeti(L, -2, i); /* get a loader */
419 if (lua_isnil(L, -1))
420 luaL_error(L, "module " LUA_QS " not found:%s",
421 name, lua_tostring(L, -2));
422 lua_pushstring(L, name);
423 lua_call(L, 1, 1); /* call it */
424 if (lua_isfunction(L, -1)) /* did it find module? */
425 break; /* module loaded successfully */
426 else if (lua_isstring(L, -1)) /* loader returned error message? */
427 lua_concat(L, 2); /* accumulate it */
428 else
429 lua_pop(L, 1);
431 lua_pushlightuserdata(L, sentinel);
432 lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
433 lua_pushstring(L, name); /* pass name as argument to module */
434 lua_call(L, 1, 1); /* run loaded module */
435 if (!lua_isnil(L, -1)) /* non-nil return? */
436 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
437 lua_getfield(L, 2, name);
438 if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */
439 lua_pushboolean(L, 1); /* use true as result */
440 lua_pushvalue(L, -1); /* extra copy to be returned */
441 lua_setfield(L, 2, name); /* _LOADED[name] = true */
443 lj_lib_checkfpu(L);
444 return 1;
447 /* ------------------------------------------------------------------------ */
449 static void setfenv(lua_State *L)
451 lua_Debug ar;
452 if (lua_getstack(L, 1, &ar) == 0 ||
453 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
454 lua_iscfunction(L, -1))
455 luaL_error(L, LUA_QL("module") " not called from a Lua function");
456 lua_pushvalue(L, -2);
457 lua_setfenv(L, -2);
458 lua_pop(L, 1);
461 static void dooptions(lua_State *L, int n)
463 int i;
464 for (i = 2; i <= n; i++) {
465 lua_pushvalue(L, i); /* get option (a function) */
466 lua_pushvalue(L, -2); /* module */
467 lua_call(L, 1, 0);
471 static void modinit(lua_State *L, const char *modname)
473 const char *dot;
474 lua_pushvalue(L, -1);
475 lua_setfield(L, -2, "_M"); /* module._M = module */
476 lua_pushstring(L, modname);
477 lua_setfield(L, -2, "_NAME");
478 dot = strrchr(modname, '.'); /* look for last dot in module name */
479 if (dot == NULL) dot = modname; else dot++;
480 /* set _PACKAGE as package name (full module name minus last part) */
481 lua_pushlstring(L, modname, (size_t)(dot - modname));
482 lua_setfield(L, -2, "_PACKAGE");
485 static int lj_cf_package_module(lua_State *L)
487 const char *modname = luaL_checkstring(L, 1);
488 int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
489 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
490 lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
491 if (!lua_istable(L, -1)) { /* not found? */
492 lua_pop(L, 1); /* remove previous result */
493 /* try global variable (and create one if it does not exist) */
494 if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL)
495 lj_err_callerv(L, LJ_ERR_BADMODN, modname);
496 lua_pushvalue(L, -1);
497 lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
499 /* check whether table already has a _NAME field */
500 lua_getfield(L, -1, "_NAME");
501 if (!lua_isnil(L, -1)) { /* is table an initialized module? */
502 lua_pop(L, 1);
503 } else { /* no; initialize it */
504 lua_pop(L, 1);
505 modinit(L, modname);
507 lua_pushvalue(L, -1);
508 setfenv(L);
509 dooptions(L, loaded - 1);
510 return 0;
513 static int lj_cf_package_seeall(lua_State *L)
515 luaL_checktype(L, 1, LUA_TTABLE);
516 if (!lua_getmetatable(L, 1)) {
517 lua_createtable(L, 0, 1); /* create new metatable */
518 lua_pushvalue(L, -1);
519 lua_setmetatable(L, 1);
521 lua_pushvalue(L, LUA_GLOBALSINDEX);
522 lua_setfield(L, -2, "__index"); /* mt.__index = _G */
523 return 0;
526 /* ------------------------------------------------------------------------ */
528 #define AUXMARK "\1"
530 static void setpath(lua_State *L, const char *fieldname, const char *envname,
531 const char *def, int noenv)
533 #if LJ_TARGET_CONSOLE
534 const char *path = NULL;
535 UNUSED(envname);
536 #else
537 const char *path = getenv(envname);
538 #endif
539 if (path == NULL || noenv) {
540 lua_pushstring(L, def);
541 } else {
542 path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
543 LUA_PATHSEP AUXMARK LUA_PATHSEP);
544 luaL_gsub(L, path, AUXMARK, def);
545 lua_remove(L, -2);
547 setprogdir(L);
548 lua_setfield(L, -2, fieldname);
551 static const luaL_Reg package_lib[] = {
552 { "loadlib", lj_cf_package_loadlib },
553 { "searchpath", lj_cf_package_searchpath },
554 { "seeall", lj_cf_package_seeall },
555 { NULL, NULL }
558 static const luaL_Reg package_global[] = {
559 { "module", lj_cf_package_module },
560 { "require", lj_cf_package_require },
561 { NULL, NULL }
564 static const lua_CFunction package_loaders[] =
566 lj_cf_package_loader_preload,
567 lj_cf_package_loader_lua,
568 lj_cf_package_loader_c,
569 lj_cf_package_loader_croot,
570 NULL
573 LUALIB_API int luaopen_package(lua_State *L)
575 int i;
576 int noenv;
577 luaL_newmetatable(L, "_LOADLIB");
578 lj_lib_pushcf(L, lj_cf_package_unloadlib, 1);
579 lua_setfield(L, -2, "__gc");
580 luaL_register(L, LUA_LOADLIBNAME, package_lib);
581 lua_pushvalue(L, -1);
582 lua_replace(L, LUA_ENVIRONINDEX);
583 lua_createtable(L, sizeof(package_loaders)/sizeof(package_loaders[0])-1, 0);
584 for (i = 0; package_loaders[i] != NULL; i++) {
585 lj_lib_pushcf(L, package_loaders[i], 1);
586 lua_rawseti(L, -2, i+1);
588 lua_setfield(L, -2, "loaders");
589 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
590 noenv = lua_toboolean(L, -1);
591 lua_pop(L, 1);
592 setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT, noenv);
593 setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT, noenv);
594 lua_pushliteral(L, LUA_PATH_CONFIG);
595 lua_setfield(L, -2, "config");
596 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16);
597 lua_setfield(L, -2, "loaded");
598 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 4);
599 lua_setfield(L, -2, "preload");
600 lua_pushvalue(L, LUA_GLOBALSINDEX);
601 luaL_register(L, NULL, package_global);
602 lua_pop(L, 1);
603 return 1;