Coverage Report

Created: 2025-08-25 07:03

/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
128k
#define LUA_CSUBSEP   LUA_DIRSEP
36
#endif
37
38
#if !defined(LUA_LSUBSEP)
39
83.7k
#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
53.6k
#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
26.8k
#define LUA_PATH_VAR    "LUA_PATH"
250
#endif
251
252
#if !defined(LUA_CPATH_VAR)
253
26.8k
#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
53.6k
                                   const char *dft) {
277
53.6k
  const char *dftmark;
278
53.6k
  const char *nver = lua_pushfstring(L, "%s%s", envname, LUA_VERSUFFIX);
279
53.6k
  const char *path = getenv(nver);  /* try versioned name */
280
53.6k
  if (path == NULL)  /* no versioned environment variable? */
281
53.6k
    path = getenv(envname);  /* try unversioned name */
282
53.6k
  if (path == NULL || noenv(L))  /* no environment variable? */
283
53.6k
    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
53.6k
  setprogdir(L);
302
53.6k
  lua_setfield(L, -3, fieldname);  /* package[fieldname] = path value */
303
53.6k
  lua_pop(L, 1);  /* pop versioned variable name ('nver') */
304
53.6k
}
305
306
/* }================================================================== */
307
308
309
/*
310
** External strings created by DLLs may need the DLL code to be
311
** deallocated. This implies that a DLL can only be unloaded after all
312
** its strings were deallocated. To ensure that, we create a 'library
313
** string' to represent each DLL, and when this string is deallocated
314
** it closes its corresponding DLL.
315
** (The string itself is irrelevant; its userdata is the DLL pointer.)
316
*/
317
318
319
/*
320
** return registry.CLIBS[path]
321
*/
322
0
static void *checkclib (lua_State *L, const char *path) {
323
0
  void *plib;
324
0
  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
325
0
  lua_getfield(L, -1, path);
326
0
  plib = lua_touserdata(L, -1);  /* plib = CLIBS[path] */
327
0
  lua_pop(L, 2);  /* pop CLIBS table and 'plib' */
328
0
  return plib;
329
0
}
330
331
332
/*
333
** Deallocate function for library strings.
334
** Unload the DLL associated with the string being deallocated.
335
*/
336
0
static void *freelib (void *ud, void *ptr, size_t osize, size_t nsize) {
337
  /* string itself is irrelevant and static */
338
0
  (void)ptr; (void)osize; (void)nsize;
339
0
  lsys_unloadlib(ud);  /* unload library represented by the string */
340
0
  return NULL;
341
0
}
342
343
344
/*
345
** Create a library string that, when deallocated, will unload 'plib'
346
*/
347
0
static void createlibstr (lua_State *L, void *plib) {
348
  /* common content for all library strings */
349
0
  static const char dummy[] = "01234567890";
350
0
  lua_pushexternalstring(L, dummy, sizeof(dummy) - 1, freelib, plib);
351
0
}
352
353
354
/*
355
** registry.CLIBS[path] = plib          -- for queries.
356
** Also create a reference to strlib, so that the library string will
357
** only be collected when registry.CLIBS is collected.
358
*/
359
0
static void addtoclib (lua_State *L, const char *path, void *plib) {
360
0
  lua_getfield(L, LUA_REGISTRYINDEX, CLIBS);
361
0
  lua_pushlightuserdata(L, plib);
362
0
  lua_setfield(L, -2, path);  /* CLIBS[path] = plib */
363
0
  createlibstr(L, plib);
364
0
  luaL_ref(L, -2);  /* keep library string in CLIBS */
365
0
  lua_pop(L, 1);  /* pop CLIBS table */
366
0
}
367
368
369
/* error codes for 'lookforfunc' */
370
7
#define ERRLIB    1
371
0
#define ERRFUNC   2
372
373
/*
374
** Look for a C function named 'sym' in a dynamically loaded library
375
** 'path'.
376
** First, check whether the library is already loaded; if not, try
377
** to load it.
378
** Then, if 'sym' is '*', return true (as library has been loaded).
379
** Otherwise, look for symbol 'sym' in the library and push a
380
** C function with that symbol.
381
** Return 0 with 'true' or a function in the stack; in case of
382
** errors, return an error code with an error message in the stack.
383
*/
384
0
static int lookforfunc (lua_State *L, const char *path, const char *sym) {
385
0
  void *reg = checkclib(L, path);  /* check loaded C libraries */
386
0
  if (reg == NULL) {  /* must load library? */
387
0
    reg = lsys_load(L, path, *sym == '*');  /* global symbols if 'sym'=='*' */
388
0
    if (reg == NULL) return ERRLIB;  /* unable to load library */
389
0
    addtoclib(L, path, reg);
390
0
  }
391
0
  if (*sym == '*') {  /* loading only library (no function)? */
392
0
    lua_pushboolean(L, 1);  /* return 'true' */
393
0
    return 0;  /* no errors */
394
0
  }
395
0
  else {
396
0
    lua_CFunction f = lsys_sym(L, reg, sym);
397
0
    if (f == NULL)
398
0
      return ERRFUNC;  /* unable to find function */
399
0
    lua_pushcfunction(L, f);  /* else create new function */
400
0
    return 0;  /* no errors */
401
0
  }
402
0
}
403
404
405
7
static int ll_loadlib (lua_State *L) {
406
7
  const char *path = luaL_checkstring(L, 1);
407
7
  const char *init = luaL_checkstring(L, 2);
408
7
  int stat = lookforfunc(L, path, init);
409
7
  if (l_likely(stat == 0))  /* no errors? */
410
0
    return 1;  /* return the loaded function */
411
7
  else {  /* error; error message is on stack top */
412
7
    luaL_pushfail(L);
413
7
    lua_insert(L, -2);
414
7
    lua_pushstring(L, (stat == ERRLIB) ?  LIB_FAIL : "init");
415
7
    return 3;  /* return fail, error message, and where */
416
7
  }
417
7
}
418
419
420
421
/*
422
** {======================================================
423
** 'require' function
424
** =======================================================
425
*/
426
427
428
2.24M
static int readable (const char *filename) {
429
2.24M
  FILE *f = fopen(filename, "r");  /* try to open file */
430
2.24M
  if (f == NULL) return 0;  /* open failed */
431
838
  fclose(f);
432
838
  return 1;
433
2.24M
}
434
435
436
/*
437
** Get the next name in '*path' = 'name1;name2;name3;...', changing
438
** the ending ';' to '\0' to create a zero-terminated string. Return
439
** NULL when list ends.
440
*/
441
2.45M
static const char *getnextfilename (char **path, char *end) {
442
2.45M
  char *sep;
443
2.45M
  char *name = *path;
444
2.45M
  if (name == end)
445
211k
    return NULL;  /* no more names */
446
2.24M
  else if (*name == '\0') {  /* from previous iteration? */
447
2.02M
    *name = *LUA_PATH_SEP;  /* restore separator */
448
2.02M
    name++;  /* skip it */
449
2.02M
  }
450
2.24M
  sep = strchr(name, *LUA_PATH_SEP);  /* find next separator */
451
2.24M
  if (sep == NULL)  /* separator not found? */
452
211k
    sep = end;  /* name goes until the end */
453
2.24M
  *sep = '\0';  /* finish file name */
454
2.24M
  *path = sep;  /* will start next search from here */
455
2.24M
  return name;
456
2.45M
}
457
458
459
/*
460
** Given a path such as ";blabla.so;blublu.so", pushes the string
461
**
462
** no file 'blabla.so'
463
**  no file 'blublu.so'
464
*/
465
210k
static void pusherrornotfound (lua_State *L, const char *path) {
466
210k
  luaL_Buffer b;
467
210k
  luaL_buffinit(L, &b);
468
210k
  luaL_addstring(&b, "no file '");
469
210k
  luaL_addgsub(&b, path, LUA_PATH_SEP, "'\n\tno file '");
470
210k
  luaL_addstring(&b, "'");
471
210k
  luaL_pushresult(&b);
472
210k
}
473
474
475
static const char *searchpath (lua_State *L, const char *name,
476
                                             const char *path,
477
                                             const char *sep,
478
212k
                                             const char *dirsep) {
479
212k
  luaL_Buffer buff;
480
212k
  char *pathname;  /* path with name inserted */
481
212k
  char *endpathname;  /* its end */
482
212k
  const char *filename;
483
  /* separator is non-empty and appears in 'name'? */
484
212k
  if (*sep != '\0' && strchr(name, *sep) != NULL)
485
92.6k
    name = luaL_gsub(L, name, sep, dirsep);  /* replace it by 'dirsep' */
486
212k
  luaL_buffinit(L, &buff);
487
  /* add path to the buffer, replacing marks ('?') with the file name */
488
212k
  luaL_addgsub(&buff, path, LUA_PATH_MARK, name);
489
212k
  luaL_addchar(&buff, '\0');
490
212k
  pathname = luaL_buffaddr(&buff);  /* writable list of file names */
491
212k
  endpathname = pathname + luaL_bufflen(&buff) - 1;
492
2.45M
  while ((filename = getnextfilename(&pathname, endpathname)) != NULL) {
493
2.24M
    if (readable(filename))  /* does file exist and is readable? */
494
838
      return lua_pushstring(L, filename);  /* save and return name */
495
2.24M
  }
496
211k
  luaL_pushresult(&buff);  /* push path to create error message */
497
211k
  pusherrornotfound(L, lua_tostring(L, -1));  /* create error message */
498
211k
  return NULL;  /* not found */
499
212k
}
500
501
502
53
static int ll_searchpath (lua_State *L) {
503
53
  const char *f = searchpath(L, luaL_checkstring(L, 1),
504
53
                                luaL_checkstring(L, 2),
505
53
                                luaL_optstring(L, 3, "."),
506
53
                                luaL_optstring(L, 4, LUA_DIRSEP));
507
53
  if (f != NULL) return 1;
508
53
  else {  /* error message is on top of the stack */
509
53
    luaL_pushfail(L);
510
53
    lua_insert(L, -2);
511
53
    return 2;  /* return fail + error message */
512
53
  }
513
53
}
514
515
516
static const char *findfile (lua_State *L, const char *name,
517
                                           const char *pname,
518
212k
                                           const char *dirsep) {
519
212k
  const char *path;
520
212k
  lua_getfield(L, lua_upvalueindex(1), pname);
521
212k
  path = lua_tostring(L, -1);
522
212k
  if (l_unlikely(path == NULL))
523
0
    luaL_error(L, "'package.%s' must be a string", pname);
524
212k
  return searchpath(L, name, path, ".", dirsep);
525
212k
}
526
527
528
838
static int checkload (lua_State *L, int stat, const char *filename) {
529
838
  if (l_likely(stat)) {  /* module loaded successfully? */
530
14
    lua_pushstring(L, filename);  /* will be 2nd argument to module */
531
14
    return 2;  /* return open function and file name */
532
14
  }
533
824
  else
534
824
    return luaL_error(L, "error loading module '%s' from file '%s':\n\t%s",
535
824
                          lua_tostring(L, 1), filename, lua_tostring(L, -1));
536
838
}
537
538
539
83.7k
static int searcher_Lua (lua_State *L) {
540
83.7k
  const char *filename;
541
83.7k
  const char *name = luaL_checkstring(L, 1);
542
83.7k
  filename = findfile(L, name, "path", LUA_LSUBSEP);
543
83.7k
  if (filename == NULL) return 1;  /* module not found in this path */
544
1.45k
  return checkload(L, (luaL_loadfile(L, filename) == LUA_OK), filename);
545
83.7k
}
546
547
548
/*
549
** Try to find a load function for module 'modname' at file 'filename'.
550
** First, change '.' to '_' in 'modname'; then, if 'modname' has
551
** the form X-Y (that is, it has an "ignore mark"), build a function
552
** name "luaopen_X" and look for it. (For compatibility, if that
553
** fails, it also tries "luaopen_Y".) If there is no ignore mark,
554
** look for a function named "luaopen_modname".
555
*/
556
0
static int loadfunc (lua_State *L, const char *filename, const char *modname) {
557
0
  const char *openfunc;
558
0
  const char *mark;
559
0
  modname = luaL_gsub(L, modname, ".", LUA_OFSEP);
560
0
  mark = strchr(modname, *LUA_IGMARK);
561
0
  if (mark) {
562
0
    int stat;
563
0
    openfunc = lua_pushlstring(L, modname, ct_diff2sz(mark - modname));
564
0
    openfunc = lua_pushfstring(L, LUA_POF"%s", openfunc);
565
0
    stat = lookforfunc(L, filename, openfunc);
566
0
    if (stat != ERRFUNC) return stat;
567
0
    modname = mark + 1;  /* else go ahead and try old-style name */
568
0
  }
569
0
  openfunc = lua_pushfstring(L, LUA_POF"%s", modname);
570
0
  return lookforfunc(L, filename, openfunc);
571
0
}
572
573
574
82.3k
static int searcher_C (lua_State *L) {
575
82.3k
  const char *name = luaL_checkstring(L, 1);
576
82.3k
  const char *filename = findfile(L, name, "cpath", LUA_CSUBSEP);
577
82.3k
  if (filename == NULL) return 1;  /* module not found in this path */
578
0
  return checkload(L, (loadfunc(L, filename, name) == 0), filename);
579
82.3k
}
580
581
582
82.3k
static int searcher_Croot (lua_State *L) {
583
82.3k
  const char *filename;
584
82.3k
  const char *name = luaL_checkstring(L, 1);
585
82.3k
  const char *p = strchr(name, '.');
586
82.3k
  int stat;
587
82.3k
  if (p == NULL) return 0;  /* is root */
588
46.1k
  lua_pushlstring(L, name, ct_diff2sz(p - name));
589
46.1k
  filename = findfile(L, lua_tostring(L, -1), "cpath", LUA_CSUBSEP);
590
46.1k
  if (filename == NULL) return 1;  /* root not found */
591
0
  if ((stat = loadfunc(L, filename, name)) != 0) {
592
0
    if (stat != ERRFUNC)
593
0
      return checkload(L, 0, filename);  /* real error */
594
0
    else {  /* open function not found */
595
0
      lua_pushfstring(L, "no module '%s' in file '%s'", name, filename);
596
0
      return 1;
597
0
    }
598
0
  }
599
0
  lua_pushstring(L, filename);  /* will be 2nd argument to module */
600
0
  return 2;
601
0
}
602
603
604
83.7k
static int searcher_preload (lua_State *L) {
605
83.7k
  const char *name = luaL_checkstring(L, 1);
606
83.7k
  lua_getfield(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
607
83.7k
  if (lua_getfield(L, -1, name) == LUA_TNIL) {  /* not found? */
608
83.7k
    lua_pushfstring(L, "no field package.preload['%s']", name);
609
83.7k
    return 1;
610
83.7k
  }
611
0
  else {
612
0
    lua_pushliteral(L, ":preload:");
613
0
    return 2;
614
0
  }
615
83.7k
}
616
617
618
84.4k
static void findloader (lua_State *L, const char *name) {
619
84.4k
  int i;
620
84.4k
  luaL_Buffer msg;  /* to build error message */
621
  /* push 'package.searchers' to index 3 in the stack */
622
84.4k
  if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), "searchers")
