-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathquickjs-misc.c
More file actions
4051 lines (3224 loc) · 104 KB
/
quickjs-misc.c
File metadata and controls
4051 lines (3224 loc) · 104 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
#ifdef _WIN32
#include <process.h>
#include <windows.h>
#else
#include <unistd.h>
#endif
#include "defines.h"
#include <quickjs.h>
#include <cutils.h>
#include <quickjs-libc.h>
#include <quickjs-config.h>
#include "quickjs-location.h"
#include "quickjs-textcode.h"
#include "quickjs-syscallerror.h"
#include "utils.h"
#include "buffer-utils.h"
#include "path.h"
#include "vector.h"
#include "base64.h"
#include <time.h>
#include <stddef.h>
#include <sys/types.h>
#ifndef _WIN32
#include <sys/utsname.h>
#endif
#include <errno.h>
#ifdef HAVE_FNMATCH_H
#include <fnmatch.h>
#endif
#ifndef PATH_MAX
#define PATH_MAX 4096
#endif
#if defined(HAVE_GLOB) && defined(HAVE_GLOB_H)
#include <glob.h>
#ifndef GLOB_APPEND
#define GLOB_APPEND 0x0001
#endif
#ifndef GLOB_DOOFFS
#define GLOB_DOOFFS 0x0002
#endif
#ifndef GLOB_ERR
#define GLOB_ERR 0x0004
#endif
#ifndef GLOB_MARK
#define GLOB_MARK 0x0008
#endif
#ifndef GLOB_NOCHECK
#define GLOB_NOCHECK 0x0010
#endif
#ifndef GLOB_NOSORT
#define GLOB_NOSORT 0x0020
#endif
#ifndef GLOB_ALTDIRFUNC
#define GLOB_ALTDIRFUNC 0x0040
#endif
#ifndef GLOB_BRACE
#define GLOB_BRACE 0x0080
#endif
#ifndef GLOB_MAGCHAR
#define GLOB_MAGCHAR 0x0100
#endif
#ifndef GLOB_NOMAGIC
#define GLOB_NOMAGIC 0x0200
#endif
#ifndef GLOB_QUOTE
#define GLOB_QUOTE 0x0400
#endif
#ifndef GLOB_TILDE
#define GLOB_TILDE 0x0800
#endif
#ifndef GLOB_NOESCAPE
#define GLOB_NOESCAPE 0x1000
#endif
#ifndef GLOB_NOSPACE
#define GLOB_NOSPACE (-1)
#endif
#ifndef GLOB_ABORTED
#define GLOB_ABORTED (-2)
#endif
#ifndef GLOB_NOMATCH
#define GLOB_NOMATCH (-3)
#endif
#ifndef GLOB_NOSYS
#define GLOB_NOSYS (-4)
#endif
#else
#define glob openbsd_glob
#define globfree openbsd_globfree
#include "glob.h"
#endif
#if HAVE_WORDEXP
#include "wordexp.h"
#endif
#if HAVE_INOTIFY_INIT1
#include <sys/inotify.h>
#endif
#include "buffer-utils.h"
#ifdef HAVE_TERMIOS_H
#include <termios.h>
#include <sys/ioctl.h>
#include <signal.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include "debug.h"
#include "js-utils.h"
#ifdef HAVE_SYS_TIME_H
#include <sys/time.h>
#endif
#if defined(HAVE_UTIME) || defined(HAVE_UTIMES) || defined(HAVE_FUTIMES) || defined(HAVE_LUTIMES)
#include <sys/types.h>
#include <utime.h>
#ifdef __ANDROID__
#if !(__ANDROID_API__ >= 26)
int futimes(int, const struct timeval[2]);
int lutimes(const char*, const struct timeval[2]);
#endif
#endif
#endif
#ifndef HAVE_MKSTEMP
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#ifndef O_NOFOLLOW
#define O_NOFOLLOW 0
#endif
#define mkstemp qjs_mkstemp
static int
qjs_mkstemp(char* template) {
char* tmp = template + strlen(template) - 6;
int res = -1;
unsigned int random;
if(tmp < template)
goto error;
for(int i = 0; i < 6; ++i)
if(tmp[i] != 'X') {
error:
errno = EINVAL;
return -1;
}
int randfd = open("/dev/urandom", O_RDONLY);
for(;;) {
read(randfd, &random, sizeof(random));
for(int i = 0; i < 6; ++i) {
int hexdigit = (random >> (i * 5)) & 0x1f;
tmp[i] = hexdigit > 9 ? hexdigit + 'a' - 10 : hexdigit + '0';
}
if((res = open(template, O_CREAT | O_RDWR | O_EXCL | O_NOFOLLOW, 0600)) >= 0 || errno != EEXIST)
break;
}
close(randfd);
return res;
}
#endif
#ifndef HAVE_TEMPNAM
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#define tempnam qjs_tempnam
static char*
qjs_tempnam(const char* dir, const char* template) {
char x[1024];
const size_t n = sizeof(x) - 1;
int fd;
size_t p = 0;
if(dir && *dir) {
p += str_copyn(&x[p], dir, n - p);
p += str_copyn(&x[p], "/", n - p);
} else
p += str_copyn(x, "/tmp/", n - p);
if((n - p) < 1)
return 0;
p += str_copyn(&x[p], template ? template : "temp_", n - p);
p += str_copyn(&x[p], "XXXXXX", n - p);
if((fd = mkstemp(x)) < 0)
return 0;
close(fd);
unlink(x);
return str_ndup(x, p);
}
#endif
#ifndef _WIN32
#define FOREGROUND_BLUE (1 << 0)
#define FOREGROUND_GREEN (1 << 1)
#define FOREGROUND_RED (1 << 2)
#define FOREGROUND_INTENSITY (1 << 3)
#define BACKGROUND_BLUE (1 << 4)
#define BACKGROUND_GREEN (1 << 5)
#define BACKGROUND_RED (1 << 6)
#define BACKGROUND_INTENSITY (1 << 7)
#define COMMON_LVB_REVERSE_VIDEO (1 << 14)
#endif
#define TextAttrColor(n) \
(((n)&1) * FOREGROUND_RED + (((n) >> 1) & 1) * FOREGROUND_GREEN + (((n) >> 2) & 1) * FOREGROUND_BLUE + (((n) >> 3) & 1) * FOREGROUND_INTENSITY)
#define ColorIsBG(c) ((c) >= 100 ? TRUE : (c) >= 90 ? FALSE : (c) >= 40 ? TRUE : FALSE)
#define ColorIsBold(c) ((c) >= 90)
#define ColorIndex(c) (((c) >= 30 ? (c) % 10 : (c)) & 7)
#define ColorRed(c) (ColorIndex(c) & 1)
#define ColorGreen(c) ((ColorIndex(c) >> 1) & 1)
#define ColorBlue(c) ((ColorIndex(c) >> 2) & 1)
#define ColorToBits(c) ((ColorIsBG(c) << 4) | (ColorIsBold(c) << 3) | ColorBlue(c) | ColorGreen(c) << 1 | ColorRed(c) << 2)
BOOL JS_IsUncatchableError(JSContext* ctx, JSValueConst val);
/**
* \addtogroup quickjs-misc
* @{
*/
#ifndef HAVE_MEMMEM
void* memmem(const void*, size_t, const void*, size_t);
#endif
// static thread_local int inotify_fd = -1;
typedef struct pcg_state_setseq_64 {
uint64_t state, inc;
} pcg32_random_t;
static thread_local pcg32_random_t pcg32_global = {0x853c49e6748fea9bULL, 0xda3e39cb94b95bdbULL};
static inline uint32_t
pcg32_random_r(pcg32_random_t* rng) {
uint64_t oldstate = rng->state;
rng->state = oldstate * 6364136223846793005ULL + rng->inc;
uint32_t xorshifted = (uint32_t)(((oldstate >> 18u) ^ oldstate) >> 27u);
uint32_t rot = oldstate >> 59u;
return (xorshifted >> rot) | (xorshifted << ((-rot) & 31));
}
static uint32_t
pcg32_random(void) {
return pcg32_random_r(&pcg32_global);
}
static void
pcg32_init_state(uint32_t state) {
pcg32_global.state = ~(((uint64_t)state) << 32) | state;
}
static uint32_t
pcg32_random_bounded_divisionless(uint32_t range) {
uint64_t random32bit, multiresult;
uint32_t leftover, threshold;
random32bit = pcg32_random();
multiresult = random32bit * range;
leftover = (uint32_t)multiresult;
if(leftover < range) {
threshold = -range % range;
while(leftover < threshold) {
random32bit = pcg32_random();
multiresult = random32bit * range;
leftover = (uint32_t)multiresult;
}
}
return multiresult >> 32; // [0, range)
}
typedef enum {
CLEAR_TO_END = 0,
CLEAR_TO_BEGIN,
CLEAR_ENTIRE,
} ClearMode;
#ifdef _WIN32
static BOOL
clear_screen(intptr_t h, ClearMode mode, BOOL line) {
COORD coords = {0, 0};
DWORD w, n;
CONSOLE_SCREEN_BUFFER_INFO sbi;
if(!GetConsoleScreenBufferInfo((HANDLE)h, &sbi))
return FALSE;
#define CHAR_POS(c) (((c).Y * sbi.dwSize.X) + (c).X)
switch(mode) {
case CLEAR_TO_END: {
coords = sbi.dwCursorPosition;
n = line ? sbi.dwSize.X - sbi.dwCursorPosition.X : (sbi.dwSize.X * sbi.dwSize.Y) - CHAR_POS(sbi.dwCursorPosition);
break;
}
case CLEAR_TO_BEGIN: {
if(line)
coords.Y = sbi.dwCursorPosition.Y;
n = line ? sbi.dwCursorPosition.X : CHAR_POS(sbi.dwCursorPosition);
break;
}
case CLEAR_ENTIRE: {
if(line)
coords.Y = sbi.dwCursorPosition.Y;
n = line ? sbi.dwSize.X : sbi.dwSize.X * sbi.dwSize.Y;
break;
}
}
if(!FillConsoleOutputCharacter((HANDLE)h, (TCHAR)' ', n, coords, &w))
return FALSE;
if(!GetConsoleScreenBufferInfo((HANDLE)h, &sbi))
return FALSE;
if(!FillConsoleOutputAttribute((HANDLE)h, sbi.wAttributes, n, coords, &w))
return FALSE;
// SetConsoleCursorPosition((HANDLE)h, coords);
return TRUE;
}
#else
static BOOL
clear_screen(int fd, ClearMode mode, BOOL line) {
char buf[] = {27, '[', mode + '0', line ? 'K' : 'J'};
return write(fd, buf, sizeof(buf)) > 0;
}
#endif
#ifdef _WIN32
static BOOL
set_cursor_position(intptr_t h, int x, int y) {
COORD coords = {0, 0};
CONSOLE_SCREEN_BUFFER_INFO sbi;
if(!GetConsoleScreenBufferInfo((HANDLE)h, &sbi))
return FALSE;
coords.X = x == -1 ? sbi.dwCursorPosition.X : x;
coords.Y = y == -1 ? sbi.dwCursorPosition.Y : y;
return !!SetConsoleCursorPosition((HANDLE)h, coords);
}
#else
static BOOL
set_cursor_position(int fd, int x, int y) {
char buf[2 + (FMT_ULONG + 1) * 2] = {27, '['};
size_t pos = 2;
if(y == -1 && x >= 0) {
pos += fmt_ulong(&buf[pos], x + 1);
buf[pos++] = 'G';
} else {
if(y >= 0 && x >= 0) {
pos += fmt_ulong(&buf[pos], y + 1);
buf[pos++] = ';';
pos += fmt_ulong(&buf[pos], x + 1);
}
buf[pos++] = 'H';
}
return write(fd, buf, pos) > 0;
}
#endif
#ifdef _WIN32
static BOOL
move_cursor(intptr_t h, int x, int y) {
COORD coords = {0, 0};
CONSOLE_SCREEN_BUFFER_INFO sbi;
if(!GetConsoleScreenBufferInfo((HANDLE)h, &sbi))
return FALSE;
coords.X = sbi.dwCursorPosition.X + x;
coords.Y = sbi.dwCursorPosition.Y + y;
return !!SetConsoleCursorPosition((HANDLE)h, coords);
}
#else
static BOOL
move_cursor(int fd, int x, int y) {
char buf[(2 + (FMT_ULONG) + 1) * 2];
size_t pos = 0;
if(y) {
buf[pos++] = 27;
buf[pos++] = '[';
if(ABS_NUM(y) != 1)
pos += fmt_ulong(&buf[pos], ABS_NUM(y));
buf[pos++] = y < 0 ? 'A' : 'B';
}
if(x) {
buf[pos++] = 27;
buf[pos++] = '[';
if(ABS_NUM(x) != 1)
pos += fmt_ulong(&buf[pos], ABS_NUM(x));
buf[pos++] = x < 0 ? 'D' : 'C';
}
return write(fd, buf, pos) > 0;
}
#endif
#ifdef _WIN32
static BOOL
set_text_attributes(intptr_t h, uint32_t attr) {
return !!SetConsoleTextAttribute((HANDLE)h, attr);
}
static BOOL
get_text_attributes(intptr_t h, uint32_t* attr) {
CONSOLE_SCREEN_BUFFER_INFO sbi;
if(GetConsoleScreenBufferInfo((HANDLE)h, &sbi)) {
*attr = sbi.wAttributes;
return TRUE;
}
return FALSE;
}
#else
static BOOL
set_text_color(intptr_t fd, int intc, int32_t intv[]) {
ssize_t r;
DynBuf dbuf;
dbuf_init2(&dbuf, 0, 0);
dbuf_putstr(&dbuf, "\x1b[");
for(int i = 0; i < intc; i++) {
uint8_t* ptr;
if(!(ptr = dbuf_reserve(&dbuf, FMT_ULONG))) {
dbuf_free(&dbuf);
return FALSE;
}
dbuf.size += fmt_ulong((void*)ptr, intv[i]);
dbuf_putc(&dbuf, i < (intc - 1) ? ';' : 'm');
}
dbuf_0(&dbuf);
r = dbuf.size > 0 ? write(fd, dbuf.buf, dbuf.size) : 0;
#ifdef DEBUG_OUTPUT
for(size_t i = 0; i < dbuf.size; i++)
if(dbuf.buf[i] == '\x1b')
dbuf.buf[i] = 0xac;
printf("%s intc = %d, buf = '%s'\n", __func__, intc, dbuf.buf);
#endif
dbuf_free(&dbuf);
return r > 0;
}
static BOOL
set_text_attributes(intptr_t fd, uint32_t attr) {
int fg, bg;
char buf[(2 + (FMT_ULONG) + 1) * 3];
size_t pos = 0;
buf[pos++] = 27;
buf[pos++] = '[';
fg = ((attr & FOREGROUND_RED) ? 1 : 0) + ((attr & FOREGROUND_GREEN) ? 2 : 0) + ((attr & FOREGROUND_BLUE) ? 4 : 0) + ((attr & FOREGROUND_INTENSITY) ? 90 : 30);
pos += fmt_ulong(&buf[pos], fg);
buf[pos++] = ';';
bg =
((attr & BACKGROUND_RED) ? 1 : 0) + ((attr & BACKGROUND_GREEN) ? 2 : 0) + ((attr & BACKGROUND_BLUE) ? 4 : 0) + ((attr & BACKGROUND_INTENSITY) ? 100 : 40);
pos += fmt_ulong(&buf[pos], bg);
buf[pos++] = ';';
pos += fmt_ulong(&buf[pos], (attr & COMMON_LVB_REVERSE_VIDEO) ? 7 : 27);
buf[pos++] = 'm';
return write(fd, buf, pos) > 0;
}
#endif
static void
js_arraybuffer_free_pointer(JSRuntime* rt, void* opaque, void* ptr) {
js_free_rt(rt, ptr);
}
static void
js_arraybuffer_free_object(JSRuntime* rt, void* opaque, void* ptr) {
JSValue value = JS_MKPTR(JS_TAG_OBJECT, opaque);
JS_FreeValueRT(rt, value);
}
static void*
js_get_pointer(JSContext* ctx, JSValueConst value) {
void* ptr;
size_t len;
int64_t i64;
if((ptr = JS_GetArrayBuffer(ctx, &len, value)))
return ptr;
if(!JS_ToInt64Ext(ctx, &i64, value))
return (void*)(ptrdiff_t)i64;
return 0;
}
static JSValue
js_misc_getrelease(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, ret, "name", JS_NewString(ctx, "quickjs"));
JS_SetPropertyStr(ctx, ret, "sourceUrl", JS_NewString(ctx, "https://bellard.org/quickjs/quickjs-" CONFIG_VERSION ".tar.xz"));
return ret;
}
static JSValue
js_misc_char(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[], int magic) {
InputBuffer input = js_input_args(ctx, argc, argv);
size_t size = inputbuffer_length(&input);
const uint8_t* data = inputbuffer_data(&input);
int64_t len = 0;
UTF8Char c;
if(size)
c = utf8_char((const char*)data, size);
inputbuffer_free(&input, ctx);
return JS_NewUint32(ctx, magic ? c.len : c.code);
}
static JSValue
js_misc_tostring(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret = JS_UNDEFINED;
InputBuffer buf = js_input_args(ctx, argc, argv);
const uint8_t* s = inputbuffer_data(&buf);
size_t n = inputbuffer_length(&buf);
if(s) {
if(n == SIZE_MAX /* && memchr(s, '\0', n)*/)
ret = JS_NewString(ctx, (const char*)s);
else
ret = JS_NewStringLen(ctx, (const char*)s, n);
} else {
ret = js_value_tostring(ctx, "Object", argc > 0 ? argv[0] : this_val);
}
inputbuffer_free(&buf, ctx);
return ret;
}
static JSValue
js_misc_strcmp(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret = JS_UNDEFINED;
const char *a, *b;
size_t alen, blen;
a = JS_ToCStringLen(ctx, &alen, argv[0]);
b = JS_ToCStringLen(ctx, &blen, argv[1]);
ret = JS_NewInt32(ctx, byte_diff2(a, alen, b, blen));
JS_FreeCString(ctx, a);
JS_FreeCString(ctx, b);
return ret;
}
static JSValue
js_misc_topointer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
JSValue ret = JS_NULL;
const uint8_t* ptr;
char str[64];
InputBuffer buf = js_input_chars(ctx, argv[0]);
if(JS_IsException(buf.value))
return JS_EXCEPTION;
if((ptr = inputbuffer_data(&buf)))
ret = JS_NewStringLen(ctx, str, snprintf(str, sizeof(str), "%p", ptr));
inputbuffer_free(&buf, ctx);
return ret;
}
static JSValue
js_misc_toarraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
BOOL is_bigint = JS_IsBigInt(ctx, argv[0]);
if(argc >= 2 && (JS_IsNumber(argv[0]) || is_bigint)) {
uintptr_t addr = (uintptr_t)js_topointer(ctx, argv[0]);
if(addr == 0)
return JS_NULL;
uintptr_t len = (uintptr_t)js_topointer(ctx, argv[1]);
if(len == 0)
return JS_ThrowInternalError(ctx, "zero length given");
return JS_NewArrayBuffer(ctx, (void*)addr, len, 0, 0, 0);
}
InputBuffer input = js_input_chars(ctx, argv[0]);
if(argc > 1)
js_offset_length(ctx, input.size, argc, argv, 1, &input.range);
return inputbuffer_toarraybuffer_free(&input, ctx);
}
static JSValue
js_misc_slicearraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
uint8_t* data;
size_t len;
if((data = JS_GetArrayBuffer(ctx, &len, argv[0]))) {
IndexRange ir = INDEX_RANGE_INIT();
js_index_range(ctx, len, argc - 1, argv + 1, 0, &ir);
return JS_NewArrayBuffer(ctx,
indexrange_begin(ir, data, len),
indexrange_size(ir, len),
js_arraybuffer_free_object,
js_value_obj2(ctx, argv[0]),
js_is_sharedarraybuffer(ctx, argv[0]));
}
return JS_ThrowTypeError(ctx, "argument 1 must be an ArrayBuffer");
}
static JSValue
js_misc_duparraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
uint8_t* data;
size_t len;
if((data = JS_GetArrayBuffer(ctx, &len, argv[0]))) {
OffsetLength ol = OFFSET_LENGTH_0();
if(argc > 1)
if(offsetlength_from_argv(&ol, len, argc - 1, argv + 1, ctx) < 0)
return JS_EXCEPTION;
return JS_NewArrayBuffer(ctx,
offsetlength_begin(ol, data),
offsetlength_size(ol, len),
js_arraybuffer_free_object,
js_value_obj2(ctx, argv[0]),
js_is_sharedarraybuffer(ctx, argv[0]));
}
return JS_ThrowTypeError(ctx, "argument 1 must be an ArrayBuffer");
}
static JSValue
js_misc_concatarraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
MemoryBlock m[argc];
int i = 0, k = 0;
for(k = 0; i < argc; k++) {
m[k] = MEMORY_BLOCK(0, 0);
if(i == argc || !block_from_arraybuffer(&m[k], argv[i], ctx))
return JS_ThrowTypeError(ctx, "argument %d (%s) must be an ArrayBuffer", i + 1, CONST_STRARRAY("src", "dst")[k]);
i++;
IndexRange slice = INDEX_RANGE(0, m[k].size);
for(int j = 0; j < countof(slice.arr); j++) {
if(i == argc || js_is_arraybuffer(ctx, argv[i]))
break;
js_toint64clamp(ctx, &slice.arr[j], argv[i++], j ? slice.start : 0, slice.end, slice.end);
}
m[k] = indexrange_block(slice, m[k]);
}
size_t total_size = 0, pos = 0;
uint8_t* buf;
for(int j = 0; j < k; j++) {
total_size += m[j].size;
}
if(!(buf = js_malloc(ctx, total_size)))
return JS_EXCEPTION;
for(int j = 0; j < k; j++) {
size_t n = m[j].size;
memcpy(&buf[pos], m[j].base, n);
pos += n;
}
return JS_NewArrayBuffer(ctx, buf, total_size, js_arraybuffer_free_pointer, 0, FALSE);
}
static JSValue
js_misc_searcharraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
MemoryBlock haystack, needle, mask;
OffsetLength h_ol = OFFSET_LENGTH_0();
int i = 0, n;
if(i >= argc || !block_from_arraybuffer(&haystack, argv[i++], ctx))
return JS_ThrowTypeError(ctx, "argument 1 (haystack) must be an ArrayBuffer");
if(i >= argc || !block_from_arraybuffer(&needle, argv[i++], ctx))
return JS_ThrowTypeError(ctx, "argument %d (needle) must be an ArrayBuffer", i + 1);
if(needle.size == 0)
return JS_ThrowRangeError(ctx, "needle size is 0");
if(needle.size > haystack.size)
return JS_ThrowRangeError(ctx, "needle size %zu is greater than haystack size %zu", needle.size, haystack.size);
if((n = offsetlength_from_argv(&h_ol, haystack.size, argc - i, argv + i, ctx)) < 0)
return JS_EXCEPTION;
if(n) {
i += n;
}
if(i == argc) {
uint8_t* ptr;
MemoryBlock range = offsetlength_block(h_ol, haystack);
if(needle.size <= range.size && (ptr = memmem(range.base, range.size, needle.base, needle.size))) {
ptrdiff_t ofs = ptr - haystack.base;
if(ofs > MAX_SAFE_INTEGER || (n && JS_IsBigInt(ctx, argv[i - n])))
return JS_NewBigUint64(ctx, ofs);
return JS_NewInt64(ctx, ofs);
}
return JS_NULL;
}
if(!block_from_arraybuffer(&mask, argv[2], ctx))
return JS_ThrowTypeError(ctx, "argument 3 (mask) must be an ArrayBuffer");
size_t n_size = MIN_NUM(needle.size, mask.size);
size_t h_end = haystack.size - n_size;
// naive searching algorithm (slow)
for(size_t i = 0; i < h_end; i++) {
int found = 1;
for(size_t j = 0; j < n_size; j++) {
if((haystack.base[i + j] ^ needle.base[j]) & mask.base[j]) {
found = 0;
break;
}
}
if(found) {
/*for(size_t j = 0; j < n_size; j++) {
uint8_t xorval = haystack.base[i + j] ^ needle.base[j];
printf("@(%lu + %lu); ", (unsigned long)i, (unsigned long)j);
printf("%02x XOR %02x = %02x; ", haystack.base[i + j], needle.base[j], xorval);
printf("%02x AND %02x = %02x\n", xorval, mask.base[j], xorval & mask.base[j]);
}*/
return JS_NewInt64(ctx, (int64_t)i + h_ol.offset);
}
}
return JS_NULL;
}
int JS_ToInt64Clamp(JSContext*, int64_t*, JSValueConst, int64_t, int64_t, int64_t);
static JSValue
js_misc_copyarraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
MemoryBlock m[2];
int i = 0;
for(int k = 0; k < countof(m); k++) {
if(i == argc || !block_from_arraybuffer(&m[k], argv[i], ctx))
return JS_ThrowTypeError(ctx, "argument %d (%s) must be an ArrayBuffer", i + 1, CONST_STRARRAY("src", "dst")[k]);
i++;
IndexRange ir = INDEX_RANGE(0, m[k].size);
int64_t* const slice = ir.arr;
for(int j = 0; j < countof(ir.arr); j++) {
if(i == argc || js_is_arraybuffer(ctx, argv[i]))
break;
js_toint64clamp(ctx, &slice[j], argv[i++], j ? slice[0] : 0, m[k].size, m[k].size);
}
m[k] = block_indexrange(m[k], ir);
}
size_t n = MIN_NUM(m[0].size, m[1].size);
memcpy(m[0].base, m[1].base, n);
return JS_NewInt64(ctx, n);
}
static JSValue
js_misc_comparearraybuffer(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
MemoryBlock m[2];
int i = 0;
for(int k = 0; k < countof(m); k++) {
if(i == argc || !block_from_arraybuffer(&m[k], argv[i], ctx))
return JS_ThrowTypeError(ctx, "argument %d (%s) must be an ArrayBuffer", i + 1, CONST_STRARRAY("s2", "s1")[k]);
i++;
IndexRange ir = INDEX_RANGE(0, m[k].size);
int64_t* const slice = ir.arr;
for(int j = 0; j < countof(ir.arr); j++) {
if(i == argc || js_is_arraybuffer(ctx, argv[i]))
break;
js_toint64clamp(ctx, &slice[j], argv[i++], j ? slice[0] : 0, m[k].size, m[k].size);
}
m[k] = block_indexrange(m[k], ir);
}
return JS_NewInt32(ctx, memcmp(m[0].base, m[1].base, MIN_NUM(m[0].size, m[1].size)));
}
#if HAVE_FMEMOPEN
static JSValue
js_misc_fmemopen(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
uint8_t* ptr;
size_t len;
int i = 0;
const char* mode;
if(!(ptr = JS_GetArrayBuffer(ctx, &len, argv[0])))
return JS_ThrowTypeError(ctx, "argument 1 (dst) must be an ArrayBuffer");
++i;
if(i + 1 < argc && JS_IsNumber(argv[i])) {
int64_t offset = 0;
JS_ToInt64Ext(ctx, &offset, argv[i++]);
offset = MIN_NUM((int64_t)len, offset);
ptr += offset;
len -= offset;
}
if(i + 1 < argc && JS_IsNumber(argv[i])) {
int64_t length = 0;
if(!JS_ToInt64Ext(ctx, &length, argv[i++]))
len = MIN_NUM((int64_t)len, length);
}
mode = JS_ToCString(ctx, argv[0]);
FILE* f = fmemopen(ptr, len, mode);
JS_FreeCString(ctx, mode);
return
#if HAVE_JS_STD_FILE
f ? js_std_file(ctx, f) :
#endif
JS_NULL;
}
#endif
static JSValue
js_misc_getperformancecounter(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[]) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return JS_NewFloat64(ctx, (double)ts.tv_sec * 1000 + ((double)ts.tv_nsec / 1e06));
}
enum {
FUNC_GETEXECUTABLE = 0,
FUNC_GETWORKINGDIRECTORY,
FUNC_GETROOTDIRECTORY,
FUNC_GETFILEDESCRIPTOR,
};
static JSValue
js_misc_proclink(JSContext* ctx, JSValueConst this_val, int argc, JSValueConst argv[], int magic) {
JSValue ret = JS_UNDEFINED;
const char* link = NULL;
char x[PATH_MAX];
int i = 0;
int64_t fd = -1;
size_t p = str_copyn(x, "/proc/", sizeof(x));
static const char* const links[] = {"/exe", "/cwd", "/root", "/fd/"};
if(magic == FUNC_GETFILEDESCRIPTOR) {
if(argc <= i || !JS_IsNumber(argv[i]))
return JS_ThrowTypeError(ctx, "argument 1 must be Number");
JS_ToInt64(ctx, &fd, argv[i]);
++i;
}
if(argc > i) {
int64_t pid;
JS_ToInt64(ctx, &pid, argv[i]);
p += fmt_longlong(&x[p], pid);
} else
p += str_copyn(&x[p], "self", sizeof(x) - p);
p += str_copyn(&x[p], links[magic], sizeof(x) - p);
if(magic == FUNC_GETFILEDESCRIPTOR)
p += fmt_longlong(&x[p], fd);
x[p] = '\0';
ssize_t r;
DynBuf dbuf = DBUF_INIT_CTX(ctx);
if((r = path_readlink2(x, &dbuf)) > 0)
ret = dbuf_tostring_free(&dbuf, ctx);
return ret;
}
static JSValue
js_misc_procline(JSContext* ctx, const char* x, size_t len, int max_items) {
JSValue ret = JS_NewArray(ctx);
for(size_t p = 0, i = 0; p < len; p += scan_whitenskip(&x[p], len - p)) {
size_t q = (max_items >= 0 && (i + 1) == max_items) ? len - p : scan_nonwhitenskip(&x[p], len - p);
JS_SetPropertyUint32(ctx, ret, i++, JS_NewStringLen(ctx, &x[p], q));
if(i >= max_items)
break;
p += q;
}
return ret;
}
enum {
FUNC_GETCOMMANDLINE = 0,