File: WebAssemblyBuiltin.cpp

package info (click to toggle)
webkit2gtk 2.51.3-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 477,912 kB
  • sloc: cpp: 3,898,343; javascript: 198,215; ansic: 165,229; python: 50,371; asm: 21,819; ruby: 18,095; perl: 16,953; xml: 4,623; sh: 2,398; yacc: 2,356; java: 2,019; lex: 1,358; pascal: 372; makefile: 197
file content (840 lines) | stat: -rw-r--r-- 36,116 bytes parent folder | download | duplicates (2)
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
/*
 * Copyright (C) 2025 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include "config.h"
#include "WebAssemblyBuiltin.h"

#if ENABLE(WEBASSEMBLY)

#include "JITExceptions.h"
#include "JSStringInlines.h"
#include "JSWebAssemblyArrayInlines.h"
#include "JSWebAssemblyInstance.h"
#include "JSWebAssemblyRuntimeError.h"
#include <wtf/Vector.h>
#include <wtf/text/MakeString.h>

/*
    Implementation Overview

    Builtins are organized into sets, and sets are held by a registry, which is a singleton object.
    Important APIs:
        - static WebAssemblyBuiltinRegistry::singleton()
        - WebAssemblyBuiltinRegistry::findByQualifiedName(String&)
        - WebAssemblyBuiltinSet::findBuiltin(String&)
    The registry and other objects are created once and stay alive "forever".

    A builtin is implemented as a triplet of functions: an implementation function and two
    entrypoint functions wrapping the implementation. Their names are dictated by the macros:

        - BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)
        - BUILTIN_WASM_ENTRY_NAME(setName, builtinName)
        - BUILTIN_JS_ENTRY_NAME(setName, builtinName)

    The JS entrypoint is called by the JSFunction object produced by the builtin's .jsWrapper()
    member function. The JS wrapper is used when the builtin is re-exported by the module.

    The Wasm entrypoint is used by the "normal" call path when the builtin is called from
    Wasm code. The Wasm entrypoint is declared as a JIT operation.

    The entrypoint is called from Wasm via a helper "trampoline" function. The trampoline
    in set as the builtin callee's entrypoint, which eventually makes it the "official"
    entrypoint of the builtin import's link info. The trampoline ensures the Callee and
    the CodeBlock slots of the call frame are initialized and calls the Wasm entrypoint
    with the additional wasmInstance argument. After the Wasm entrypoint returns, the
    trampoline checks for an exception and if needed kicks off exception handling.

    A builtin instance holds a pointer to a trampoline defined in InPlaceInterpreter.asm.
    That "static" trampoline is used if JIT cage is disabled in the current configuration.
    If JIT cage is enabled, an equivalent trampoline is generated by
    WebAssemblyBuiltinTrampoline.cpp, and used instead of the static once.

    To properly set up the call frame, a trampoline needs to be able to find the callee of
    its builtin. That is done using the unique integer ID of the builtin. IDs start from 0
    and increase consecutively up to WASM_BUILTIN_COUNT. A JSWebAssemblyInstance has a
    table of CalleeBits, which is populated at creation time with callee bits of callees
    of all builtins imported by the module, in positions matching builtin IDs. A builtin
    call trampoline fetches the callee of its builtin from that table. Each builtin has
    its own trampoline because the table offset is hardcoded in the trampoline.

    Builtin callees are owned by WebAssemblyBuiltin instances. Like builtin instances, callees
    are immutable and never destroyed.
*/

