Repository navigation
Expand file tree
/
Copy pathLoadLib.cs
More file actions
503 lines (462 loc) · 18.3 KB
/
Copy pathLoadLib.cs
File metadata and controls
503 lines (462 loc) · 18.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
// Port of loadlib.c - the 'package' library. See LICENSE_LUA.txt.
//
// Dynamic C libraries are not supported by this port (as in a C build with
// no LUA_USE_DLOPEN / LUA_DL_DLL), so 'lsys_load' reports that condition.
using System.Runtime.InteropServices;
namespace LinkBridge.Lua;
public static unsafe partial class LuaApi
{
private const string LUA_CSUBSEP = LUA_DIRSEP;
private const string LUA_LSUBSEP = LUA_DIRSEP;
/* prefix for open functions in C libraries */
private static ReadOnlySpan<byte> LUA_POF => "luaopen_"u8;
/* separator for open functions in C libraries */
private const string LUA_OFSEP = "_";
private static ReadOnlySpan<byte> CLIBS => "_CLIBS"u8;
private static ReadOnlySpan<byte> LIB_FAIL => "absent"u8;
private static ReadOnlySpan<byte> DLMSG =>
"dynamic libraries not enabled; check your Lua installation"u8;
private static void lsys_unloadlib(void* lib)
{
}
private static void* lsys_load(lua_State* L, byte* path, int seeglb)
{
lua_pushstring(L, CSTR(DLMSG));
return null;
}
private static lua_CFunction lsys_sym(lua_State* L, void* lib, byte* sym)
{
lua_pushstring(L, CSTR(DLMSG));
return null;
}
/*
** {==================================================================
** Set Paths
** ===================================================================
*/
private const string LUA_PATH_VAR = "LUA_PATH";
private const string LUA_CPATH_VAR = "LUA_CPATH";
/*
** return registry.LUA_NOENV as a boolean
*/
private static int noenv(lua_State* L)
{
int b;
lua_getfield(L, LUA_REGISTRYINDEX, CSTR("LUA_NOENV"u8));
b = lua_toboolean(L, -1);
lua_pop(L, 1); // remove value
return b;
}
/*
** Set a path.
*/
private static void setpath(lua_State* L, byte* fieldname, string envname, string dft)
{
byte* dftmark;
byte* nver = lua_pushfstring(L, CSTR("%s%s"u8), CSTR(envname), CSTR(LUA_VERSUFFIX));
byte* path = getenv(CStr(nver)); // try versioned name
if (path == null) // no versioned environment variable?
path = getenv(envname); // try unversioned name
if (path == null || noenv(L) != 0) // no environment variable?
lua_pushstring(L, CSTR(dft)); // use default
else if ((dftmark = strstr(path, CSTR(";;"u8))) == null)
lua_pushstring(L, path); // nothing to change
else
{ // path contains a ";;": insert default path in its place
nuint len = strlen(path);
luaL_Buffer b;
luaL_buffinit(L, &b);
if (path < dftmark)
{ // is there a prefix before ';;'?
luaL_addlstring(&b, path, ct_diff2sz((nint)(dftmark - path))); // add it
luaL_addchar(&b, ';');
}
luaL_addstring(&b, CSTR(dft)); // add default
if (dftmark < path + len - 2)
{ // is there a suffix after ';;'?
luaL_addchar(&b, ';');
luaL_addlstring(&b, dftmark + 2,
ct_diff2sz((nint)((path + len - 2) - dftmark)));
}
luaL_pushresult(&b);
}
lua_setfield(L, -3, fieldname); // package[fieldname] = path value
lua_pop(L, 1); // pop versioned variable name ('nver')
}
/*
** return registry.CLIBS[path]
*/
private static void* checkclib(lua_State* L, byte* path)
{
void* plib;
lua_getfield(L, LUA_REGISTRYINDEX, CSTR(CLIBS));
lua_getfield(L, -1, path);
plib = lua_touserdata(L, -1); // plib = CLIBS[path]
lua_pop(L, 2); // pop CLIBS table and 'plib'
return plib;
}
/*
** registry.CLIBS[path] = plib -- for queries.
*/
private static void addtoclib(lua_State* L, byte* path, void* plib)
{
lua_getfield(L, LUA_REGISTRYINDEX, CSTR(CLIBS));
lua_pushlightuserdata(L, plib);
lua_setfield(L, -2, path); // CLIBS[path] = plib
lua_pop(L, 1); // pop CLIBS table
}
/* error codes for 'lookforfunc' */
private const int ERRLIB = 1;
private const int ERRFUNC = 2;
/*
** Look for a C function named 'sym' in a dynamically loaded library.
*/
private static int lookforfunc(lua_State* L, byte* path, byte* sym)
{
void* reg = checkclib(L, path); // check loaded C libraries
if (reg == null)
{ // must load library?
reg = lsys_load(L, path, *sym == '*' ? 1 : 0);
if (reg == null) return ERRLIB; // unable to load library
addtoclib(L, path, reg);
}
if (*sym == '*')
{ // loading only library (no function)?
lua_pushboolean(L, 1); // return 'true'
return 0; // no errors
}
else
{
lua_CFunction f = lsys_sym(L, reg, sym);
if (f == null)
return ERRFUNC; // unable to find function
lua_pushcfunction(L, f); // else create new function
return 0; // no errors
}
}
private static int ll_loadlib(lua_State* L)
{
byte* path = luaL_checkstring(L, 1);
byte* init = luaL_checkstring(L, 2);
int stat = lookforfunc(L, path, init);
if (l_likely(stat == 0)) // no errors?
return 1; // return the loaded function
else
{ // error; error message is on stack top
luaL_pushfail(L);
lua_insert(L, -2);
lua_pushstring(L, stat == ERRLIB ? CSTR(LIB_FAIL) : CSTR("init"u8));
return 3; // return fail, error message, and where
}
}
/*
** {======================================================
** 'require' function
** =======================================================
*/
private static int readable(byte* filename)
{
FILE* f = fopen(filename, CSTR("r"u8)); // try to open file
if (f == null) return 0; // open failed
fclose(f);
return 1;
}
/*
** Get the next name in '*path' = 'name1;name2;name3;...'.
*/
private static byte* getnextfilename(byte** path, byte* end)
{
byte* sep;
byte* name = *path;
if (name == end)
return null; // no more names
else if (*name == '\0')
{ // from previous iteration?
*name = (byte)';'; // restore separator
name++; // skip it
}
sep = strchr(name, ';'); // find next separator
if (sep == null) // separator not found?
sep = end; // name goes until the end
*sep = 0; // finish file name
*path = sep; // will start next search from here
return name;
}
/*
** Given a path such as ";blabla.so;blublu.so", pushes an error message.
*/
private static void pusherrornotfound(lua_State* L, byte* path)
{
luaL_Buffer b;
luaL_buffinit(L, &b);
luaL_addstring(&b, CSTR("no file '"u8));
luaL_addgsub(&b, path, CSTR(";"u8), CSTR("'\n\tno file '"u8));
luaL_addstring(&b, CSTR("'"u8));
luaL_pushresult(&b);
}
private static byte* searchpath(lua_State* L, byte* name, byte* path,
byte* sep, byte* dirsep)
{
luaL_Buffer buff;
byte* pathname; // path with name inserted
byte* endpathname; // its end
byte* filename;
// separator is non-empty and appears in 'name'?
if (*sep != '\0' && strchr(name, *sep) != null)
name = luaL_gsub(L, name, sep, dirsep); // replace it by 'dirsep'
luaL_buffinit(L, &buff);
// add path to the buffer, replacing marks ('?') with the file name
luaL_addgsub(&buff, path, CSTR(LUA_PATH_MARK), name);
luaL_addchar(&buff, '\0');
pathname = luaL_buffaddr(&buff); // writable list of file names
endpathname = pathname + luaL_bufflen(&buff) - 1;
while ((filename = getnextfilename(&pathname, endpathname)) != null)
{
if (readable(filename) != 0) // does file exist and is readable?
return lua_pushstring(L, filename); // save and return name
}
luaL_pushresult(&buff); // push path to create error message
pusherrornotfound(L, lua_tostring(L, -1)); // create error message
return null; // not found
}
private static int ll_searchpath(lua_State* L)
{
byte* f = searchpath(L, luaL_checkstring(L, 1),
luaL_checkstring(L, 2),
luaL_optstring(L, 3, CSTR("."u8)),
luaL_optstring(L, 4, CSTR(LUA_DIRSEP)));
if (f != null) return 1;
else
{ // error message is on top of the stack
luaL_pushfail(L);
lua_insert(L, -2);
return 2; // return fail + error message
}
}
private static byte* findfile(lua_State* L, byte* name, byte* pname, byte* dirsep)
{
byte* path;
lua_getfield(L, lua_upvalueindex(1), pname);
path = lua_tostring(L, -1);
if (l_unlikely(path == null))
luaL_error(L, CSTR("'package.%s' must be a string"u8), pname);
return searchpath(L, name, path, CSTR("."u8), dirsep);
}
private static int checkload(lua_State* L, int stat, byte* filename)
{
if (l_likely(stat != 0))
{ // module loaded successfully?
lua_pushstring(L, filename); // will be 2nd argument to module
return 2; // return open function and file name
}
else
return luaL_error(L,
CSTR("error loading module '%s' from file '%s':\n\t%s"u8),
lua_tostring(L, 1), filename, lua_tostring(L, -1));
}
private static int searcher_Lua(lua_State* L)
{
byte* filename;
byte* name = luaL_checkstring(L, 1);
filename = findfile(L, name, CSTR("path"u8), CSTR(LUA_LSUBSEP));
if (filename == null) return 1; // module not found in this path
return checkload(L, luaL_loadfilex(L, filename, CSTR("bt"u8)) == LUA_OK ? 1 : 0,
filename);
}
/*
** Try to find a load function for module 'modname' at file 'filename'.
*/
private static int loadfunc(lua_State* L, byte* filename, byte* modname)
{
byte* openfunc;
byte* mark;
modname = luaL_gsub(L, modname, CSTR("."u8), CSTR(LUA_OFSEP));
mark = strchr(modname, LUA_IGMARK[0]);
if (mark != null)
{
int stat;
openfunc = lua_pushlstring(L, modname, ct_diff2sz((nint)(mark - modname)));
openfunc = lua_pushfstring(L, CSTR("luaopen_%s"u8), openfunc);
stat = lookforfunc(L, filename, openfunc);
if (stat != ERRFUNC) return stat;
modname = mark + 1; // else go ahead and try old-style name
}
openfunc = lua_pushfstring(L, CSTR("luaopen_%s"u8), modname);
return lookforfunc(L, filename, openfunc);
}
private static int searcher_C(lua_State* L)
{
byte* name = luaL_checkstring(L, 1);
byte* filename = findfile(L, name, CSTR("cpath"u8), CSTR(LUA_CSUBSEP));
if (filename == null) return 1; // module not found in this path
return checkload(L, loadfunc(L, filename, name) == 0 ? 1 : 0, filename);
}
private static int searcher_Croot(lua_State* L)
{
byte* filename;
byte* name = luaL_checkstring(L, 1);
byte* p = strchr(name, '.');
int stat;
if (p == null) return 0; // is root
lua_pushlstring(L, name, ct_diff2sz((nint)(p - name)));
filename = findfile(L, lua_tostring(L, -1), CSTR("cpath"u8), CSTR(LUA_CSUBSEP));
if (filename == null) return 1; // root not found
if ((stat = loadfunc(L, filename, name)) != 0)
{
if (stat != ERRFUNC)
return checkload(L, 0, filename); // real error
else
{ // open function not found
lua_pushfstring(L, CSTR("no module '%s' in file '%s'"u8), name, filename);
return 1;
}
}
lua_pushstring(L, filename); // will be 2nd argument to module
return 2;
}
private static int searcher_preload(lua_State* L)
{
byte* name = luaL_checkstring(L, 1);
lua_getfield(L, LUA_REGISTRYINDEX, CSTR(LUA_PRELOAD_TABLE));
if (lua_getfield(L, -1, name) == LUA_TNIL)
{ // not found?
lua_pushfstring(L, CSTR("no field package.preload['%s']"u8), name);
return 1;
}
else
{
lua_pushstring(L, CSTR(":preload:"u8));
return 2;
}
}
private static void findloader(lua_State* L, byte* name)
{
int i;
luaL_Buffer msg; // to build error message
// push 'package.searchers' to index 3 in the stack
if (l_unlikely(lua_getfield(L, lua_upvalueindex(1), CSTR("searchers"u8))
!= LUA_TTABLE))
luaL_error(L, CSTR("'package.searchers' must be a table"u8));
luaL_buffinit(L, &msg);
luaL_addstring(&msg, CSTR("\n\t"u8)); // error-message prefix
// iterate over available searchers to find a loader
for (i = 1; ; i++)
{
if (l_unlikely(lua_rawgeti(L, 3, i) == LUA_TNIL))
{ // no more searchers?
lua_pop(L, 1); // remove nil
luaL_buffsub(&msg, 2); // remove last prefix
luaL_pushresult(&msg); // create error message
luaL_error(L, CSTR("module '%s' not found:%s"u8), name,
lua_tostring(L, -1));
}
lua_pushstring(L, name);
lua_call(L, 1, 2); // call it
if (lua_isfunction(L, -2)) // did it find a loader?
return; // module loader found
else if (lua_isstring(L, -2) != 0)
{ // searcher returned error message?
lua_pop(L, 1); // remove extra return
luaL_addvalue(&msg); // concatenate error message
luaL_addstring(&msg, CSTR("\n\t"u8)); // prefix for next message
}
else // no error message
lua_pop(L, 2); // remove both returns
}
}
private static int ll_require(lua_State* L)
{
byte* name = luaL_checkstring(L, 1);
lua_settop(L, 1); // LOADED table will be at index 2
lua_getfield(L, LUA_REGISTRYINDEX, CSTR(LUA_LOADED_TABLE));
lua_getfield(L, 2, name); // LOADED[name]
if (lua_toboolean(L, -1) != 0) // is it there?
return 1; // package is already loaded
// else must load package
lua_pop(L, 1); // remove 'getfield' result
findloader(L, name);
lua_rotate(L, -2, 1); // function <-> loader data
lua_pushvalue(L, 1); // name is 1st argument to module loader
lua_pushvalue(L, -3); // loader data is 2nd argument
lua_call(L, 2, 1); // run loader to load module
if (!lua_isnil(L, -1)) // non-nil return?
lua_setfield(L, 2, name); // LOADED[name] = returned value
else
lua_pop(L, 1); // pop nil
if (lua_getfield(L, 2, name) == LUA_TNIL)
{ // module set no value?
lua_pushboolean(L, 1); // use true as result
lua_copy(L, -1, -2); // replace loader result
lua_setfield(L, 2, name); // LOADED[name] = true
}
lua_rotate(L, -2, 1); // loader data <-> module result
return 2; // return module result and loader data
}
private static readonly IntPtr _pk_funcs = create_pk_funcs();
private static IntPtr create_pk_funcs()
{
luaL_Reg* r = newregs(7);
int i = 0;
reg(r, ref i, "loadlib"u8, &ll_loadlib);
reg(r, ref i, "searchpath"u8, &ll_searchpath);
// placeholders
reg(r, ref i, "preload"u8, null);
reg(r, ref i, "cpath"u8, null);
reg(r, ref i, "path"u8, null);
reg(r, ref i, "searchers"u8, null);
reg(r, ref i, "loaded"u8, null);
return (IntPtr)r;
}
private static readonly IntPtr _ll_funcs = create_ll_funcs();
private static IntPtr create_ll_funcs()
{
luaL_Reg* r = newregs(1);
int i = 0;
reg(r, ref i, "require"u8, &ll_require);
return (IntPtr)r;
}
private static void createsearcherstable(lua_State* L)
{
// create 'searchers' table
lua_createtable(L, 4, 0);
// fill it with predefined searchers
lua_CFunction* searchers = stackalloc lua_CFunction[4];
searchers[0] = &searcher_preload;
searchers[1] = &searcher_Lua;
searchers[2] = &searcher_C;
searchers[3] = &searcher_Croot;
for (int i = 0; i < 4; i++)
{
lua_pushvalue(L, -2); // set 'package' as upvalue for all searchers
lua_pushcclosure(L, searchers[i], 1);
lua_rawseti(L, -2, i + 1);
}
lua_setfield(L, -2, CSTR("searchers"u8)); // put it in field 'searchers'
}
public static int luaopen_package(lua_State* L)
{
luaL_getsubtable(L, LUA_REGISTRYINDEX, CSTR(CLIBS)); // create CLIBS table
lua_pop(L, 1); // will not use it now
luaL_newlib(L, (luaL_Reg*)_pk_funcs, 7); // create 'package' table
createsearcherstable(L);
// set paths
setpath(L, CSTR("path"u8), LUA_PATH_VAR, LUA_PATH_DEFAULT);
setpath(L, CSTR("cpath"u8), LUA_CPATH_VAR, LUA_CPATH_DEFAULT);
// store config information
lua_pushstring(L, CSTR(LUA_DIRSEP + "\n" + LUA_PATH_SEP + "\n" +
LUA_PATH_MARK + "\n" + LUA_EXEC_DIR + "\n" +
LUA_IGMARK + "\n"));
lua_setfield(L, -2, CSTR("config"u8));
// set field 'loaded'
luaL_getsubtable(L, LUA_REGISTRYINDEX, CSTR(LUA_LOADED_TABLE));
lua_setfield(L, -2, CSTR("loaded"u8));
// set field 'preload'
luaL_getsubtable(L, LUA_REGISTRYINDEX, CSTR(LUA_PRELOAD_TABLE));
lua_setfield(L, -2, CSTR("preload"u8));
lua_pushglobaltable(L);
lua_pushvalue(L, -2); // set 'package' as upvalue for next lib
luaL_setfuncs(L, (luaL_Reg*)_ll_funcs, 1); // open lib into global table
lua_pop(L, 1); // pop global table
return 1; // return 'package' table
}
}