Fix package.searchpath().
[luajit-2.0/celess22.git] / src / lib_package.c
blobca5a5a16a07886cd144e56f03761aa2e3af0dc6c
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-2011 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)
46 void *lib = dlopen(path, RTLD_NOW);
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)
117 HINSTANCE lib = LoadLibraryA(path);
118 if (lib == NULL) pusherror(L);
119 return lib;
122 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
124 lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
125 if (f == NULL) pusherror(L);
126 return f;
129 static const char *ll_bcsym(void *lib, const char *sym)
131 if (lib) {
132 return (const char *)GetProcAddress((HINSTANCE)lib, sym);
133 } else {
134 HINSTANCE h = GetModuleHandleA(NULL);
135 const char *p = (const char *)GetProcAddress(h, sym);
136 if (p == NULL && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS|GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,
137 (const char *)ll_bcsym, &h))
138 p = (const char *)GetProcAddress(h, sym);
139 return p;
143 #else
145 #undef PACKAGE_LIB_FAIL
146 #define PACKAGE_LIB_FAIL "absent"
148 #define DLMSG "dynamic libraries not enabled; no support for target OS"
150 static void ll_unloadlib(void *lib)
152 (void)lib;
155 static void *ll_load(lua_State *L, const char *path)
157 (void)path;
158 lua_pushliteral(L, DLMSG);
159 return NULL;
162 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
164 (void)lib; (void)sym;
165 lua_pushliteral(L, DLMSG);
166 return NULL;
169 static const char *ll_bcsym(void *lib, const char *sym)
171 (void)lib; (void)sym;
172 return NULL;
175 #endif
177 /* ------------------------------------------------------------------------ */
179 static void **ll_register(lua_State *L, const char *path)
181 void **plib;
182 lua_pushfstring(L, "LOADLIB: %s", path);
183 lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
184 if (!lua_isnil(L, -1)) { /* is there an entry? */
185 plib = (void **)lua_touserdata(L, -1);
186 } else { /* no entry yet; create one */
187 lua_pop(L, 1);
188 plib = (void **)lua_newuserdata(L, sizeof(void *));
189 *plib = NULL;
190 luaL_getmetatable(L, "_LOADLIB");
191 lua_setmetatable(L, -2);
192 lua_pushfstring(L, "LOADLIB: %s", path);
193 lua_pushvalue(L, -2);
194 lua_settable(L, LUA_REGISTRYINDEX);
196 return plib;
199 static const char *mksymname(lua_State *L, const char *modname,
200 const char *prefix)
202 const char *funcname;
203 const char *mark = strchr(modname, *LUA_IGMARK);
204 if (mark) modname = mark + 1;
205 funcname = luaL_gsub(L, modname, ".", "_");
206 funcname = lua_pushfstring(L, prefix, funcname);
207 lua_remove(L, -2); /* remove 'gsub' result */
208 return funcname;
211 static int ll_loadfunc(lua_State *L, const char *path, const char *name, int r)
213 void **reg = ll_register(L, path);
214 if (*reg == NULL) *reg = ll_load(L, path);
215 if (*reg == NULL) {
216 return PACKAGE_ERR_LIB; /* unable to load library */
217 } else {
218 const char *sym = r ? name : mksymname(L, name, SYMPREFIX_CF);
219 lua_CFunction f = ll_sym(L, *reg, sym);
220 if (f) {
221 lua_pushcfunction(L, f);
222 return 0;
224 if (!r) {
225 const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC));
226 lua_pop(L, 1);
227 if (bcdata) {
228 if (luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0)
229 return PACKAGE_ERR_LOAD;
230 return 0;
233 return PACKAGE_ERR_FUNC; /* unable to find function */
237 static int lj_cf_package_loadlib(lua_State *L)
239 const char *path = luaL_checkstring(L, 1);
240 const char *init = luaL_checkstring(L, 2);
241 int st = ll_loadfunc(L, path, init, 1);
242 if (st == 0) { /* no errors? */
243 return 1; /* return the loaded function */
244 } else { /* error; error message is on stack top */
245 lua_pushnil(L);
246 lua_insert(L, -2);
247 lua_pushstring(L, (st == PACKAGE_ERR_LIB) ? PACKAGE_LIB_FAIL : "init");
248 return 3; /* return nil, error message, and where */
252 static int lj_cf_package_unloadlib(lua_State *L)
254 void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
255 if (*lib) ll_unloadlib(*lib);
256 *lib = NULL; /* mark library as closed */
257 return 0;
260 /* ------------------------------------------------------------------------ */
262 static int readable(const char *filename)
264 FILE *f = fopen(filename, "r"); /* try to open file */
265 if (f == NULL) return 0; /* open failed */
266 fclose(f);
267 return 1;
270 static const char *pushnexttemplate(lua_State *L, const char *path)
272 const char *l;
273 while (*path == *LUA_PATHSEP) path++; /* skip separators */
274 if (*path == '\0') return NULL; /* no more templates */
275 l = strchr(path, *LUA_PATHSEP); /* find next separator */
276 if (l == NULL) l = path + strlen(path);
277 lua_pushlstring(L, path, (size_t)(l - path)); /* template */
278 return l;
281 static const char *searchpath (lua_State *L, const char *name,
282 const char *path, const char *sep,
283 const char *dirsep)
285 luaL_Buffer msg; /* to build error message */
286 luaL_buffinit(L, &msg);
287 if (*sep != '\0') /* non-empty separator? */
288 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
289 while ((path = pushnexttemplate(L, path)) != NULL) {
290 const char *filename = luaL_gsub(L, lua_tostring(L, -1),
291 LUA_PATH_MARK, name);
292 lua_remove(L, -2); /* remove path template */
293 if (readable(filename)) /* does file exist and is readable? */
294 return filename; /* return that file name */
295 lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
296 lua_remove(L, -2); /* remove file name */
297 luaL_addvalue(&msg); /* concatenate error msg. entry */
299 luaL_pushresult(&msg); /* create error message */
300 return NULL; /* not found */
303 static int lj_cf_package_searchpath(lua_State *L)
305 const char *f = searchpath(L, luaL_checkstring(L, 1),
306 luaL_checkstring(L, 2),
307 luaL_optstring(L, 3, "."),
308 luaL_optstring(L, 4, LUA_DIRSEP));
309 if (f != NULL) {
310 return 1;
311 } else { /* error message is on top of the stack */
312 lua_pushnil(L);
313 lua_insert(L, -2);
314 return 2; /* return nil + error message */
318 static const char *findfile(lua_State *L, const char *name,
319 const char *pname)
321 const char *path;
322 lua_getfield(L, LUA_ENVIRONINDEX, pname);
323 path = lua_tostring(L, -1);
324 if (path == NULL)
325 luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
326 return searchpath(L, name, path, ".", LUA_DIRSEP);
329 static void loaderror(lua_State *L, const char *filename)
331 luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
332 lua_tostring(L, 1), filename, lua_tostring(L, -1));
335 static int lj_cf_package_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) != 0)
342 loaderror(L, filename);
343 return 1; /* library loaded successfully */
346 static int lj_cf_package_loader_c(lua_State *L)
348 const char *name = luaL_checkstring(L, 1);
349 const char *filename = findfile(L, name, "cpath");
350 if (filename == NULL) return 1; /* library not found in this path */
351 if (ll_loadfunc(L, filename, name, 0) != 0)
352 loaderror(L, filename);
353 return 1; /* library loaded successfully */
356 static int lj_cf_package_loader_croot(lua_State *L)
358 const char *filename;
359 const char *name = luaL_checkstring(L, 1);
360 const char *p = strchr(name, '.');
361 int st;
362 if (p == NULL) return 0; /* is root */
363 lua_pushlstring(L, name, (size_t)(p - name));
364 filename = findfile(L, lua_tostring(L, -1), "cpath");
365 if (filename == NULL) return 1; /* root not found */
366 if ((st = ll_loadfunc(L, filename, name, 0)) != 0) {
367 if (st != PACKAGE_ERR_FUNC) loaderror(L, filename); /* real error */
368 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
369 name, filename);
370 return 1; /* function not found */
372 return 1;
375 static int lj_cf_package_loader_preload(lua_State *L)
377 const char *name = luaL_checkstring(L, 1);
378 lua_getfield(L, LUA_ENVIRONINDEX, "preload");
379 if (!lua_istable(L, -1))
380 luaL_error(L, LUA_QL("package.preload") " must be a table");
381 lua_getfield(L, -1, name);
382 if (lua_isnil(L, -1)) { /* Not found? */
383 const char *bcname = mksymname(L, name, SYMPREFIX_BC);
384 const char *bcdata = ll_bcsym(NULL, bcname);
385 if (bcdata == NULL || luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0)
386 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
388 return 1;
391 /* ------------------------------------------------------------------------ */
393 static const int sentinel_ = 0;
394 #define sentinel ((void *)&sentinel_)
396 static int lj_cf_package_require(lua_State *L)
398 const char *name = luaL_checkstring(L, 1);
399 int i;
400 lua_settop(L, 1); /* _LOADED table will be at index 2 */
401 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
402 lua_getfield(L, 2, name);
403 if (lua_toboolean(L, -1)) { /* is it there? */
404 if (lua_touserdata(L, -1) == sentinel) /* check loops */
405 luaL_error(L, "loop or previous error loading module " LUA_QS, name);
406 return 1; /* package is already loaded */
408 /* else must load it; iterate over available loaders */
409 lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
410 if (!lua_istable(L, -1))
411 luaL_error(L, LUA_QL("package.loaders") " must be a table");
412 lua_pushliteral(L, ""); /* error message accumulator */
413 for (i = 1; ; i++) {
414 lua_rawgeti(L, -2, i); /* get a loader */
415 if (lua_isnil(L, -1))
416 luaL_error(L, "module " LUA_QS " not found:%s",
417 name, lua_tostring(L, -2));
418 lua_pushstring(L, name);
419 lua_call(L, 1, 1); /* call it */
420 if (lua_isfunction(L, -1)) /* did it find module? */
421 break; /* module loaded successfully */
422 else if (lua_isstring(L, -1)) /* loader returned error message? */
423 lua_concat(L, 2); /* accumulate it */
424 else
425 lua_pop(L, 1);
427 lua_pushlightuserdata(L, sentinel);
428 lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
429 lua_pushstring(L, name); /* pass name as argument to module */
430 lua_call(L, 1, 1); /* run loaded module */
431 if (!lua_isnil(L, -1)) /* non-nil return? */
432 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
433 lua_getfield(L, 2, name);
434 if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */
435 lua_pushboolean(L, 1); /* use true as result */
436 lua_pushvalue(L, -1); /* extra copy to be returned */
437 lua_setfield(L, 2, name); /* _LOADED[name] = true */
439 lj_lib_checkfpu(L);
440 return 1;
443 /* ------------------------------------------------------------------------ */
445 static void setfenv(lua_State *L)
447 lua_Debug ar;
448 if (lua_getstack(L, 1, &ar) == 0 ||
449 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
450 lua_iscfunction(L, -1))
451 luaL_error(L, LUA_QL("module") " not called from a Lua function");
452 lua_pushvalue(L, -2);
453 lua_setfenv(L, -2);
454 lua_pop(L, 1);
457 static void dooptions(lua_State *L, int n)
459 int i;
460 for (i = 2; i <= n; i++) {
461 lua_pushvalue(L, i); /* get option (a function) */
462 lua_pushvalue(L, -2); /* module */
463 lua_call(L, 1, 0);
467 static void modinit(lua_State *L, const char *modname)
469 const char *dot;
470 lua_pushvalue(L, -1);
471 lua_setfield(L, -2, "_M"); /* module._M = module */
472 lua_pushstring(L, modname);
473 lua_setfield(L, -2, "_NAME");
474 dot = strrchr(modname, '.'); /* look for last dot in module name */
475 if (dot == NULL) dot = modname; else dot++;
476 /* set _PACKAGE as package name (full module name minus last part) */
477 lua_pushlstring(L, modname, (size_t)(dot - modname));
478 lua_setfield(L, -2, "_PACKAGE");
481 static int lj_cf_package_module(lua_State *L)
483 const char *modname = luaL_checkstring(L, 1);
484 int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
485 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
486 lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
487 if (!lua_istable(L, -1)) { /* not found? */
488 lua_pop(L, 1); /* remove previous result */
489 /* try global variable (and create one if it does not exist) */
490 if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL)
491 lj_err_callerv(L, LJ_ERR_BADMODN, modname);
492 lua_pushvalue(L, -1);
493 lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
495 /* check whether table already has a _NAME field */
496 lua_getfield(L, -1, "_NAME");
497 if (!lua_isnil(L, -1)) { /* is table an initialized module? */
498 lua_pop(L, 1);
499 } else { /* no; initialize it */
500 lua_pop(L, 1);
501 modinit(L, modname);
503 lua_pushvalue(L, -1);
504 setfenv(L);
505 dooptions(L, loaded - 1);
506 return 0;
509 static int lj_cf_package_seeall(lua_State *L)
511 luaL_checktype(L, 1, LUA_TTABLE);
512 if (!lua_getmetatable(L, 1)) {
513 lua_createtable(L, 0, 1); /* create new metatable */
514 lua_pushvalue(L, -1);
515 lua_setmetatable(L, 1);
517 lua_pushvalue(L, LUA_GLOBALSINDEX);
518 lua_setfield(L, -2, "__index"); /* mt.__index = _G */
519 return 0;
522 /* ------------------------------------------------------------------------ */
524 #define AUXMARK "\1"
526 static void setpath(lua_State *L, const char *fieldname, const char *envname,
527 const char *def, int noenv)
529 #if LJ_TARGET_CONSOLE
530 const char *path = NULL;
531 UNUSED(envname);
532 #else
533 const char *path = getenv(envname);
534 #endif
535 if (path == NULL || noenv) {
536 lua_pushstring(L, def);
537 } else {
538 path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
539 LUA_PATHSEP AUXMARK LUA_PATHSEP);
540 luaL_gsub(L, path, AUXMARK, def);
541 lua_remove(L, -2);
543 setprogdir(L);
544 lua_setfield(L, -2, fieldname);
547 static const luaL_Reg package_lib[] = {
548 { "loadlib", lj_cf_package_loadlib },
549 { "searchpath", lj_cf_package_searchpath },
550 { "seeall", lj_cf_package_seeall },
551 { NULL, NULL }
554 static const luaL_Reg package_global[] = {
555 { "module", lj_cf_package_module },
556 { "require", lj_cf_package_require },
557 { NULL, NULL }
560 static const lua_CFunction package_loaders[] =
562 lj_cf_package_loader_preload,
563 lj_cf_package_loader_lua,
564 lj_cf_package_loader_c,
565 lj_cf_package_loader_croot,
566 NULL
569 LUALIB_API int luaopen_package(lua_State *L)
571 int i;
572 int noenv;
573 luaL_newmetatable(L, "_LOADLIB");
574 lj_lib_pushcf(L, lj_cf_package_unloadlib, 1);
575 lua_setfield(L, -2, "__gc");
576 luaL_register(L, LUA_LOADLIBNAME, package_lib);
577 lua_pushvalue(L, -1);
578 lua_replace(L, LUA_ENVIRONINDEX);
579 lua_createtable(L, sizeof(package_loaders)/sizeof(package_loaders[0])-1, 0);
580 for (i = 0; package_loaders[i] != NULL; i++) {
581 lj_lib_pushcf(L, package_loaders[i], 1);
582 lua_rawseti(L, -2, i+1);
584 lua_setfield(L, -2, "loaders");
585 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
586 noenv = lua_toboolean(L, -1);
587 lua_pop(L, 1);
588 setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT, noenv);
589 setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT, noenv);
590 lua_pushliteral(L, LUA_PATH_CONFIG);
591 lua_setfield(L, -2, "config");
592 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16);
593 lua_setfield(L, -2, "loaded");
594 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 4);
595 lua_setfield(L, -2, "preload");
596 lua_pushvalue(L, LUA_GLOBALSINDEX);
597 luaL_register(L, NULL, package_global);
598 lua_pop(L, 1);
599 return 1;