namespace JSC {

JSFunction* WebAssemblyBuiltin::jsWrapper(JSGlobalObject* globalObject) const
{
    return JSFunction::create(globalObject->vm(), globalObject, 0, m_name, m_jsHostFunction, ImplementationVisibility::Public, JSC::NoIntrinsic);
}

const WebAssemblyBuiltin* WebAssemblyBuiltinSet::findBuiltin(const String& name) const
{
    auto it = m_builtinsByName.find(name);
    return it != m_builtinsByName.end() ? it->value : nullptr;
}

void WebAssemblyBuiltinSet::add(WebAssemblyBuiltin&& builtin)
{
    m_builtins.append(WTFMove(builtin));
}

void WebAssemblyBuiltinSet::finalizeCreation()
{
    // Should not be called repeatedly
    ASSERT(m_builtinsByName.isEmpty());
    ASSERT(m_nameSection->functionNames.isEmpty());

    size_t builtinCount = m_builtins.size();
    m_nameSection->functionNames.resize(builtinCount);
    for (size_t i = 0; i < builtinCount; i++) {
        auto& builtin = m_builtins[i];
        String builtinName = String(builtin.name());

        // Enter the builtin into the lookup table
        m_builtinsByName.add(builtinName, &builtin);

        // Create a simulated wasm name section entry for the builtin
        String fullName = makeString(String(m_qualifiedName), "."_s, builtinName);
        auto span = fullName.span8();
        Wasm::Name name;
        name.grow(span.size());
        memcpySpan(name.mutableSpan(), span);
        m_nameSection->functionNames[i] = WTFMove(name);
        builtin.m_wasmName = &m_nameSection->functionNames[i];
        builtin.m_nameSection = m_nameSection.ptr();
        // Effectively leaked, which is okay because builtins live forever
        builtin.m_callee = new Wasm::WasmBuiltinCallee(&builtin, { builtin.m_wasmName, builtin.m_nameSection });
    }
}

const WebAssemblyBuiltinRegistry& WebAssemblyBuiltinRegistry::singleton()
{
    static std::once_flag onceFlag;
    static LazyNeverDestroyed<WebAssemblyBuiltinRegistry> registry;
    std::call_once(onceFlag, [] {
        registry.construct();
    });
    return registry.get();
}

WebAssemblyBuiltinRegistry::WebAssemblyBuiltinRegistry()
{
    m_builtinSets.append(WebAssemblyBuiltinSet::jsString());
}

// The registry is immutable once constructed so we don't worry about concurrency.
const WebAssemblyBuiltinSet* WebAssemblyBuiltinRegistry::findByQualifiedName(const String& name) const
{
    size_t index = m_builtinSets.findIf([&](auto& builtinSet) {
        return name == builtinSet.qualifiedName();
    });
    return index != notFound ? &m_builtinSets[index] : nullptr;
}

bool WebAssemblyArrayMutI16TypeExpectation::isValid(const Wasm::Type& type) const
{
    if (!type.isRefNull())
        return false;
    Ref<const Wasm::TypeDefinition> referentType = Wasm::TypeInformation::get(type.index);
    if (!referentType->is<Wasm::ArrayType>())
        return false;
    Wasm::FieldType elementType = referentType->as<Wasm::ArrayType>()->elementType();
    return elementType.mutability == Wasm::Mutability::Mutable
        && elementType.type.is<Wasm::PackedType>()
        && elementType.type.as<Wasm::PackedType>() == Wasm::PackedType::I16;
}

bool WebAssemblyBuiltinSignature::isValid(const Wasm::FunctionSignature& sig) const
{
    if (sig.returnCount() != m_results.size() || sig.argumentCount() != m_params.size())
        return false;
    for (unsigned i = 0; i < sig.returnCount(); ++i) {
        auto type = sig.returnType(i);
        if (!m_results[i]->isValid(type))
            return false;
    }
    for (unsigned i = 0; i < sig.argumentCount(); ++i) {
        auto type = sig.argumentType(i);
        if (!m_params[i]->isValid(type))
            return false;
    }
    return true;
}

/*
    Builtin implementation support

    In macro names such as DEFINE_BUILTIN_ENTRY_*, the builtin signature is encoded as a suffix
    using the scheme borrowed from wasm-module-builder.js used by WPT tests:

        _<return type code>_<param type code>+

    with the following type codes:

        I = i32
        R = externref
        A = ref null array mut i16
*/

// Dynamic array type check, required in JS entrypoints.
static bool isMutI16Array(const JSWebAssemblyArray* array)
{
    auto elementType = array->elementType();
    return elementType.mutability == Wasm::Mutability::Mutable
        && elementType.type.is<Wasm::PackedType>()
        && elementType.type.as<Wasm::PackedType>() == Wasm::PackedType::I16;
}

// The naming scheme. Changes should be matched in InPlaceInterpreter.asm
// macros wasmBuiltinCallTrampoline and defineWasmBuiltinCallTrampoline.

#define BUILTIN_TRAMPOLINE_NAME(setName, builtinName) CONCAT(wasm_builtin_trampoline__, BUILTIN_FULL_NAME(setName, builtinName))
#define BUILTIN_JS_ENTRY_NAME(setName, builtinName) CONCAT(wasm_builtinJS__, BUILTIN_FULL_NAME(setName, builtinName))
#define BUILTIN_IMPLEMENTATION_NAME(setName, builtinName) CONCAT(wasm_builtin_impl__, BUILTIN_FULL_NAME(setName, builtinName))

#define DEFINE_BUILTIN_IMPLEMENTATION(setName, builtinName, ...) \
    static ALWAYS_INLINE EncodedJSValue BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(__VA_ARGS__)

#define DEFINE_BUILTIN_IMPLEMENTATION_I32(setName, builtinName, ...) \
    static ALWAYS_INLINE UCPUStrictInt32 BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(__VA_ARGS__)

// A trampoline is a builtin entry point stored in the builtin callee.
// It properly sets up the call frame, then calls the host function, then checks for exceptions.
#define DECLARE_BUILTIN_TRAMPOLINE(setName, builtinName) \
    extern "C" EncodedJSValue BUILTIN_TRAMPOLINE_NAME(setName, builtinName)()

// A host function called by the trampoline. Actually implements the builtin logic.
#define DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, ...) \
    extern "C" EncodedJSValue SYSV_ABI BUILTIN_WASM_ENTRY_NAME(setName, builtinName)(__VA_ARGS__) REFERENCED_FROM_ASM WTF_INTERNAL; \
    JSC_ANNOTATE_JIT_OPERATION(BUILTIN_WASM_ENTRY_NAME(setName, builtinName)); \
    EncodedJSValue SYSV_ABI BUILTIN_WASM_ENTRY_NAME(setName, builtinName)(__VA_ARGS__)

#define THROW_ILLEGAL_ARGUMENT_EXCEPTION \
    do { \
        JSObject* error = createJSWebAssemblyRuntimeError(globalObject, globalObject->vm(), Wasm::ExceptionType::IllegalArgument); \
        throwException(globalObject, scope, error); \
        return encodedJSValue(); \
    } while (false)

// For use in JS wrappers, assuming 'valueVar' is defined at the expansion site.
// Expand into code defining 'i32Var' and setting it to valueVar's value converted to i32.
// The function using it should establish a throw scope as 'scope'.
#define JSVALUE_TO_I32(valueVar, i32Var) \
    int32_t i32Var = valueVar.toInt32(globalObject); \
    RETURN_IF_EXCEPTION(scope, { });

// For use in JS wrappers, assuming 'var' is defined at the expansion site and contains a JSValue.
// Expands into code that verifies that the variable contains a (non-null) array of mutable i16s.
#define ENSURE_ARRAY_MUT_I16(var) \
    { \
        auto* tmpArray = jsDynamicCast<JSWebAssemblyArray*>(var); \
        if (!tmpArray || !isMutI16Array(tmpArray)) [[unlikely]] \
            THROW_ILLEGAL_ARGUMENT_EXCEPTION; \
    }

// externref (externref)

#define DEFINE_BUILTIN_ENTRY_R_R(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value = JSValue::decode(arg); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_R_R(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        JSValue value = callFrame->argument(0); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, value); \
    }

