Coverage Report

Created: 2025-06-16 06:56

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