Coverage Report

Created: 2024-04-23 06:32

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