// i32 (externref)

#define DEFINE_BUILTIN_ENTRY_I_R(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value = JSValue::decode(arg); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_I_R(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        JSValue value = callFrame->argument(0); \
        int32_t result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, value); \
        return JSValue::encode(JSValue(result)); \
    }

// externref (i32)

#define DEFINE_BUILTIN_ENTRY_R_I(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, int32_t arg, const JSWebAssemblyInstance* wasmInstance) \
    { \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), arg); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_R_I(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); \
        JSValue arg = callFrame->argument(0); \
        JSVALUE_TO_I32(arg, intArg); \
        EncodedJSValue result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, intArg); \
        RELEASE_AND_RETURN(scope, result); \
    }

// externref (externref, externref)

#define DEFINE_BUILTIN_ENTRY_R_RR(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg0, EncodedJSValue arg1, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue left = JSValue::decode(arg0); \
        JSValue right = JSValue::decode(arg1); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), left, right); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_R_RR(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        JSValue left = callFrame->argument(0); \
        JSValue right = callFrame->argument(1); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, left, right); \
    }

// i32 (externref, externref)

#define DEFINE_BUILTIN_ENTRY_I_RR(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg0, EncodedJSValue arg1, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value0 = JSValue::decode(arg0); \
        JSValue value1 = JSValue::decode(arg1); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value0, value1); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_I_RR(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        JSValue arg0 = callFrame->argument(0); \
        JSValue arg1 = callFrame->argument(1); \
        int32_t result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, arg0, arg1); \
        return JSValue::encode(JSValue(result)); \
    }

