-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjsiCmds.c
More file actions
2394 lines (2231 loc) · 79.3 KB
/
Copy pathjsiCmds.c
File metadata and controls
2394 lines (2231 loc) · 79.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
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
#ifndef JSI_LITE_ONLY
#ifndef JSI_AMALGAMATION
#include "jsiInt.h"
#else
char *strptime(const char *buf, const char *fmt, struct tm *tm);
#endif
#include <errno.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <signal.h>
#include <limits.h>
static int consoleInputCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char buf[1024];
char *p = buf;
if (fgets(buf, 1024, stdin) == NULL) {
Jsi_ValueMakeUndef(interp,*ret);
return JSI_OK;
}
if ((p = strchr(buf, '\r'))) *p = 0;
if ((p = strchr(buf, '\n'))) *p = 0;
Jsi_ValueMakeString(interp, *ret, Jsi_Strdup(buf));
return JSI_OK;
}
typedef struct {
int debug;
char index;
char isInvoked;
} SourceData;
static Jsi_OptionSpec SourceOptions[] = {
JSI_OPT(INT, SourceData, debug, .help="Debug level" ),
JSI_OPT(BOOL, SourceData, index, .help="Setup for load of jsiIndex.jsi files" ),
JSI_OPT(BOOL, SourceData, isInvoked, .help="Force info.isInvoke() to true" ),
JSI_OPT_END(SourceData)
};
static int sourceCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
jsi_Pstate *ps = interp->ps;
int rc = JSI_OK, flags = 0;
int i, argc, oisi;
SourceData data = {};
Jsi_Value *v, *va = Jsi_ValueArrayIndex(interp, args, 0);
Jsi_Value *vo = Jsi_ValueArrayIndex(interp, args, 1);
if (vo) {
if (!Jsi_ValueIsObjType(interp, vo, JSI_OT_OBJECT)) { /* Future options. */
Jsi_LogError("expected options object");
return JSI_ERROR;
}
if (Jsi_OptionsProcess(interp, SourceOptions, vo, &data, 0) < 0) {
return JSI_ERROR;
}
if (data.index)
flags |= JSI_EVAL_INDEX;
}
if ((interp->includeDepth+1) > interp->maxIncDepth) {
Jsi_LogError("max source depth exceeded");
return JSI_ERROR;
}
interp->includeDepth++;
oisi = interp->isInvoked;
interp->isInvoked = data.isInvoked;
if (!Jsi_ValueIsArray(interp, va)) {
v = va;
if (v && Jsi_ValueIsString(interp,v)) {
if (data.debug)
fprintf(stderr, "sourcing: %s\n", Jsi_ValueString(interp, v, 0));
rc = Jsi_EvalFile(ps->interp, v, flags);
} else {
Jsi_LogError("expected string");
rc = JSI_ERROR;
}
goto done;
}
argc = Jsi_ValueGetLength(interp, va);
for (i=0; i<argc && rc == JSI_OK; i++) {
v = Jsi_ValueArrayIndex(interp, va, i);
if (v && Jsi_ValueIsString(interp,v)) {
if (data.debug)
fprintf(stderr, "sourcing: %s\n", Jsi_ValueString(interp, v, 0));
rc = Jsi_EvalFile(ps->interp, v, flags);
} else {
Jsi_LogError("expected string");
rc = JSI_ERROR;
break;
}
}
done:
interp->isInvoked = oisi;
interp->includeDepth--;
return rc;
}
static void jsiGetTime(long *seconds, long *milliseconds)
{
struct timeval tv;
gettimeofday(&tv, NULL);
*seconds = tv.tv_sec;
*milliseconds = tv.tv_usec / 1000;
}
void Jsi_EventFree(Jsi_Interp *interp, Jsi_Event* event) {
SIGASSERT(event,EVENT);
if (event->funcVal)
Jsi_DecrRefCount(interp, event->funcVal);
if (event->hPtr)
Jsi_HashEntryDelete(event->hPtr);
MEMCLEAR(event);
Jsi_Free(event);
}
/* Create an event and add to interp event table. */
Jsi_Event* Jsi_EventNew(Jsi_Interp *interp, Jsi_EventHandlerProc *callback, void* data)
{
Jsi_Event *ev;
while (1) {
int isNew, id = interp->eventIdx++;
Jsi_HashEntry *hPtr = Jsi_HashEntryCreate(interp->eventTbl, (void*)id, &isNew);
if (!isNew)
continue;
ev = Jsi_Calloc(1, sizeof(*ev));
SIGINIT(ev,EVENT);
ev->id = id;
ev->handler = callback;
ev->data = data;
ev->hPtr = hPtr;
Jsi_HashValueSet(hPtr, ev);
break;
}
return ev;
}
/* Process events and return count. */
int Jsi_EventProcess(Jsi_Interp *interp, int maxEvents)
{
Jsi_Event *ev;
Jsi_HashEntry *hPtr;
Jsi_HashSearch search;
Jsi_Value* nret = NULL;
int rc, cnt = 0, newIdx = interp->eventIdx;
long cur_sec, cur_ms;
jsiGetTime(&cur_sec, &cur_ms);
Jsi_Value *vpargs = NULL;
/*if (Jsi_MutexLock(interp, interp->Mutex) != JSI_OK)
return JSI_ERROR;*/
for (hPtr = Jsi_HashEntryFirst(interp->eventTbl, &search);
hPtr != NULL; hPtr = Jsi_HashEntryNext(&search)) {
if (!(ev = Jsi_HashValueGet(hPtr)))
continue;
SIGASSERT(ev,EVENT);
if (ev->id >= newIdx) /* Avoid infinite loop of event creating events. */
continue;
switch (ev->evType) {
case JSI_EVENT_SIGNAL:
#ifndef JSI_OMIT_SIGNAL /* TODO: win signals? */
if (!jsi_SignalIsSet(interp, ev->sigNum))
continue;
jsi_SignalClear(interp, ev->sigNum);
#endif
break;
case JSI_EVENT_TIMER:
if (cur_sec <= ev->when_sec && (cur_sec != ev->when_sec || cur_ms < ev-> when_ms)) {
if (ev->when_sec && ev->when_ms)
continue;
}
break;
case JSI_EVENT_ALWAYS:
break;
default: assert(0);
}
cnt++;
ev->count++;
if (ev->handler) {
rc = ev->handler(interp, ev->data);
} else {
if (vpargs == NULL) {
vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, NULL, 0));
Jsi_IncrRefCount(interp, vpargs);
}
nret = Jsi_ValueNew1(interp);
Jsi_ValueReset(interp, nret);
rc = Jsi_FunctionInvoke(interp, ev->funcVal, vpargs, &nret, NULL);
}
if (interp->deleting) {
cnt = -1;
goto bail;
}
if (rc != JSI_OK) {
if (interp->exited) {
cnt = -1;
return rc;
}
Jsi_LogError("event function call failure");
}
if (ev->once) {
if (ev->funcVal)
Jsi_ObjDecrRefCount(interp, ev->funcVal->d.obj);
Jsi_HashEntryDelete(ev->hPtr);
Jsi_Free(ev);
} else {
ev->when_sec = cur_sec + ev->initialms / 1000;
ev->when_ms = cur_ms + ev->initialms % 1000;
if (ev->when_ms >= 1000) {
ev->when_sec++;
ev->when_ms -= 1000;
}
}
if (maxEvents>0 && cnt>=maxEvents)
break;
}
bail:
if (vpargs)
Jsi_DecrRefCount(interp, vpargs);
if (nret)
Jsi_DecrRefCount(interp, nret);
/*Jsi_MutexUnlock(interp, interp->Mutex);*/
return cnt;
}
/*
* \brief: sleep for so many milliseconds with mutex unlocked.
*/
int Jsi_Sleep(Jsi_Interp *interp, Jsi_Number dtim) {
uint utim = 0;
Jsi_MutexUnlock(interp, interp->Mutex);
if (dtim>0) {
dtim = (dtim/1e3);
if (dtim>1) {
utim = 1e6*(dtim - (Jsi_Number)((int)dtim));
dtim = (int)dtim;
} else if (dtim<1) {
utim = 1e6 * dtim;
dtim = 0;
}
if (utim>0)
usleep(utim);
if (dtim>0)
sleep(dtim);
}
if (Jsi_MutexLock(interp, interp->Mutex) != JSI_OK) {
Jsi_LogBug("could not reget mutex");
return JSI_ERROR;
}
return JSI_OK;
}
typedef struct {
int minTime;
int maxEvents;
int maxPasses;
int sleep;
} UpdateData;
static Jsi_OptionSpec UpdateOptions[] = {
JSI_OPT(INT, UpdateData, maxEvents, .help="Maximum number of events to process", .init="-1" ),
JSI_OPT(INT, UpdateData, maxPasses, .help="Maximum passes through event queue" ),
JSI_OPT(INT, UpdateData, minTime, .help="Minimum milliseconds before returning, or -1 to loop forever" ),
JSI_OPT(INT, UpdateData, sleep, .help="Sleep time between event checks in milliseconds", .init="1" ),
JSI_OPT_END(UpdateData)
};
#define FN_update JSI_INFO("\
Process events until minTime milliseconds exceeded, or forever if -1. Default minTime is 0. \
With a positive mintime \
a sleep occurs between each event check pass. The returned value is the number of events processed.")
static int SysUpdateCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
int maxEvents = -1, hasopts = 0;
int cnt = 0, lcnt = 0, rc = JSI_OK;
Jsi_Value *opts = Jsi_ValueArrayIndex(interp, args, 0);
long cur_sec, cur_ms;
long start_sec, start_ms;
jsiGetTime(&start_sec, &start_ms);
UpdateData udata;
memset(&udata, 0, sizeof(udata));
udata.sleep = 1;
jsi_AddEventHandler(interp);
if (opts != NULL) {
Jsi_Number dms;
if (opts->vt == JSI_VT_OBJECT) {
hasopts = 1;
if (Jsi_OptionsProcess(interp, UpdateOptions, opts, &udata, 0) < 0) {
return JSI_ERROR;
}
} else if (opts->vt != JSI_VT_NULL && Jsi_GetNumberFromValue(interp, opts, &dms) != JSI_OK)
return JSI_ERROR;
else
udata.minTime = (unsigned long)dms;
}
while (1) {
long long diftime;
int ne = Jsi_EventProcess(interp, maxEvents);
if (ne<0)
break;
cnt += ne;
if (Jsi_InterpGone(interp))
return JSI_ERROR;
if (udata.minTime==0)
break;
jsiGetTime(&cur_sec, &cur_ms);
if (cur_sec == start_sec)
diftime = (long long)(cur_ms-start_ms);
else
diftime = (cur_sec-start_sec)*1000LL + cur_ms + (1000-start_ms);
if (udata.minTime>0 && diftime >= (long long)udata.minTime)
break;
if (udata.maxPasses && ++lcnt >= udata.maxPasses)
break;
if ((rc = Jsi_Sleep(interp, udata.sleep)) != JSI_OK)
break;
}
if (hasopts)
Jsi_OptionsFree(interp, UpdateOptions, &udata, 0);
Jsi_ValueMakeNumber(interp, *ret, (Jsi_Number)cnt);
return rc;
}
static int intervalTimer(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value *ret, Jsi_Func *funcPtr, int once)
{
int isNew;
Jsi_Event *ev;
uint id;
Jsi_Number milli;
long milliseconds, cur_sec, cur_ms;
Jsi_Value *fv = Jsi_ValueArrayIndex(interp, args, 0);
Jsi_Value *tv = Jsi_ValueArrayIndex(interp, args, 1);
if (!Jsi_ValueIsFunction(interp, fv)) {
Jsi_LogError("expected function");
return JSI_ERROR;
}
if (Jsi_GetNumberFromValue(interp, tv, &milli) != JSI_OK) {
Jsi_LogError("expected number");
return JSI_ERROR;
}
milliseconds = (long)milli;
if (milliseconds < 0)
milliseconds = 0;
while (1) {
id = interp->eventIdx++;
Jsi_HashEntry *hPtr = Jsi_HashEntryCreate(interp->eventTbl, (void*)id, &isNew);
if (!isNew)
continue;
ev = Jsi_Calloc(1, sizeof(*ev));
SIGINIT(ev,EVENT);
ev->id = id;
ev->funcVal = fv;
Jsi_IncrRefCount(interp, fv);
ev->hPtr = hPtr;
jsiGetTime(&cur_sec, &cur_ms);
ev->initialms = milliseconds;
ev->when_sec = cur_sec + milliseconds / 1000;
ev->when_ms = cur_ms + milliseconds % 1000;
if (ev->when_ms >= 1000) {
ev->when_sec++;
ev->when_ms -= 1000;
}
ev->once = once;
Jsi_HashValueSet(hPtr, ev);
break;
}
Jsi_ValueMakeNumber(interp, ret, (Jsi_Number)id);
return JSI_OK;
}
static int setIntervalCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
return intervalTimer(interp, args, _this, *ret, funcPtr, 0);
}
static int clearIntervalCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Event *ev;
Jsi_Number nid;
int id;
Jsi_Value *tv = Jsi_ValueArrayIndex(interp, args, 0);
Jsi_HashEntry *hPtr;
if (Jsi_GetNumberFromValue(interp, tv, &nid) != JSI_OK) {
Jsi_LogError("expected number");
return JSI_ERROR;
}
id = (uint)nid;
hPtr = Jsi_HashEntryFind(interp->eventTbl, (void*)id);
if (hPtr == NULL) {
Jsi_LogError("id not found: %d", id);
return JSI_ERROR;
}
ev = Jsi_HashValueGet(hPtr);
Jsi_EventFree(interp, ev);
return JSI_OK;
}
static int setTimeoutCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
return intervalTimer(interp, args, _this, *ret, funcPtr, 1);
}
static int exitCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
int err = 0;
Jsi_Value *v = NULL;
if (Jsi_ValueGetLength(interp, args) > 0) {
v = Jsi_ValueArrayIndex(interp, args, 0);
if (v && Jsi_ValueIsType(interp,v, JSI_VT_NUMBER))
err = (int)v->d.num;
else {
Jsi_LogError("expected number");
return JSI_ERROR;
}
}
if (interp->onExit && interp->parent && Jsi_FunctionInvokeBool(interp->parent, interp->onExit, v))
return JSI_OK;
if (interp->parent == NULL && 0) {
if (interp == jsiMainInterp)
exit(err);
Jsi_InterpDelete(interp);
return JSI_ERROR;
} else {
interp->exited = 1;
interp->exitCode = err;
return JSI_ERROR;
/* TODO: cleanup events, etc. */
}
return JSI_OK;
}
int jsi_AssertCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
int rc = 0, n;
Jsi_Number d;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
char *msg = Jsi_ValueArrayIndexToStr(interp, args, 1, NULL);
if (interp->nDebug)
return JSI_OK;
if (Jsi_ValueGetNumber(interp,v, &d) == JSI_OK)
rc = (int)d;
else if (Jsi_ValueGetBoolean(interp,v, &n) == JSI_OK)
rc = n;
else if (Jsi_ValueIsFunction(interp, v)) {
Jsi_Value *vpargs = Jsi_ValueMakeObject(interp, NULL, Jsi_ObjNewArray(interp, NULL, 0));
Jsi_IncrRefCount(interp, vpargs);
rc = Jsi_FunctionInvoke(interp, v, vpargs, ret, NULL);
Jsi_DecrRefCount(interp, vpargs);
if (Jsi_ValueGetNumber(interp, *ret, &d) == JSI_OK)
rc = (int)d;
else if (Jsi_ValueGetBoolean(interp, *ret, &n) == JSI_OK)
rc = n;
else {
Jsi_LogWarn("invalid function assert");
return JSI_ERROR;
}
} else {
Jsi_LogWarn("invalid assert");
return JSI_ERROR;
}
if (rc == 0) {
Jsi_ValueCopy(interp, *ret, Jsi_ValueArrayIndex(interp, args, 1));
Jsi_LogError("assert failed: %s", msg?msg:"");
return JSI_ERROR;
}
return JSI_OK;
}
static int parseIntCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Wide w;
Jsi_Number d;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
Jsi_Value *bv = Jsi_ValueArrayIndex(interp, args, 1);
if (!v)
return JSI_ERROR;
if (!bv)
d = Jsi_ValueToNumberInt(interp, v, 1);
else {
int base = 0;
char *eptr, *str = Jsi_ValueString(interp, v, NULL);
if (str == NULL || JSI_OK != Jsi_GetIntFromValue(interp, bv, &base) || base<2 || base>36)
return JSI_ERROR;
d = (Jsi_Number)strtoll(str, &eptr, base);
}
if (jsi_num_isFinite(d)==0 &&
Jsi_GetDoubleFromValue(interp, v, &d) != JSI_OK)
Jsi_ValueCopy(interp, *ret, interp->NaNValue);
else {
w = (Jsi_Wide)d;
Jsi_ValueMakeNumber(interp, *ret, (Jsi_Number)w);
}
return JSI_OK;
}
static int parseFloatCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Number n;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (Jsi_GetDoubleFromValue(interp, v, &n) != JSI_OK)
Jsi_ValueCopy(interp, *ret, interp->NaNValue);
else
Jsi_ValueMakeNumber(interp, *ret, n);
return JSI_OK;
}
static int SysNoOpCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
return JSI_OK;
}
static int isNaNCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Number n;
int rc = 0;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (Jsi_GetDoubleFromValue(interp, v, &n) != JSI_OK || jsi_num_isNaN(n))
rc = 1;
Jsi_ValueMakeBool(interp, *ret, rc);
return JSI_OK;
}
static int isFiniteCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Number n;
int rc = 1;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (Jsi_GetDoubleFromValue(interp, v, &n) != JSI_OK || !jsi_num_isFinite(n))
rc = 0;
Jsi_ValueMakeBool(interp, *ret, rc);
return JSI_OK;
}
/* Converts a hex character to its integer value */
static char from_hex(char ch) {
return isdigit(ch) ? ch - '0' : tolower(ch) - 'a' + 10;
}
/* Converts an integer value to its hex character*/
static char to_hex(char code) {
static char hex[] = "0123456789abcdef";
return hex[code & 15];
}
/* Returns a url-encoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
static char *url_encode(char *str) {
char *pstr = str, *buf = malloc(strlen(str) * 3 + 1), *pbuf = buf;
while (*pstr) {
if (isalnum(*pstr) || *pstr == '-' || *pstr == '_' || *pstr == '.' || *pstr == '~')
*pbuf++ = *pstr;
else if (*pstr == ' ')
*pbuf++ = '+';
else
*pbuf++ = '%', *pbuf++ = to_hex(*pstr >> 4), *pbuf++ = to_hex(*pstr & 15);
pstr++;
}
*pbuf = '\0';
return buf;
}
/* Returns a url-decoded version of str */
/* IMPORTANT: be sure to free() the returned string after use */
static char *url_decode(char *str) {
char *pstr = str, *buf = malloc(strlen(str) + 1), *pbuf = buf;
while (*pstr) {
if (*pstr == '%') {
if (pstr[1] && pstr[2]) {
*pbuf++ = from_hex(pstr[1]) << 4 | from_hex(pstr[2]);
pstr += 2;
}
} else if (*pstr == '+') {
*pbuf++ = ' ';
} else {
*pbuf++ = *pstr;
}
pstr++;
}
*pbuf = '\0';
return buf;
}
/*
static int EscapeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
}
static int UnescapeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
}*/
static int EncodeURICmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char *cp, *str = Jsi_ValueArrayIndexToStr(interp, args, 0, NULL);
cp = url_encode(str);
Jsi_ValueMakeString(interp, *ret, cp);
return JSI_OK;
}
static int DecodeURICmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
char *cp, *str = Jsi_ValueArrayIndexToStr(interp, args, 0, NULL);
cp = url_decode(str);
Jsi_ValueMakeString(interp, *ret, cp);
return JSI_OK;
}
static int SysSleepCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Number dtim = 1;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (v) {
if (Jsi_GetDoubleFromValue(interp, v, &dtim) != JSI_OK) {
return JSI_ERROR;
}
}
return Jsi_Sleep(interp, dtim);
}
static int SysGetEnvCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
extern char **environ;
char *cp;
int i;
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
if (v != NULL) {
const char *fnam = Jsi_ValueString(interp, v, NULL);
if (!fnam) {
Jsi_LogError("expected string");
return JSI_ERROR;
}
cp = getenv(fnam);
if (cp != NULL) {
Jsi_ValueMakeString(interp, *ret, Jsi_Strdup(cp));
}
return JSI_OK;
}
/* Single object containing result members. */
Jsi_Value *vres;
Jsi_Obj *ores = Jsi_ObjNew(interp);
Jsi_Value *nnv;
char *val, nam[200];
Jsi_ObjIncrRefCount(interp, ores);
vres = Jsi_ValueMakeObject(interp, NULL, ores);
Jsi_IncrRefCount(interp, vres);
for (i=0; ; i++) {
int n;
cp = environ[i];
if (cp == 0 || ((val = strchr(cp, '='))==NULL))
break;
n = val-cp;
if (n>=sizeof(nam))
n = sizeof(nam)-1;
Jsi_Strncpy(nam, cp, n);
val = val+1;
nnv = Jsi_ValueNew(interp);
Jsi_ValueMakeString(interp, nnv, Jsi_Strdup(val));
Jsi_ObjInsert(interp, ores, nam, nnv, 0);
}
Jsi_ValueCopy(interp, *ret, vres);
Jsi_DecrRefCount(interp, vres);
return JSI_OK;
}
static int SysSetEnvCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, 0);
const char *fnam = Jsi_ValueString(interp, v, NULL);
Jsi_Value *vv = Jsi_ValueArrayIndex(interp, args, 1);
const char *fval = Jsi_ValueString(interp, vv, NULL);
int rc = -1;
if (fnam == 0 || fval == 0) {
Jsi_LogError("expected string");
return JSI_ERROR;
}
if (fnam[0] != 0) {
#ifndef __WIN32
rc = setenv(fnam, fval, 1);
#else /* TODO: win setenv */
char ebuf[BUFSIZ];
snprintf(ebuf, sizeof(ebuf), "%s=%s", fnam, fval);
rc = _putenv(ebuf);
#endif
}
if (rc != 0) {
Jsi_LogError("setenv failure: %s = %s", fnam, fval);
return JSI_ERROR;
}
return JSI_OK;
}
static int SysGetPidCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
Jsi_ValueMakeNumber(interp, *ret, (Jsi_Number)getpid());
return JSI_OK;
}
static int SysGetPpidCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
#ifndef __WIN32
Jsi_ValueMakeNumber(interp, *ret, (Jsi_Number)getppid());
#endif
return JSI_OK;
}
#define FN_exec JSI_INFO("\
Execute an operating system command and returns the result. \
A command pipeline is created with support for redirection eg. 2>&1 > outfile < infile. \
The input command is either an array, or a string which is split on the space char. \
A command ending in a single & is executed in the background (ie. no waiting). \
The second boolean argument if given as false means do not error-out non-zero result code, \
and true means returned value is an object with data in the 'output' property.")
static int SysExecCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
int rc, exitCode = 0, ignoreEC = 0;
/*Jsi_Value * opts = Jsi_ValueArrayIndex(interp, args, 1);*/
Jsi_DString dStr, cStr, *dS = &dStr, *cS = &cStr;
Jsi_DSInit(&dStr);
Jsi_DSInit(&cStr);
Jsi_Value *arg = Jsi_ValueArrayIndex(interp, args, 0);
Jsi_Value *opt = Jsi_ValueArrayIndex(interp, args, 1);
if (!opt)
cS = NULL;
else {
int bool;
if (Jsi_ValueIsBoolean(interp, opt))
Jsi_GetBoolFromValue(interp, opt, &bool);
else {
Jsi_LogError("expected bool");
return JSI_ERROR;
}
ignoreEC = 1;
if (!bool)
cS = NULL;
}
if (cS)
Jsi_DSAppend(cS, "{", NULL);
char *cpp=Jsi_ValueString(interp,arg, 0);
if (arg->vt == JSI_VT_OBJECT && arg->d.obj->isArray) {
rc = jsi_execCmd(interp, arg, dS, cS, &exitCode);
} else if (cpp == NULL || !strchr(cpp,' ')) {
rc = jsi_execCmd(interp, args, dS, cS, &exitCode);
} else {
Jsi_Value *nret = Jsi_StringSplit(interp, cpp, " ");
Jsi_IncrRefCount(interp, nret);
rc = jsi_execCmd(interp, nret, dS, cS, &exitCode);
Jsi_DecrRefCount(interp, nret);
}
/* Format data in dStr and property info in cStr */
if (!cS) {
Jsi_ValueFromDS(interp, &dStr, *ret);
} else {
Jsi_DSAppend(cS, "}", NULL);
if (Jsi_JSONParse(interp, Jsi_DSValue(cS), *ret, 0) != JSI_OK) {
Jsi_LogBug("invalid exec json: %s", Jsi_DSValue(cS));
} else {
Jsi_Value *dval = Jsi_ValueNew(interp);
Jsi_ValueFromDS(interp, &dStr, dval);
Jsi_ValueInsert(interp, *ret, "output", dval, 0);
}
}
Jsi_DSFree(&dStr);
Jsi_DSFree(&cStr);
if (rc == JSI_OK && exitCode != 0 && !ignoreEC) {
if (exitCode==127)
Jsi_LogError("command not found: %s", Jsi_ValueToString(interp, arg));
else
Jsi_LogError("program exit code (%d)", exitCode);
rc = JSI_ERROR;
}
return rc;
}
#define FN_conslog JSI_INFO("\
Print arguments to stderr. Each argument is quoted (unlike the builtin string concatenation).\
If called with 0 or 1 argument, a newline is output, otherwise stderr is flushed")
static int consoleLogCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret,
Jsi_Func *funcPtr)
{
int argc = Jsi_ValueGetLength(interp, args);
int i, cnt = 0;
for (i = 0; i < argc; ++i) {
Jsi_Value *v = Jsi_ValueArrayIndex(interp, args, i);
if (!v) continue;
if (cnt++)
fprintf(stderr, " ");
Jsi_Puts(interp, v, JSI_OUTPUT_QUOTE|JSI_OUTPUT_STDERR);
}
if (argc<=1)
printf("\n");
else
fflush(stderr);
return JSI_OK;
}
#define FN_puts JSI_INFO("\
Print arguments to stdout. Each argument is quoted (unlike the builtin string concatenation).\
If called with 0 or 1 argument, a newline is output, otherwise stdout is flushed")
static int PutsCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this, Jsi_Value **ret,
Jsi_Func *funcPtr)
{
int argc = Jsi_ValueGetLength(interp, args);;
Jsi_Value *v;
int i, cnt = 0;
for (i=0; i<argc; i++) {
v = Jsi_ValueArrayIndex(interp, args, i);
if (!v) continue;
if (cnt++)
printf(" ");
Jsi_Puts(interp, v, JSI_OUTPUT_QUOTE);
}
if (argc<=1)
printf("\n");
else
fflush(stdout);
return JSI_OK;
}
static int DateNowCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)
{
struct timeval tv;
gettimeofday(&tv, NULL);
Jsi_Number n = ((double)(tv.tv_usec/1000)) + ((double)tv.tv_sec)*1000;
Jsi_ValueMakeNumber(interp, *ret, n);
return JSI_OK;
}
typedef struct {
char utc;
const char *fmt;
} DateOpts;
static Jsi_OptionSpec DateOptions[] = {
JSI_OPT(BOOL, DateOpts, utc, .help="time is in utc" ),
JSI_OPT(STRKEY, DateOpts, fmt, .help="format string for time" ),
{JSI_OPTION_END}
};
static const char *timeFmts[] = {
"%c",
"%Y-%m-%d %H:%M:%S.",
"%Y-%m-%dT%H:%M:%S.",
"%Y-%m-%d %H:%M:%S %Z",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d",
"%Y-%m-%dT%H:%M:%S %Z",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%dT%H:%M",
"%Y-%m-%d",
"%H:%M:%S.",
"%H:%M:%S",
"%H:%M",
"%z",
NULL
};
int Jsi_DatetimeParse(Jsi_Interp *interp, const char *str, const char *fmt, int isUtc, Jsi_Wide *datePtr)
{
const char *rv = NULL;
Jsi_Wide n = -1;
int j = 0, rc = JSI_OK;
Jsi_Number ms = 0;
struct tm tm = {};
time_t t;
if (!Jsi_Strcmp("now", str)) {
struct timeval tv;
gettimeofday(&tv, NULL);
n = tv.tv_sec*1000LL + ((Jsi_Wide)tv.tv_usec)/1000LL;
if (isUtc) {
}
if (datePtr)
*datePtr = n;
return rc;
}
if (fmt && fmt[0]) {
rv = strptime(str, fmt, &tm);
} else {
if (fmt) j++;
while (timeFmts[j]) {
rv = strptime(str, timeFmts[j], &tm);
if (rv != NULL)
break;
j++;
}
}
if (!rv)
rc = JSI_ERROR;
else {
if (j <= 1 && rv != str && *(rv-1) == '.') {
ms = atof(rv-1);
}
if (isUtc) {
#ifdef __WIN32
t = _mkgmtime(&tm);
#else
t = timegm(&tm);
#endif
} else {
t = mktime(&tm);
if (tm.tm_isdst)
t -= 3600;
}
n = (Jsi_Number)t + ms;
}
if (rc == JSI_OK && datePtr)
*datePtr = n;
return rc;
}
int Jsi_DatetimeFormat(Jsi_Interp *interp, Jsi_Wide num, const char *fmt, int isUtc, Jsi_DString *dStr)
{
char buf[1000];
time_t tt;
int rc = JSI_OK;
Jsi_DString eStr;
Jsi_DSInit(&eStr);
tt = (time_t)(num/1000);
if (fmt==NULL)
fmt = timeFmts[0];
else if (*fmt == 0)
fmt = timeFmts[1];
int flen = Jsi_Strlen(fmt);
if (flen>4 && Jsi_Strcmp(fmt+flen-2, "%f")==0) {
Jsi_DSAppendLen(&eStr, fmt, flen-2);
Jsi_DSAppendLen(&eStr, "%S.", -1);
fmt = Jsi_DSValue(&eStr);
}
#ifdef __WIN32
struct tm *tm;
if (opts.utc)
tm = gmtime(&tt);
else
tm = localtime(&tt);
int rr = strftime(buf, sizeof(buf), fmt, tm);
#else
struct tm tm;
if (isUtc)
gmtime_r(&tt, &tm);
else
localtime_r(&tt, &tm);
int rr = strftime(buf, sizeof(buf), fmt, &tm);
#endif
if (rr<=0) {
Jsi_LogError("time format error");
rc = JSI_ERROR;
} else {
Jsi_DSAppendLen(dStr, buf, -1);
if (buf[rr-1] == '.') {
snprintf(buf, sizeof(buf), "%3.3d", (int)(num%1000));
Jsi_DSAppendLen(dStr, buf[1]=='.'?buf+2:buf, -1);
}
}
Jsi_DSFree(&eStr);
return rc;
}
static int DateStrptimeCmd(Jsi_Interp *interp, Jsi_Value *args, Jsi_Value *_this,
Jsi_Value **ret, Jsi_Func *funcPtr)