623
84.4k
                 != LUA_TTABLE))
624
0
    luaL_error(L, "'package.searchers' must be a table");
625
84.4k
  luaL_buffinit(L, &msg);
626
84.4k
  luaL_addstring(&msg, "\n\t");  /* error-message prefix for first message */
627
  /*  iterate over available searchers to find a loader */
628
415k
  for (i = 1; ; i++) {
629
415k
    if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL)) {  /* no more searchers? */
630
82.3k
      lua_pop(L, 1);  /* remove nil */
631
82.3k
      luaL_buffsub(&msg, 2);  /* remove last prefix */
632
82.3k
      luaL_pushresult(&msg);  /* create error message */
633
82.3k
      luaL_error(L, "module '%s' not found:%s", name, lua_tostring(L, -1));
634
82.3k
    }
635
415k
    lua_pushstring(L, name);
636
415k
    lua_call(L, 1, 2);  /* call it */
637
415k
    if (lua_isfunction(L, -2))  /* did it find a loader? */
638
14
      return;  /* module loader found */
639
415k
    else if (lua_isstring(L, -2)) {  /* searcher returned error message? */
640
294k
      lua_pop(L, 1);  /* remove extra return */
641
294k
      luaL_addvalue(&msg);  /* concatenate error message */
642
294k
      luaL_addstring(&msg, "\n\t");  /* prefix for next message */
643
294k
    }