// i32 (externref, i32)

#define DEFINE_BUILTIN_ENTRY_I_RI(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg0, int32_t arg1, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value0 = JSValue::decode(arg0); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value0, arg1); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_I_RI(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); \
        JSValue arg0 = callFrame->argument(0); \
        JSValue arg1 = callFrame->argument(1); \
        JSVALUE_TO_I32(arg1, intArg1); \
        int32_t result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, arg0, intArg1); \
        RELEASE_AND_RETURN(scope, JSValue::encode(JSValue(result))); \
    }

// externref (externref, i32, i32)

#define DEFINE_BUILTIN_ENTRY_R_RII(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg0, int32_t arg1, int32_t arg2, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value0 = JSValue::decode(arg0); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value0, arg1, arg2); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_R_RII(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); \
        JSValue arg0 = callFrame->argument(0); \
        JSValue arg1 = callFrame->argument(1); \
        JSValue arg2 = callFrame->argument(2); \
        JSVALUE_TO_I32(arg1, intArg1); \
        JSVALUE_TO_I32(arg2, intArg2); \
        EncodedJSValue result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, arg0, intArg1, intArg2); \
        RELEASE_AND_RETURN(scope, result); \
    }

// externref (ref null array mut i16, i32, i32)

#define DEFINE_BUILTIN_ENTRY_R_AII(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg0, int32_t arg1, int32_t arg2, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value0 = JSValue::decode(arg0); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value0, arg1, arg2); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_R_AII(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); \
        JSValue arg0 = callFrame->argument(0); \
        JSValue arg1 = callFrame->argument(1); \
        JSValue arg2 = callFrame->argument(2); \
        ENSURE_ARRAY_MUT_I16(arg0); \
        JSVALUE_TO_I32(arg1, intArg1); \
        JSVALUE_TO_I32(arg2, intArg2); \
        EncodedJSValue result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, arg0, intArg1, intArg2); \
        RELEASE_AND_RETURN(scope, result); \
    }

// i32 (externref, ref null array mut i16, i)

#define DEFINE_BUILTIN_ENTRY_I_RAI(setName, builtinName) \
    DEFINE_WASM_BUILTIN_HOST_FUNCTION(setName, builtinName, EncodedJSValue arg0, EncodedJSValue arg1, int32_t arg2, const JSWebAssemblyInstance* wasmInstance) \
    { \
        JSValue value0 = JSValue::decode(arg0); \
        JSValue value1 = JSValue::decode(arg1); \
        return BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(wasmInstance->globalObject(), value0, value1, arg2); \
    }

