/
lua_glue.c
637 lines (524 loc) · 18.5 KB
1
#include "universal.h"
2
#include "lua_glue.h"
3
#include "platform.h"
4
5
6
7
#include "fileio.h"
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
8
#include "gui.h"
9
10
11
12
13
#define MOJOSETUP_NAMESPACE "MojoSetup"
static lua_State *luaState = NULL;
14
15
16
17
18
19
20
21
22
23
24
25
// Allocator interface for internal Lua use.
static void *MojoLua_alloc(void *ud, void *ptr, size_t osize, size_t nsize)
{
if (nsize == 0)
{
free(ptr);
return NULL;
} // if
return xrealloc(ptr, nsize);
} // MojoLua_alloc
26
27
28
29
// Read data from a MojoInput when loading Lua code.
static const char *MojoLua_reader(lua_State *L, void *data, size_t *size)
{
MojoInput *in = (MojoInput *) data;
30
char *retval = (char *) scratchbuf_128k;
31
32
33
34
35
36
37
38
39
40
41
42
int64 br = in->read(in, scratchbuf_128k, sizeof (scratchbuf_128k));
if (br <= 0) // eof or error? (lua doesn't care which?!)
{
br = 0;
retval = NULL;
} // if
*size = (size_t) br;
return retval;
} // MojoLua_reader
43
44
45
46
47
48
49
50
51
52
53
54
55
static inline int snprintfcat(char **ptr, size_t *len, const char *fmt, ...)
{
int bw = 0;
va_list ap;
va_start(ap, fmt);
bw = vsnprintf(*ptr, *len, fmt, ap);
va_end(ap);
*ptr += bw;
*len -= bw;
return bw;
} // snprintfcat
56
57
58
59
60
61
62
static int luahook_stackwalk(lua_State *L)
{
const char *errstr = lua_tostring(L, 1);
lua_Debug ldbg;
int i = 0;
if (errstr != NULL)
63
logDebug("%s\n", errstr);
64
65
logDebug("Lua stack backtrace:");
66
67
68
69
// start at 1 to skip this function.
for (i = 1; lua_getstack(L, i, &ldbg); i++)
{
70
71
72
char *ptr = (char *) scratchbuf_128k;
size_t len = sizeof (scratchbuf_128k);
int bw = snprintfcat(&ptr, &len, "#%d", i-1);
73
74
75
const int maxspacing = 4;
int spacing = maxspacing - bw;
while (spacing-- > 0)
76
snprintfcat(&ptr, &len, " ");
77
78
79
if (!lua_getinfo(L, "nSl", &ldbg))
{
80
81
snprintfcat(&ptr, &len, "???\n");
logDebug((const char *) scratchbuf_128k);
82
83
84
85
continue;
} // if
if (ldbg.namewhat[0])
86
snprintfcat(&ptr, &len, "%s ", ldbg.namewhat);
87
88
if ((ldbg.name) && (ldbg.name[0]))
89
snprintfcat(&ptr, &len, "function %s ()", ldbg.name);
90
91
92
else
{
if (strcmp(ldbg.what, "main") == 0)
93
snprintfcat(&ptr, &len, "mainline of chunk");
94
else if (strcmp(ldbg.what, "tail") == 0)
95
snprintfcat(&ptr, &len, "tail call");
96
else
97
snprintfcat(&ptr, &len, "unidentifiable function");
98
99
} // if
100
101
102
103
logDebug((const char *) scratchbuf_128k);
ptr = (char *) scratchbuf_128k;
len = sizeof (scratchbuf_128k);
104
for (spacing = 0; spacing < maxspacing; spacing++)
105
snprintfcat(&ptr, &len, " ");
106
107
if (strcmp(ldbg.what, "C") == 0)
108
snprintfcat(&ptr, &len, "in native code");
109
else if (strcmp(ldbg.what, "tail") == 0)
110
snprintfcat(&ptr, &len, "in Lua code");
111
112
else if ( (strcmp(ldbg.source, "=?") == 0) && (ldbg.currentline == 0) )
snprintfcat(&ptr, &len, "in Lua code (debug info stripped)");
113
114
else
{
115
snprintfcat(&ptr, &len, "in Lua code at %s", ldbg.short_src);
116
if (ldbg.currentline != -1)
117
snprintfcat(&ptr, &len, ":%d", ldbg.currentline);
118
} // else
119
logDebug((const char *) scratchbuf_128k);
120
121
122
123
124
125
126
} // for
lua_pushstring(L, errstr ? errstr : "");
return 1;
} // luahook_stackwalk
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
// This just lets you punch in one-liners and Lua will run them as individual
// chunks, but you can completely access all Lua state, including calling C
// functions and altering tables. At this time, it's more of a "console"
// than a debugger. You can do "p MojoLua_debugger()" from gdb to launch this
// from a breakpoint in native code, or call MojoSetup.debugger() to launch
// it from Lua code (with stacktrace intact, too: type 'bt' to see it).
static int luahook_debugger(lua_State *L)
{
#if DISABLE_LUA_PARSER
logError("Lua debugger is disabled in this build (no parser).");
#else
int origtop;
lua_pushcfunction(luaState, luahook_stackwalk);
origtop = lua_gettop(L);
printf("Quick and dirty Lua debugger. Type 'exit' to quit.\n");
while (true)
{
char *buf = (char *) scratchbuf_128k;
int len = 0;
printf("> ");
fflush(stdout);
if (fgets(buf, sizeof (scratchbuf_128k), stdin) == NULL)
{
printf("\n\n fgets() on stdin failed: ");
break;
} // if
len = (int) (strlen(buf) - 1);
while ( (len >= 0) && ((buf[len] == '\n') || (buf[len] == '\r')) )
buf[len--] = '\0';
if (strcmp(buf, "q") == 0)
break;
else if (strcmp(buf, "exit") == 0)
break;
else if (strcmp(buf, "bt") == 0)
strcpy(buf, "MojoSetup.stackwalk()");
if ( (luaL_loadstring(L, buf) != 0) ||
(lua_pcall(luaState, 0, LUA_MULTRET, -2) != 0) )
{
printf("%s\n", lua_tostring(L, -1));
lua_pop(L, 1);
} // if
else
{
printf("Returned %d values.\n", lua_gettop(L) - origtop);
while (lua_gettop(L) != origtop)
{
// !!! FIXME: dump details of values to stdout here.
lua_pop(L, 1);
} // while
printf("\n");
} // else
} // while
lua_pop(L, 1);
printf("exiting debugger...\n");
#endif
189
190
return 0;
191
192
193
194
195
196
197
198
199
} // luahook_debugger
void MojoLua_debugger(void)
{
luahook_debugger(luaState);
} // MojoLua_debugger
200
201
boolean MojoLua_runFile(const char *basefname)
{
202
203
MojoArchive *ar = GBaseArchive; // in case we want to generalize later.
const MojoArchiveEntryInfo *entinfo;
204
boolean retval = false;
205
206
char clua[128]; // compiled filename.
char ulua[128]; // uncompiled filename.
207
208
209
int rc = 0;
MojoInput *io = NULL;
210
211
if (snprintf(clua, sizeof (clua), "%s.luac", basefname) >= sizeof (clua))
return false;
212
213
214
215
216
if (snprintf(ulua, sizeof (ulua), "%s.lua", basefname) >= sizeof (ulua))
return false;
if (ar->enumerate(ar, "lua"))
217
{
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
while ((entinfo = ar->enumNext(ar)) != NULL)
{
boolean match = (strcmp(entinfo->filename, clua) == 0);
#if !DISABLE_LUA_PARSER
if (!match)
match = (strcmp(entinfo->filename, ulua) == 0);
#endif
if (match)
{
if (entinfo->type == MOJOARCHIVE_ENTRY_FILE)
io = ar->openCurrentEntry(ar);
break;
} // if
} // while
233
234
235
236
} // if
if (io != NULL)
{
237
238
char *realfname = xmalloc(strlen(entinfo->filename) + 6);
sprintf(realfname, "@lua/%s", entinfo->filename);
239
lua_pushcfunction(luaState, luahook_stackwalk);
240
241
rc = lua_load(luaState, MojoLua_reader, io, realfname);
free(realfname);
242
243
244
245
246
247
io->close(io);
if (rc != 0)
lua_error(luaState);
else
{
248
// Call new chunk on top of the stack (lua_pcall will pop it off).
249
250
251
252
if (lua_pcall(luaState, 0, 0, -2) != 0) // retvals are dumped.
lua_error(luaState); // error on stack has debug info.
else
retval = true; // if this didn't panic, we succeeded.
253
} // if
254
lua_pop(luaState, 1); // dump stackwalker.
255
256
257
258
259
260
} // if
return retval;
} // MojoLua_runFile
261
262
263
void MojoLua_collectGarbage(void)
{
lua_State *L = luaState;
264
uint32 ticks = 0;
265
266
267
268
int pre = 0;
int post = 0;
pre = (lua_gc(L, LUA_GCCOUNT, 0) * 1024) + lua_gc(L, LUA_GCCOUNTB, 0);
269
logDebug("Collecting garbage (currently using %d bytes).", pre);
270
ticks = MojoPlatform_ticks();
271
lua_gc (L, LUA_GCCOLLECT, 0);
272
profile("Garbage collection", ticks);
273
post = (lua_gc(L, LUA_GCCOUNT, 0) * 1024) + lua_gc(L, LUA_GCCOUNTB, 0);
274
logDebug("Now using %d bytes (%d bytes savings).\n", post, pre - post);
275
276
277
} // MojoLua_collectGarbage
278
279
280
281
282
283
284
285
286
// You can trigger the garbage collector with more control in the standard
// Lua runtime, but this notes profiling and statistics via logDebug().
static int luahook_collectgarbage(lua_State *L)
{
MojoLua_collectGarbage();
return 0;
} // luahook_collectgarbage
287
288
289
290
291
292
293
294
295
static inline void pushStringOrNil(lua_State *L, const char *str)
{
if (str != NULL)
lua_pushstring(L, str);
else
lua_pushnil(L);
} // pushStringOrNil
296
297
298
299
300
// Since localization is kept in Lua tables, I stuck this in the Lua glue.
const char *translate(const char *str)
{
const char *retval = str;
301
if (luaState != NULL) // No translations before Lua is initialized.
302
{
303
if (lua_checkstack(luaState, 3))
304
{
305
306
307
int popcount = 0;
lua_getglobal(luaState, MOJOSETUP_NAMESPACE); popcount++;
if (lua_istable(luaState, -1)) // namespace is sane?
308
{
309
310
lua_getfield(luaState, -1, "translations"); popcount++;
if (lua_istable(luaState, -1)) // translation table is sane?
311
{
312
313
314
315
316
const char *tr = NULL;
lua_getfield(luaState, -1, str); popcount++;
tr = lua_tostring(luaState, -1);
if (tr != NULL) // translated for this locale?
{
317
318
319
char *dst = (char *) scratchbuf_128k;
xstrncpy(dst, tr, sizeof(scratchbuf_128k));
retval = dst;
320
} // if
321
} // if
322
} // if
323
lua_pop(luaState, popcount); // remove our stack salsa.
324
325
326
327
328
329
330
331
} // if
} // if
return retval;
} // translate
// Hook into our error handling in case Lua throws a runtime error.
332
static int luahook_panic(lua_State *L)
333
{
334
335
const char *errstr = lua_tostring(L, 1);
if (errstr == NULL)
336
errstr = _("Unknown error");
337
return fatal(errstr); // doesn't actually return.
338
} // luahook_panic
339
340
341
342
343
344
345
346
347
348
349
// Use this instead of Lua's error() function if you don't have a
// programatic error, so you don't get stack callback stuff:
// MojoSetup.fatal("You need the base game to install this expansion pack.")
// Doesn't actually return.
static int luahook_fatal(lua_State *L)
{
const char *err = luaL_checkstring(L, 1);
fatal(err);
return 0;
350
} // luahook_fatal
351
352
353
354
355
356
357
358
359
360
361
362
// Lua interface to MojoLua_runFile(). This is needed instead of Lua's
// require(), since it can access scripts inside an archive.
static int luahook_runfile(lua_State *L)
{
const char *fname = luaL_checkstring(L, 1);
lua_pushboolean(L, MojoLua_runFile(fname));
return 1;
} // luahook_runfile
363
364
365
366
367
368
369
370
371
// Lua interface to translate().
static int luahook_translate(lua_State *L)
{
const char *str = luaL_checkstring(L, 1);
lua_pushstring(L, translate(str));
return 1;
} // luahook_translate
372
373
374
375
376
377
378
static int luahook_ticks(lua_State *L)
{
lua_pushnumber(L, MojoPlatform_ticks());
return 1;
} // luahook_ticks
379
380
381
382
383
384
static int luahook_msgbox(lua_State *L)
{
if (GGui != NULL)
{
const char *title = luaL_checkstring(L, 1);
const char *text = luaL_checkstring(L, 2);
385
GGui->msgbox(title, text);
386
387
388
389
390
391
392
393
394
395
396
397
} // if
return 0;
} // luahook_msgbox
static int luahook_promptyn(lua_State *L)
{
boolean rc = false;
if (GGui != NULL)
{
const char *title = luaL_checkstring(L, 1);
const char *text = luaL_checkstring(L, 2);
398
rc = GGui->promptyn(title, text);
399
400
401
402
403
404
405
} // if
lua_pushboolean(L, rc);
return 1;
} // luahook_msgbox
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
static int luahook_logwarning(lua_State *L)
{
logWarning(luaL_checkstring(L, 1));
return 0;
} // luahook_logwarning
static int luahook_logerror(lua_State *L)
{
logError(luaL_checkstring(L, 1));
return 0;
} // luahook_logerror
static int luahook_loginfo(lua_State *L)
{
logInfo(luaL_checkstring(L, 1));
return 0;
} // luahook_loginfo
static int luahook_logdebug(lua_State *L)
{
logDebug(luaL_checkstring(L, 1));
return 0;
} // luahook_logdebug
static int luahook_cmdline(lua_State *L)
{
const char *arg = luaL_checkstring(L, 1);
lua_pushboolean(L, cmdline(arg));
return 1;
} // luahook_cmdline
static int luahook_cmdlinestr(lua_State *L)
{
int argc = lua_gettop(L);
const char *arg = luaL_checkstring(L, 1);
const char *envr = (argc < 2) ? NULL : lua_tostring(L, 2);
const char *deflt = (argc < 3) ? NULL : lua_tostring(L, 3);
pushStringOrNil(L, cmdlinestr(arg, envr, deflt));
return 1;
} // luahook_cmdlinestr
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
static int luahook_startgui(lua_State *L)
{
const char *title = luaL_checkstring(L, 1);
const char *splash = lua_tostring(L, 2);
lua_pushboolean(L, GGui->startgui(title, splash));
return 1;
} // luahook_startgui
static int luahook_endgui(lua_State *L)
{
GGui->endgui();
return 0;
} // luahook_endgui
469
470
471
472
473
474
475
476
// Sets t[sym]=f, where t is on the top of the Lua stack.
static inline void set_cfunc(lua_State *L, lua_CFunction f, const char *sym)
{
lua_pushcfunction(luaState, f);
lua_setfield(luaState, -2, sym);
} // set_cfunc
477
478
479
480
481
482
483
// Sets t[sym]=f, where t is on the top of the Lua stack.
static inline void set_string(lua_State *L, const char *str, const char *sym)
{
lua_pushstring(luaState, str);
lua_setfield(luaState, -2, sym);
} // set_string
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
static inline void set_string_array(lua_State *L, int argc, const char **argv,
const char *sym)
{
int i;
lua_newtable(luaState);
for (i = 0; i < argc; i++)
{
lua_pushinteger(luaState, i+1); // lua is option base 1!
lua_pushstring(luaState, argv[i]);
lua_settable(luaState, -3);
} // for
lua_setfield(luaState, -2, sym);
} // set_string_array
void MojoLua_setString(const char *str, const char *sym)
{
lua_getglobal(luaState, MOJOSETUP_NAMESPACE);
set_string(luaState, str, sym);
lua_pop(luaState, 1);
} // MojoLua_setString
void MojoLua_setStringArray(int argc, const char **argv, const char *sym)
{
lua_getglobal(luaState, MOJOSETUP_NAMESPACE);
set_string_array(luaState, argc, argv, sym);
lua_pop(luaState, 1);
} // MojoLua_setStringArray
514
515
516
boolean MojoLua_initLua(void)
{
517
char locale[16];
518
519
char ostype[64];
char osversion[64];
520
521
522
if (!MojoPlatform_locale(locale, sizeof (locale)))
xstrncpy(locale, "???", sizeof (locale));
523
524
525
526
527
528
if (!MojoPlatform_osType(ostype, sizeof (ostype)))
xstrncpy(ostype, "???", sizeof (ostype));
if (!MojoPlatform_osVersion(osversion, sizeof (osversion)))
xstrncpy(osversion, "???", sizeof (osversion));
assert(luaState == NULL);
529
530
luaState = lua_newstate(MojoLua_alloc, NULL);
531
532
533
if (luaState == NULL)
return false;
534
lua_atpanic(luaState, luahook_panic);
535
536
537
538
539
540
541
542
543
544
545
546
if (!lua_checkstack(luaState, 20)) // Just in case.
{
lua_close(luaState);
luaState = NULL;
return false;
} // if
luaL_openlibs(luaState);
// Build MojoSetup namespace for Lua to access and fill in C bridges...
lua_newtable(luaState);
547
// Set up initial C functions, etc we want to expose to Lua code...
548
set_cfunc(luaState, luahook_runfile, "runfile");
549
set_cfunc(luaState, luahook_translate, "translate");
550
set_cfunc(luaState, luahook_ticks, "ticks");
551
552
553
set_cfunc(luaState, luahook_fatal, "fatal");
set_cfunc(luaState, luahook_msgbox, "msgbox");
set_cfunc(luaState, luahook_promptyn, "promptyn");
554
set_cfunc(luaState, luahook_stackwalk, "stackwalk");
555
556
557
558
559
560
set_cfunc(luaState, luahook_logwarning, "logwarning");
set_cfunc(luaState, luahook_logerror, "logerror");
set_cfunc(luaState, luahook_loginfo, "loginfo");
set_cfunc(luaState, luahook_logdebug, "logdebug");
set_cfunc(luaState, luahook_cmdline, "cmdline");
set_cfunc(luaState, luahook_cmdlinestr, "cmdlinestr");
561
562
set_cfunc(luaState, luahook_collectgarbage, "collectgarbage");
set_cfunc(luaState, luahook_debugger, "debugger");
563
564
set_cfunc(luaState, luahook_startgui, "startgui");
set_cfunc(luaState, luahook_endgui, "endgui");
565
set_string(luaState, locale, "locale");
566
567
568
569
set_string(luaState, PLATFORM_NAME, "platform");
set_string(luaState, PLATFORM_ARCH, "arch");
set_string(luaState, ostype, "ostype");
set_string(luaState, osversion, "osversion");
570
set_string(luaState, GBuildVer, "buildver");
571
set_string(luaState, GLuaLicense, "lualicense");
572
set_string_array(luaState, GArgc, GArgv, "argv");
573
lua_setglobal(luaState, MOJOSETUP_NAMESPACE);
574
575
// Set up localization table, if possible.
576
MojoLua_runFile("localization");
577
578
579
580
// Transfer control to Lua to setup some APIs and state...
if (!MojoLua_runFile("mojosetup_init"))
return false;
581
582
// ...and run the installer-specific config file.
583
584
585
if (!MojoLua_runFile("config"))
return false;
586
587
588
589
590
591
592
593
594
595
596
597
// We don't need the MojoSetup.schema namespace anymore. Make it
// eligible for garbage collection.
lua_getglobal(luaState, MOJOSETUP_NAMESPACE);
if (lua_istable(luaState, -1))
{
lua_pushnil(luaState);
lua_setfield(luaState, -2, "schema");
} // if
lua_pop(luaState, 1);
MojoLua_collectGarbage(); // get rid of old init crap we don't need.
598
599
600
601
602
603
604
605
606
607
608
609
610
return true;
} // MojoLua_initLua
void MojoLua_deinitLua(void)
{
if (luaState != NULL)
{
lua_close(luaState);
luaState = NULL;
} // if
} // MojoLua_deinitLua
611
612
const char *GLuaLicense =
613
614
"Lua:\n"
"\n"
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
"Copyright (C) 1994-2006 Lua.org, PUC-Rio.\n"
"\n"
"Permission is hereby granted, free of charge, to any person obtaining a copy\n"
"of this software and associated documentation files (the \"Software\"), to deal\n"
"in the Software without restriction, including without limitation the rights\n"
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n"
"copies of the Software, and to permit persons to whom the Software is\n"
"furnished to do so, subject to the following conditions:\n"
"\n"
"The above copyright notice and this permission notice shall be included in\n"
"all copies or substantial portions of the Software.\n"
"\n"
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n"
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n"
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n"
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n"
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n"
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n"
"THE SOFTWARE.\n"
"\n";
636
// end of lua_glue.c ...