644
120k
    else  /* no error message */
645
120k
      lua_pop(L, 2);  /* remove both returns */
646
415k
  }
647
84.4k
}
648
649
650
86.4k
static int ll_require (lua_State *L) {
651
86.4k
  const char *name = luaL_checkstring(L, 1);
652
86.4k
  lua_settop(L, 1);  /* LOADED table will be at index 2 */
653
86.4k
  lua_getfield(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
654
86.4k
  lua_getfield(L, 2, name);  /* LOADED[name] */
655
86.4k
  if (lua_toboolean(L, -1))  /* is it there? */
656
238
    return 1;  /* package is already loaded */
657
  /* else must load package */
658
86.1k
  lua_pop(L, 1);  /* remove 'getfield' result */
659
86.1k
  findloader(L, name);
660
86.1k
  lua_rotate(L, -2, 1);  /* function <-> loader data */
661
86.1k
  lua_pushvalue(L, 1);  /* name is 1st argument to module loader */
662
86.1k
  lua_pushvalue(L, -3);  /* loader data is 2nd argument */
663
  /* stack: ...; loader data; loader function; mod. name; loader data */
664
86.1k
  lua_call(L, 2, 1);  /* run loader to load module */
665
  /* stack: ...; loader data; result from loader */
666
86.1k
  if (!lua_isnil(L, -1))  /* non-nil return? */
667
0
    lua_setfield(L, 2, name);  /* LOADED[name] = returned value */
668
86.1k
  else
669
86.1k
    lua_pop(L, 1);  /* pop nil */
670
86.1k
  if (lua_getfield(L, 2, name) == LUA_TNIL) {   /* module set no value? */
671
14
    lua_pushboolean(L, 1);  /* use true as result */
672
14
    lua_copy(L, -1, -2);  /* replace loader result */
673
14
    lua_setfield(L, 2, name);  /* LOADED[name] = true */
674
14
  }
675
86.1k
  lua_rotate(L, -2, 1);  /* loader data <-> module result  */
676
86.1k
  return 2;  /* return module result and loader data */
677
86.4k
}
678
679
/* }====================================================== */
680
681
682
683
684
static const luaL_Reg pk_funcs[] = {
685
  {"loadlib", ll_loadlib},
686
  {"searchpath", ll_searchpath},
687
  /* placeholders */
688
  {"preload", NULL},
689
  {"cpath", NULL},
690
  {"path", NULL},
691
  {"searchers", NULL},
692
  {"loaded", NULL},
693
  {NULL, NULL}
694
};
695
696
697
static const luaL_Reg ll_funcs[] = {
698
  {"require", ll_require},
699
  {NULL, NULL}
700
};
701
702
703
26.8k
static void createsearcherstable (lua_State *L) {
704
26.8k
  static const lua_CFunction searchers[] = {
705
26.8k
    searcher_preload,
706
26.8k
    searcher_Lua,
707
26.8k
    searcher_C,
708
26.8k
    searcher_Croot,
709
26.8k
    NULL
710
26.8k
  };
711
26.8k
  int i;
712
  /* create 'searchers' table */
713
26.8k
  lua_createtable(L, sizeof(searchers)/sizeof(searchers[0]) - 1, 0);
714
  /* fill it with predefined searchers */
715
134k
  for (i=0; searchers[i] != NULL; i++) {
716
107k
    lua_pushvalue(L, -2);  /* set 'package' as upvalue for all searchers */
717
107k
    lua_pushcclosure(L, searchers[i], 1);
718
107k
    lua_rawseti(L, -2, i+1);
719
107k
  }
720
26.8k
  lua_setfield(L, -2, "searchers");  /* put it in field 'searchers' */
721
26.8k
}
722
723
724
26.8k
LUAMOD_API int luaopen_package (lua_State *L) {
725
26.8k
  luaL_getsubtable(L, LUA_REGISTRYINDEX, CLIBS);  /* create CLIBS table */
726
26.8k
  lua_pop(L, 1);  /* will not use it now */
727
26.8k
  luaL_newlib(L, pk_funcs);  /* create 'package' table */
728
26.8k
  createsearcherstable(L);
729
  /* set paths */
730
26.8k
  setpath(L, "path", LUA_PATH_VAR, LUA_PATH_DEFAULT);
731
26.8k
  setpath(L, "cpath", LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
732
  /* store config information */
733
26.8k
  lua_pushliteral(L, LUA_DIRSEP "\n" LUA_PATH_SEP "\n" LUA_PATH_MARK "\n"
734
26.8k
                     LUA_EXEC_DIR "\n" LUA_IGMARK "\n");
735
26.8k
  lua_setfield(L, -2, "config");
736
  /* set field 'loaded' */
737
26.8k
  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_LOADED_TABLE);
738
26.8k
  lua_setfield(L, -2, "loaded");
739
  /* set field 'preload' */
740
26.8k
  luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
741
26.8k
  lua_setfield(L, -2, "preload");
742
26.8k
  lua_pushglobaltable(L);
743
26.8k
  lua_pushvalue(L, -2);  /* set 'package' as upvalue for next lib */
744
26.8k
  luaL_setfuncs(L, ll_funcs, 1);  /* open lib into global table */
745
26.8k
  lua_pop(L, 1);  /* pop global table */
746
26.8k
  return 1;  /* return 'package' table */
747
26.8k
}
748