#define DEFINE_BUILTIN_JS_ENTRY_I_RAI(setName, builtinName) \
    static JSC_DECLARE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName)); \
    JSC_DEFINE_HOST_FUNCTION(BUILTIN_JS_ENTRY_NAME(setName, builtinName), (JSGlobalObject* globalObject, CallFrame* callFrame)) \
    { \
        auto scope = DECLARE_THROW_SCOPE(globalObject->vm()); \
        JSValue arg0 = callFrame->argument(0); \
        JSValue arg1 = callFrame->argument(1); \
        JSValue arg2 = callFrame->argument(2); \
        ENSURE_ARRAY_MUT_I16(arg1); \
        JSVALUE_TO_I32(arg2, intArg2); \
        int32_t result = BUILTIN_IMPLEMENTATION_NAME(setName, builtinName)(globalObject, arg0, arg1, intArg2); \
        RELEASE_AND_RETURN(scope, JSValue::encode(JSValue(result))); \
    }

/*
    wasm:js-string builtin set

    Builtins in this set resemble the standard JS functions defined in String.prototype and String
    constructor object (StringPrototype.cpp and StringConstructor.cpp), but there are subtle
    differences in their precise semantics. For example, String.prototype.charCodeAt returns NaN if
    the position is out of bounds, while wasm:js-string.charCodeAt throws an exception. In
    JavaScript the argument is a JS value, but in wasm it's a native `int32`. That's on top of the
    differences in calling conventions: most JS string operations operate on 'this' while there is
    no such special argument in wasm functions.

    These differences make it difficult to directly share implementation. For this reason, builtin
    implementations here are independent from StringPrototype and StringConstructor. That also
    applies to JS representatives of builtin functions (JS functions exported when a builtin is
    re-exported). Again, that's because even when re-exported as a JS function, a Wasm builtin
    receives arguments in a different way and in general behaves slightly differently.
*/


/**
 * See: https://webassembly.github.io/js-string-builtins/js-api/#js-string-cast
 *
 * If the arg is a string, return it, otherwise throw a RuntimeError.
 */
DEFINE_BUILTIN_IMPLEMENTATION(jsstring, cast, JSGlobalObject* globalObject, JSValue value)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!value.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    RELEASE_AND_RETURN(scope, JSValue::encode(value));
}

DEFINE_BUILTIN_ENTRY_R_R(jsstring, cast);
DEFINE_BUILTIN_JS_ENTRY_R_R(jsstring, cast);
DECLARE_BUILTIN_TRAMPOLINE(jsstring, cast);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-test
 *
 * Return 1 if the arg is a string, 0 otherwise.
 */

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, test, JSGlobalObject* globalObject, JSValue value)
{
    UNUSED_PARAM(globalObject);
    return toUCPUStrictInt32(value.isString() ? 1 : 0);
}

DEFINE_BUILTIN_ENTRY_I_R(jsstring, test)
DEFINE_BUILTIN_JS_ENTRY_I_R(jsstring, test)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, test);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-fromCharCodeArray
 *
 * Create a string with characters contained in the array between indices 'start' and 'end'.
*/

