FFI: Add unwind definitions for lj_vm_ffi_call.
[luajit-2.0/celess22.git] / src / lib_package.c
blob3ee9f77a19a0b81008e7ee2e8114a7f9407e03fe
1 /*
2 ** Package library.
3 ** Copyright (C) 2005-2011 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 BOOL WINAPI GetModuleHandleExA(DWORD, LPCSTR, HMODULE*);
79 #endif
81 #undef setprogdir
83 static void setprogdir(lua_State *L)
85 char buff[MAX_PATH + 1];
86 char *lb;
87 DWORD nsize = sizeof(buff);
88 DWORD n = GetModuleFileNameA(NULL, buff, nsize);
89 if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) {
90 luaL_error(L, "unable to get ModuleFileName");
91 } else {
92 *lb = '\0';
93 luaL_gsub(L, lua_tostring(L, -1), LUA_EXECDIR, buff);
94 lua_remove(L, -2); /* remove original string */
98 static void pusherror(lua_State *L)
100 DWORD error = GetLastError();
101 char buffer[128];
102 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
103 NULL, error, 0, buffer, sizeof(buffer), NULL))
104 lua_pushstring(L, buffer);
105 else
106 lua_pushfstring(L, "system error %d\n", error);
109 static void ll_unloadlib(void *lib)
111 FreeLibrary((HINSTANCE)lib);
114 static void *ll_load(lua_State *L, const char *path)
116 HINSTANCE lib = LoadLibraryA(path);
117 if (lib == NULL) pusherror(L);
118 return lib;
121 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
123 lua_CFunction f = (lua_CFunction)GetProcAddress((HINSTANCE)lib, sym);
124 if (f == NULL) pusherror(L);
125 return f;
128 static const char *ll_bcsym(void *lib, const char *sym)
130 if (lib) {
131 return (const char *)GetProcAddress((HINSTANCE)lib, sym);
132 } else {
133 HINSTANCE h = GetModuleHandleA(NULL);
134 const char *p = (const char *)GetProcAddress(h, sym);
135 if (p == NULL && GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS,
136 (const char *)ll_bcsym, &h))
137 p = (const char *)GetProcAddress(h, sym);
138 return p;
142 #else
144 #undef PACKAGE_LIB_FAIL
145 #define PACKAGE_LIB_FAIL "absent"
147 #define DLMSG "dynamic libraries not enabled; no support for target OS"
149 static void ll_unloadlib(void *lib)
151 (void)lib;
154 static void *ll_load(lua_State *L, const char *path)
156 (void)path;
157 lua_pushliteral(L, DLMSG);
158 return NULL;
161 static lua_CFunction ll_sym(lua_State *L, void *lib, const char *sym)
163 (void)lib; (void)sym;
164 lua_pushliteral(L, DLMSG);
165 return NULL;
168 static const char *ll_bcsym(void *lib, const char *sym)
170 (void)lib; (void)sym;
171 return NULL;
174 #endif
176 /* ------------------------------------------------------------------------ */
178 static void **ll_register(lua_State *L, const char *path)
180 void **plib;
181 lua_pushfstring(L, "LOADLIB: %s", path);
182 lua_gettable(L, LUA_REGISTRYINDEX); /* check library in registry? */
183 if (!lua_isnil(L, -1)) { /* is there an entry? */
184 plib = (void **)lua_touserdata(L, -1);
185 } else { /* no entry yet; create one */
186 lua_pop(L, 1);
187 plib = (void **)lua_newuserdata(L, sizeof(void *));
188 *plib = NULL;
189 luaL_getmetatable(L, "_LOADLIB");
190 lua_setmetatable(L, -2);
191 lua_pushfstring(L, "LOADLIB: %s", path);
192 lua_pushvalue(L, -2);
193 lua_settable(L, LUA_REGISTRYINDEX);
195 return plib;
198 static const char *mksymname(lua_State *L, const char *modname,
199 const char *prefix)
201 const char *funcname;
202 const char *mark = strchr(modname, *LUA_IGMARK);
203 if (mark) modname = mark + 1;
204 funcname = luaL_gsub(L, modname, ".", "_");
205 funcname = lua_pushfstring(L, prefix, funcname);
206 lua_remove(L, -2); /* remove 'gsub' result */
207 return funcname;
210 static int ll_loadfunc(lua_State *L, const char *path, const char *name, int r)
212 void **reg = ll_register(L, path);
213 if (*reg == NULL) *reg = ll_load(L, path);
214 if (*reg == NULL) {
215 return PACKAGE_ERR_LIB; /* unable to load library */
216 } else {
217 const char *sym = r ? name : mksymname(L, name, SYMPREFIX_CF);
218 lua_CFunction f = ll_sym(L, *reg, sym);
219 if (f) {
220 lua_pushcfunction(L, f);
221 return 0;
223 if (!r) {
224 const char *bcdata = ll_bcsym(*reg, mksymname(L, name, SYMPREFIX_BC));
225 lua_pop(L, 1);
226 if (bcdata) {
227 if (luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0)
228 return PACKAGE_ERR_LOAD;
229 return 0;
232 return PACKAGE_ERR_FUNC; /* unable to find function */
236 static int lj_cf_package_loadlib(lua_State *L)
238 const char *path = luaL_checkstring(L, 1);
239 const char *init = luaL_checkstring(L, 2);
240 int st = ll_loadfunc(L, path, init, 1);
241 if (st == 0) { /* no errors? */
242 return 1; /* return the loaded function */
243 } else { /* error; error message is on stack top */
244 lua_pushnil(L);
245 lua_insert(L, -2);
246 lua_pushstring(L, (st == PACKAGE_ERR_LIB) ? PACKAGE_LIB_FAIL : "init");
247 return 3; /* return nil, error message, and where */
251 static int lj_cf_package_unloadlib(lua_State *L)
253 void **lib = (void **)luaL_checkudata(L, 1, "_LOADLIB");
254 if (*lib) ll_unloadlib(*lib);
255 *lib = NULL; /* mark library as closed */
256 return 0;
259 /* ------------------------------------------------------------------------ */
261 static int readable(const char *filename)
263 FILE *f = fopen(filename, "r"); /* try to open file */
264 if (f == NULL) return 0; /* open failed */
265 fclose(f);
266 return 1;
269 static const char *pushnexttemplate(lua_State *L, const char *path)
271 const char *l;
272 while (*path == *LUA_PATHSEP) path++; /* skip separators */
273 if (*path == '\0') return NULL; /* no more templates */
274 l = strchr(path, *LUA_PATHSEP); /* find next separator */
275 if (l == NULL) l = path + strlen(path);
276 lua_pushlstring(L, path, (size_t)(l - path)); /* template */
277 return l;
280 static const char *searchpath (lua_State *L, const char *name,
281 const char *path)
283 name = luaL_gsub(L, name, ".", LUA_DIRSEP);
284 lua_pushliteral(L, ""); /* error accumulator */
285 while ((path = pushnexttemplate(L, path)) != NULL) {
286 const char *filename = luaL_gsub(L, lua_tostring(L, -1),
287 LUA_PATH_MARK, name);
288 lua_remove(L, -2); /* remove path template */
289 if (readable(filename)) /* does file exist and is readable? */
290 return filename; /* return that file name */
291 lua_pushfstring(L, "\n\tno file " LUA_QS, filename);
292 lua_remove(L, -2); /* remove file name */
293 lua_concat(L, 2); /* add entry to possible error message */
295 return NULL; /* not found */
298 static int lj_cf_package_searchpath(lua_State *L)
300 const char *f = searchpath(L, luaL_checkstring(L, 1), luaL_checkstring(L, 2));
301 if (f != NULL) {
302 return 1;
303 } else { /* error message is on top of the stack */
304 lua_pushnil(L);
305 lua_insert(L, -2);
306 return 2; /* return nil + error message */
310 static const char *findfile(lua_State *L, const char *name,
311 const char *pname)
313 const char *path;
314 lua_getfield(L, LUA_ENVIRONINDEX, pname);
315 path = lua_tostring(L, -1);
316 if (path == NULL)
317 luaL_error(L, LUA_QL("package.%s") " must be a string", pname);
318 return searchpath(L, name, path);
321 static void loaderror(lua_State *L, const char *filename)
323 luaL_error(L, "error loading module " LUA_QS " from file " LUA_QS ":\n\t%s",
324 lua_tostring(L, 1), filename, lua_tostring(L, -1));
327 static int lj_cf_package_loader_lua(lua_State *L)
329 const char *filename;
330 const char *name = luaL_checkstring(L, 1);
331 filename = findfile(L, name, "path");
332 if (filename == NULL) return 1; /* library not found in this path */
333 if (luaL_loadfile(L, filename) != 0)
334 loaderror(L, filename);
335 return 1; /* library loaded successfully */
338 static int lj_cf_package_loader_c(lua_State *L)
340 const char *name = luaL_checkstring(L, 1);
341 const char *filename = findfile(L, name, "cpath");
342 if (filename == NULL) return 1; /* library not found in this path */
343 if (ll_loadfunc(L, filename, name, 0) != 0)
344 loaderror(L, filename);
345 return 1; /* library loaded successfully */
348 static int lj_cf_package_loader_croot(lua_State *L)
350 const char *filename;
351 const char *name = luaL_checkstring(L, 1);
352 const char *p = strchr(name, '.');
353 int st;
354 if (p == NULL) return 0; /* is root */
355 lua_pushlstring(L, name, (size_t)(p - name));
356 filename = findfile(L, lua_tostring(L, -1), "cpath");
357 if (filename == NULL) return 1; /* root not found */
358 if ((st = ll_loadfunc(L, filename, name, 0)) != 0) {
359 if (st != PACKAGE_ERR_FUNC) loaderror(L, filename); /* real error */
360 lua_pushfstring(L, "\n\tno module " LUA_QS " in file " LUA_QS,
361 name, filename);
362 return 1; /* function not found */
364 return 1;
367 static int lj_cf_package_loader_preload(lua_State *L)
369 const char *name = luaL_checkstring(L, 1);
370 lua_getfield(L, LUA_ENVIRONINDEX, "preload");
371 if (!lua_istable(L, -1))
372 luaL_error(L, LUA_QL("package.preload") " must be a table");
373 lua_getfield(L, -1, name);
374 if (lua_isnil(L, -1)) { /* Not found? */
375 const char *bcname = mksymname(L, name, SYMPREFIX_BC);
376 const char *bcdata = ll_bcsym(NULL, bcname);
377 if (bcdata == NULL || luaL_loadbuffer(L, bcdata, ~(size_t)0, name) != 0)
378 lua_pushfstring(L, "\n\tno field package.preload['%s']", name);
380 return 1;
383 /* ------------------------------------------------------------------------ */
385 static const int sentinel_ = 0;
386 #define sentinel ((void *)&sentinel_)
388 static int lj_cf_package_require(lua_State *L)
390 const char *name = luaL_checkstring(L, 1);
391 int i;
392 lua_settop(L, 1); /* _LOADED table will be at index 2 */
393 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
394 lua_getfield(L, 2, name);
395 if (lua_toboolean(L, -1)) { /* is it there? */
396 if (lua_touserdata(L, -1) == sentinel) /* check loops */
397 luaL_error(L, "loop or previous error loading module " LUA_QS, name);
398 return 1; /* package is already loaded */
400 /* else must load it; iterate over available loaders */
401 lua_getfield(L, LUA_ENVIRONINDEX, "loaders");
402 if (!lua_istable(L, -1))
403 luaL_error(L, LUA_QL("package.loaders") " must be a table");
404 lua_pushliteral(L, ""); /* error message accumulator */
405 for (i = 1; ; i++) {
406 lua_rawgeti(L, -2, i); /* get a loader */
407 if (lua_isnil(L, -1))
408 luaL_error(L, "module " LUA_QS " not found:%s",
409 name, lua_tostring(L, -2));
410 lua_pushstring(L, name);
411 lua_call(L, 1, 1); /* call it */
412 if (lua_isfunction(L, -1)) /* did it find module? */
413 break; /* module loaded successfully */
414 else if (lua_isstring(L, -1)) /* loader returned error message? */
415 lua_concat(L, 2); /* accumulate it */
416 else
417 lua_pop(L, 1);
419 lua_pushlightuserdata(L, sentinel);
420 lua_setfield(L, 2, name); /* _LOADED[name] = sentinel */
421 lua_pushstring(L, name); /* pass name as argument to module */
422 lua_call(L, 1, 1); /* run loaded module */
423 if (!lua_isnil(L, -1)) /* non-nil return? */
424 lua_setfield(L, 2, name); /* _LOADED[name] = returned value */
425 lua_getfield(L, 2, name);
426 if (lua_touserdata(L, -1) == sentinel) { /* module did not set a value? */
427 lua_pushboolean(L, 1); /* use true as result */
428 lua_pushvalue(L, -1); /* extra copy to be returned */
429 lua_setfield(L, 2, name); /* _LOADED[name] = true */
431 lj_lib_checkfpu(L);
432 return 1;
435 /* ------------------------------------------------------------------------ */
437 static void setfenv(lua_State *L)
439 lua_Debug ar;
440 if (lua_getstack(L, 1, &ar) == 0 ||
441 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */
442 lua_iscfunction(L, -1))
443 luaL_error(L, LUA_QL("module") " not called from a Lua function");
444 lua_pushvalue(L, -2);
445 lua_setfenv(L, -2);
446 lua_pop(L, 1);
449 static void dooptions(lua_State *L, int n)
451 int i;
452 for (i = 2; i <= n; i++) {
453 lua_pushvalue(L, i); /* get option (a function) */
454 lua_pushvalue(L, -2); /* module */
455 lua_call(L, 1, 0);
459 static void modinit(lua_State *L, const char *modname)
461 const char *dot;
462 lua_pushvalue(L, -1);
463 lua_setfield(L, -2, "_M"); /* module._M = module */
464 lua_pushstring(L, modname);
465 lua_setfield(L, -2, "_NAME");
466 dot = strrchr(modname, '.'); /* look for last dot in module name */
467 if (dot == NULL) dot = modname; else dot++;
468 /* set _PACKAGE as package name (full module name minus last part) */
469 lua_pushlstring(L, modname, (size_t)(dot - modname));
470 lua_setfield(L, -2, "_PACKAGE");
473 static int lj_cf_package_module(lua_State *L)
475 const char *modname = luaL_checkstring(L, 1);
476 int loaded = lua_gettop(L) + 1; /* index of _LOADED table */
477 lua_getfield(L, LUA_REGISTRYINDEX, "_LOADED");
478 lua_getfield(L, loaded, modname); /* get _LOADED[modname] */
479 if (!lua_istable(L, -1)) { /* not found? */
480 lua_pop(L, 1); /* remove previous result */
481 /* try global variable (and create one if it does not exist) */
482 if (luaL_findtable(L, LUA_GLOBALSINDEX, modname, 1) != NULL)
483 lj_err_callerv(L, LJ_ERR_BADMODN, modname);
484 lua_pushvalue(L, -1);
485 lua_setfield(L, loaded, modname); /* _LOADED[modname] = new table */
487 /* check whether table already has a _NAME field */
488 lua_getfield(L, -1, "_NAME");
489 if (!lua_isnil(L, -1)) { /* is table an initialized module? */
490 lua_pop(L, 1);
491 } else { /* no; initialize it */
492 lua_pop(L, 1);
493 modinit(L, modname);
495 lua_pushvalue(L, -1);
496 setfenv(L);
497 dooptions(L, loaded - 1);
498 return 0;
501 static int lj_cf_package_seeall(lua_State *L)
503 luaL_checktype(L, 1, LUA_TTABLE);
504 if (!lua_getmetatable(L, 1)) {
505 lua_createtable(L, 0, 1); /* create new metatable */
506 lua_pushvalue(L, -1);
507 lua_setmetatable(L, 1);
509 lua_pushvalue(L, LUA_GLOBALSINDEX);
510 lua_setfield(L, -2, "__index"); /* mt.__index = _G */
511 return 0;
514 /* ------------------------------------------------------------------------ */
516 #define AUXMARK "\1"
518 static void setpath(lua_State *L, const char *fieldname, const char *envname,
519 const char *def)
521 const char *path = getenv(envname);
522 if (path == NULL) {
523 lua_pushstring(L, def);
524 } else {
525 path = luaL_gsub(L, path, LUA_PATHSEP LUA_PATHSEP,
526 LUA_PATHSEP AUXMARK LUA_PATHSEP);
527 luaL_gsub(L, path, AUXMARK, def);
528 lua_remove(L, -2);
530 setprogdir(L);
531 lua_setfield(L, -2, fieldname);
534 static const luaL_Reg package_lib[] = {
535 { "loadlib", lj_cf_package_loadlib },
536 { "searchpath", lj_cf_package_searchpath },
537 { "seeall", lj_cf_package_seeall },
538 { NULL, NULL }
541 static const luaL_Reg package_global[] = {
542 { "module", lj_cf_package_module },
543 { "require", lj_cf_package_require },
544 { NULL, NULL }
547 static const lua_CFunction package_loaders[] =
549 lj_cf_package_loader_preload,
550 lj_cf_package_loader_lua,
551 lj_cf_package_loader_c,
552 lj_cf_package_loader_croot,
553 NULL
556 LUALIB_API int luaopen_package(lua_State *L)
558 int i;
559 luaL_newmetatable(L, "_LOADLIB");
560 lj_lib_pushcf(L, lj_cf_package_unloadlib, 1);
561 lua_setfield(L, -2, "__gc");
562 luaL_register(L, LUA_LOADLIBNAME, package_lib);
563 lua_pushvalue(L, -1);
564 lua_replace(L, LUA_ENVIRONINDEX);
565 lua_createtable(L, sizeof(package_loaders)/sizeof(package_loaders[0])-1, 0);
566 for (i = 0; package_loaders[i] != NULL; i++) {
567 lj_lib_pushcf(L, package_loaders[i], 1);
568 lua_rawseti(L, -2, i+1);
570 lua_setfield(L, -2, "loaders");
571 setpath(L, "path", LUA_PATH, LUA_PATH_DEFAULT);
572 setpath(L, "cpath", LUA_CPATH, LUA_CPATH_DEFAULT);
573 lua_pushliteral(L, LUA_PATH_CONFIG);
574 lua_setfield(L, -2, "config");
575 luaL_findtable(L, LUA_REGISTRYINDEX, "_LOADED", 16);
576 lua_setfield(L, -2, "loaded");
577 luaL_findtable(L, LUA_REGISTRYINDEX, "_PRELOAD", 4);
578 lua_setfield(L, -2, "preload");
579 lua_pushvalue(L, LUA_GLOBALSINDEX);
580 luaL_register(L, NULL, package_global);
581 lua_pop(L, 1);
582 return 1;