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