DEFINE_BUILTIN_IMPLEMENTATION(jsstring, fromCharCodeArray, JSGlobalObject* globalObject, JSValue arg0, int32_t startArg, int32_t endArg)
{
    auto& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    JSObject* arrayObject = arg0.getObject();
    if (!arrayObject) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;

    // At this point 'array' must be an (array mut i16), guaranteed by Wasm type rules
    // or by a runtime check in JS entrypoint wrapper.
    auto* array = jsCast<JSWebAssemblyArray*>(arrayObject);
    ASSERT(isMutI16Array(array));

    if (startArg < 0 || endArg < 0)
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    size_t start = startArg;
    size_t end = endArg;
    if (start > end || end > array->size()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;

    auto chars = array->span<char16_t>();
    auto slice = chars.subspan(start, end - start);
    JSString* result = jsString(vm, String(slice));
    RELEASE_AND_RETURN(scope, JSValue::encode(result));
}

DEFINE_BUILTIN_ENTRY_R_AII(jsstring, fromCharCodeArray)
DEFINE_BUILTIN_JS_ENTRY_R_AII(jsstring, fromCharCodeArray)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, fromCharCodeArray);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-intoCharCodeArray
 *
 * Copy character codes of all characters of the string into the array. First character
 * is placed at the index 'start' in the array. The array must be large enough.
*/

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, intoCharCodeArray, JSGlobalObject* globalObject, JSValue stringArg, JSValue arrayArg, int32_t startArg)
{
    auto& vm = globalObject->vm();
    auto scope = DECLARE_THROW_SCOPE(vm);

    JSObject* arrayObject = arrayArg.getObject();
    if (!arrayObject || !stringArg.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;

    JSString* string = jsCast<JSString*>(stringArg);
    // At this point 'array' must be an (array mut i16), guaranteed by Wasm type rules
    // or by a runtime check in JS entrypoint wrapper.
    auto* array = jsCast<JSWebAssemblyArray*>(arrayObject);
    ASSERT(isMutI16Array(array));

    size_t stringLength = string->length();
    size_t arrayLength = array->size();
    if (startArg < 0)
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    size_t start = startArg;
    if (start + stringLength > arrayLength) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;

    auto data = array->span<char16_t>();
    auto dest = data.subspan(start, stringLength);
    auto stringValue = string->value(globalObject);

    if (stringValue.data.is8Bit()) {
        for (size_t i = 0; i < stringLength; ++i)
            dest[i] = stringValue.data[i];
    } else {
        auto source = stringValue.data.span<char16_t>();
        memcpySpan(dest, source);
    }

    return toUCPUStrictInt32(stringLength);
}

DEFINE_BUILTIN_ENTRY_I_RAI(jsstring, intoCharCodeArray)
DEFINE_BUILTIN_JS_ENTRY_I_RAI(jsstring, intoCharCodeArray)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, intoCharCodeArray);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-fromCharCode
 *
 * Create a single-character string from the given char code.
 */

DEFINE_BUILTIN_IMPLEMENTATION(jsstring, fromCharCode, JSGlobalObject* globalObject, int32_t arg)
{
    return JSValue::encode(jsSingleCharacterString(globalObject->vm(), static_cast<char16_t>(arg)));
}

DEFINE_BUILTIN_ENTRY_R_I(jsstring, fromCharCode)
DEFINE_BUILTIN_JS_ENTRY_R_I(jsstring, fromCharCode)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, fromCharCode);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-fromCodePoint
 *
 * Create a single-character string from the given code point.
 */

DEFINE_BUILTIN_IMPLEMENTATION(jsstring, fromCodePoint, JSGlobalObject* globalObject, int32_t arg)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    auto codePoint = static_cast<char32_t>(arg);
    if (codePoint > 0x10ffff) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    JSValue result = JSValue(jsString(globalObject->vm(), makeString(codePoint)));
    RELEASE_AND_RETURN(scope, JSValue::encode(result));
}

DEFINE_BUILTIN_ENTRY_R_I(jsstring, fromCodePoint)
DEFINE_BUILTIN_JS_ENTRY_R_I(jsstring, fromCodePoint)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, fromCodePoint);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-charCodeAt
 *
 * The proposal states that if the index is greater than or equal to the string length, an exception
 * is thrown. However, it does not currently specify what happens if the index is negative.
 *
 * In Chrome, an exception is thrown because the index is cast to u32, turning negative values
 * into very large positive values, which then fail the 'index < length' test for all possible
 * combinations of the original negative indices and string lengths.
 *
 * I submitted https://github.com/WebAssembly/js-string-builtins/issues/51 to report this omission.
 */

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, charCodeAt, JSGlobalObject* globalObject, JSValue arg, int32_t index)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!arg.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    auto* string = arg.toString(globalObject);
    RETURN_IF_EXCEPTION(scope, { });
    auto view = string->view(globalObject);
    RETURN_IF_EXCEPTION(scope, { });
    if (index < 0 || view->length() <= static_cast<unsigned>(index)) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    char16_t result = view[index];
    RELEASE_AND_RETURN(scope, toUCPUStrictInt32(result));
}

