loadlib.c revision 344220
1276541Sdes/* 2276541Sdes** $Id: loadlib.c,v 1.130.1.1 2017/04/19 17:20:42 roberto Exp $ 3276541Sdes** Dynamic library loader for Lua 4276541Sdes** See Copyright Notice in lua.h 5276541Sdes** 6276541Sdes** This module contains an implementation of loadlib for Unix systems 7276541Sdes** that have dlfcn, an implementation for Windows, and a stub for other 8276541Sdes** systems. 9276541Sdes*/ 10276541Sdes 11276541Sdes#define loadlib_c 12276541Sdes#define LUA_LIB 13276541Sdes 14276541Sdes#include "lprefix.h" 15276541Sdes 16276541Sdes 17276541Sdes#include <stdio.h> 18276541Sdes#include <stdlib.h> 19276541Sdes#include <string.h> 20276541Sdes 21276541Sdes#include "lua.h" 22276541Sdes 23276541Sdes#include "lauxlib.h" 24276541Sdes#include "lualib.h" 25276541Sdes 26276541Sdes 27276541Sdes/* 28276541Sdes** LUA_IGMARK is a mark to ignore all before it when building the 29276541Sdes** luaopen_ function name. 30276541Sdes*/ 31276541Sdes#if !defined (LUA_IGMARK) 32276541Sdes#define LUA_IGMARK "-" 33294190Sdes#endif 34276541Sdes 35294190Sdes 36276541Sdes/* 37276541Sdes** LUA_CSUBSEP is the character that replaces dots in submodule names 38276541Sdes** when searching for a C loader. 39276541Sdes** LUA_LSUBSEP is the character that replaces dots in submodule names 40276541Sdes** when searching for a Lua loader. 41276541Sdes*/ 42276541Sdes#if !defined(LUA_CSUBSEP) 43276541Sdes#define LUA_CSUBSEP LUA_DIRSEP 44294190Sdes#endif 45276541Sdes 46276541Sdes#if !defined(LUA_LSUBSEP) 47276541Sdes#define LUA_LSUBSEP LUA_DIRSEP 48276541Sdes#endif 49294190Sdes 50294190Sdes 51294190Sdes/* prefix for open functions in C libraries */ 52276541Sdes#define LUA_POF "luaopen_" 53276541Sdes 54276541Sdes/* separator for open functions in C libraries */ 55276541Sdes#define LUA_OFSEP "_" 56276541Sdes 57276541Sdes 58276541Sdes/* 59276541Sdes** unique key for table in the registry that keeps handles 60276541Sdes** for all loaded C libraries 61276541Sdes*/ 62276541Sdesstatic const int CLIBS = 0; 63276541Sdes 64276541Sdes#define LIB_FAIL "open" 65276541Sdes 66276541Sdes 67276541Sdes#define setprogdir(L) ((void)0) 68276541Sdes 69276541Sdes 70276541Sdes/* 71276541Sdes** system-dependent functions 72276541Sdes*/ 73276541Sdes 74276541Sdes/* 75276541Sdes** unload library 'lib' 76276541Sdes*/ 77276541Sdesstatic void lsys_unloadlib (void *lib); 78276541Sdes 79276541Sdes/* 80276541Sdes** load C library in file 'path'. If 'seeglb', load with all names in 81276541Sdes** the library global. 82276541Sdes** Returns the library; in case of error, returns NULL plus an 83276541Sdes** error string in the stack. 84276541Sdes*/ 85276541Sdesstatic void *lsys_load (lua_State *L, const char *path, int seeglb); 86276541Sdes 87276541Sdes/* 88276541Sdes** Try to find a function named 'sym' in library 'lib'. 89276541Sdes** Returns the function; in case of error, returns NULL plus an 90276541Sdes** error string in the stack. 91276541Sdes*/ 92276541Sdesstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym); 93276541Sdes 94276541Sdes 95276541Sdes 96276541Sdes 97276541Sdes#if defined(LUA_USE_DLOPEN) /* { */ 98276541Sdes/* 99276541Sdes** {======================================================================== 100276541Sdes** This is an implementation of loadlib based on the dlfcn interface. 101276541Sdes** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD, 102276541Sdes** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least 103276541Sdes** as an emulation layer on top of native functions. 104276541Sdes** ========================================================================= 105276541Sdes*/ 106276541Sdes 107276541Sdes#include <dlfcn.h> 108276541Sdes 109276541Sdes/* 110276541Sdes** Macro to convert pointer-to-void* to pointer-to-function. This cast 111276541Sdes** is undefined according to ISO C, but POSIX assumes that it works. 112276541Sdes** (The '__extension__' in gnu compilers is only to avoid warnings.) 113276541Sdes*/ 114276541Sdes#if defined(__GNUC__) 115276541Sdes#define cast_func(p) (__extension__ (lua_CFunction)(p)) 116276541Sdes#else 117276541Sdes#define cast_func(p) ((lua_CFunction)(p)) 118276541Sdes#endif 119276541Sdes 120276541Sdes 121276541Sdesstatic void lsys_unloadlib (void *lib) { 122276541Sdes dlclose(lib); 123276541Sdes} 124276541Sdes 125276541Sdes 126276541Sdesstatic void *lsys_load (lua_State *L, const char *path, int seeglb) { 127276541Sdes void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL)); 128276541Sdes if (lib == NULL) lua_pushstring(L, dlerror()); 129276541Sdes return lib; 130276541Sdes} 131276541Sdes 132276541Sdes 133276541Sdesstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { 134276541Sdes lua_CFunction f = cast_func(dlsym(lib, sym)); 135276541Sdes if (f == NULL) lua_pushstring(L, dlerror()); 136276541Sdes return f; 137276541Sdes} 138276541Sdes 139276541Sdes/* }====================================================== */ 140276541Sdes 141276541Sdes 142276541Sdes 143276541Sdes#elif defined(LUA_DL_DLL) /* }{ */ 144276541Sdes/* 145276541Sdes** {====================================================================== 146276541Sdes** This is an implementation of loadlib for Windows using native functions. 147276541Sdes** ======================================================================= 148276541Sdes*/ 149276541Sdes 150276541Sdes#include <windows.h> 151276541Sdes 152276541Sdes 153276541Sdes/* 154276541Sdes** optional flags for LoadLibraryEx 155276541Sdes*/ 156276541Sdes#if !defined(LUA_LLE_FLAGS) 157276541Sdes#define LUA_LLE_FLAGS 0 158276541Sdes#endif 159276541Sdes 160276541Sdes 161276541Sdes#undef setprogdir 162276541Sdes 163276541Sdes 164276541Sdes/* 165276541Sdes** Replace in the path (on the top of the stack) any occurrence 166276541Sdes** of LUA_EXEC_DIR with the executable's path. 167276541Sdes*/ 168276541Sdesstatic void setprogdir (lua_State *L) { 169276541Sdes char buff[MAX_PATH + 1]; 170276541Sdes char *lb; 171276541Sdes DWORD nsize = sizeof(buff)/sizeof(char); 172276541Sdes DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */ 173276541Sdes if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL) 174276541Sdes luaL_error(L, "unable to get ModuleFileName"); 175276541Sdes else { 176276541Sdes *lb = '\0'; /* cut name on the last '\\' to get the path */ 177276541Sdes luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff); 178276541Sdes lua_remove(L, -2); /* remove original string */ 179276541Sdes } 180276541Sdes} 181276541Sdes 182276541Sdes 183276541Sdes 184276541Sdes 185276541Sdesstatic void pusherror (lua_State *L) { 186276541Sdes int error = GetLastError(); 187276541Sdes char buffer[128]; 188276541Sdes if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, 189276541Sdes NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL)) 190276541Sdes lua_pushstring(L, buffer); 191276541Sdes else 192276541Sdes lua_pushfstring(L, "system error %d\n", error); 193276541Sdes} 194276541Sdes 195276541Sdesstatic void lsys_unloadlib (void *lib) { 196276541Sdes FreeLibrary((HMODULE)lib); 197276541Sdes} 198276541Sdes 199276541Sdes 200276541Sdesstatic void *lsys_load (lua_State *L, const char *path, int seeglb) { 201276541Sdes HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS); 202276541Sdes (void)(seeglb); /* not used: symbols are 'global' by default */ 203276541Sdes if (lib == NULL) pusherror(L); 204276541Sdes return lib; 205276541Sdes} 206276541Sdes 207276541Sdes 208276541Sdesstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { 209276541Sdes lua_CFunction f = (lua_CFunction)GetProcAddress((HMODULE)lib, sym); 210276541Sdes if (f == NULL) pusherror(L); 211276541Sdes return f; 212276541Sdes} 213276541Sdes 214276541Sdes/* }====================================================== */ 215276541Sdes 216276541Sdes 217276541Sdes#else /* }{ */ 218276541Sdes/* 219276541Sdes** {====================================================== 220276541Sdes** Fallback for other systems 221276541Sdes** ======================================================= 222276541Sdes*/ 223276541Sdes 224276541Sdes#undef LIB_FAIL 225276541Sdes#define LIB_FAIL "absent" 226276541Sdes 227276541Sdes 228276541Sdes#define DLMSG "dynamic libraries not enabled; check your Lua installation" 229276541Sdes 230276541Sdes 231276541Sdesstatic void lsys_unloadlib (void *lib) { 232276541Sdes (void)(lib); /* not used */ 233276541Sdes} 234276541Sdes 235276541Sdes 236276541Sdesstatic void *lsys_load (lua_State *L, const char *path, int seeglb) { 237276541Sdes (void)(path); (void)(seeglb); /* not used */ 238276541Sdes lua_pushliteral(L, DLMSG); 239276541Sdes return NULL; 240276541Sdes} 241276541Sdes 242276541Sdes 243276541Sdesstatic lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) { 244276541Sdes (void)(lib); (void)(sym); /* not used */ 245276541Sdes lua_pushliteral(L, DLMSG); 246276541Sdes return NULL; 247276541Sdes} 248276541Sdes 249276541Sdes/* }====================================================== */ 250276541Sdes#endif /* } */ 251276541Sdes 252276541Sdes 253276541Sdes/* 254276541Sdes** {================================================================== 255276541Sdes** Set Paths 256276541Sdes** =================================================================== 257276541Sdes*/ 258276541Sdes 259276541Sdes/* 260276541Sdes** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment 261276541Sdes** variables that Lua check to set its paths. 262276541Sdes*/ 263276541Sdes#if !defined(LUA_PATH_VAR) 264276541Sdes#define LUA_PATH_VAR "LUA_PATH" 265276541Sdes#endif 266276541Sdes 267276541Sdes#if !defined(LUA_CPATH_VAR) 268276541Sdes#define LUA_CPATH_VAR "LUA_CPATH" 269276541Sdes#endif 270276541Sdes 271276541Sdes 272276541Sdes#define AUXMARK "\1" /* auxiliary mark */ 273276541Sdes 274276541Sdes 275276541Sdes/* 276276541Sdes** return registry.LUA_NOENV as a boolean 277276541Sdes*/ 278276541Sdesstatic int noenv (lua_State *L) { 279276541Sdes int b; 280276541Sdes lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV"); 281276541Sdes b = lua_toboolean(L, -1); 282276541Sdes lua_pop(L, 1); /* remove value */ 283276541Sdes return b; 284276541Sdes} 285276541Sdes 286276541Sdes 287276541Sdes/* 288276541Sdes** Set a path 289276541Sdes*/ 290276541Sdesstatic void setpath (lua_State *L, const char *fieldname, 291276541Sdes const char *envname, 292276541Sdes const char *dft) { 293276541Sdes const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX); 294276541Sdes const char *path = getenv(nver); /* use versioned name */ 295276541Sdes if (path == NULL) /* no environment variable? */ 296276541Sdes path = getenv(envname); /* try unversioned name */ 297276541Sdes if (path == NULL || noenv(L)) /* no environment variable? */ 298276541Sdes lua_pushstring(L, dft); /* use default */ 299276541Sdes else { 300276541Sdes /* replace ";;" by ";AUXMARK;" and then AUXMARK by default path */ 301276541Sdes path = luaL_gsub(L, path, LUA_PATH_SEP LUA_PATH_SEP, 302276541Sdes LUA_PATH_SEP AUXMARK LUA_PATH_SEP); 303276541Sdes luaL_gsub(L, path, AUXMARK, dft); 304276541Sdes lua_remove(L, -2); /* remove result from 1st 'gsub' */ 305276541Sdes } 306276541Sdes setprogdir(L); 307276541Sdes lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */ 308276541Sdes lua_pop(L, 1); /* pop versioned variable name */ 309276541Sdes} 310276541Sdes 311276541Sdes/* }================================================================== */ 312276541Sdes 313276541Sdes 314276541Sdes/* 315276541Sdes** return registry.CLIBS[path] 316276541Sdes*/ 317276541Sdesstatic void *checkclib (lua_State *L, const char *path) { 318276541Sdes void *plib; 319276541Sdes lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); 320276541Sdes lua_getfield(L, -1, path); 321276541Sdes plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */ 322276541Sdes lua_pop(L, 2); /* pop CLIBS table and 'plib' */ 323276541Sdes return plib; 324276541Sdes} 325276541Sdes 326276541Sdes 327276541Sdes/* 328276541Sdes** registry.CLIBS[path] = plib -- for queries 329276541Sdes** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries 330276541Sdes*/ 331276541Sdesstatic void addtoclib (lua_State *L, const char *path, void *plib) { 332276541Sdes lua_rawgetp(L, LUA_REGISTRYINDEX, &CLIBS); 333276541Sdes lua_pushlightuserdata(L, plib); 334276541Sdes lua_pushvalue(L, -1); 335276541Sdes lua_setfield(L, -3, path); /* CLIBS[path] = plib */ 336276541Sdes lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */ 337276541Sdes lua_pop(L, 1); /* pop CLIBS table */ 338276541Sdes} 339276541Sdes 340276541Sdes 341276541Sdes/* 342276541Sdes** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib 343276541Sdes** handles in list CLIBS 344276541Sdes*/ 345276541Sdesstatic int gctm (lua_State *L) { 346276541Sdes lua_Integer n = luaL_len(L, 1); 347276541Sdes for (; n >= 1; n--) { /* for each handle, in reverse order */ 348276541Sdes lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */ 349276541Sdes lsys_unloadlib(lua_touserdata(L, -1)); 350276541Sdes lua_pop(L, 1); /* pop handle */ 351276541Sdes } 352276541Sdes return 0; 353276541Sdes} 354276541Sdes 355276541Sdes 356276541Sdes 357276541Sdes/* error codes for 'lookforfunc' */ 358276541Sdes#define ERRLIB 1 359276541Sdes#define ERRFUNC 2 360276541Sdes 361276541Sdes/* 362276541Sdes** Look for a C function named 'sym' in a dynamically loaded library 363276541Sdes** 'path'. 364276541Sdes** First, check whether the library is already loaded; if not, try 365276541Sdes** to load it. 366276541Sdes** Then, if 'sym' is '*', return true (as library has been loaded). 367276541Sdes** Otherwise, look for symbol 'sym' in the library and push a 368276541Sdes** C function with that symbol. 369276541Sdes** Return 0 and 'true' or a function in the stack; in case of 370276541Sdes** errors, return an error code and an error message in the stack. 371276541Sdes*/ 372276541Sdesstatic int lookforfunc (lua_State *L, const char *path, const char *sym) { 373276541Sdes void *reg = checkclib(L, path); /* check loaded C libraries */ 374276541Sdes if (reg == NULL) { /* must load library? */ 375276541Sdes reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */ 376276541Sdes if (reg == NULL) return ERRLIB; /* unable to load library */ 377276541Sdes addtoclib(L, path, reg); 378276541Sdes } 379276541Sdes if (*sym == '*') { /* loading only library (no function)? */ 380276541Sdes lua_pushboolean(L, 1); /* return 'true' */ 381276541Sdes return 0; /* no errors */ 382276541Sdes } 383276541Sdes else { 384276541Sdes lua_CFunction f = lsys_sym(L, reg, sym); 385276541Sdes if (f == NULL) 386276541Sdes return ERRFUNC; /* unable to find function */ 387276541Sdes lua_pushcfunction(L, f); /* else create new function */ 388276541Sdes return 0; /* no errors */ 389276541Sdes } 390276541Sdes} 391276541Sdes 392276541Sdes 393276541Sdesstatic int ll_loadlib (lua_State *L) { 394276541Sdes const char *path = luaL_checkstring(L, 1); 395276541Sdes const char *init = luaL_checkstring(L, 2); 396276541Sdes int stat = lookforfunc(L, path, init); 397276541Sdes if (stat == 0) /* no errors? */ 398276541Sdes return 1; /* return the loaded function */ 399276541Sdes else { /* error; error message is on stack top */ 400276541Sdes lua_pushnil(L); 401276541Sdes lua_insert(L, -2); 402276541Sdes lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init"); 403276541Sdes return 3; /* return nil, error message, and where */ 404276541Sdes } 405276541Sdes} 406276541Sdes 407276541Sdes 408276541Sdes 409276541Sdes/* 410276541Sdes** {====================================================== 411276541Sdes** 'require' function 412276541Sdes** ======================================================= 413276541Sdes*/ 414276541Sdes 415276541Sdes 416276541Sdesstatic int readable (const char *filename) { 417276541Sdes FILE *f = fopen(filename, "r"); /* try to open file */ 418276541Sdes if (f == NULL) return 0; /* open failed */ 419276541Sdes fclose(f); 420276541Sdes return 1; 421276541Sdes} 422276541Sdes 423276541Sdes 424276541Sdesstatic const char *pushnexttemplate (lua_State *L, const char *path) { 425276541Sdes const char *l; 426276541Sdes while (*path == *LUA_PATH_SEP) path++; /* skip separators */ 427276541Sdes if (*path == '\0') return NULL; /* no more templates */ 428276541Sdes l = strchr(path, *LUA_PATH_SEP); /* find next separator */ 429276541Sdes if (l == NULL) l = path + strlen(path); 430276541Sdes lua_pushlstring(L, path, l - path); /* template */ 431276541Sdes return l; 432276541Sdes} 433276541Sdes 434276541Sdes 435276541Sdesstatic const char *searchpath (lua_State *L, const char *name, 436276541Sdes const char *path, 437276541Sdes const char *sep, 438276541Sdes const char *dirsep) { 439276541Sdes luaL_Buffer msg; /* to build error message */ 440276541Sdes luaL_buffinit(L, &msg); 441276541Sdes if (*sep != '\0') /* non-empty separator? */ 442 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */ 443 while ((path = pushnexttemplate(L, path)) != NULL) { 444 const char *filename = luaL_gsub(L, lua_tostring(L, -1), 445 LUA_PATH_MARK, name); 446 lua_remove(L, -2); /* remove path template */ 447 if (readable(filename)) /* does file exist and is readable? */ 448 return filename; /* return that file name */ 449 lua_pushfstring(L, "\n\tno file '%s'", filename); 450 lua_remove(L, -2); /* remove file name */ 451 luaL_addvalue(&msg); /* concatenate error msg. entry */ 452 } 453 luaL_pushresult(&msg); /* create error message */ 454 return NULL; /* not found */ 455} 456 457 458static int ll_searchpath (lua_State *L) { 459 const char *f = searchpath(L, luaL_checkstring(L, 1), 460 luaL_checkstring(L, 2), 461 luaL_optstring(L, 3, "."), 462 luaL_optstring(L, 4, LUA_DIRSEP)); 463 if (f != NULL) return 1; 464 else { /* error message is on top of the stack */ 465 lua_pushnil(L); 466 lua_insert(L, -2); 467 return 2; /* return nil + error message */ 468 } 469} 470 471 472static const char *findfile (lua_State *L, const char *name, 473 const char *pname, 474 const char *dirsep) { 475 const char *path; 476 lua_getfield(L, lua_upvalueindex(1), pname); 477 path = lua_tostring(L, -1); 478 if (path == NULL) 479 luaL_error(L, "'package.%s' must be a string", pname); 480 return searchpath(L, name, path, ".", dirsep); 481} 482 483 484static int checkload (lua_State *L, int stat, const char *filename) { 485 if (stat) { /* module loaded successfully? */ 486 lua_pushstring(L, filename); /* will be 2nd argument to module */ 487 return 2; /* return open function and file name */ 488 } 489 else 490 return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s", 491 lua_tostring(L, 1), filename, lua_tostring(L, -1)); 492} 493 494 495static int searcher_Lua (lua_State *L) { 496 const char *filename; 497 const char *name = luaL_checkstring(L, 1); 498 filename = findfile(L, name, "path", LUA_LSUBSEP); 499 if (filename == NULL) return 1; /* module not found in this path */ 500 return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename); 501} 502 503 504/* 505** Try to find a load function for module 'modname' at file 'filename'. 506** First, change '.' to '_' in 'modname'; then, if 'modname' has 507** the form X-Y (that is, it has an "ignore mark"), build a function 508** name "luaopen_X" and look for it. (For compatibility, if that 509** fails, it also tries "luaopen_Y".) If there is no ignore mark, 510** look for a function named "luaopen_modname". 511*/ 512static int loadfunc (lua_State *L, const char *filename, const char *modname) { 513 const char *openfunc; 514 const char *mark; 515 modname = luaL_gsub(L, modname, ".", LUA_OFSEP); 516 mark = strchr(modname, *LUA_IGMARK); 517 if (mark) { 518 int stat; 519 openfunc = lua_pushlstring(L, modname, mark - modname); 520 openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc); 521 stat = lookforfunc(L, filename, openfunc); 522 if (stat != ERRFUNC) return stat; 523 modname = mark + 1; /* else go ahead and try old-style name */ 524 } 525 openfunc = lua_pushfstring(L, LUA_POF"%s", modname); 526 return lookforfunc(L, filename, openfunc); 527} 528 529 530static int searcher_C (lua_State *L) { 531 const char *name = luaL_checkstring(L, 1); 532 const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP); 533 if (filename == NULL) return 1; /* module not found in this path */ 534 return checkload(L, (loadfunc(L, filename, name) == 0), filename); 535} 536 537 538static int searcher_Croot (lua_State *L) { 539 const char *filename; 540 const char *name = luaL_checkstring(L, 1); 541 const char *p = strchr(name, '.'); 542 int stat; 543 if (p == NULL) return 0; /* is root */ 544 lua_pushlstring(L, name, p - name); 545 filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP); 546 if (filename == NULL) return 1; /* root not found */ 547 if ((stat = loadfunc(L, filename, name)) != 0) { 548 if (stat != ERRFUNC) 549 return checkload(L, 0, filename); /* real error */ 550 else { /* open function not found */ 551 lua_pushfstring(L, "\n\tno module '%s' in file '%s'", name, filename); 552 return 1; 553 } 554 } 555 lua_pushstring(L, filename); /* will be 2nd argument to module */ 556 return 2; 557} 558 559 560static int searcher_preload (lua_State *L) { 561 const char *name = luaL_checkstring(L, 1); 562 lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); 563 if (lua_getfield(L, -1, name) == LUA_TNIL) /* not found? */ 564 lua_pushfstring(L, "\n\tno field package.preload['%s']", name); 565 return 1; 566} 567 568 569static void findloader (lua_State *L, const char *name) { 570 int i; 571 luaL_Buffer msg; /* to build error message */ 572 luaL_buffinit(L, &msg); 573 /* push 'package.searchers' to index 3 in the stack */ 574 if (lua_getfield(L, lua_upvalueindex(1), "searchers") != LUA_TTABLE) 575 luaL_error(L, "'package.searchers' must be a table"); 576 /* iterate over available searchers to find a loader */ 577 for (i = 1; ; i++) { 578 if (lua_rawgeti(L, 3, i) == LUA_TNIL) { /* no more searchers? */ 579 lua_pop(L, 1); /* remove nil */ 580 luaL_pushresult(&msg); /* create error message */ 581 luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1)); 582 } 583 lua_pushstring(L, name); 584 lua_call(L, 1, 2); /* call it */ 585 if (lua_isfunction(L, -2)) /* did it find a loader? */ 586 return; /* module loader found */ 587 else if (lua_isstring(L, -2)) { /* searcher returned error message? */ 588 lua_pop(L, 1); /* remove extra return */ 589 luaL_addvalue(&msg); /* concatenate error message */ 590 } 591 else 592 lua_pop(L, 2); /* remove both returns */ 593 } 594} 595 596 597static int ll_require (lua_State *L) { 598 const char *name = luaL_checkstring(L, 1); 599 lua_settop(L, 1); /* LOADED table will be at index 2 */ 600 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); 601 lua_getfield(L, 2, name); /* LOADED[name] */ 602 if (lua_toboolean(L, -1)) /* is it there? */ 603 return 1; /* package is already loaded */ 604 /* else must load package */ 605 lua_pop(L, 1); /* remove 'getfield' result */ 606 findloader(L, name); 607 lua_pushstring(L, name); /* pass name as argument to module loader */ 608 lua_insert(L, -2); /* name is 1st argument (before search data) */ 609 lua_call(L, 2, 1); /* run loader to load module */ 610 if (!lua_isnil(L, -1)) /* non-nil return? */ 611 lua_setfield(L, 2, name); /* LOADED[name] = returned value */ 612 if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */ 613 lua_pushboolean(L, 1); /* use true as result */ 614 lua_pushvalue(L, -1); /* extra copy to be returned */ 615 lua_setfield(L, 2, name); /* LOADED[name] = true */ 616 } 617 return 1; 618} 619 620/* }====================================================== */ 621 622 623 624/* 625** {====================================================== 626** 'module' function 627** ======================================================= 628*/ 629#if defined(LUA_COMPAT_MODULE) 630 631/* 632** changes the environment variable of calling function 633*/ 634static void set_env (lua_State *L) { 635 lua_Debug ar; 636 if (lua_getstack(L, 1, &ar) == 0 || 637 lua_getinfo(L, "f", &ar) == 0 || /* get calling function */ 638 lua_iscfunction(L, -1)) 639 luaL_error(L, "'module' not called from a Lua function"); 640 lua_pushvalue(L, -2); /* copy new environment table to top */ 641 lua_setupvalue(L, -2, 1); 642 lua_pop(L, 1); /* remove function */ 643} 644 645 646static void dooptions (lua_State *L, int n) { 647 int i; 648 for (i = 2; i <= n; i++) { 649 if (lua_isfunction(L, i)) { /* avoid 'calling' extra info. */ 650 lua_pushvalue(L, i); /* get option (a function) */ 651 lua_pushvalue(L, -2); /* module */ 652 lua_call(L, 1, 0); 653 } 654 } 655} 656 657 658static void modinit (lua_State *L, const char *modname) { 659 const char *dot; 660 lua_pushvalue(L, -1); 661 lua_setfield(L, -2, "_M"); /* module._M = module */ 662 lua_pushstring(L, modname); 663 lua_setfield(L, -2, "_NAME"); 664 dot = strrchr(modname, '.'); /* look for last dot in module name */ 665 if (dot == NULL) dot = modname; 666 else dot++; 667 /* set _PACKAGE as package name (full module name minus last part) */ 668 lua_pushlstring(L, modname, dot - modname); 669 lua_setfield(L, -2, "_PACKAGE"); 670} 671 672 673static int ll_module (lua_State *L) { 674 const char *modname = luaL_checkstring(L, 1); 675 int lastarg = lua_gettop(L); /* last parameter */ 676 luaL_pushmodule(L, modname, 1); /* get/create module table */ 677 /* check whether table already has a _NAME field */ 678 if (lua_getfield(L, -1, "_NAME") != LUA_TNIL) 679 lua_pop(L, 1); /* table is an initialized module */ 680 else { /* no; initialize it */ 681 lua_pop(L, 1); 682 modinit(L, modname); 683 } 684 lua_pushvalue(L, -1); 685 set_env(L); 686 dooptions(L, lastarg); 687 return 1; 688} 689 690 691static int ll_seeall (lua_State *L) { 692 luaL_checktype(L, 1, LUA_TTABLE); 693 if (!lua_getmetatable(L, 1)) { 694 lua_createtable(L, 0, 1); /* create new metatable */ 695 lua_pushvalue(L, -1); 696 lua_setmetatable(L, 1); 697 } 698 lua_pushglobaltable(L); 699 lua_setfield(L, -2, "__index"); /* mt.__index = _G */ 700 return 0; 701} 702 703#endif 704/* }====================================================== */ 705 706 707 708static const luaL_Reg pk_funcs[] = { 709 {"loadlib", ll_loadlib}, 710 {"searchpath", ll_searchpath}, 711#if defined(LUA_COMPAT_MODULE) 712 {"seeall", ll_seeall}, 713#endif 714 /* placeholders */ 715 {"preload", NULL}, 716 {"cpath", NULL}, 717 {"path", NULL}, 718 {"searchers", NULL}, 719 {"loaded", NULL}, 720 {NULL, NULL} 721}; 722 723 724static const luaL_Reg ll_funcs[] = { 725#if defined(LUA_COMPAT_MODULE) 726 {"module", ll_module}, 727#endif 728 {"require", ll_require}, 729 {NULL, NULL} 730}; 731 732 733static void createsearcherstable (lua_State *L) { 734 static const lua_CFunction searchers[] = 735 {searcher_preload, searcher_Lua, searcher_C, searcher_Croot, NULL}; 736 int i; 737 /* create 'searchers' table */ 738 lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0); 739 /* fill it with predefined searchers */ 740 for (i=0; searchers[i] != NULL; i++) { 741 lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */ 742 lua_pushcclosure(L, searchers[i], 1); 743 lua_rawseti(L, -2, i+1); 744 } 745#if defined(LUA_COMPAT_LOADERS) 746 lua_pushvalue(L, -1); /* make a copy of 'searchers' table */ 747 lua_setfield(L, -3, "loaders"); /* put it in field 'loaders' */ 748#endif 749 lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */ 750} 751 752 753/* 754** create table CLIBS to keep track of loaded C libraries, 755** setting a finalizer to close all libraries when closing state. 756*/ 757static void createclibstable (lua_State *L) { 758 lua_newtable(L); /* create CLIBS table */ 759 lua_createtable(L, 0, 1); /* create metatable for CLIBS */ 760 lua_pushcfunction(L, gctm); 761 lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */ 762 lua_setmetatable(L, -2); 763 lua_rawsetp(L, LUA_REGISTRYINDEX, &CLIBS); /* set CLIBS table in registry */ 764} 765 766 767LUAMOD_API int luaopen_package (lua_State *L) { 768 createclibstable(L); 769 luaL_newlib(L, pk_funcs); /* create 'package' table */ 770 createsearcherstable(L); 771 /* set paths */ 772 setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT); 773 setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT); 774 /* store config information */ 775 lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n" 776 LUA_EXEC_DIR "\n" LUA_IGMARK "\n"); 777 lua_setfield(L, -2, "config"); 778 /* set field 'loaded' */ 779 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE); 780 lua_setfield(L, -2, "loaded"); 781 /* set field 'preload' */ 782 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE); 783 lua_setfield(L, -2, "preload"); 784 lua_pushglobaltable(L); 785 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */ 786 luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */ 787 lua_pop(L, 1); /* pop global table */ 788 return 1; /* return 'package' table */ 789} 790 791