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