DEFINE_BUILTIN_ENTRY_I_RI(jsstring, charCodeAt)
DEFINE_BUILTIN_JS_ENTRY_I_RI(jsstring, charCodeAt)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, charCodeAt);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-codePointAt
 *
 * See the note on index validation in charCodeAt.
 */

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, codePointAt, JSGlobalObject* globalObject, JSValue arg, int32_t index)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!arg.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    auto* string = arg.toString(globalObject);
    RETURN_IF_EXCEPTION(scope, { });
    auto view = string->view(globalObject);
    RETURN_IF_EXCEPTION(scope, { });
    unsigned length = view->length();
    if (index < 0 || length <= static_cast<unsigned>(index)) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    int32_t result;
    if (view->is8Bit())
        result = view->span8()[index];
    else {
        char32_t character;
        auto characters = view->span16();
        unsigned i = static_cast<unsigned>(index);
        U16_NEXT(characters, i, length, character);
        result = static_cast<int32_t>(character);
    }
    RELEASE_AND_RETURN(scope, toUCPUStrictInt32(result));
}

DEFINE_BUILTIN_ENTRY_I_RI(jsstring, codePointAt)
DEFINE_BUILTIN_JS_ENTRY_I_RI(jsstring, codePointAt)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, codePointAt);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-length
 *
 * If the value is a string, return its length. Otherwise throw a RuntimeError.
 */

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, length, JSGlobalObject* globalObject, JSValue arg)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!arg.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    unsigned length = asString(arg)->length();
    ASSERT(length <= static_cast<unsigned>(std::numeric_limits<int32_t>::max())); // guaranteed by String::MaxLength
    RELEASE_AND_RETURN(scope, toUCPUStrictInt32(length));
}

DEFINE_BUILTIN_ENTRY_I_R(jsstring, length)
DEFINE_BUILTIN_JS_ENTRY_I_R(jsstring, length)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, length);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-concat
 *
 * If both values are strings, return the result of concatenating them.
 * Otherwise throw a RuntimeError.
 */

DEFINE_BUILTIN_IMPLEMENTATION(jsstring, concat, JSGlobalObject* globalObject, JSValue left, JSValue right)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!left.isString() || !right.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    JSString* result = jsString(globalObject, asString(left), asString(right)); // creates a rope string
    RELEASE_AND_RETURN(scope, JSValue::encode(JSValue(result)));
}

DEFINE_BUILTIN_ENTRY_R_RR(jsstring, concat)
DEFINE_BUILTIN_JS_ENTRY_R_RR(jsstring, concat)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, concat);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-substring
 */

DEFINE_BUILTIN_IMPLEMENTATION(jsstring, substring, JSGlobalObject* globalObject, JSValue arg, int32_t start, int32_t end)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!arg.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    JSString* string = asString(arg);
    unsigned length = string->length();
    unsigned substringStart = start >= 0 ? static_cast<unsigned>(start) : 0;
    unsigned substringEnd = end >= 0 ? static_cast<unsigned>(end) : 0;
    if (substringStart >= length)
        substringStart = length;
    if (substringEnd > length)
        substringEnd = length;
    if (substringStart > substringEnd)
        substringStart = substringEnd;
    unsigned substringLength = substringEnd - substringStart;
    JSString* result = jsSubstring(globalObject, string, substringStart, substringLength);
    RELEASE_AND_RETURN(scope, JSValue::encode(JSValue(result)));
}

