forked from quickjs-ng/quickjs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
run-test262.c
2357 lines (2147 loc) · 68.3 KB
/
run-test262.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
/*
* ECMA Test 262 Runner for QuickJS
*
* Copyright (c) 2017-2021 Fabrice Bellard
* Copyright (c) 2017-2021 Charlie Gordon
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdarg.h>
#include <inttypes.h>
#include <string.h>
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <time.h>
#ifdef _WIN32
#include <windows.h>
#include <process.h>
typedef HANDLE js_thread_t;
#else
#include <dirent.h>
#include <pthread.h>
#include <unistd.h>
typedef pthread_t js_thread_t;
#endif
#include "cutils.h"
#include "list.h"
#include "quickjs.h"
#include "quickjs-c-atomics.h"
#include "quickjs-libc.h"
#define CMD_NAME "run-test262"
// not quite correct because in theory someone could compile quickjs.c
// with a different compiler but in practice no one does that, right?
#ifdef __TINYC__
#define CC_IS_TCC 1
#else
#define CC_IS_TCC 0
#endif
typedef struct {
js_mutex_t agent_mutex;
js_cond_t agent_cond;
/* list of Test262Agent.link */
struct list_head agent_list;
js_mutex_t report_mutex;
/* list of AgentReport.link */
struct list_head report_list;
int async_done;
} ThreadLocalStorage;
typedef struct namelist_t {
char **array;
int count;
int size;
} namelist_t;
long nthreads; // invariant: 0 < nthreads < countof(threads)
js_thread_t threads[32];
js_thread_t progress_thread;
js_cond_t progress_cond;
js_mutex_t progress_mutex;
namelist_t test_list;
namelist_t exclude_list;
namelist_t exclude_dir_list;
FILE *outfile;
enum test_mode_t {
TEST_DEFAULT_NOSTRICT, /* run tests as nostrict unless test is flagged as strictonly */
TEST_DEFAULT_STRICT, /* run tests as strict unless test is flagged as nostrict */
TEST_NOSTRICT, /* run tests as nostrict, skip strictonly tests */
TEST_STRICT, /* run tests as strict, skip nostrict tests */
TEST_ALL, /* run tests in both strict and nostrict, unless restricted by spec */
} test_mode = TEST_DEFAULT_NOSTRICT;
int local;
int skip_async;
int skip_module;
int dump_memory;
int stats_count;
JSMemoryUsage stats_all, stats_avg, stats_min, stats_max;
char *stats_min_filename;
char *stats_max_filename;
js_mutex_t stats_mutex;
int verbose;
char *harness_dir;
char *harness_exclude;
char *harness_features;
char *harness_skip_features;
char *error_filename;
char *error_file;
FILE *error_out;
int update_errors;
int slow_test_threshold;
int start_index, stop_index;
int test_excluded;
_Atomic int test_count, test_failed, test_skipped;
_Atomic int new_errors, changed_errors, fixed_errors;
void warning(const char *, ...) __attribute__((__format__(__printf__, 1, 2)));
void fatal(int, const char *, ...) __attribute__((__format__(__printf__, 2, 3)));
void atomic_inc(volatile _Atomic int *p)
{
atomic_fetch_add(p, 1);
}
void warning(const char *fmt, ...)
{
va_list ap;
fflush(stdout);
fprintf(stderr, "%s: ", CMD_NAME);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
}
void fatal(int errcode, const char *fmt, ...)
{
va_list ap;
fflush(stdout);
fprintf(stderr, "%s: ", CMD_NAME);
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fputc('\n', stderr);
exit(errcode);
}
void perror_exit(int errcode, const char *s)
{
fflush(stdout);
fprintf(stderr, "%s: ", CMD_NAME);
perror(s);
exit(errcode);
}
char *strdup_len(const char *str, int len)
{
char *p = malloc(len + 1);
memcpy(p, str, len);
p[len] = '\0';
return p;
}
static inline int str_equal(const char *a, const char *b) {
return !strcmp(a, b);
}
static inline int str_count(const char *a, const char *b) {
int count = 0;
while ((a = strstr(a, b))) {
a += strlen(b);
count++;
}
return count;
}
char *str_append(char **pp, const char *sep, const char *str) {
char *res, *p;
size_t len = 0;
p = *pp;
if (p) {
len = strlen(p) + strlen(sep);
}
res = malloc(len + strlen(str) + 1);
if (p) {
strcpy(res, p);
strcat(res, sep);
}
strcpy(res + len, str);
free(p);
return *pp = res;
}
char *str_strip(char *p)
{
size_t len = strlen(p);
while (len > 0 && isspace((unsigned char)p[len - 1]))
p[--len] = '\0';
while (isspace((unsigned char)*p))
p++;
return p;
}
int has_prefix(const char *str, const char *prefix)
{
return !strncmp(str, prefix, strlen(prefix));
}
char *skip_prefix(const char *str, const char *prefix)
{
int i;
for (i = 0;; i++) {
if (prefix[i] == '\0') { /* skip the prefix */
str += i;
break;
}
if (str[i] != prefix[i])
break;
}
return (char *)str;
}
char *get_basename(const char *filename)
{
char *p;
p = strrchr(filename, '/');
if (!p)
return NULL;
return strdup_len(filename, p - filename);
}
char *compose_path(const char *path, const char *name)
{
int path_len, name_len;
char *d, *q;
if (!path || path[0] == '\0' || *name == '/') {
d = strdup(name);
} else {
path_len = strlen(path);
name_len = strlen(name);
d = malloc(path_len + 1 + name_len + 1);
if (d) {
q = d;
memcpy(q, path, path_len);
q += path_len;
if (path[path_len - 1] != '/')
*q++ = '/';
memcpy(q, name, name_len + 1);
}
}
return d;
}
int namelist_cmp(const char *a, const char *b)
{
/* compare strings in modified lexicographical order */
for (;;) {
int ca = (unsigned char)*a++;
int cb = (unsigned char)*b++;
if (isdigit(ca) && isdigit(cb)) {
int na = ca - '0';
int nb = cb - '0';
while (isdigit(ca = (unsigned char)*a++))
na = na * 10 + ca - '0';
while (isdigit(cb = (unsigned char)*b++))
nb = nb * 10 + cb - '0';
if (na < nb)
return -1;
if (na > nb)
return +1;
}
if (ca < cb)
return -1;
if (ca > cb)
return +1;
if (ca == '\0')
return 0;
}
}
int namelist_cmp_indirect(const void *a, const void *b)
{
return namelist_cmp(*(const char **)a, *(const char **)b);
}
void namelist_sort(namelist_t *lp)
{
int i, count;
if (lp->count > 1) {
qsort(lp->array, lp->count, sizeof(*lp->array), namelist_cmp_indirect);
/* remove duplicates */
for (count = i = 1; i < lp->count; i++) {
if (namelist_cmp(lp->array[count - 1], lp->array[i]) == 0) {
free(lp->array[i]);
} else {
lp->array[count++] = lp->array[i];
}
}
lp->count = count;
}
}
int namelist_find(const namelist_t *lp, const char *name)
{
int a, b, m, cmp;
for (a = 0, b = lp->count; a < b;) {
m = a + (b - a) / 2;
cmp = namelist_cmp(lp->array[m], name);
if (cmp < 0)
a = m + 1;
else if (cmp > 0)
b = m;
else
return m;
}
return -1;
}
void namelist_add(namelist_t *lp, const char *base, const char *name)
{
char *s;
s = compose_path(base, name);
if (!s)
goto fail;
if (lp->count == lp->size) {
size_t newsize = lp->size + (lp->size >> 1) + 4;
char **a = realloc(lp->array, sizeof(lp->array[0]) * newsize);
if (!a)
goto fail;
lp->array = a;
lp->size = newsize;
}
lp->array[lp->count] = s;
lp->count++;
return;
fail:
fatal(1, "allocation failure\n");
}
void namelist_load(namelist_t *lp, const char *filename)
{
char buf[1024];
char *base_name;
FILE *f;
f = fopen(filename, "r");
if (!f) {
perror_exit(1, filename);
}
base_name = get_basename(filename);
while (fgets(buf, sizeof(buf), f) != NULL) {
char *p = str_strip(buf);
if (*p == '#' || *p == ';' || *p == '\0')
continue; /* line comment */
namelist_add(lp, base_name, p);
}
free(base_name);
fclose(f);
}
void namelist_add_from_error_file(namelist_t *lp, const char *file)
{
const char *p, *p0;
char *pp;
for (p = file; (p = strstr(p, ".js:")) != NULL; p++) {
for (p0 = p; p0 > file && p0[-1] != '\n'; p0--)
continue;
pp = strdup_len(p0, p + 3 - p0);
namelist_add(lp, NULL, pp);
free(pp);
}
}
void namelist_free(namelist_t *lp)
{
while (lp->count > 0) {
free(lp->array[--lp->count]);
}
free(lp->array);
lp->array = NULL;
lp->size = 0;
}
static int add_test_file(const char *filename)
{
namelist_t *lp = &test_list;
if (has_suffix(filename, ".js") && !has_suffix(filename, "_FIXTURE.js"))
namelist_add(lp, NULL, filename);
return 0;
}
static void find_test_files(const char *path);
static void consider_test_file(const char *path, const char *name, int is_dir)
{
char s[1024];
if (str_equal(name, ".") || str_equal(name, ".."))
return;
snprintf(s, sizeof(s), "%s/%s", path, name);
if (is_dir)
find_test_files(s);
else
add_test_file(s);
}
static void find_test_files(const char *path)
{
#ifdef _WIN32
WIN32_FIND_DATAA d;
HANDLE h;
char s[1024];
snprintf(s, sizeof(s), "%s/*", path);
h = FindFirstFileA(s, &d);
if (h != INVALID_HANDLE_VALUE) {
do {
consider_test_file(path,
d.cFileName,
d.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
} while (FindNextFileA(h, &d));
FindClose(h);
}
#else
struct dirent *d, **ds = NULL;
int i, n;
n = scandir(path, &ds, NULL, alphasort);
for (i = 0; i < n; i++) {
d = ds[i];
consider_test_file(path, d->d_name, d->d_type == DT_DIR);
free(d);
}
free(ds);
#endif
}
/* find js files from the directory tree and sort the list */
static void enumerate_tests(const char *path)
{
namelist_t *lp = &test_list;
int start = lp->count;
find_test_files(path);
qsort(lp->array + start, lp->count - start, sizeof(*lp->array),
namelist_cmp_indirect);
}
static JSValue js_print_262(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
ThreadLocalStorage *tls = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
int i;
const char *str;
for (i = 0; i < argc; i++) {
str = JS_ToCString(ctx, argv[i]);
if (!str)
return JS_EXCEPTION;
if (!strcmp(str, "Test262:AsyncTestComplete")) {
tls->async_done++;
} else if (strstart(str, "Test262:AsyncTestFailure", NULL)) {
tls->async_done = 2; /* force an error */
}
if (outfile) {
if (i != 0)
fputc(' ', outfile);
fputs(str, outfile);
}
if (verbose > 1)
printf("%s%s", &" "[i < 1], str);
JS_FreeCString(ctx, str);
}
if (outfile)
fputc('\n', outfile);
if (verbose > 1)
printf("\n");
return JS_UNDEFINED;
}
static JSValue js_detachArrayBuffer(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
JS_DetachArrayBuffer(ctx, argv[0]);
return JS_UNDEFINED;
}
static JSValue js_evalScript_262(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
const char *str;
size_t len;
JSValue ret;
str = JS_ToCStringLen(ctx, &len, argv[0]);
if (!str)
return JS_EXCEPTION;
ret = JS_Eval(ctx, str, len, "<evalScript>", JS_EVAL_TYPE_GLOBAL);
JS_FreeCString(ctx, str);
return ret;
}
static void start_thread(js_thread_t *thrd, void *(*start)(void *), void *arg)
{
// musl libc gives threads 80 kb stacks, much smaller than
// JS_DEFAULT_STACK_SIZE (256 kb)
static const unsigned stacksize = 2 << 20; // 2 MB, glibc default
#ifdef _WIN32
HANDLE h, cp;
cp = GetCurrentProcess();
h = (HANDLE)_beginthread((void (*)(void *))(void *)start, stacksize, arg);
if (!h)
fatal(1, "_beginthread error");
// _endthread() automatically closes the handle but we want to wait on
// it so make a copy. Race-y for very short-lived threads. Can be solved
// by switching to _beginthreadex(CREATE_SUSPENDED) but means changing
// |start| from __cdecl to __stdcall.
if (!DuplicateHandle(cp, h, cp, thrd, 0, FALSE, DUPLICATE_SAME_ACCESS))
fatal(1, "DuplicateHandle error");
#else
pthread_attr_t attr;
if (pthread_attr_init(&attr))
fatal(1, "pthread_attr_init");
if (pthread_attr_setstacksize(&attr, stacksize))
fatal(1, "pthread_attr_setstacksize");
if (pthread_create(thrd, &attr, start, arg))
fatal(1, "pthread_create error");
pthread_attr_destroy(&attr);
#endif
}
static void join_thread(js_thread_t thrd)
{
#ifdef _WIN32
if (WaitForSingleObject(thrd, INFINITE))
fatal(1, "WaitForSingleObject error");
CloseHandle(thrd);
#else
if (pthread_join(thrd, NULL))
fatal(1, "pthread_join error");
#endif
}
static long cpu_count(void)
{
#ifdef _WIN32
DWORD_PTR procmask, sysmask;
long count;
int i;
count = 0;
if (GetProcessAffinityMask(GetCurrentProcess(), &procmask, &sysmask))
for (i = 0; i < 8 * sizeof(procmask); i++)
count += 1 & (procmask >> i);
return count;
#else
return sysconf(_SC_NPROCESSORS_ONLN);
#endif
}
static void init_thread_local_storage(ThreadLocalStorage *p)
{
js_mutex_init(&p->agent_mutex);
js_cond_init(&p->agent_cond);
init_list_head(&p->agent_list);
js_mutex_init(&p->report_mutex);
init_list_head(&p->report_list);
p->async_done = 0;
}
typedef struct {
struct list_head link;
js_thread_t tid;
char *script;
JSValue broadcast_func;
BOOL broadcast_pending;
JSValue broadcast_sab; /* in the main context */
uint8_t *broadcast_sab_buf;
size_t broadcast_sab_size;
int32_t broadcast_val;
ThreadLocalStorage *tls;
} Test262Agent;
typedef struct {
struct list_head link;
char *str;
} AgentReport;
static JSValue add_helpers1(JSContext *ctx);
static void add_helpers(JSContext *ctx);
static void *agent_start(void *arg)
{
ThreadLocalStorage *tls;
Test262Agent *agent;
JSRuntime *rt;
JSContext *ctx;
JSValue ret_val;
int ret;
agent = arg;
tls = agent->tls; // shares thread-local storage with parent thread
rt = JS_NewRuntime();
if (rt == NULL) {
fatal(1, "JS_NewRuntime failure");
}
JS_SetRuntimeOpaque(rt, tls);
ctx = JS_NewContext(rt);
if (ctx == NULL) {
JS_FreeRuntime(rt);
fatal(1, "JS_NewContext failure");
}
JS_SetContextOpaque(ctx, agent);
JS_SetRuntimeInfo(rt, "agent");
JS_SetCanBlock(rt, TRUE);
add_helpers(ctx);
ret_val = JS_Eval(ctx, agent->script, strlen(agent->script),
"<evalScript>", JS_EVAL_TYPE_GLOBAL);
free(agent->script);
agent->script = NULL;
if (JS_IsException(ret_val))
js_std_dump_error(ctx);
JS_FreeValue(ctx, ret_val);
for(;;) {
JSContext *ctx1;
ret = JS_ExecutePendingJob(JS_GetRuntime(ctx), &ctx1);
if (ret < 0) {
js_std_dump_error(ctx);
break;
} else if (ret == 0) {
if (JS_IsUndefined(agent->broadcast_func)) {
break;
} else {
JSValue args[2];
js_mutex_lock(&tls->agent_mutex);
while (!agent->broadcast_pending) {
js_cond_wait(&tls->agent_cond, &tls->agent_mutex);
}
agent->broadcast_pending = FALSE;
js_cond_signal(&tls->agent_cond);
js_mutex_unlock(&tls->agent_mutex);
args[0] = JS_NewArrayBuffer(ctx, agent->broadcast_sab_buf,
agent->broadcast_sab_size,
NULL, NULL, TRUE);
args[1] = JS_NewInt32(ctx, agent->broadcast_val);
ret_val = JS_Call(ctx, agent->broadcast_func, JS_UNDEFINED,
2, args);
JS_FreeValue(ctx, args[0]);
JS_FreeValue(ctx, args[1]);
if (JS_IsException(ret_val))
js_std_dump_error(ctx);
JS_FreeValue(ctx, ret_val);
JS_FreeValue(ctx, agent->broadcast_func);
agent->broadcast_func = JS_UNDEFINED;
}
}
}
JS_FreeValue(ctx, agent->broadcast_func);
JS_FreeContext(ctx);
JS_FreeRuntime(rt);
return NULL;
}
static JSValue js_agent_start(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
ThreadLocalStorage *tls = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
const char *script;
Test262Agent *agent;
if (JS_GetContextOpaque(ctx) != NULL)
return JS_ThrowTypeError(ctx, "cannot be called inside an agent");
script = JS_ToCString(ctx, argv[0]);
if (!script)
return JS_EXCEPTION;
agent = malloc(sizeof(*agent));
memset(agent, 0, sizeof(*agent));
agent->broadcast_func = JS_UNDEFINED;
agent->broadcast_sab = JS_UNDEFINED;
agent->script = strdup(script);
agent->tls = tls;
JS_FreeCString(ctx, script);
list_add_tail(&agent->link, &tls->agent_list);
start_thread(&agent->tid, agent_start, agent);
return JS_UNDEFINED;
}
static void js_agent_free(JSContext *ctx)
{
ThreadLocalStorage *tls = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
struct list_head *el, *el1;
Test262Agent *agent;
list_for_each_safe(el, el1, &tls->agent_list) {
agent = list_entry(el, Test262Agent, link);
join_thread(agent->tid);
JS_FreeValue(ctx, agent->broadcast_sab);
list_del(&agent->link);
free(agent);
}
}
static JSValue js_agent_leaving(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
Test262Agent *agent = JS_GetContextOpaque(ctx);
if (!agent)
return JS_ThrowTypeError(ctx, "must be called inside an agent");
/* nothing to do */
return JS_UNDEFINED;
}
static BOOL is_broadcast_pending(ThreadLocalStorage *tls)
{
struct list_head *el;
Test262Agent *agent;
list_for_each(el, &tls->agent_list) {
agent = list_entry(el, Test262Agent, link);
if (agent->broadcast_pending)
return TRUE;
}
return FALSE;
}
static JSValue js_agent_broadcast(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
ThreadLocalStorage *tls = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
JSValue sab = argv[0];
struct list_head *el;
Test262Agent *agent;
uint8_t *buf;
size_t buf_size;
int32_t val;
if (JS_GetContextOpaque(ctx) != NULL)
return JS_ThrowTypeError(ctx, "cannot be called inside an agent");
buf = JS_GetArrayBuffer(ctx, &buf_size, sab);
if (!buf)
return JS_EXCEPTION;
if (JS_ToInt32(ctx, &val, argv[1]))
return JS_EXCEPTION;
/* broadcast the values and wait until all agents have started
calling their callbacks */
js_mutex_lock(&tls->agent_mutex);
list_for_each(el, &tls->agent_list) {
agent = list_entry(el, Test262Agent, link);
agent->broadcast_pending = TRUE;
/* the shared array buffer is used by the thread, so increment
its refcount */
agent->broadcast_sab = JS_DupValue(ctx, sab);
agent->broadcast_sab_buf = buf;
agent->broadcast_sab_size = buf_size;
agent->broadcast_val = val;
}
js_cond_broadcast(&tls->agent_cond);
while (is_broadcast_pending(tls)) {
js_cond_wait(&tls->agent_cond, &tls->agent_mutex);
}
js_mutex_unlock(&tls->agent_mutex);
return JS_UNDEFINED;
}
static JSValue js_agent_receiveBroadcast(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
Test262Agent *agent = JS_GetContextOpaque(ctx);
if (!agent)
return JS_ThrowTypeError(ctx, "must be called inside an agent");
if (!JS_IsFunction(ctx, argv[0]))
return JS_ThrowTypeError(ctx, "expecting function");
JS_FreeValue(ctx, agent->broadcast_func);
agent->broadcast_func = JS_DupValue(ctx, argv[0]);
return JS_UNDEFINED;
}
static JSValue js_agent_sleep(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
uint32_t duration;
if (JS_ToUint32(ctx, &duration, argv[0]))
return JS_EXCEPTION;
#ifdef _WIN32
Sleep(duration);
#else
usleep(duration * 1000);
#endif
return JS_UNDEFINED;
}
static int64_t get_clock_ms(void)
{
#ifdef _WIN32
return GetTickCount64();
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000 + (ts.tv_nsec / 1000000);
#endif
}
static JSValue js_agent_monotonicNow(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
return JS_NewInt64(ctx, get_clock_ms());
}
static JSValue js_agent_getReport(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
ThreadLocalStorage *tls = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
AgentReport *rep;
JSValue ret;
js_mutex_lock(&tls->report_mutex);
if (list_empty(&tls->report_list)) {
rep = NULL;
} else {
rep = list_entry(tls->report_list.next, AgentReport, link);
list_del(&rep->link);
}
js_mutex_unlock(&tls->report_mutex);
if (rep) {
ret = JS_NewString(ctx, rep->str);
free(rep->str);
free(rep);
} else {
ret = JS_NULL;
}
return ret;
}
static JSValue js_agent_report(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
ThreadLocalStorage *tls = JS_GetRuntimeOpaque(JS_GetRuntime(ctx));
const char *str;
AgentReport *rep;
str = JS_ToCString(ctx, argv[0]);
if (!str)
return JS_EXCEPTION;
rep = malloc(sizeof(*rep));
rep->str = strdup(str);
JS_FreeCString(ctx, str);
js_mutex_lock(&tls->report_mutex);
list_add_tail(&rep->link, &tls->report_list);
js_mutex_unlock(&tls->report_mutex);
return JS_UNDEFINED;
}
static const JSCFunctionListEntry js_agent_funcs[] = {
/* only in main */
JS_CFUNC_DEF("start", 1, js_agent_start ),
JS_CFUNC_DEF("getReport", 0, js_agent_getReport ),
JS_CFUNC_DEF("broadcast", 2, js_agent_broadcast ),
/* only in agent */
JS_CFUNC_DEF("report", 1, js_agent_report ),
JS_CFUNC_DEF("leaving", 0, js_agent_leaving ),
JS_CFUNC_DEF("receiveBroadcast", 1, js_agent_receiveBroadcast ),
/* in both */
JS_CFUNC_DEF("sleep", 1, js_agent_sleep ),
JS_CFUNC_DEF("monotonicNow", 0, js_agent_monotonicNow ),
};
static JSValue js_new_agent(JSContext *ctx)
{
JSValue agent;
agent = JS_NewObject(ctx);
JS_SetPropertyFunctionList(ctx, agent, js_agent_funcs,
countof(js_agent_funcs));
return agent;
}
static JSValue js_createRealm(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
JSContext *ctx1;
JSValue ret;
ctx1 = JS_NewContext(JS_GetRuntime(ctx));
if (!ctx1)
return JS_ThrowOutOfMemory(ctx);
ret = add_helpers1(ctx1);
/* ctx1 has a refcount so it stays alive */
JS_FreeContext(ctx1);
return ret;
}
static JSValue js_IsHTMLDDA(JSContext *ctx, JSValue this_val,
int argc, JSValue *argv)
{
return JS_NULL;
}
static JSValue add_helpers1(JSContext *ctx)
{
JSValue global_obj;
JSValue obj262, obj;
global_obj = JS_GetGlobalObject(ctx);
JS_SetPropertyStr(ctx, global_obj, "print",
JS_NewCFunction(ctx, js_print_262, "print", 1));
/* $262 special object used by the tests */
obj262 = JS_NewObject(ctx);
JS_SetPropertyStr(ctx, obj262, "detachArrayBuffer",
JS_NewCFunction(ctx, js_detachArrayBuffer,
"detachArrayBuffer", 1));
JS_SetPropertyStr(ctx, obj262, "evalScript",
JS_NewCFunction(ctx, js_evalScript_262,
"evalScript", 1));
JS_SetPropertyStr(ctx, obj262, "codePointRange",
JS_NewCFunction(ctx, js_string_codePointRange,
"codePointRange", 2));
JS_SetPropertyStr(ctx, obj262, "agent", js_new_agent(ctx));
JS_SetPropertyStr(ctx, obj262, "global",
JS_DupValue(ctx, global_obj));
JS_SetPropertyStr(ctx, obj262, "createRealm",
JS_NewCFunction(ctx, js_createRealm,
"createRealm", 0));
obj = JS_NewCFunction(ctx, js_IsHTMLDDA, "IsHTMLDDA", 0);
JS_SetIsHTMLDDA(ctx, obj);
JS_SetPropertyStr(ctx, obj262, "IsHTMLDDA", obj);
JS_SetPropertyStr(ctx, global_obj, "$262", JS_DupValue(ctx, obj262));
JS_FreeValue(ctx, global_obj);
return obj262;
}
static void add_helpers(JSContext *ctx)
{
JS_FreeValue(ctx, add_helpers1(ctx));
}
static char *load_file(const char *filename, size_t *lenp)
{
char *buf;
size_t buf_len;
buf = (char *)js_load_file(NULL, &buf_len, filename);
if (!buf)
perror_exit(1, filename);
if (lenp)
*lenp = buf_len;
return buf;
}
static JSModuleDef *js_module_loader_test(JSContext *ctx,
const char *module_name, void *opaque)
{
size_t buf_len;
uint8_t *buf;
JSModuleDef *m;
JSValue func_val;
char *filename, *slash, path[1024];
// interpret import("bar.js") from path/to/foo.js as
// import("path/to/bar.js") but leave import("./bar.js") untouched
filename = opaque;
if (!strchr(module_name, '/')) {
slash = strrchr(filename, '/');
if (slash) {
snprintf(path, sizeof(path), "%.*s/%s",
(int) (slash - filename), filename, module_name);
module_name = path;
}
}
buf = js_load_file(ctx, &buf_len, module_name);
if (!buf) {
JS_ThrowReferenceError(ctx, "could not load module filename '%s'",