-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathui_main.cpp
More file actions
2230 lines (2076 loc) · 73.5 KB
/
Copy pathui_main.cpp
File metadata and controls
2230 lines (2076 loc) · 73.5 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
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// DyLua: SimpleGraphic
// (c) David Gowor, 2014
//
// Module: UI Main
//
#include "ui_local.h"
#if __APPLE__ && __MACH__
#include <dlfcn.h>
#include <luajit.h>
// Light C function replacements for LuaJIT built-ins whose interpreter fast-paths
// are broken in GC64 mode on arm64. Protected calls use lua_resume on a helper
// coroutine — lua_pcall from inside a LIGHTFUNC corrupts interpreter return state. (#8)
#if __APPLE__ && __MACH__
// Copy launch from helper thread into uicallbacks.MainObject (SetMainObject from co is unreliable). (#8)
static void mac_sync_main_object_from_co(lua_State* L, lua_State* co) {
lua_getglobal(co, "launch");
if (!lua_istable(co, -1)) {
lua_pop(co, 1);
return;
}
lua_getfield(L, LUA_REGISTRYINDEX, "uicallbacks");
lua_pushstring(L, "MainObject");
lua_xmove(co, L, 1);
lua_rawset(L, -3);
lua_pop(L, 1);
}
// SetMainObject from the launch coroutine may not update _G.launch; modules read the global. (#8)
static void mac_ensure_global_launch(lua_State* L) {
lua_getfield(L, LUA_REGISTRYINDEX, "uicallbacks");
if (!lua_istable(L, -1)) {
lua_settop(L, 0);
return;
}
lua_getfield(L, -1, "MainObject");
if (lua_istable(L, -1)) {
lua_setglobal(L, "launch");
}
lua_settop(L, 0);
}
#endif
static void mac_restore_raw_coroutine_create(lua_State* L) {
lua_getglobal(L, "coroutine");
lua_getfield(L, LUA_REGISTRYINDEX, "mac_co_create");
lua_setfield(L, -2, "create");
lua_pop(L, 1);
}
static int l_mac_restore_co(lua_State* L) {
mac_restore_raw_coroutine_create(L);
return 0;
}
// Disable the whole JIT engine via the LuaJIT C API (reliable on arm64 GC64). (#8)
void mac_jit_off(lua_State* L) {
const int off = LUAJIT_MODE_ENGINE | LUAJIT_MODE_OFF;
if (luaJIT_setmode(L, 0, off) != 1) {
lua_getglobal(L, "jit");
if (lua_istable(L, -1)) {
lua_getfield(L, -1, "off");
if (lua_isfunction(L, -1)) {
lua_call(L, 0, 0);
}
lua_pop(L, 1);
} else {
lua_pop(L, 1);
}
}
luaJIT_setmode(L, 0, LUAJIT_MODE_ENGINE | LUAJIT_MODE_FLUSH);
}
// LuaJIT arm64 FFUNC replacement: LJLIB_ASM fast functions have broken assembly
// dispatch on arm64 GC64. Functions with lua_tocfunction() != NULL (LJLIB_CF)
// are re-registered as LIGHTFUNCs. Functions returning NULL need manual C
// implementations. (#8)
//
// Converts one function: if LJLIB_ASM (tocfunction==NULL), skip (needs manual).
// If LJLIB_CF, re-register as LIGHTFUNC.
static int mac_convert_cfunc_in_table(lua_State* L, sys_IMain* sys,
const char* tblName, int tblIdx)
{
int converted = 0;
lua_pushnil(L);
while (lua_next(L, tblIdx) != 0) {
if (lua_type(L, -1) == LUA_TFUNCTION && lua_iscfunction(L, -1)) {
lua_CFunction cfn = lua_tocfunction(L, -1);
if (cfn) {
// CClosures with upvalues must keep them — skip
const char* upname = lua_getupvalue(L, -1, 1);
if (upname) {
lua_pop(L, 2); // pop upvalue value + function value, keep key
continue;
}
lua_pop(L, 1); // pop value
lua_pushcfunction(L, cfn);
const char* key = lua_isstring(L, -2) ? lua_tostring(L, -2) : nullptr;
if (key) {
lua_setfield(L, tblIdx, key);
converted++;
} else {
lua_pop(L, 1);
}
} else {
lua_pop(L, 1); // pop value, keep key
}
} else {
lua_pop(L, 1); // pop value, keep key
}
}
return converted;
}
// Manual LIGHTFUNC replacements for LJLIB_ASM functions (tocfunction==NULL).
static int mac_lf_tostring(lua_State* L) {
luaL_checkany(L, 1);
if (luaL_callmeta(L, 1, "__tostring")) return 1;
switch (lua_type(L, 1)) {
case LUA_TNIL: lua_pushliteral(L, "nil"); break;
case LUA_TBOOLEAN: lua_pushstring(L, lua_toboolean(L, 1) ? "true" : "false"); break;
case LUA_TNUMBER: {
char buf[64];
if (lua_isinteger(L, 1))
snprintf(buf, sizeof(buf), "%lld", (long long)lua_tointeger(L, 1));
else
snprintf(buf, sizeof(buf), "%.14g", lua_tonumber(L, 1));
lua_pushstring(L, buf);
break;
}
case LUA_TSTRING: lua_pushvalue(L, 1); break;
default:
lua_pushfstring(L, "%s: %p", luaL_typename(L, 1), lua_topointer(L, 1));
break;
}
return 1;
}
static int mac_lf_tonumber(lua_State* L) {
int base = (int)luaL_optinteger(L, 2, 10);
if (base == 10) {
luaL_checkany(L, 1);
if (lua_type(L, 1) == LUA_TNUMBER) {
lua_pushvalue(L, 1);
return 1;
}
const char* s = lua_tostring(L, 1);
if (s) {
char* end;
double d = strtod(s, &end);
if (end != s && *end == '\0') { lua_pushnumber(L, d); return 1; }
while (*end == ' ' || *end == '\t' || *end == '\n' || *end == '\r') end++;
if (*end == '\0' && end != s) { lua_pushnumber(L, d); return 1; }
}
lua_pushnil(L);
return 1;
}
const char* s = luaL_checkstring(L, 1);
luaL_argcheck(L, base >= 2 && base <= 36, 2, "base out of range");
char* end;
unsigned long long r = strtoull(s, &end, base);
while (*end == ' ' || *end == '\t') end++;
if (end == s || *end != '\0') { lua_pushnil(L); return 1; }
lua_pushnumber(L, (lua_Number)r);
return 1;
}
static int mac_lf_assert(lua_State* L) {
if (!lua_toboolean(L, 1)) {
const char* msg = lua_isstring(L, 2) ? lua_tostring(L, 2) : "assertion failed!";
return luaL_error(L, "%s", msg);
}
return lua_gettop(L);
}
static int mac_lf_next(lua_State* L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_settop(L, 2);
if (lua_next(L, 1)) return 2;
lua_pushnil(L);
return 1;
}
static int mac_lf_rawget(lua_State* L) {
luaL_checktype(L, 1, LUA_TTABLE);
luaL_checkany(L, 2);
lua_rawget(L, 1);
return 1;
}
static int mac_lf_rawlen(lua_State* L) {
int t = lua_type(L, 1);
luaL_argcheck(L, t == LUA_TTABLE || t == LUA_TSTRING, 1, "table or string expected");
lua_pushinteger(L, (lua_Integer)lua_rawlen(L, 1));
return 1;
}
static int mac_lf_setmetatable(lua_State* L) {
luaL_checktype(L, 1, LUA_TTABLE);
int t2 = lua_type(L, 2);
luaL_argcheck(L, t2 == LUA_TNIL || t2 == LUA_TTABLE, 2, "nil or table expected");
lua_settop(L, 2);
lua_setmetatable(L, 1);
lua_settop(L, 1);
return 1;
}
static int mac_lf_getmetatable(lua_State* L) {
luaL_checkany(L, 1);
if (!lua_getmetatable(L, 1)) { lua_pushnil(L); return 1; }
lua_getfield(L, -1, "__metatable");
if (!lua_isnil(L, -1)) return 1;
lua_pop(L, 1);
return 1;
}
static int mac_lf_rawequal(lua_State* L) {
luaL_checkany(L, 1);
luaL_checkany(L, 2);
lua_pushboolean(L, lua_rawequal(L, 1, 2));
return 1;
}
static int mac_lf_collectgarbage(lua_State* L) {
static const char* const opts[] = {
"stop", "restart", "collect", "count", "step",
"setpause", "setstepmul", "isrunning", nullptr
};
static const int optsnum[] = {
LUA_GCSTOP, LUA_GCRESTART, LUA_GCCOLLECT, LUA_GCCOUNT, LUA_GCSTEP,
LUA_GCSETPAUSE, LUA_GCSETSTEPMUL, 9/*LUA_GCISRUNNING*/
};
int o = luaL_checkoption(L, 1, "collect", opts);
int ex = (int)luaL_optinteger(L, 2, 0);
int res = lua_gc(L, optsnum[o], ex);
if (o == 3) { // count
int b = lua_gc(L, LUA_GCCOUNTB, 0);
lua_pushnumber(L, (lua_Number)res + (lua_Number)b / 1024.0);
return 1;
}
lua_pushinteger(L, res);
return 1;
}
// String library LJLIB_ASM replacements
static int mac_lf_string_byte(lua_State* L) {
size_t len;
const char* s = luaL_checklstring(L, 1, &len);
lua_Integer pi = luaL_optinteger(L, 2, 1);
lua_Integer pj = luaL_optinteger(L, 3, pi);
if (pi < 0) pi += (lua_Integer)len + 1;
if (pj < 0) pj += (lua_Integer)len + 1;
if (pi < 1) pi = 1;
if (pj > (lua_Integer)len) pj = (lua_Integer)len;
int n = 0;
for (lua_Integer i = pi; i <= pj; i++) {
lua_pushinteger(L, (unsigned char)s[i - 1]);
n++;
}
return n;
}
static int mac_lf_string_char(lua_State* L) {
int n = lua_gettop(L);
luaL_Buffer b;
luaL_buffinit(L, &b);
for (int i = 1; i <= n; i++) {
int c = (int)luaL_checkinteger(L, i);
luaL_argcheck(L, (unsigned int)c <= 255, i, "invalid value");
luaL_addchar(&b, (char)c);
}
luaL_pushresult(&b);
return 1;
}
static int mac_lf_string_len(lua_State* L) {
size_t len;
luaL_checklstring(L, 1, &len);
lua_pushinteger(L, (lua_Integer)len);
return 1;
}
static int mac_lf_string_sub(lua_State* L) {
size_t len;
const char* s = luaL_checklstring(L, 1, &len);
lua_Integer start = luaL_checkinteger(L, 2);
lua_Integer end = luaL_optinteger(L, 3, -1);
if (start < 0) start += (lua_Integer)len + 1;
if (end < 0) end += (lua_Integer)len + 1;
if (start < 1) start = 1;
if (end > (lua_Integer)len) end = (lua_Integer)len;
if (start > end) { lua_pushliteral(L, ""); return 1; }
lua_pushlstring(L, s + start - 1, (size_t)(end - start + 1));
return 1;
}
static int mac_lf_string_rep(lua_State* L) {
size_t len;
const char* s = luaL_checklstring(L, 1, &len);
int n = (int)luaL_checkinteger(L, 2);
if (n <= 0) { lua_pushliteral(L, ""); return 1; }
luaL_Buffer b;
luaL_buffinit(L, &b);
while (n-- > 0) luaL_addlstring(&b, s, len);
luaL_pushresult(&b);
return 1;
}
static int mac_lf_string_reverse(lua_State* L) {
size_t len;
const char* s = luaL_checklstring(L, 1, &len);
luaL_Buffer b;
char* p = luaL_buffinitsize(L, &b, len);
for (size_t i = 0; i < len; i++) p[i] = s[len - 1 - i];
luaL_pushresultsize(&b, len);
return 1;
}
static int mac_lf_string_lower(lua_State* L) {
size_t len;
const char* s = luaL_checklstring(L, 1, &len);
luaL_Buffer b;
char* p = luaL_buffinitsize(L, &b, len);
for (size_t i = 0; i < len; i++) p[i] = (char)tolower((unsigned char)s[i]);
luaL_pushresultsize(&b, len);
return 1;
}
static int mac_lf_string_upper(lua_State* L) {
size_t len;
const char* s = luaL_checklstring(L, 1, &len);
luaL_Buffer b;
char* p = luaL_buffinitsize(L, &b, len);
for (size_t i = 0; i < len; i++) p[i] = (char)toupper((unsigned char)s[i]);
luaL_pushresultsize(&b, len);
return 1;
}
// Math library LJLIB_ASM replacements
static int mac_lf_math_abs(lua_State* L) { lua_pushnumber(L, fabs(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_floor(lua_State* L) { lua_pushnumber(L, floor(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_ceil(lua_State* L) { lua_pushnumber(L, ceil(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_sqrt(lua_State* L) { lua_pushnumber(L, sqrt(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_log(lua_State* L) { lua_pushnumber(L, log(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_log10(lua_State* L) { lua_pushnumber(L, log10(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_exp(lua_State* L) { lua_pushnumber(L, exp(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_sin(lua_State* L) { lua_pushnumber(L, sin(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_cos(lua_State* L) { lua_pushnumber(L, cos(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_tan(lua_State* L) { lua_pushnumber(L, tan(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_asin(lua_State* L) { lua_pushnumber(L, asin(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_acos(lua_State* L) { lua_pushnumber(L, acos(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_atan(lua_State* L) { lua_pushnumber(L, atan(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_atan2(lua_State* L) { lua_pushnumber(L, atan2(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); return 1; }
static int mac_lf_math_sinh(lua_State* L) { lua_pushnumber(L, sinh(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_cosh(lua_State* L) { lua_pushnumber(L, cosh(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_tanh(lua_State* L) { lua_pushnumber(L, tanh(luaL_checknumber(L, 1))); return 1; }
static int mac_lf_math_pow(lua_State* L) { lua_pushnumber(L, pow(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); return 1; }
static int mac_lf_math_fmod(lua_State* L) { lua_pushnumber(L, fmod(luaL_checknumber(L, 1), luaL_checknumber(L, 2))); return 1; }
static int mac_lf_math_max(lua_State* L) {
int n = lua_gettop(L);
luaL_argcheck(L, n >= 1, 1, "value expected");
lua_Number m = luaL_checknumber(L, 1);
for (int i = 2; i <= n; i++) { lua_Number v = luaL_checknumber(L, i); if (v > m) m = v; }
lua_pushnumber(L, m);
return 1;
}
static int mac_lf_math_min(lua_State* L) {
int n = lua_gettop(L);
luaL_argcheck(L, n >= 1, 1, "value expected");
lua_Number m = luaL_checknumber(L, 1);
for (int i = 2; i <= n; i++) { lua_Number v = luaL_checknumber(L, i); if (v < m) m = v; }
lua_pushnumber(L, m);
return 1;
}
static int mac_lf_math_frexp(lua_State* L) {
int e; lua_pushnumber(L, frexp(luaL_checknumber(L, 1), &e));
lua_pushinteger(L, e); return 2;
}
static int mac_lf_math_ldexp(lua_State* L) {
lua_pushnumber(L, ldexp(luaL_checknumber(L, 1), (int)luaL_checkinteger(L, 2))); return 1;
}
static int mac_lf_math_modf(lua_State* L) {
double ip; double fp = modf(luaL_checknumber(L, 1), &ip);
lua_pushnumber(L, ip); lua_pushnumber(L, fp); return 2;
}
static int mac_lf_math_deg(lua_State* L) { lua_pushnumber(L, luaL_checknumber(L, 1) * (180.0 / M_PI)); return 1; }
static int mac_lf_math_rad(lua_State* L) { lua_pushnumber(L, luaL_checknumber(L, 1) * (M_PI / 180.0)); return 1; }
// Table library replacements
static int mac_lf_table_concat(lua_State* L) {
luaL_checktype(L, 1, LUA_TTABLE);
size_t seplen;
const char* sep = luaL_optlstring(L, 2, "", &seplen);
lua_Integer i = luaL_optinteger(L, 3, 1);
lua_Integer j = luaL_optinteger(L, 4, (lua_Integer)lua_rawlen(L, 1));
luaL_Buffer b;
luaL_buffinit(L, &b);
for (; i <= j; i++) {
lua_rawgeti(L, 1, i);
luaL_addvalue(&b);
if (i < j) luaL_addlstring(&b, sep, seplen);
}
luaL_pushresult(&b);
return 1;
}
// Master function to replace all broken LJLIB_ASM FFUNCs
static void mac_replace_broken_ffuncs(lua_State* L, sys_IMain* sys) {
int total = 0;
// 1. Replace LJLIB_ASM globals with manual implementations
struct { const char* name; lua_CFunction fn; } baseReplacements[] = {
{"tostring", mac_lf_tostring},
{"tonumber", mac_lf_tonumber},
{"assert", mac_lf_assert},
{"next", mac_lf_next},
{"rawget", mac_lf_rawget},
{"rawlen", mac_lf_rawlen},
{"rawequal", mac_lf_rawequal},
{"setmetatable", mac_lf_setmetatable},
{"getmetatable", mac_lf_getmetatable},
{"collectgarbage", mac_lf_collectgarbage},
};
for (auto& r : baseReplacements) {
lua_pushcfunction(L, r.fn);
lua_setglobal(L, r.name);
total++;
}
// 2. Convert all LJLIB_CF globals (with valid C pointers) to LIGHTFUNCs
lua_pushglobaltable(L);
total += mac_convert_cfunc_in_table(L, sys, "_G", lua_gettop(L));
lua_pop(L, 1);
// 3. Replace LJLIB_ASM string functions
lua_getglobal(L, "string");
if (lua_istable(L, -1)) {
struct { const char* name; lua_CFunction fn; } strReplacements[] = {
{"byte", mac_lf_string_byte},
{"char", mac_lf_string_char},
{"len", mac_lf_string_len},
{"sub", mac_lf_string_sub},
{"rep", mac_lf_string_rep},
{"reverse", mac_lf_string_reverse},
{"lower", mac_lf_string_lower},
{"upper", mac_lf_string_upper},
};
for (auto& r : strReplacements) {
lua_pushcfunction(L, r.fn);
lua_setfield(L, -2, r.name);
total++;
}
// Convert remaining LJLIB_CF string functions
total += mac_convert_cfunc_in_table(L, sys, "string", lua_gettop(L));
}
lua_pop(L, 1);
// 4. Replace LJLIB_ASM math functions
lua_getglobal(L, "math");
if (lua_istable(L, -1)) {
struct { const char* name; lua_CFunction fn; } mathReplacements[] = {
{"abs", mac_lf_math_abs}, {"floor", mac_lf_math_floor},
{"ceil", mac_lf_math_ceil}, {"sqrt", mac_lf_math_sqrt},
{"log", mac_lf_math_log}, {"log10", mac_lf_math_log10},
{"exp", mac_lf_math_exp}, {"sin", mac_lf_math_sin},
{"cos", mac_lf_math_cos}, {"tan", mac_lf_math_tan},
{"asin", mac_lf_math_asin}, {"acos", mac_lf_math_acos},
{"atan", mac_lf_math_atan}, {"atan2", mac_lf_math_atan2},
{"sinh", mac_lf_math_sinh}, {"cosh", mac_lf_math_cosh},
{"tanh", mac_lf_math_tanh}, {"pow", mac_lf_math_pow},
{"fmod", mac_lf_math_fmod}, {"max", mac_lf_math_max},
{"min", mac_lf_math_min}, {"frexp", mac_lf_math_frexp},
{"ldexp", mac_lf_math_ldexp}, {"modf", mac_lf_math_modf},
{"deg", mac_lf_math_deg}, {"rad", mac_lf_math_rad},
};
for (auto& r : mathReplacements) {
lua_pushcfunction(L, r.fn);
lua_setfield(L, -2, r.name);
total++;
}
total += mac_convert_cfunc_in_table(L, sys, "math", lua_gettop(L));
}
lua_pop(L, 1);
// 5. Convert LJLIB_CF functions in remaining library tables
// Skip "io" — its functions use lj_lib_upvalue internally (not exposed via
// lua_getupvalue) to set file-handle metatables; converting to LIGHTFUNC
// strips those hidden upvalues, producing bare userdata from io.open.
const char* libs[] = {"table", "os", "debug", "coroutine", nullptr};
for (int i = 0; libs[i]; i++) {
lua_getglobal(L, libs[i]);
if (lua_istable(L, -1)) {
if (strcmp(libs[i], "table") == 0) {
lua_pushcfunction(L, mac_lf_table_concat);
lua_setfield(L, -2, "concat");
total++;
}
total += mac_convert_cfunc_in_table(L, sys, libs[i], lua_gettop(L));
}
lua_pop(L, 1);
}
// 6. Also update string metatable so s:method() calls use our replacements
lua_pushliteral(L, "");
if (lua_getmetatable(L, -1)) {
lua_getglobal(L, "string");
lua_setfield(L, -2, "__index");
lua_pop(L, 1); // metatable
}
lua_pop(L, 1); // empty string
sys->con->Printf("macOS arm64: replaced %d broken FFUNC builtins with LIGHTFUNCs\n", total);
}
static int s_macHelperCoRef = LUA_NOREF;
void mac_sync_globals_from_helper_co(lua_State* L)
{
if (s_macHelperCoRef == LUA_NOREF) {
return;
}
lua_rawgeti(L, LUA_REGISTRYINDEX, s_macHelperCoRef);
if (!lua_isthread(L, -1)) {
lua_pop(L, 1);
return;
}
lua_State* co = lua_tothread(L, -1);
lua_pop(L, 1);
static const char* const kSyncKeys[] = { "main", "launch", nullptr };
for (int i = 0; kSyncKeys[i]; i++) {
lua_getglobal(co, kSyncKeys[i]);
if (!lua_isnil(co, -1)) {
lua_xmove(co, L, 1);
lua_setglobal(L, kSyncKeys[i]);
} else {
lua_pop(co, 1);
}
}
}
// Entry: L = [chunk, arg1..argN]. Run in fresh coroutine; store coroutine for
// mac_sync_globals_from_helper_co. Exit: [true, results...] or [false, errmsg]. (#8)
// Uses copy+xmove pattern from CallCallbackOnThread: push copies in reverse, xmove
// reverses them back to correct order on co. mac_lightfunc_pcall's plain xmove
// moves co_thread instead of chunk from direct C call sites.
int mac_pload_coroutine_call(lua_State* L, int extraArgs) {
mac_restore_raw_coroutine_create(L);
lua_State* co = lua_newthread(L); // L = [chunk, args..., co_thread]
for (int i = extraArgs; i >= 0; --i) { // push copies in reverse
lua_pushvalue(L, 1 + i);
}
lua_xmove(L, co, extraArgs + 1); // xmove reversal → correct order on co
// co_thread is at extraArgs+2 on L after xmove consumed the copies
if (s_macHelperCoRef != LUA_NOREF) {
luaL_unref(L, LUA_REGISTRYINDEX, s_macHelperCoRef);
}
lua_pushvalue(L, extraArgs + 2);
s_macHelperCoRef = luaL_ref(L, LUA_REGISTRYINDEX);
lua_settop(L, 0);
const int status = lua_resume(co, nullptr, extraArgs);
if (status == 0) {
const int nres = lua_gettop(co);
lua_pushboolean(L, 1);
if (nres > 0) lua_xmove(co, L, nres);
return nres + 1;
}
lua_pushboolean(L, 0);
if (lua_gettop(co) > 0) {
lua_xmove(co, L, 1);
} else {
lua_pushliteral(L, "PLoadModule: unknown error");
}
return 2;
}
// Entry: L = [func, arg1, ..., argN]. Exit: [true, ...] or [false, err].
int mac_lightfunc_pcall(lua_State* L, int nargs) {
mac_restore_raw_coroutine_create(L);
lua_State* co = lua_newthread(L);
lua_xmove(L, co, nargs + 1);
const int status = lua_resume(co, nullptr, nargs);
if (status == 0) {
const int nres = lua_gettop(co);
if (s_macHelperCoRef != LUA_NOREF) {
luaL_unref(L, LUA_REGISTRYINDEX, s_macHelperCoRef);
}
lua_pushvalue(L, 1); // helper thread object left on root stack by lua_newthread
s_macHelperCoRef = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushboolean(L, 1);
lua_xmove(co, L, nres);
lua_pop(L, 1); // drop thread
return nres + 1;
}
if (status == LUA_YIELD) {
lua_settop(co, 0);
lua_pushliteral(co, "cannot resume non-synchronous function in pcall");
}
lua_pushboolean(L, 0);
if (lua_gettop(co) > 0) {
lua_xmove(co, L, 1);
} else {
lua_pushliteral(L, "(error object is not a string)");
}
lua_pop(L, 1); // drop thread
return 2;
}
static int mac_run_chunk_result_table(lua_State* L, bool ok, int firstResultIndex) {
if (!ok) {
lua_createtable(L, 0, 2);
lua_pushboolean(L, 0);
lua_setfield(L, -2, "ok");
if (lua_gettop(L) >= firstResultIndex && lua_isstring(L, firstResultIndex)) {
lua_pushvalue(L, firstResultIndex);
} else {
lua_pushliteral(L, "unknown error");
}
lua_setfield(L, -2, "err");
lua_settop(L, 1);
return 1;
}
const int n = lua_gettop(L) - firstResultIndex + 1;
lua_createtable(L, n, 2);
lua_pushboolean(L, 1);
lua_setfield(L, -2, "ok");
for (int i = 0; i < n; i++) {
lua_pushvalue(L, firstResultIndex + i);
lua_rawseti(L, -2, i + 1);
}
lua_pushinteger(L, n);
lua_setfield(L, -2, "n");
lua_replace(L, 1);
lua_settop(L, 1);
return 1;
}
// Stack: [func, arg1..argN] -> { ok=true, n=N, [1..N]=... } or { ok=false, err=... }.
// Fast path: lua_pcall on main state (no select('#', ...) in Lua). (#8)
static int l_mac_call_chunk(lua_State* L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
const int nargs = lua_gettop(L) - 1;
const int err = lua_pcall(L, nargs, LUA_MULTRET, 0);
if (err != LUA_OK) {
return mac_run_chunk_result_table(L, false, 1);
}
return mac_run_chunk_result_table(L, true, 1);
}
// Stack: [func, arg1..argN] -> { ok=true, n=N, [1..N]=... } or { ok=false, err=... }.
// Always uses mac_lightfunc_pcall (restore raw coroutine.create before lua_newthread). (#8)
static int l_mac_run_chunk(lua_State* L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
const int nargs = lua_gettop(L) - 1;
const int pret = mac_lightfunc_pcall(L, nargs);
if (!lua_toboolean(L, 1)) {
return mac_run_chunk_result_table(L, false, 2);
}
lua_remove(L, 1);
return mac_run_chunk_result_table(L, true, 1);
}
static int l_mac_setmetatable(lua_State* L) {
luaL_checkany(L, 1);
luaL_checkany(L, 2);
lua_settop(L, 2);
if (!lua_setmetatable(L, 1)) {
lua_pushboolean(L, 0);
return 1;
}
lua_settop(L, 1);
return 1;
}
static int l_mac_pcall(lua_State* L) {
const int n = lua_gettop(L);
if (n < 1) {
luaL_error(L, "bad argument #1 to 'pcall' (value expected)");
}
// Use lua_pcall instead of mac_lightfunc_pcall: lua_resume hangs
// when called from inside a lua_pcall-protected frame on arm64 GC64. (#8)
const int status = lua_pcall(L, n - 1, LUA_MULTRET, 0);
lua_pushboolean(L, status == LUA_OK);
lua_insert(L, 1);
return lua_gettop(L);
}
#if __APPLE__ && __MACH__
// Prerequire(name) -> status, lib — avoids pcall(require, ...) on arm64 GC64. (#8)
static int l_mac_prerequire(lua_State* L) {
const char* name = luaL_checkstring(L, 1);
lua_settop(L, 1);
lua_getglobal(L, "package");
lua_getfield(L, -1, "loaded");
lua_getfield(L, -1, name);
if (!lua_isnil(L, -1)) {
lua_pushboolean(L, 1);
lua_insert(L, -2);
lua_settop(L, 2);
return 2;
}
lua_settop(L, 1);
lua_getglobal(L, "require");
lua_pushvalue(L, 1);
const int status = lua_pcall(L, 1, 1, 0);
if (status != LUA_OK) {
lua_settop(L, 0);
lua_pushboolean(L, 0);
lua_pushnil(L);
return 2;
}
lua_pushboolean(L, 1);
lua_insert(L, 1);
return 2;
}
#endif
static int l_mac_xpcall(lua_State* L) {
const int n = lua_gettop(L);
if (n < 2) {
luaL_error(L, "bad argument #2 to 'xpcall' (value expected)");
}
// xpcall(f, msgh, ...) → status, ... using lua_pcall with error handler. (#8)
lua_pushvalue(L, 2); // error handler
lua_insert(L, 1); // [msgh, f, msgh_orig, arg1, ...]
lua_remove(L, 3); // [msgh, f, arg1, ...]
const int nargs = n - 2;
const int status = lua_pcall(L, nargs, LUA_MULTRET, 1);
lua_remove(L, 1); // remove error handler
lua_pushboolean(L, status == LUA_OK);
lua_insert(L, 1);
return lua_gettop(L);
}
// loadfile + lua_pcall on the main state, then package.loaded[modname] = result. (#8)
static bool mac_preload_lua_file(lua_State* L, sys_IMain* sys, char const* modname,
std::filesystem::path const& file) {
if (!std::filesystem::exists(file)) {
sys->con->Printf("Warning: macOS preload %s: file not found: %s\n", modname,
file.generic_u8string().c_str());
return false;
}
const auto path = file.generic_u8string();
if (luaL_loadfile(L, path.c_str()) != LUA_OK) {
sys->con->Printf("Warning: macOS preload %s: load failed: %s\n", modname,
lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
if (lua_pcall(L, 0, 1, 0) != LUA_OK) {
sys->con->Printf("Warning: macOS preload %s: run failed: %s\n", modname,
lua_tostring(L, -1));
lua_pop(L, 1);
return false;
}
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_pushboolean(L, 1);
}
// stack: [1]=result, [2]=package, [3]=loaded
lua_getglobal(L, "package");
lua_getfield(L, -1, "loaded");
lua_pushvalue(L, -3);
lua_setfield(L, -2, modname);
lua_pop(L, 3);
return true;
}
// Call func+args on a helper coroutine (lua_resume). Replaces lua_call from LIGHTFUNCs. (#8)
static void mac_resume_call(lua_State* L, int nargs, int nresults) {
const int func = lua_gettop(L) - nargs;
lua_State* co = lua_newthread(L);
lua_pushvalue(L, func);
for (int i = 1; i <= nargs; i++) {
lua_pushvalue(L, func + i);
}
lua_xmove(L, co, nargs + 1);
lua_pop(L, 1); // drop thread handle
lua_settop(L, func - 1); // drop func and args from parent stack
const int status = lua_resume(co, nullptr, nargs);
if (status != 0) {
if (lua_gettop(co) > 0) {
lua_xmove(co, L, 1);
} else {
lua_pushliteral(L, "error in require loader");
}
lua_error(L);
}
const int got = lua_gettop(co);
const int want = (nresults == LUA_MULTRET) ? got : nresults;
lua_xmove(co, L, want);
for (int i = got; i < want; i++) {
lua_pushnil(L);
}
}
static int l_mac_coroutine_create(lua_State* L) {
luaL_checktype(L, 1, LUA_TFUNCTION);
lua_getfield(L, LUA_REGISTRYINDEX, "mac_co_create");
lua_insert(L, 1);
mac_resume_call(L, 1, 1);
return 1;
}
// loadfile() from Lua bytecode crashes after RenderInit on arm64 GC64 (same as setmetatable). (#8)
static int l_mac_loadfile(lua_State* L) {
lua_geti(L, LUA_REGISTRYINDEX, ui_main_c::REGISTRY_KEY);
auto* ui = static_cast<ui_main_c*>(lua_touserdata(L, -1));
lua_pop(L, 1);
const char* path = luaL_checkstring(L, 1);
auto filePath = std::filesystem::u8path(path);
if (!filePath.is_absolute()) {
filePath = (ui->scriptWorkDir / filePath).lexically_normal();
}
const auto pathStr = filePath.generic_u8string();
ui->sys->SetWorkDir(ui->scriptPath);
const int err = luaL_loadfile(L, pathStr.c_str());
ui->sys->SetWorkDir(ui->scriptWorkDir);
if (err != LUA_OK) {
return 1;
}
return 1;
}
// Stash loadfile result for MacLoadfile() Lua wrapper (bytecode cannot capture C returns). (#8)
static int l_mac_loadfile_stash(lua_State* L) {
const int err = l_mac_loadfile(L);
if (err == 1 && lua_isfunction(L, -1)) {
lua_setglobal(L, "__mac_loadfile_chunk");
lua_pushnil(L);
lua_setglobal(L, "__mac_loadfile_err");
return 0;
}
if (err == 1) {
lua_setglobal(L, "__mac_loadfile_err");
} else {
lua_pushliteral(L, "loadfile failed");
lua_setglobal(L, "__mac_loadfile_err");
}
lua_pushnil(L);
lua_setglobal(L, "__mac_loadfile_chunk");
return 0;
}
// Load and run a file; stash {ok,err,...} for MacDofile() Lua wrapper. (#8)
static int l_mac_dofile(lua_State* L) {
const int err = l_mac_loadfile(L);
if (err != 1 || !lua_isfunction(L, -1)) {
if (lua_gettop(L) < 1 || !lua_isstring(L, -1)) {
lua_settop(L, 0);
lua_pushliteral(L, "loadfile failed");
}
mac_run_chunk_result_table(L, false, 1);
lua_setglobal(L, "__mac_dofile_result");
return 0;
}
const int perr = lua_pcall(L, 0, 0, 0);
if (perr != LUA_OK) {
mac_run_chunk_result_table(L, false, 1);
lua_setglobal(L, "__mac_dofile_result");
return 0;
}
mac_run_chunk_result_table(L, true, lua_gettop(L) + 1);
lua_setglobal(L, "__mac_dofile_result");
return 0;
}
#if __APPLE__ && __MACH__
// __mac_loadfile_stash_c from Lua bytecode crashes arm64 GC64; call from C only. (#8)
static void mac_stash_loadfile(lua_State* L, ui_main_c* ui, char const* path) {
lua_getglobal(L, "__mac_loadfile_stash_c");
if (!lua_isfunction(L, -1)) {
lua_pop(L, 1);
return;
}
auto const filePath = (ui->scriptWorkDir / path).lexically_normal();
lua_pushstring(L, filePath.generic_u8string().c_str());
if (lua_pcall(L, 1, 0, 0) != LUA_OK) {
ui->sys->con->Printf("mac_stash_loadfile(%s) failed: %s\n", path, lua_tostring(L, -1));
lua_pop(L, 1);
}
}
static void mac_run_stashed_chunk(lua_State* L, ui_main_c* ui, char const* label) {
lua_getglobal(L, "__mac_loadfile_chunk");
if (!lua_isfunction(L, -1)) {
lua_getglobal(L, "__mac_loadfile_err");
ui->sys->con->Printf("%s load failed: %s\n", label, lua_tostring(L, -1));
lua_settop(L, 0);
return;
}
if (lua_pcall(L, 0, 0, 0) != LUA_OK) {
ui->sys->con->Printf("%s failed: %s\n", label, lua_tostring(L, -1));
lua_pop(L, 1);
}
lua_pushnil(L);
lua_setglobal(L, "__mac_loadfile_chunk");
lua_pushnil(L);
lua_setglobal(L, "__mac_loadfile_err");
lua_settop(L, 0);
}
// Call main:Init via C API (Init must be fetched from global main, not launch). (#8)
static void mac_invoke_main_init(lua_State* L, ui_main_c* ui) {
lua_settop(L, 0);
lua_getglobal(L, "main");
if (lua_isnil(L, -1)) {
ui->sys->con->Printf("main.Init: global main is nil after PLoadModule\n");
lua_settop(L, 0);
return;
}
lua_getglobal(L, "launch");
if (lua_istable(L, -1)) {
lua_pushvalue(L, -2);
lua_setfield(L, -2, "main");
lua_pop(L, 1);
} else {
lua_pop(L, 1);
}
lua_getfield(L, -1, "Init");
if (!lua_isfunction(L, -1)) {
ui->sys->con->Printf("main.Init: Init is %s\n", luaL_typename(L, -1));
lua_settop(L, 0);
return;
}
lua_pushvalue(L, -2); // push main as self argument
ui->sys->con->Printf("macOS: calling main.Init...\n");
if (lua_pcall(L, 1, 0, 0) != LUA_OK) {
ui->sys->con->Printf("main.Init failed: %s\n", lua_tostring(L, -1));
lua_pop(L, 1);
} else {
ui->sys->con->Printf("macOS: main.Init OK\n");
}
lua_settop(L, 0);
}
// Run LaunchAfterMain.lua from C after PLoadModule (split from OnInit on arm64 GC64). (#8)
static void mac_run_after_main_if_requested(lua_State* L, ui_main_c* ui) {
mac_ensure_global_launch(L);
lua_getglobal(L, "launch");
if (!lua_istable(L, -1)) {
lua_pop(L, 1);
return;
}
lua_pop(L, 1);
// Set platform flag so Lua side can skip unsupported features (e.g. update check). (#8)
lua_getglobal(L, "launch");
if (lua_istable(L, -1)) {
lua_pushboolean(L, 1);
lua_setfield(L, -2, "_isMacOS");
}
lua_pop(L, 1);
mac_stash_loadfile(L, ui, "LaunchCallbacks.lua");
lua_getglobal(L, "launch");
if (!lua_istable(L, -1)) {
ui->sys->con->Printf("macOS: global launch missing before LaunchCallbacks\n");
lua_settop(L, 0);
return;
}
lua_pop(L, 1);
mac_run_stashed_chunk(L, ui, "LaunchCallbacks.lua");
lua_getglobal(L, "launch");
lua_getfield(L, -1, "_finishAfterMain");
if (!lua_isfunction(L, -1)) {
ui->sys->con->Printf("macOS: launch._finishAfterMain missing after LaunchCallbacks\n");
lua_settop(L, 0);
return;
}
lua_pop(L, 2);
ui->sys->con->Printf("macOS: PLoadModule Modules/Main from C...\n");
if (!mac_pload_module_pcall(L, "Modules/Main")) {
const char* err = lua_tostring(L, -1);
ui->sys->con->Printf("PLoadModule failed: %s\n", err ? err : "(no message)");
lua_settop(L, 0);
return;
}
ui->sys->con->Printf("macOS: PLoadModule done (C path)\n");
mac_sync_globals_from_helper_co(L); // copy main/launch from coroutine _G to root _G (#8)
lua_getglobal(L, "main");
ui->sys->con->Printf("macOS: global main after plm is %s\n", luaL_typename(L, -1));
lua_settop(L, 0);
mac_ensure_global_launch(L);
ui->sys->con->Printf("macOS: global launch synced\n");
ui->sys->con->Printf("macOS: running LaunchAfterMain (_finishAfterMain)...\n");
lua_getglobal(L, "launch");
lua_getfield(L, -1, "_finishAfterMain");
if (!lua_isfunction(L, -1)) {
ui->sys->con->Printf("macOS: launch._finishAfterMain is not a function\n");
lua_settop(L, 0);
return;
}
lua_insert(L, -2);
int errfunc = 0;