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