1 /* $NetBSD: loadlib.c,v 1.11 2023/06/08 21:12:08 nikita Exp $ */
2
3 /*
4 ** Id: loadlib.c
5 ** Dynamic library loader for Lua
6 ** See Copyright Notice in lua.h
7 **
8 ** This module contains an implementation of loadlib for Unix systems
9 ** that have dlfcn, an implementation for Windows, and a stub for other
10 ** systems.
11 */
12
13 #define loadlib_c
14 #define LUA_LIB
15
16 #include "lprefix.h"
17
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <string.h>
22
23 #include "lua.h"
24
25 #include "lauxlib.h"
26 #include "lualib.h"
27
28
29 /*
30 ** LUA_IGMARK is a mark to ignore all before it when building the
31 ** luaopen_ function name.
32 */
33 #if !defined (LUA_IGMARK)
34 #define LUA_IGMARK "-"
35 #endif
36
37
38 /*
39 ** LUA_CSUBSEP is the character that replaces dots in submodule names
40 ** when searching for a C loader.
41 ** LUA_LSUBSEP is the character that replaces dots in submodule names
42 ** when searching for a Lua loader.
43 */
44 #if !defined(LUA_CSUBSEP)
45 #define LUA_CSUBSEP LUA_DIRSEP
46 #endif
47
48 #if !defined(LUA_LSUBSEP)
49 #define LUA_LSUBSEP LUA_DIRSEP
50 #endif
51
52
53 /* prefix for open functions in C libraries */
54 #define LUA_POF "luaopen_"
55
56 /* separator for open functions in C libraries */
57 #define LUA_OFSEP "_"
58
59
60 /*
61 ** key for table in the registry that keeps handles
62 ** for all loaded C libraries
63 */
64 static const char *const CLIBS = "_CLIBS";
65
66 #define LIB_FAIL "open"
67
68
69 #define setprogdir(L) ((void)0)
70
71
72 /*
73 ** Special type equivalent to '(void*)' for functions in gcc
74 ** (to suppress warnings when converting function pointers)
75 */
76 typedef void (*voidf)(void);
77
78
79 /*
80 ** system-dependent functions
81 */
82
83 /*
84 ** unload library 'lib'
85 */
86 static void lsys_unloadlib (void *lib);
87
88 /*
89 ** load C library in file 'path'. If 'seeglb', load with all names in
90 ** the library global.
91 ** Returns the library; in case of error, returns NULL plus an
92 ** error string in the stack.
93 */
94 static void *lsys_load (lua_State *L, const char *path, int seeglb);
95
96 /*
97 ** Try to find a function named 'sym' in library 'lib'.
98 ** Returns the function; in case of error, returns NULL plus an
99 ** error string in the stack.
100 */
101 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym);
102
103
104
105
106 #if defined(LUA_USE_DLOPEN) /* { */
107 /*
108 ** {========================================================================
109 ** This is an implementation of loadlib based on the dlfcn interface.
110 ** The dlfcn interface is available in Linux, SunOS, Solaris, IRIX, FreeBSD,
111 ** NetBSD, AIX 4.2, HPUX 11, and probably most other Unix flavors, at least
112 ** as an emulation layer on top of native functions.
113 ** =========================================================================
114 */
115
116 #include <dlfcn.h>
117
118 /*
119 ** Macro to convert pointer-to-void* to pointer-to-function. This cast
120 ** is undefined according to ISO C, but POSIX assumes that it works.
121 ** (The '__extension__' in gnu compilers is only to avoid warnings.)
122 */
123 #if defined(__GNUC__)
124 #define cast_func(p) (__extension__ (lua_CFunction)(p))
125 #else
126 #define cast_func(p) ((lua_CFunction)(p))
127 #endif
128
129
lsys_unloadlib(void * lib)130 static void lsys_unloadlib (void *lib) {
131 dlclose(lib);
132 }
133
134
lsys_load(lua_State * L,const char * path,int seeglb)135 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
136 void *lib = dlopen(path, RTLD_NOW | (seeglb ? RTLD_GLOBAL : RTLD_LOCAL));
137 if (l_unlikely(lib == NULL))
138 lua_pushstring(L, dlerror());
139 return lib;
140 }
141
142
lsys_sym(lua_State * L,void * lib,const char * sym)143 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
144 lua_CFunction f = cast_func(dlsym(lib, sym));
145 if (l_unlikely(f == NULL))
146 lua_pushstring(L, dlerror());
147 return f;
148 }
149
150 /* }====================================================== */
151
152
153
154 #elif defined(LUA_DL_DLL) /* }{ */
155 /*
156 ** {======================================================================
157 ** This is an implementation of loadlib for Windows using native functions.
158 ** =======================================================================
159 */
160
161 #include <windows.h>
162
163
164 /*
165 ** optional flags for LoadLibraryEx
166 */
167 #if !defined(LUA_LLE_FLAGS)
168 #define LUA_LLE_FLAGS 0
169 #endif
170
171
172 #undef setprogdir
173
174
175 /*
176 ** Replace in the path (on the top of the stack) any occurrence
177 ** of LUA_EXEC_DIR with the executable's path.
178 */
setprogdir(lua_State * L)179 static void setprogdir (lua_State *L) {
180 char buff[MAX_PATH + 1];
181 char *lb;
182 DWORD nsize = sizeof(buff)/sizeof(char);
183 DWORD n = GetModuleFileNameA(NULL, buff, nsize); /* get exec. name */
184 if (n == 0 || n == nsize || (lb = strrchr(buff, '\\')) == NULL)
185 luaL_error(L, "unable to get ModuleFileName");
186 else {
187 *lb = '\0'; /* cut name on the last '\\' to get the path */
188 luaL_gsub(L, lua_tostring(L, -1), LUA_EXEC_DIR, buff);
189 lua_remove(L, -2); /* remove original string */
190 }
191 }
192
193
194
195
pusherror(lua_State * L)196 static void pusherror (lua_State *L) {
197 int error = GetLastError();
198 char buffer[128];
199 if (FormatMessageA(FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM,
200 NULL, error, 0, buffer, sizeof(buffer)/sizeof(char), NULL))
201 lua_pushstring(L, buffer);
202 else
203 lua_pushfstring(L, "system error %d\n", error);
204 }
205
lsys_unloadlib(void * lib)206 static void lsys_unloadlib (void *lib) {
207 FreeLibrary((HMODULE)lib);
208 }
209
210
lsys_load(lua_State * L,const char * path,int seeglb)211 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
212 HMODULE lib = LoadLibraryExA(path, NULL, LUA_LLE_FLAGS);
213 (void)(seeglb); /* not used: symbols are 'global' by default */
214 if (lib == NULL) pusherror(L);
215 return lib;
216 }
217
218
lsys_sym(lua_State * L,void * lib,const char * sym)219 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
220 lua_CFunction f = (lua_CFunction)(voidf)GetProcAddress((HMODULE)lib, sym);
221 if (f == NULL) pusherror(L);
222 return f;
223 }
224
225 /* }====================================================== */
226
227
228 #else /* }{ */
229 /*
230 ** {======================================================
231 ** Fallback for other systems
232 ** =======================================================
233 */
234
235 #undef LIB_FAIL
236 #define LIB_FAIL "absent"
237
238
239 #define DLMSG "dynamic libraries not enabled; check your Lua installation"
240
241
lsys_unloadlib(void * lib)242 static void lsys_unloadlib (void *lib) {
243 (void)(lib); /* not used */
244 }
245
246
lsys_load(lua_State * L,const char * path,int seeglb)247 static void *lsys_load (lua_State *L, const char *path, int seeglb) {
248 (void)(path); (void)(seeglb); /* not used */
249 lua_pushliteral(L, DLMSG);
250 return NULL;
251 }
252
253
lsys_sym(lua_State * L,void * lib,const char * sym)254 static lua_CFunction lsys_sym (lua_State *L, void *lib, const char *sym) {
255 (void)(lib); (void)(sym); /* not used */
256 lua_pushliteral(L, DLMSG);
257 return NULL;
258 }
259
260 /* }====================================================== */
261 #endif /* } */
262
263
264 /*
265 ** {==================================================================
266 ** Set Paths
267 ** ===================================================================
268 */
269
270 /*
271 ** LUA_PATH_VAR and LUA_CPATH_VAR are the names of the environment
272 ** variables that Lua check to set its paths.
273 */
274 #if !defined(LUA_PATH_VAR)
275 #define LUA_PATH_VAR "LUA_PATH"
276 #endif
277
278 #if !defined(LUA_CPATH_VAR)
279 #define LUA_CPATH_VAR "LUA_CPATH"
280 #endif
281
282
283
284 /*
285 ** return registry.LUA_NOENV as a boolean
286 */
noenv(lua_State * L)287 static int noenv (lua_State *L) {
288 int b;
289 lua_getfield(L, LUA_REGISTRYINDEX, "LUA_NOENV");
290 b = lua_toboolean(L, -1);
291 lua_pop(L, 1); /* remove value */
292 return b;
293 }
294
295
296 /*
297 ** Set a path
298 */
setpath(lua_State * L,const char * fieldname,const char * envname,const char * dft)299 static void setpath (lua_State *L, const char *fieldname,
300 const char *envname,
301 const char *dft) {
302 const char *dftmark;
303 const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX);
304 const char *path = getenv(nver); /* try versioned name */
305 if (path == NULL) /* no versioned environment variable? */
306 path = getenv(envname); /* try unversioned name */
307 if (path == NULL || noenv(L)) /* no environment variable? */
308 lua_pushstring(L, dft); /* use default */
309 else if ((dftmark = strstr(path, LUA_PATH_SEP LUA_PATH_SEP)) == NULL)
310 lua_pushstring(L, path); /* nothing to change */
311 else { /* path contains a ";;": insert default path in its place */
312 size_t len = strlen(path);
313 luaL_Buffer b;
314 luaL_buffinit(L, &b);
315 if (path < dftmark) { /* is there a prefix before ';;'? */
316 luaL_addlstring(&b, path, dftmark - path); /* add it */
317 luaL_addchar(&b, *LUA_PATH_SEP);
318 }
319 luaL_addstring(&b, dft); /* add default */
320 if (dftmark < path + len - 2) { /* is there a suffix after ';;'? */
321 luaL_addchar(&b, *LUA_PATH_SEP);
322 luaL_addlstring(&b, dftmark + 2, (path + len - 2) - dftmark);
323 }
324 luaL_pushresult(&b);
325 }
326 setprogdir(L);
327 lua_setfield(L, -3, fieldname); /* package[fieldname] = path value */
328 lua_pop(L, 1); /* pop versioned variable name ('nver') */
329 }
330
331 /* }================================================================== */
332
333
334 /*
335 ** return registry.CLIBS[path]
336 */
checkclib(lua_State * L,const char * path)337 static void *checkclib (lua_State *L, const char *path) {
338 void *plib;
339 lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
340 lua_getfield(L, -1, path);
341 plib = lua_touserdata(L, -1); /* plib = CLIBS[path] */
342 lua_pop(L, 2); /* pop CLIBS table and 'plib' */
343 return plib;
344 }
345
346
347 /*
348 ** registry.CLIBS[path] = plib -- for queries
349 ** registry.CLIBS[#CLIBS + 1] = plib -- also keep a list of all libraries
350 */
addtoclib(lua_State * L,const char * path,void * plib)351 static void addtoclib (lua_State *L, const char *path, void *plib) {
352 lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
353 lua_pushlightuserdata(L, plib);
354 lua_pushvalue(L, -1);
355 lua_setfield(L, -3, path); /* CLIBS[path] = plib */
356 lua_rawseti(L, -2, luaL_len(L, -2) + 1); /* CLIBS[#CLIBS + 1] = plib */
357 lua_pop(L, 1); /* pop CLIBS table */
358 }
359
360
361 /*
362 ** __gc tag method for CLIBS table: calls 'lsys_unloadlib' for all lib
363 ** handles in list CLIBS
364 */
gctm(lua_State * L)365 static int gctm (lua_State *L) {
366 lua_Integer n = luaL_len(L, 1);
367 for (; n >= 1; n--) { /* for each handle, in reverse order */
368 lua_rawgeti(L, 1, n); /* get handle CLIBS[n] */
369 lsys_unloadlib(lua_touserdata(L, -1));
370 lua_pop(L, 1); /* pop handle */
371 }
372 return 0;
373 }
374
375
376
377 /* error codes for 'lookforfunc' */
378 #define ERRLIB 1
379 #define ERRFUNC 2
380
381 /*
382 ** Look for a C function named 'sym' in a dynamically loaded library
383 ** 'path'.
384 ** First, check whether the library is already loaded; if not, try
385 ** to load it.
386 ** Then, if 'sym' is '*', return true (as library has been loaded).
387 ** Otherwise, look for symbol 'sym' in the library and push a
388 ** C function with that symbol.
389 ** Return 0 and 'true' or a function in the stack; in case of
390 ** errors, return an error code and an error message in the stack.
391 */
lookforfunc(lua_State * L,const char * path,const char * sym)392 static int lookforfunc (lua_State *L, const char *path, const char *sym) {
393 void *reg = checkclib(L, path); /* check loaded C libraries */
394 if (reg == NULL) { /* must load library? */
395 reg = lsys_load(L, path, *sym == '*'); /* global symbols if 'sym'=='*' */
396 if (reg == NULL) return ERRLIB; /* unable to load library */
397 addtoclib(L, path, reg);
398 }
399 if (*sym == '*') { /* loading only library (no function)? */
400 lua_pushboolean(L, 1); /* return 'true' */
401 return 0; /* no errors */
402 }
403 else {
404 lua_CFunction f = lsys_sym(L, reg, sym);
405 if (f == NULL)
406 return ERRFUNC; /* unable to find function */
407 lua_pushcfunction(L, f); /* else create new function */
408 return 0; /* no errors */
409 }
410 }
411
412
ll_loadlib(lua_State * L)413 static int ll_loadlib (lua_State *L) {
414 const char *path = luaL_checkstring(L, 1);
415 const char *init = luaL_checkstring(L, 2);
416 int stat = lookforfunc(L, path, init);
417 if (l_likely(stat == 0)) /* no errors? */
418 return 1; /* return the loaded function */
419 else { /* error; error message is on stack top */
420 luaL_pushfail(L);
421 lua_insert(L, -2);
422 lua_pushstring(L, (stat == ERRLIB) ? LIB_FAIL : "init");
423 return 3; /* return fail, error message, and where */
424 }
425 }
426
427
428
429 /*
430 ** {======================================================
431 ** 'require' function
432 ** =======================================================
433 */
434
435
readable(const char * filename)436 static int readable (const char *filename) {
437 FILE *f = fopen(filename, "r"); /* try to open file */
438 if (f == NULL) return 0; /* open failed */
439 fclose(f);
440 return 1;
441 }
442
443
444 /*
445 ** Get the next name in '*path' = 'name1;name2;name3;...', changing
446 ** the ending ';' to '\0' to create a zero-terminated string. Return
447 ** NULL when list ends.
448 */
getnextfilename(char ** path,char * end)449 static const char *getnextfilename (char **path, char *end) {
450 char *sep;
451 char *name = *path;
452 if (name == end)
453 return NULL; /* no more names */
454 else if (*name == '\0') { /* from previous iteration? */
455 *name = *LUA_PATH_SEP; /* restore separator */
456 name++; /* skip it */
457 }
458 sep = strchr(name, *LUA_PATH_SEP); /* find next separator */
459 if (sep == NULL) /* separator not found? */
460 sep = end; /* name goes until the end */
461 *sep = '\0'; /* finish file name */
462 *path = sep; /* will start next search from here */
463 return name;
464 }
465
466
467 /*
468 ** Given a path such as ";blabla.so;blublu.so", pushes the string
469 **
470 ** no file 'blabla.so'
471 ** no file 'blublu.so'
472 */
pusherrornotfound(lua_State * L,const char * path)473 static void pusherrornotfound (lua_State *L, const char *path) {
474 luaL_Buffer b;
475 luaL_buffinit(L, &b);
476 luaL_addstring(&b, "no file '");
477 luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
478 luaL_addstring(&b, "'");
479 luaL_pushresult(&b);
480 }
481
482
searchpath(lua_State * L,const char * name,const char * path,const char * sep,const char * dirsep)483 static const char *searchpath (lua_State *L, const char *name,
484 const char *path,
485 const char *sep,
486 const char *dirsep) {
487 luaL_Buffer buff;
488 char *pathname; /* path with name inserted */
489 char *endpathname; /* its end */
490 const char *filename;
491 /* separator is non-empty and appears in 'name'? */
492 if (*sep != '\0' && strchr(name, *sep) != NULL)
493 name = luaL_gsub(L, name, sep, dirsep); /* replace it by 'dirsep' */
494 luaL_buffinit(L, &buff);
495 /* add path to the buffer, replacing marks ('?') with the file name */
496 luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
497 luaL_addchar(&buff, '\0');
498 pathname = luaL_buffaddr(&buff); /* writable list of file names */
499 endpathname = pathname + luaL_bufflen(&buff) - 1;
500 while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
501 if (readable(filename)) /* does file exist and is readable? */
502 return lua_pushstring(L, filename); /* save and return name */
503 }
504 luaL_pushresult(&buff); /* push path to create error message */
505 pusherrornotfound(L, lua_tostring(L, -1)); /* create error message */
506 return NULL; /* not found */
507 }
508
509
ll_searchpath(lua_State * L)510 static int ll_searchpath (lua_State *L) {
511 const char *f = searchpath(L, luaL_checkstring(L, 1),
512 luaL_checkstring(L, 2),
513 luaL_optstring(L, 3, "."),
514 luaL_optstring(L, 4, LUA_DIRSEP));
515 if (f != NULL) return 1;
516 else { /* error message is on top of the stack */
517 luaL_pushfail(L);
518 lua_insert(L, -2);
519 return 2; /* return fail + error message */
520 }
521 }
522
523
findfile(lua_State * L,const char * name,const char * pname,const char * dirsep)524 static const char *findfile (lua_State *L, const char *name,
525 const char *pname,
526 const char *dirsep) {
527 const char *path;
528 lua_getfield(L, lua_upvalueindex(1), pname);
529 path = lua_tostring(L, -1);
530 if (l_unlikely(path == NULL))
531 luaL_error(L, "'package.%s' must be a string", pname);
532 return searchpath(L, name, path, ".", dirsep);
533 }
534
535
checkload(lua_State * L,int stat,const char * filename)536 static int checkload (lua_State *L, int stat, const char *filename) {
537 if (l_likely(stat)) { /* module loaded successfully? */
538 lua_pushstring(L, filename); /* will be 2nd argument to module */
539 return 2; /* return open function and file name */
540 }
541 else
542 return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
543 lua_tostring(L, 1), filename, lua_tostring(L, -1));
544 }
545
546
searcher_Lua(lua_State * L)547 static int searcher_Lua (lua_State *L) {
548 const char *filename;
549 const char *name = luaL_checkstring(L, 1);
550 filename = findfile(L, name, "path", LUA_LSUBSEP);
551 if (filename == NULL) return 1; /* module not found in this path */
552 return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
553 }
554
555
556 /*
557 ** Try to find a load function for module 'modname' at file 'filename'.
558 ** First, change '.' to '_' in 'modname'; then, if 'modname' has
559 ** the form X-Y (that is, it has an "ignore mark"), build a function
560 ** name "luaopen_X" and look for it. (For compatibility, if that
561 ** fails, it also tries "luaopen_Y".) If there is no ignore mark,
562 ** look for a function named "luaopen_modname".
563 */
loadfunc(lua_State * L,const char * filename,const char * modname)564 static int loadfunc (lua_State *L, const char *filename, const char *modname) {
565 const char *openfunc;
566 const char *mark;
567 modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
568 mark = strchr(modname, *LUA_IGMARK);
569 if (mark) {
570 int stat;
571 openfunc = lua_pushlstring(L, modname, mark - modname);
572 openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
573 stat = lookforfunc(L, filename, openfunc);
574 if (stat != ERRFUNC) return stat;
575 modname = mark + 1; /* else go ahead and try old-style name */
576 }
577 openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
578 return lookforfunc(L, filename, openfunc);
579 }
580
581
searcher_C(lua_State * L)582 static int searcher_C (lua_State *L) {
583 const char *name = luaL_checkstring(L, 1);
584 const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
585 if (filename == NULL) return 1; /* module not found in this path */
586 return checkload(L, (loadfunc(L, filename, name) == 0), filename);
587 }
588
589
searcher_Croot(lua_State * L)590 static int searcher_Croot (lua_State *L) {
591 const char *filename;
592 const char *name = luaL_checkstring(L, 1);
593 const char *p = strchr(name, '.');
594 int stat;
595 if (p == NULL) return 0; /* is root */
596 lua_pushlstring(L, name, p - name);
597 filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
598 if (filename == NULL) return 1; /* root not found */
599 if ((stat = loadfunc(L, filename, name)) != 0) {
600 if (stat != ERRFUNC)
601 return checkload(L, 0, filename); /* real error */
602 else { /* open function not found */
603 lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
604 return 1;
605 }
606 }
607 lua_pushstring(L, filename); /* will be 2nd argument to module */
608 return 2;
609 }
610
611
searcher_preload(lua_State * L)612 static int searcher_preload (lua_State *L) {
613 const char *name = luaL_checkstring(L, 1);
614 lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
615 if (lua_getfield(L, -1, name) == LUA_TNIL) { /* not found? */
616 lua_pushfstring(L, "no field package.preload['%s']", name);
617 return 1;
618 }
619 else {
620 lua_pushliteral(L, ":preload:");
621 return 2;
622 }
623 }
624
625
findloader(lua_State * L,const char * name)626 static void findloader (lua_State *L, const char *name) {
627 int i;
628 luaL_Buffer msg; /* to build error message */
629 /* push 'package.searchers' to index 3 in the stack */
630 if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
631 != LUA_TTABLE))
632 luaL_error(L, "'package.searchers' must be a table");
633 luaL_buffinit(L, &msg);
634 /* iterate over available searchers to find a loader */
635 for (i = 1; ; i++) {
636 luaL_addstring(&msg, "\n\t"); /* error-message prefix */
637 if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) { /* no more searchers? */
638 lua_pop(L, 1); /* remove nil */
639 luaL_buffsub(&msg, 2); /* remove prefix */
640 luaL_pushresult(&msg); /* create error message */
641 luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
642 }
643 lua_pushstring(L, name);
644 lua_call(L, 1, 2); /* call it */
645 if (lua_isfunction(L, -2)) /* did it find a loader? */
646 return; /* module loader found */
647 else if (lua_isstring(L, -2)) { /* searcher returned error message? */
648 lua_pop(L, 1); /* remove extra return */
649 luaL_addvalue(&msg); /* concatenate error message */
650 }
651 else { /* no error message */
652 lua_pop(L, 2); /* remove both returns */
653 luaL_buffsub(&msg, 2); /* remove prefix */
654 }
655 }
656 }
657
658
ll_require(lua_State * L)659 static int ll_require (lua_State *L) {
660 const char *name = luaL_checkstring(L, 1);
661 lua_settop(L, 1); /* LOADED table will be at index 2 */
662 lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
663 lua_getfield(L, 2, name); /* LOADED[name] */
664 if (lua_toboolean(L, -1)) /* is it there? */
665 return 1; /* package is already loaded */
666 /* else must load package */
667 lua_pop(L, 1); /* remove 'getfield' result */
668 findloader(L, name);
669 lua_rotate(L, -2, 1); /* function <-> loader data */
670 lua_pushvalue(L, 1); /* name is 1st argument to module loader */
671 lua_pushvalue(L, -3); /* loader data is 2nd argument */
672 /* stack: ...; loader data; loader function; mod. name; loader data */
673 lua_call(L, 2, 1); /* run loader to load module */
674 /* stack: ...; loader data; result from loader */
675 if (!lua_isnil(L, -1)) /* non-nil return? */
676 lua_setfield(L, 2, name); /* LOADED[name] = returned value */
677 else
678 lua_pop(L, 1); /* pop nil */
679 if (lua_getfield(L, 2, name) == LUA_TNIL) { /* module set no value? */
680 lua_pushboolean(L, 1); /* use true as result */
681 lua_copy(L, -1, -2); /* replace loader result */
682 lua_setfield(L, 2, name); /* LOADED[name] = true */
683 }
684 lua_rotate(L, -2, 1); /* loader data <-> module result */
685 return 2; /* return module result and loader data */
686 }
687
688 /* }====================================================== */
689
690
691
692
693 static const luaL_Reg pk_funcs[] = {
694 {"loadlib", ll_loadlib},
695 {"searchpath", ll_searchpath},
696 /* placeholders */
697 {"preload", NULL},
698 {"cpath", NULL},
699 {"path", NULL},
700 {"searchers", NULL},
701 {"loaded", NULL},
702 {NULL, NULL}
703 };
704
705
706 static const luaL_Reg ll_funcs[] = {
707 {"require", ll_require},
708 {NULL, NULL}
709 };
710
711
createsearcherstable(lua_State * L)712 static void createsearcherstable (lua_State *L) {
713 static const lua_CFunction searchers[] = {
714 searcher_preload,
715 searcher_Lua,
716 searcher_C,
717 searcher_Croot,
718 NULL
719 };
720 int i;
721 /* create 'searchers' table */
722 lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
723 /* fill it with predefined searchers */
724 for (i=0; searchers[i] != NULL; i++) {
725 lua_pushvalue(L, -2); /* set 'package' as upvalue for all searchers */
726 lua_pushcclosure(L, searchers[i], 1);
727 lua_rawseti(L, -2, i+1);
728 }
729 lua_setfield(L, -2, "searchers"); /* put it in field 'searchers' */
730 }
731
732
733 /*
734 ** create table CLIBS to keep track of loaded C libraries,
735 ** setting a finalizer to close all libraries when closing state.
736 */
createclibstable(lua_State * L)737 static void createclibstable (lua_State *L) {
738 luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS); /* create CLIBS table */
739 lua_createtable(L, 0, 1); /* create metatable for CLIBS */
740 lua_pushcfunction(L, gctm);
741 lua_setfield(L, -2, "__gc"); /* set finalizer for CLIBS table */
742 lua_setmetatable(L, -2);
743 }
744
745
luaopen_package(lua_State * L)746 LUAMOD_API int luaopen_package (lua_State *L) {
747 createclibstable(L);
748 luaL_newlib(L, pk_funcs); /* create 'package' table */
749 createsearcherstable(L);
750 /* set paths */
751 setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT);
752 setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
753 /* store config information */
754 lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
755 LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
756 lua_setfield(L, -2, "config");
757 /* set field 'loaded' */
758 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
759 lua_setfield(L, -2, "loaded");
760 /* set field 'preload' */
761 luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
762 lua_setfield(L, -2, "preload");
763 lua_pushglobaltable(L);
764 lua_pushvalue(L, -2); /* set 'package' as upvalue for next lib */
765 luaL_setfuncs(L, ll_funcs, 1); /* open lib into global table */
766 lua_pop(L, 1); /* pop global table */
767 return 1; /* return 'package' table */
768 }
769
770