DEFINE_BUILTIN_ENTRY_R_RII(jsstring, substring)
DEFINE_BUILTIN_JS_ENTRY_R_RII(jsstring, substring)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, substring);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-equals
 *
 * Each argument must be a string or a null, or an exception is thrown.
 * If this initial type check passes, comparison behaves as tc39's IsStrictlyEqual,
 * see https://tc39.es/ecma262/#sec-isstrictlyequal
 */

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, equals, JSGlobalObject* globalObject, JSValue left, JSValue right)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    bool leftIsString = left.isString();
    bool leftIsNull = left.isNull();
    bool rightIsString = right.isString();
    bool rightIsNull = right.isNull();
    if (!(leftIsString || leftIsNull) || !(rightIsString || rightIsNull)) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;
    if (!((leftIsString && rightIsString) || (leftIsNull && rightIsNull))) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;

    int32_t result;
    if (leftIsNull)
        result = true;
    else {
        JSString* leftString = asString(left);
        JSString* rightString = asString(right);
        result = leftString->equal(globalObject, rightString);
    }
    RELEASE_AND_RETURN(scope, toUCPUStrictInt32(result));
}

DEFINE_BUILTIN_ENTRY_I_RR(jsstring, equals)
DEFINE_BUILTIN_JS_ENTRY_I_RR(jsstring, equals)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, equals);

/**
 * See https://webassembly.github.io/js-string-builtins/js-api/#js-string-compare
 *
 * Unlike for the 'equals' builtin, the spec says here the args may only be strings--no nulls.
 */

DEFINE_BUILTIN_IMPLEMENTATION_I32(jsstring, compare, JSGlobalObject* globalObject, JSValue left, JSValue right)
{
    auto scope = DECLARE_THROW_SCOPE(globalObject->vm());
    if (!left.isString() || !right.isString()) [[unlikely]]
        THROW_ILLEGAL_ARGUMENT_EXCEPTION;

    JSString* leftString = asString(left);
    JSString* rightString = asString(right);
    auto leftView = leftString->view(globalObject);
    RETURN_IF_EXCEPTION(scope, { });
    auto rightView = rightString->view(globalObject);
    RETURN_IF_EXCEPTION(scope, { });
    std::strong_ordering ordering = WTF::codePointCompare(StringView(leftView), StringView(rightView));
    int32_t result = ordering == std::strong_ordering::less ? -1 : ordering == std::strong_ordering::greater ? 1 : 0;
    RELEASE_AND_RETURN(scope, toUCPUStrictInt32(result));
}

DEFINE_BUILTIN_ENTRY_I_RR(jsstring, compare)
DEFINE_BUILTIN_JS_ENTRY_I_RR(jsstring, compare)
DECLARE_BUILTIN_TRAMPOLINE(jsstring, compare);

/*
    The 'js-string' builtin set
*/

WebAssemblyBuiltinSet WebAssemblyBuiltinSet::jsString()
{
    WebAssemblyBuiltinSet builtinSet = WebAssemblyBuiltinSet("wasm:js-string");

#define CREATE_BUILTIN(setName, builtinName, signature) \
    builtinSet.add(WebAssemblyBuiltin( \
        static_cast<uint32_t>(WasmBuiltinID::BUILTIN_FULL_NAME(setName, builtinName)), \
        ASCIILiteral(#builtinName), \
        signature, \
        BUILTIN_WASM_ENTRY_NAME(setName, builtinName), \
        BUILTIN_TRAMPOLINE_NAME(setName, builtinName), \
        BUILTIN_JS_ENTRY_NAME(setName, builtinName) \
    ));

    FOR_EACH_WASM_JS_STRING_BUILTIN(CREATE_BUILTIN)
#undef CREATE_BUILTIN

    builtinSet.finalizeCreation();
    return builtinSet;
}

} // namespace JSC

#endif // ENABLE(WEBASSEMBLY)