/
arcan_lua.c
13227 lines (11103 loc) · 359 KB
/
arcan_lua.c
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
/*
* Copyright: Björn Ståhl
* License: GPLv2+, see COPYING file in arcan source repository.
* Reference: http://arcan-fe.com
*/
/*
* LWA changes:
* 1. split target_message into a special form for LWA
* 2. add an target_updatehandler for WORLDID that tracks a callback
* handler for the subseg_ev implementation.
* 3. map in the BCHUNK hints at least
*/
/*
* Notes regarding LUA use;
* - There are a few cases that has turned out problematic enough to
* warrant some kind of tracking to think about how things should
* be developed for the future. Due to the desire (need even) to
* support both LUA-jit and the reference lua implementation, some
* of the usual annoyances: (global scope being the default,
* double pollution, 1 indexing, no ; statement delimiter, no ternary
* operator, no aggregate operators, if (true) then return; end type
* quickhacks.
*
* - Type coersion; the whole "1" can turn into a number makes for a lot
* of problems with WORLDID and BADID being common "number-in-string"
* values with possibly hard to locate results.
*
* Worse still, true / false vs. nil use is terribly inconsistent,
* and some functions where the desire had been to force a boolean type
* integer options were temporarily used and now we have scripts in the
* wild relying on the behavior.
*
* - Double, strings and decimal points; some build-time dependencies pull
* in other dependencies where some have the audacity to change radix
* point behavior at random points during execution. Varying with window
* manager and display server conditions we run into situations where
* tonumber() tostring() class functions (and everything that maps to
* printf family) will at one time give 12345.6789 and shortly thereafter,
* 12345,6789
*/
#define arcan_luactx lua_State
#include "arcan_hmeta.h"
#include <lualib.h>
#include <lauxlib.h>
#if LUA_VERSION_NUM == 501
#define lua_rawlen(x, y) lua_objlen(x, y)
#endif
#include "arcan_lua.h"
#include "alt/types.h"
#include "alt/support.h"
#include "alt/nbio.h"
#include "alt/trace.h"
/*
* tradeoff (extra branch + loss in precision vs. assymetry and UB)
*/
#define abs( x ) ( abs( (x) == INT_MIN ? ((x)+1) : x ) )
/*
* some operations, typically resize, move and rotate suffered a lot from
* lua floats propagating, meaning that we'd get subpixel positioning
* and blurring text etc. as a consequence. For these functions, we now
* force the type to whatever acoord is specified as (here, signed).
*/
typedef int acoord;
/*
* arcan_fatal calls in this context are invalid Lua script invocations,
* these should only forward to arcan_fatal if there's no recovery script
* set.
*/
#define arcan_fatal(...) do { alt_fatal( __VA_ARGS__); } while(0)
/*
* ETRACE is used in stead of a normal return and is used to both track
* non-fatal non-warning script invocation errors and to check for
* unbalanced stacks.
* Example:
* static int lasttop = 0;
* define LUA_TRACE(fsym) lasttop = lua_gettop(ctx);
* define LUA_ETRACE(fsym, reason, argc){fprintf(stdout, "%s, %d\n",
fsym, (int)(lasttop - lua_gettop(ctx) + argc)); return argc;}
*
* Other example is measuring calls that are particularly slow to find
* blocking issues:
* #define LUA_TRACE(fsym) long long ts_in = arcan_timemillis();
* #define LUA_ETRACE(fsym, reason, argc){\
* if (arcan_timemillis() - ts_in > 2){\
* fprintf(stderr, "slow: %s, %lld\n", fsym, arcan_timemillis() - ts_in);\
* return argc;\
* }
*/
#include "arcan_img.h"
#include "arcan_ttf.h"
/* these take some explaining:
* to enforce that actual constants are used in LUA scripts and not magic
* numbers the corresponding binding functions check that the match these
* global constants (not defines as we want them maintained in debug data
* as well), but their actual values are set by defines so that they can be
* swizzled around by the build-system */
#ifndef CONST_ROTATE_RELATIVE
#define CONST_ROTATE_RELATIVE 10
#endif
#ifndef CONST_ROTATE_ABSOLUTE
#define CONST_ROTATE_ABSOLUTE 5
#endif
#ifndef CONST_MAX_SURFACEW
#define CONST_MAX_SURFACEW 8192
#endif
#ifndef CONST_MAX_SURFACEH
#define CONST_MAX_SURFACEH 4096
#endif
#ifndef CONST_RENDERTARGET_DETACH
#define CONST_RENDERTARGET_DETACH 20
#endif
#ifndef CONST_RENDERTARGET_NODETACH
#define CONST_RENDERTARGET_NODETACH 21
#endif
#ifndef CONST_RENDERTARGET_SCALE
#define CONST_RENDERTARGET_SCALE 30
#endif
#ifndef CONST_RENDERTARGET_NOSCALE
#define CONST_RENDERTARGET_NOSCALE 31
#endif
#ifndef CONST_FRAMESERVER_INPUT
#define CONST_FRAMESERVER_INPUT 41
#endif
#ifndef CONST_FRAMESERVER_OUTPUT
#define CONST_FRAMESERVER_OUTPUT 42
#endif
#ifndef CONST_DEVICE_INDIRECT
#define CONST_DEVICE_INDIRECT 1
#endif
#ifndef CONST_DEVICE_DIRECT
#define CONST_DEVICE_DIRECT 2
#endif
#ifndef CONST_DEVICE_LOST
#define CONST_DEVICE_LOST 3
#endif
#ifndef LAUNCH_EXTERNAL
#define LAUNCH_EXTERNAL 0
#endif
#ifndef LAUNCH_INTERNAL
#define LAUNCH_INTERNAL 1
#endif
#ifndef CONST_DISCOVER_PASSIVE
#define CONST_DISCOVER_PASSIVE 1
#endif
#ifndef CONST_DISCOVER_SWEEP
#define CONST_DISCOVER_SWEEP 2
#endif
#ifndef CONST_DISCOVER_BROADCAST
#define CONST_DISCOVER_BROADCAST 3
#endif
#ifndef CONST_DISCOVER_DIRECTORY
#define CONST_DISCOVER_DIRECTORY 4
#endif
#ifndef CONST_DISCOVER_TEST
#define CONST_DISCOVER_TEST 8
#endif
#ifndef CONST_TRUST_KNOWN
#define CONST_TRUST_KNOWN 11
#endif
#ifndef CONST_TRUST_PERMIT_UNKNOWN
#define CONST_TRUST_PERMIT_UNKNOWN 12
#endif
#ifndef CONST_TRUST_TRANSITIVE
#define CONST_TRUST_TRANSITIVE 13
#endif
#ifndef CONST_ANCHORHINT_SEGMENT
#define CONST_ANCHORHINT_SEGMENT 10
#endif
#ifndef CONST_ANCHORHINT_EXTERNAL
#define CONST_ANCHORHINT_EXTERNAL 11
#endif
#ifndef CONST_ANCHORHINT_PROXY
#define CONST_ANCHORHINT_PROXY 12
#endif
#ifndef CONST_ANCHORHINT_PROXY_EXTERNAL
#define CONST_ANCHORHINT_PROXY_EXTERNAL 13
#endif
/*
* disable support for all builtin frameservers
* which removes most (launch_target and target_alloc remain)
* ways of spawning external processes.
*/
static int fsrv_ok =
#ifdef DISABLE_FRAMESERVERS
0
#else
1
#endif
;
#define FATAL_MSG_FRAMESERV "specified destination is not a frameserver.\n"
/* we map the constants here so that poor or confused
* debuggers also have a chance to give us symbol resolution */
static const int MOUSE_GRAB_ON = 20;
static const int MOUSE_GRAB_OFF = 21;
static const int MAX_SURFACEH = CONST_MAX_SURFACEH;
static const int MAX_SURFACEW = CONST_MAX_SURFACEW;
static const int FRAMESET_NODETACH = 11;
static const int FRAMESET_DETACH = 10;
static const int RENDERTARGET_DETACH = CONST_RENDERTARGET_DETACH;
static const int RENDERTARGET_NODETACH = CONST_RENDERTARGET_NODETACH;
static const int RENDERTARGET_SCALE = CONST_RENDERTARGET_SCALE;
static const int RENDERTARGET_NOSCALE = CONST_RENDERTARGET_NOSCALE;
static const int RENDERFMT_COLOR = RENDERTARGET_COLOR;
static const int RENDERFMT_DEPTH = RENDERTARGET_DEPTH;
static const int RENDERFMT_FULL = RENDERTARGET_COLOR_DEPTH_STENCIL;
static const int RENDERFMT_MSAA = RENDERTARGET_MSAA;
static const int RENDERFMT_RETAIN_ALPHA = RENDERTARGET_RETAIN_ALPHA;
static const int DEVICE_INDIRECT = CONST_DEVICE_INDIRECT;
static const int DEVICE_DIRECT = CONST_DEVICE_DIRECT;
static const int DEVICE_LOST = CONST_DEVICE_LOST;
static const int ANCHORHINT_SEGMENT = CONST_ANCHORHINT_SEGMENT;
static const int ANCHORHINT_EXTERNAL = CONST_ANCHORHINT_EXTERNAL;
static const int ANCHORHINT_PROXY = CONST_ANCHORHINT_PROXY;
static const int ANCHORHINT_PROXY_EXTERNAL = CONST_ANCHORHINT_PROXY_EXTERNAL;
#define DBHANDLE arcan_db_get_shared(NULL)
static struct {
struct nonblock_io rawres;
unsigned char grab;
/* limits themename + identifier to this length
* will be modified in when calling into lua */
char* prefix_buf;
size_t prefix_ofs;
struct arcan_extevent* last_segreq;
char* pending_socket_label;
int pending_socket_descr;
const char** last_argv;
lua_State* last_ctx;
void (*error_hook)(lua_State*, lua_Debug*);
/* used by arcan_lwa to attach a handler for WORLDID display events */
intptr_t worldid_tag;
size_t last_clock;
} luactx = {0};
extern char* _n_strdup(const char* instr, const char* alt);
static const char* fsrvtos(enum ARCAN_SEGID ink);
static bool tgtevent(arcan_vobj_id dst, arcan_event ev);
static int alua_exposefuncs(lua_State* ctx, unsigned char debugfuncs);
static bool stack_to_uiarray(lua_State* ctx,
int memtype, unsigned** dst, size_t* n, size_t count);
static bool stack_to_farray(lua_State* ctx,
int memtype, float** dst, size_t* n, size_t count);
static char* colon_escape(char* in)
{
char* instr = in;
while(*instr){
if (*instr == ':')
*instr = '\t';
instr++;
}
return in;
}
/* slightly more flexible argument management, just find the first callback */
static intptr_t find_lua_callback(lua_State* ctx)
{
int nargs = lua_gettop(ctx);
for (size_t i = 1; i <= nargs; i++)
if (lua_isfunction(ctx, i) && !lua_iscfunction(ctx, i)){
lua_pushvalue(ctx, i);
intptr_t ref = luaL_ref(ctx, LUA_REGISTRYINDEX);
return ref;
}
return (intptr_t) LUA_NOREF;
}
static int find_lua_type(lua_State* ctx, int type, int ofs)
{
int nargs = lua_gettop(ctx);
for (size_t i = 1; i <= nargs; i++){
int ltype = lua_type(ctx, i);
if (ltype == type)
if (ofs-- == 0)
return i;
}
return 0;
}
static const char* luaL_lastcaller(lua_State* ctx)
{
static char msg[1024];
msg[1023] = '\0';
lua_Debug dbg;
lua_getstack(ctx, 1, &dbg);
lua_getinfo(ctx, "nlS" ,&dbg);
snprintf(msg, 1023, "%s:%d", dbg.short_src, dbg.currentline);
return msg;
}
static void trace_allocation(lua_State* ctx, const char* sym, arcan_vobj_id id)
{
if (lua_debug_level > 2)
arcan_warning("\x1b[1m %s: alloc(%s) => %"PRIxVOBJ")\x1b[39m\x1b[0m\n",
luaL_lastcaller(ctx), sym, id + lua_vid_base);
}
static void trace_coverage(const char* fsym, lua_State* ctx)
{
static FILE* outf;
static bool init;
retry:
if (!outf && init)
return;
if (!outf){
init = true;
char* fname = arcan_expand_resource("arcan.coverage", RESOURCE_SYS_DEBUG);
if (!fname)
return;
outf = fopen(fname, "w+");
arcan_mem_free(fname);
goto retry;
}
fprintf(outf, "%lld;%s;", arcan_timemillis(), fsym);
int top = lua_gettop(ctx);
for (size_t i = 1; i <= top; i++){
int t = lua_type(ctx, i);
switch (t){
case LUA_TBOOLEAN:
fputs("bool;", outf);
break;
case LUA_TNIL:
fputs("nil;", outf);
break;
case LUA_TLIGHTUSERDATA:
fputs("lightud;", outf);
break;
case LUA_TTABLE:
fputs("table;", outf);
break;
case LUA_TUSERDATA:
fputs("ud;", outf);
break;
case LUA_TTHREAD:
fputs("thread;", outf);
break;
case LUA_TSTRING:
fputs("str;", outf);
break;
case LUA_TNUMBER:
fputs("num;", outf);
break;
case LUA_TFUNCTION:
fputs("fptr;", outf);
break;
default:
fputs("unt;", outf);
break;
}
}
fputc('\n', outf);
}
/*
* iterate all vobject and drop any known tag-cb associations that
* are used to map events to lua functions
*/
void arcan_lua_cbdrop()
{
for (size_t i = 0; i <= vcontext_ind; i++){
struct arcan_video_context* ctx = &vcontext_stack[i];
for (size_t j = 0; j < ctx->vitem_limit; j++)
if (FL_TEST(&ctx->vitems_pool[j], FL_INUSE) &&
ctx->vitems_pool[j].feed.state.tag == ARCAN_TAG_FRAMESERV){
arcan_frameserver* fsrv = ctx->vitems_pool[j].feed.state.ptr;
if (!fsrv)
continue;
fsrv->tag = LUA_NOREF;
}
}
}
const char* arcan_lua_crash_source(struct arcan_luactx* ctx)
{
return alt_trace_crash_source(NULL);
}
static arcan_vobj_id luaL_checkaid(lua_State* ctx, int num)
{
return luaL_checknumber(ctx, num);
}
static void lua_pushvid(lua_State* ctx, arcan_vobj_id id)
{
if (id != ARCAN_EID && id != ARCAN_VIDEO_WORLDID)
id += lua_vid_base;
lua_pushnumber(ctx, (double) id);
}
static void lua_pushaid(lua_State* ctx, arcan_aobj_id id)
{
lua_pushnumber(ctx, id);
}
void arcan_state_dump(const char* key, const char* msg, const char* src)
{
time_t logtime = time(NULL);
struct tm* ltime = localtime(&logtime);
if (!ltime){
arcan_warning("arcan_state_dump(%s, %s, %s) failed, "
"couldn't get localtime.", key, msg, src);
return;
}
const char date_ptn[] = "%m%d_%H%M%S";
char date_str[ sizeof(date_ptn) * 2 ];
strftime(date_str, sizeof(date_str), date_ptn, ltime);
char state_fn[ strlen(key) + sizeof(".lua") + sizeof(date_str) ];
snprintf(state_fn, sizeof(state_fn), "%s_%s.lua", key, date_str);
char* fname = arcan_expand_resource(state_fn, RESOURCE_SYS_DEBUG);
if (!fname)
return;
FILE* tmpout = fopen(fname, "w+");
if (tmpout){
char dbuf[strlen(msg) + strlen(src) + 1];
snprintf(dbuf, sizeof(dbuf), "%s, %s\n", msg ? msg : "", src ? src : "");
arcan_lua_statesnap(tmpout, dbuf, false);
fclose(tmpout);
}
else
arcan_warning("crashdump requested but (%s) is not accessible.\n", fname);
arcan_mem_free(fname);
}
/* The places in _lua.c that calls this function should probably have a better
* handover as this incurs additional and almost always unnecessary strlen
* calls. To do that:
*
* lua_pushlstring(L, field, fsz),
* lua_rawget(L, ind)
*/
static const char* intblstr_sz(
lua_State* ctx, int ind, const char* field, size_t fsz)
{
lua_getfield(ctx, ind, field);
const char* rv = lua_tostring(ctx, -1);
lua_pop(ctx, 1);
return rv;
}
#define intblstr(L, I, F) intblstr_sz(L, (I), (F), (sizeof(F)/sizeof(char))-1)
static float intblfloat_sz(lua_State* ctx, int ind, const char* field, size_t fsz)
{
lua_getfield(ctx, ind, field);
float rv = lua_tonumber(ctx, -1);
lua_pop(ctx, 1);
return rv;
}
#define intblfloat(L, I, F) intblfloat_sz(L, (I), (F), (sizeof(F)/sizeof(char))-1)
static int intblint_sz(lua_State* ctx, int ind, const char* field, size_t fsz)
{
lua_getfield(ctx, ind, field);
int rv = lua_tointeger(ctx, -1);
lua_pop(ctx, 1);
return rv;
}
#define intblint(L, I, F) intblint_sz(L, (I), (F), (sizeof(F)/sizeof(char))-1)
static bool intblbool_sz(lua_State* ctx, int ind, const char* field, size_t fsz)
{
lua_getfield(ctx, ind, field);
bool rv = lua_toboolean(ctx, -1);
lua_pop(ctx, 1);
return rv;
}
#define intblbool(L, I, F) intblbool_sz(L, (I), (F), (sizeof(F)/sizeof(char))-1)
static char* findresource(
const char* arg, enum arcan_namespaces space, enum resource_type type)
{
char* res = arcan_find_resource(arg, space, type, NULL);
/* since this is invoked extremely frequently and is involved in file-system
* related stalls, maybe a sort of caching mechanism should be implemented
* (invalidate / refill every N ticks or have a flag to side-step it -- as a lot
* of resources are quite static and the rest of the API have to handle missing
* or bad resources anyhow, we also know which subdirectories to attach
* to OS specific event monitoring effects */
if (lua_debug_level){
arcan_warning("Debug, resource lookup for %s, yielded: %s\n", arg, res);
}
return res;
}
static int alua_doresolve(lua_State* ctx, const char* inp)
{
data_source source = arcan_open_resource(inp);
if (source.fd == BADFD)
return -1;
map_region map = arcan_map_resource(&source, false);
if (!map.ptr){
arcan_release_resource(&source);
return -1;
}
int rv = luaL_loadbuffer(ctx, map.ptr, map.sz, inp);
if (0 == rv)
rv = lua_pcall(ctx, 0, LUA_MULTRET, 0);
arcan_release_map(map);
arcan_release_resource(&source);
return rv;
}
void arcan_lua_tick(lua_State* ctx, size_t nticks, size_t global)
{
if (!nticks)
return;
arcan_lua_setglobalint(ctx, "CLOCK", global);
luactx.last_clock = global;
/* Many applications misused the callback handler, ignoring the nticks and
* global fields causing timed tasks to drift more than desired. Switch to
* have one preferred 'batched' and then one where we emit each tick */
if (alt_lookup_entry(ctx, "clock_pulse_batch", 17)){
TRACE_MARK_ENTER("scripting", "clock-pulse", TRACE_SYS_DEFAULT, global, nticks, "digital");
lua_pushnumber(ctx, global);
lua_pushnumber(ctx, nticks);
alt_call(ctx, CB_SOURCE_NONE, 0, 2, 0, LINE_TAG":clock_pulse_batch");
TRACE_MARK_EXIT("scripting", "clock-pulse", TRACE_SYS_DEFAULT, global, nticks, "digital");
return;
}
while (nticks){
nticks--;
if (!alt_lookup_entry(ctx, "clock_pulse", 11))
break;
TRACE_MARK_ENTER("scripting", "clock-pulse", TRACE_SYS_DEFAULT, global, 0, "digital");
lua_pushnumber(ctx, global);
lua_pushnumber(ctx, 1);
alt_call(ctx, CB_SOURCE_NONE, 0, 2, 0, LINE_TAG":clock_pulse");
TRACE_MARK_EXIT("scripting", "clock-pulse", TRACE_SYS_DEFAULT, global, 0, "digital");
}
/* trace job finished? unpack into table of tables */
alt_trace_finish(ctx);
}
char* arcan_lua_main(lua_State* ctx, const char* inp, bool file)
{
bool fail = false;
if (file){
fail = alua_doresolve(ctx, inp) != 0;
}
else
fail = luaL_dofile(ctx, inp) == 1;
if (fail){
const char* msg = lua_tostring(ctx, -1);
if (msg)
return strdup(msg);
}
return NULL;
}
/*
* explicitly call for the allocation and use of a connection-point
*/
bool arcan_lua_launch_cp(
struct arcan_luactx* ctx, const char* cp, const char* key)
{
if (!cp || !ctx)
return false;
if (!alt_lookup_entry(ctx, "adopt", sizeof("adopt")-1)){
arcan_warning("target appl lacks an _adopt handler\n");
return false;
}
struct arcan_frameserver* res =
platform_launch_listen_external(cp,
key, -1, ARCAN_SHM_UMASK, 32, 32, LUA_NOREF
);
if (!res){
arcan_warning("couldn't listen on connection point (%s)\n", cp);
return false;
}
lua_pushvid(ctx, res->vid);
lua_pushliteral(ctx, "_stdin");
lua_pushliteral(ctx, "");
lua_pushvid(ctx, ARCAN_EID);
lua_pushboolean(ctx, true);
alt_call(ctx, CB_SOURCE_NONE, 0, 5, 1, LINE_TAG":adopt");
if (lua_type(ctx, -1) == LUA_TBOOLEAN && lua_toboolean(ctx, -1)){
lua_pop(ctx, 1);
return true;
}
else {
arcan_warning("target appl rejected _stdin on adopt\n");
lua_pop(ctx, 1);
arcan_video_deleteobject(res->vid);
return false;
}
}
void arcan_lua_adopt(struct arcan_luactx* ctx)
{
/* works on the idea that the context stack has already been collapsed into
* 'only-fsrv' related vids left */
struct arcan_vobject_litem* first = vcontext_stack[0].stdoutp.first;
struct arcan_vobject_litem* current = first;
size_t n_fsrv = 0;
/* one: find out how many frameservers are running in the context */
while(current){
if (current->elem->feed.state.tag == ARCAN_TAG_FRAMESERV)
n_fsrv++;
current = current->next;
}
if (n_fsrv == 0)
return;
/* two: save all the IDs, this tracking is because every call to adopt may
* possibly change the context and number of frameservers, order losely so that
* we get primary segments before secondary ones */
arcan_vobj_id ids[n_fsrv];
size_t count = 0, lcount = n_fsrv -1;
current = first;
while(count < n_fsrv && current){
if (current->elem->feed.state.tag == ARCAN_TAG_FRAMESERV){
arcan_frameserver* fsrv = current->elem->feed.state.ptr;
if (fsrv->parent.vid != ARCAN_EID)
ids[lcount--] = current->elem->cellid;
else
ids[count++] = current->elem->cellid;
}
current = current->next;
}
arcan_vobj_id delids[n_fsrv];
size_t delcount = 0;
int tc = arcan_conductor_reset_count(false);
/* three: forward to adopt function (or delete) */
for (count = 0; count < n_fsrv; count++){
arcan_vobject* vobj = arcan_video_getobject(ids[count]);
if (!vobj || vobj->feed.state.tag != ARCAN_TAG_FRAMESERV)
continue;
arcan_frameserver* fsrv = vobj->feed.state.ptr;
fsrv->tag = LUA_NOREF;
bool delete = true;
/* use this to determine if the frameserver was created in the appl entry
* and thus should not be exposed as an adopt handler */
if (fsrv->desc.recovery_tick == tc)
continue;
if (alt_lookup_entry(ctx, "adopt", sizeof("adopt") - 1) &&
arcan_video_getobject(ids[count]) != NULL){
lua_pushvid(ctx, vobj->cellid);
lua_pushstring(ctx, fsrvtos(fsrv->segid));
lua_pushstring(ctx, fsrv->title);
lua_pushvid(ctx, fsrv->parent.vid);
lua_pushboolean(ctx, count < n_fsrv-1);
alt_call(ctx, CB_SOURCE_NONE, 0, 5, 1, LINE_TAG":adopt");
/* if we don't get an explicit accept, assume deletion */
if (lua_type(ctx, -1) == LUA_TBOOLEAN &&
lua_toboolean(ctx, -1) == true){
delete = false;
/* send register event again so adoption imposed handler might map
* to related archetype, then follow up with resized to underlying
* format. Other state restoration has to be handled by fsrv itself */
arcan_event_enqueue(arcan_event_defaultctx(), &(struct arcan_event){
.category = EVENT_EXTERNAL,
.ext.kind = EVENT_EXTERNAL_REGISTER,
.ext.registr.kind = fsrv->segid,
.ext.registr.guid[0] = fsrv->guid[0],
.ext.registr.guid[1] = fsrv->guid[1]
});
/* fake a resize event that corresponds to the last negotiated state */
arcan_event_enqueue(arcan_event_defaultctx(), &(struct arcan_event){
.category = EVENT_FSRV,
.fsrv.kind = EVENT_FSRV_RESIZED,
.fsrv.width = fsrv->desc.width,
.fsrv.height = fsrv->desc.height,
.fsrv.video = fsrv->vid,
.fsrv.audio = fsrv->aid,
.fsrv.otag = fsrv->tag,
.fsrv.fmt_fl =
(fsrv->desc.hints & SHMIF_RHINT_ORIGO_LL) |
(fsrv->desc.hints & SHMIF_RHINT_TPACK)
});
/* the RESET event to the affected frameserver, though it could be used as a
* DoS oracly, there are so many timing channels that are necessary that it
* doesn't really aid much by hiding the fact, but it can help a cooperative
* process enough that it is worth the tradeoff */
platform_fsrv_pushevent(fsrv, &(struct arcan_event){
.category = EVENT_TARGET,
.tgt.kind = TARGET_COMMAND_RESET,
.tgt.ioevs[0].iv = 2
});
}
lua_pop(ctx, 1);
}
if (delete)
delids[delcount++] = ids[count];
}
/* purge will remove all events that are not external, and those that
* are external will have its otag reset (as otherwise we'd be calling
* into a damaged luactx */
arcan_event_purge();
/* maskall will prevent new events from being added during delete,
* as we are not in a state of being able to track or interpret */
arcan_event_maskall(arcan_event_defaultctx());
for (count = 0; count < delcount; count++)
arcan_video_deleteobject(delids[count]);
arcan_event_clearmask(arcan_event_defaultctx());
/* lastly, there might be events that have been tagged to an old callback
* where we again lack state information enough to track */
}
static bool validblendmode(int m)
{
return
m == BLEND_NONE || m == BLEND_ADD || m == BLEND_SUB ||
m == BLEND_MULTIPLY || m == BLEND_NORMAL || m == BLEND_FORCE ||
m == BLEND_PREMUL;
}
static int zapresource(lua_State* ctx)
{
LUA_TRACE("zap_resource");
const char* srcpath = luaL_checkstring(ctx, 1);
char* path = findresource(srcpath,
RESOURCE_APPL_TEMP | RESOURCE_NS_USER, ARES_FILE);
if (path && unlink(path) != -1)
lua_pushboolean(ctx, true);
else
lua_pushboolean(ctx, false);
arcan_mem_free(path);
LUA_ETRACE("zap_resource", NULL, 1);
}
static int rawresource(lua_State* ctx)
{
LUA_TRACE("open_rawresource");
/* can't do more than this due to legacy */
if (luactx.rawres.fd > 0){
arcan_warning("open_rawresource(), open requested while other resource "
"still open, use close_rawresource first.\n");
close(luactx.rawres.fd);
luactx.rawres.fd = -1;
luactx.rawres.ofs = 0;
luactx.rawres.eofm = false;
}
char* path = findresource(
luaL_checkstring(ctx, 1), DEFAULT_USERMASK, ARES_FILE | ARES_RDONLY);
if (!path){
char* fname = arcan_expand_resource(
luaL_checkstring(ctx, 1), RESOURCE_APPL_TEMP);
if (fname){
luactx.rawres.fd = open(fname,
O_CREAT | O_CLOEXEC | O_RDWR, S_IRUSR | S_IWUSR);
arcan_mem_free(fname);
}
}
else{
luactx.rawres.fd = open(path, O_RDONLY | O_CLOEXEC);
arcan_mem_free(path);
}
luactx.rawres.lfstrip = true;
lua_pushboolean(ctx, luactx.rawres.fd > 0);
LUA_ETRACE("open_rawresource", "", 1);
}
static char* chop(char* str)
{
char* endptr = str + strlen(str) - 1;
while(isspace(*str)) str++;
if(!*str)
return str;
while(endptr > str && isspace(*endptr))
endptr--;
*(endptr+1) = 0;
return str;
}
static int funtable(lua_State* ctx, uint32_t kind)
{
lua_newtable(ctx);
int top = lua_gettop(ctx);
lua_pushliteral(ctx, "kind");
lua_pushnumber(ctx, kind);
lua_rawset(ctx, top);
return top;
}
static const char flt_alpha[] = "abcdefghijklmnopqrstuvwxyz-_";
static const char flt_chunkfn[] = "abcdefghijklmnopqrstuvwxyz1234567890;*";
static const char flt_alphanum[] = "abcdefghijklmnopqrstuvxwyz-0123456789-_";
static const char flt_Alphanum[] = "abcdefghijklmnopqrstuvxwyz-0123456789-_"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ";
static const char flt_Alpha[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
"abcdefghijklmnopqrstuvwxyz";
static const char flt_num[] = "0123456789_-";
static const char flt_chint[] = "abcdefhijklmnopqrstuvwyz:1234567890";
static void fltpush(char* dst, char ulim,
char* inmsg, const char* fltch, char replch)
{
while (*inmsg && ulim--){
const char* pos = fltch;
bool found = false;
while(*pos){
if (*pos == *inmsg){
found = true;
break;
}
pos++;
}
if (!found){
if (replch)
*dst++ = replch;
}
else
*dst++ = *inmsg;
inmsg++;
}
*dst = '\0';
}
/*
* Scan and check that the sequence is valid utf-8 and does not exceed the set
* upper limit. If it does, truncate and return, otherwise copy into dst. Ulim
* includes the terminating 0.
*/
#include "../frameserver/util/utf8.c"
static void slim_utf8_push(char* dst, int ulim, char* inmsg)
{
uint32_t state = 0;
uint32_t codepoint = 0;
size_t i = 0;
for (; inmsg[i] != '\0' && i < ulim; i++){
dst[i] = inmsg[i];
if (utf8_decode(&state, &codepoint, (uint8_t)(inmsg[i])) == UTF8_REJECT)
goto out;
}
if (state == UTF8_ACCEPT){
dst[i] = '\0';
return;
}
/* for broken state, just ignore. The other options would be 'warn' (will spam)
* or to truncate (might in some cases be prefered). */
out:
dst[0] = '\0';
}
static char* streamtype(int num)
{
switch (num){
case 0: return "audio";
case 1: return "video";
case 2: return "text";
case 3: return "overlay";
}
return "broken";
}
static int readrawresource(lua_State* ctx)
{
LUA_TRACE("read_rawresource");
if (luactx.rawres.eofm){
LUA_ETRACE("read_rawresource", NULL, 0);
}
if (luactx.rawres.fd <= 0){
LUA_ETRACE("read_rawresource", "no open file", 0);
}
int n = alt_nbio_process_read(ctx, &luactx.rawres, false);
LUA_ETRACE("read_rawresource", NULL, n);
}
void arcan_lua_setglobalstr(lua_State* ctx,
const char* key, const char* val)
{
lua_pushstring(ctx, val);
lua_setglobal(ctx, key);
}
void arcan_lua_setglobalint(lua_State* ctx, const char* key, int val)
{
lua_pushnumber(ctx, val);