-
Notifications
You must be signed in to change notification settings - Fork 817
Expand file tree
/
Copy pathjsi.h
More file actions
2266 lines (1896 loc) · 83.5 KB
/
Copy pathjsi.h
File metadata and controls
2266 lines (1896 loc) · 83.5 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
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <cassert>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <exception>
#include <functional>
#include <memory>
#include <string>
#include <vector>
#ifndef JSI_EXPORT
#ifdef _MSC_VER
#ifdef CREATE_SHARED_LIBRARY
#define JSI_EXPORT __declspec(dllexport)
#else
#define JSI_EXPORT
#endif // CREATE_SHARED_LIBRARY
#else // _MSC_VER
#define JSI_EXPORT __attribute__((visibility("default")))
#endif // _MSC_VER
#endif // !defined(JSI_EXPORT)
class FBJSRuntime;
namespace facebook {
namespace jsi {
/// UUID version 1 implementation. This should be constructed with constant
/// arguments to identify fixed UUIDs.
class JSI_EXPORT UUID {
public:
// Construct from raw parts
constexpr UUID(
uint32_t timeLow,
uint16_t timeMid,
uint16_t timeHighAndVersion,
uint16_t variantAndClockSeq,
uint64_t node)
: high(
((uint64_t)(timeLow) << 32) | ((uint64_t)(timeMid) << 16) |
((uint64_t)(timeHighAndVersion))),
low(((uint64_t)(variantAndClockSeq) << 48) | node) {}
// Default constructor (zero UUID)
constexpr UUID() : high(0), low(0) {}
constexpr UUID(const UUID&) = default;
constexpr UUID& operator=(const UUID&) = default;
constexpr bool operator==(const UUID& other) const {
return high == other.high && low == other.low;
}
constexpr bool operator!=(const UUID& other) const {
return !(*this == other);
}
// Ordering (for std::map, sorting, etc.)
constexpr bool operator<(const UUID& other) const {
return (high < other.high) || (high == other.high && low < other.low);
}
// Hash support for UUID (for unordered_map compatibility)
struct Hash {
std::size_t operator()(const UUID& uuid) const noexcept {
return std::hash<uint64_t>{}(uuid.high) ^
(std::hash<uint64_t>{}(uuid.low) << 1);
}
};
// UUID format: 8-4-4-4-12
std::string toString() const {
std::string buffer(36, ' ');
std::snprintf(
buffer.data(),
buffer.size() + 1,
"%08x-%04x-%04x-%04x-%012llx",
getTimeLow(),
getTimeMid(),
getTimeHighAndVersion(),
getVariantAndClockSeq(),
(unsigned long long)getNode());
return buffer;
}
constexpr uint32_t getTimeLow() const {
return (uint32_t)(high >> 32);
}
constexpr uint16_t getTimeMid() const {
return (uint16_t)(high >> 16);
}
constexpr uint16_t getTimeHighAndVersion() const {
return (uint16_t)high;
}
constexpr uint16_t getVariantAndClockSeq() const {
return (uint16_t)(low >> 48);
}
constexpr uint64_t getNode() const {
return low & 0xFFFFFFFFFFFF;
}
private:
uint64_t high;
uint64_t low;
};
/// Base interface that all JSI interfaces inherit from. Users should not try to
/// manipulate this base type directly, and should use castInterface to get the
/// appropriate subtype.
struct JSI_EXPORT ICast {
/// If the current object can be cast into the interface specified by \p
/// interfaceUUID, return a pointer to the object. Otherwise, return a null
/// pointer.
/// The returned interface has the same lifetime as the underlying object. It
/// does not need to be released when not needed.
virtual ICast* castInterface(const UUID& interfaceUUID) = 0;
protected:
/// Interfaces are not destructible, thus the destructor is intentionally
/// protected to prevent delete calls on the interface.
/// Additionally, the destructor is non-virtual to reduce the vtable
/// complexity from inheritance.
~ICast() = default;
};
/// Base class for buffers of data or bytecode that need to be passed to the
/// runtime. The buffer is expected to be fully immutable, so the result of
/// size(), data(), and the contents of the pointer returned by data() must not
/// change after construction.
class JSI_EXPORT Buffer {
public:
virtual ~Buffer();
virtual size_t size() const = 0;
virtual const uint8_t* data() const = 0;
};
class JSI_EXPORT StringBuffer : public Buffer {
public:
StringBuffer(std::string s) : s_(std::move(s)) {}
size_t size() const override {
return s_.size();
}
const uint8_t* data() const override {
return reinterpret_cast<const uint8_t*>(s_.data());
}
private:
std::string s_;
};
/// Base class for buffers of data that need to be passed to the runtime. The
/// result of size() and data() must not change after construction. However, the
/// region pointed to by data() may be modified by the user or the runtime. The
/// user must ensure that access to the contents of the buffer is properly
/// synchronised.
class JSI_EXPORT MutableBuffer {
public:
virtual ~MutableBuffer();
virtual size_t size() const = 0;
virtual uint8_t* data() = 0;
};
/// PreparedJavaScript is a base class representing JavaScript which is in a
/// form optimized for execution, in a runtime-specific way. Construct one via
/// jsi::Runtime::prepareJavaScript().
/// ** This is an experimental API that is subject to change. **
class JSI_EXPORT PreparedJavaScript {
protected:
PreparedJavaScript() = default;
public:
virtual ~PreparedJavaScript() = 0;
};
class IRuntime;
class Runtime;
class Pointer;
class PropNameID;
class Symbol;
class BigInt;
class String;
class Object;
class WeakObject;
class Array;
class ArrayBuffer;
class Function;
class Value;
class Instrumentation;
class Scope;
class JSIException;
class JSError;
class TypedArray;
class Uint8Array;
/// A function which has this type can be registered as a function
/// callable from JavaScript using Function::createFromHostFunction().
/// When the function is called, args will point to the arguments, and
/// count will indicate how many arguments are passed. The function
/// can return a Value to the caller, or throw an exception. If a C++
/// exception is thrown, a JS Error will be created and thrown into
/// JS; if the C++ exception extends std::exception, the Error's
/// message will be whatever what() returns. Note that it is undefined whether
/// HostFunctions may or may not be called in strict mode; that is `thisVal`
/// can be any value - it will not necessarily be coerced to an object or
/// or set to the global object.
using HostFunctionType = std::function<
Value(Runtime& rt, const Value& thisVal, const Value* args, size_t count)>;
/// An object which implements this interface can be registered as an
/// Object with the JS runtime.
class JSI_EXPORT HostObject {
public:
// The C++ object's dtor will be called when the GC finalizes this
// object. (This may be as late as when the Runtime is shut down.)
// You have no control over which thread it is called on. This will
// be called from inside the GC, so it is unsafe to do any VM
// operations which require a IRuntime&. Derived classes' dtors
// should also avoid doing anything expensive. Calling the dtor on
// a jsi object is explicitly ok. If you want to do JS operations,
// or any nontrivial work, you should add it to a work queue, and
// manage it externally.
virtual ~HostObject();
// When JS wants a property with a given name from the HostObject,
// it will call this method. If it throws an exception, the call
// will throw a JS \c Error object. By default this returns undefined.
// \return the value for the property.
virtual Value get(Runtime&, const PropNameID& name);
// When JS wants to set a property with a given name on the HostObject,
// it will call this method. If it throws an exception, the call will
// throw a JS \c Error object. By default this throws a type error exception
// mimicking the behavior of a frozen object in strict mode.
virtual void set(Runtime&, const PropNameID& name, const Value& value);
// When JS wants a list of property names for the HostObject, it will
// call this method. If it throws an exception, the call will throw a
// JS \c Error object. The default implementation returns empty vector.
virtual std::vector<PropNameID> getPropertyNames(Runtime& rt);
};
/// Native state (and destructor) that can be attached to any JS object
/// using setNativeState.
class JSI_EXPORT NativeState {
public:
virtual ~NativeState();
};
// JSI_UNSTABLE gates features that will be released with a Hermes version in
// the future. Until released, these features may be subject to change. After
// release, these features will be moved out of JSI_UNSTABLE and become frozen.
#ifdef JSI_UNSTABLE
/// Opaque class that is used to store serialized object from a runtime. The
/// lifetime of this object is orthogonal to the original runtime object, and
/// may outlive the original object.
class JSI_EXPORT Serialized {
public:
/// Uses \p secretAddr to validate if the Serialized data is supported. If so,
/// return the pointer to the underlying serialized data. Otherwise, return a
/// nullptr. This should be used by the runtime to deserialize the data.
virtual void* getPrivate(const void* secretAddr) = 0;
virtual ~Serialized();
};
/// Provides a set of APIs that allows copying objects between different
/// runtime instances. The runtimes instances must be of the same type. As an
/// example, a serialized object from Hermes runtime may only be deserialized by
/// another Hermes runtime.
class JSI_EXPORT ISerialization : public ICast {
public:
static constexpr jsi::UUID uuid{
0xd40fe0ec,
0xa47c,
0x42c9,
0x8c09,
0x661aeab832d8};
/// Serializes the given Value \p value using the structured clone algorithm.
/// It returns a shared pointer of an opaque Serialized object that can be
/// deserialized multiple times. The lifetime of the Serialized object is not
/// tied to the lifetime of the original object.
virtual std::shared_ptr<Serialized> serialize(const Value& value) = 0;
/// Given a Serialized object provided by \p serialized, deserialize it using
/// the structured clone algorithm into a JS value in the current runtime.
/// Returns the deserialized JS value.
virtual Value deserialize(const std::shared_ptr<Serialized>& serialized) = 0;
/// Serializes the given jsi::Value \p value using the structured clone
/// algorithm. \p transferList must be a JS Array. Given the length property
/// of \p transferList, this API will transfer everything at index [0, length
/// - 1] to the serialized object. The transferred values will no longer be
/// usable in the original runtime. It returns a unique pointer of an opaque
/// Serialized object that can be deserialized once only by
/// deserializeWithTransfer. The lifetime of the Serialized object is not tied
/// to the lifetime of the original object.
virtual std::unique_ptr<Serialized> serializeWithTransfer(
const Value& value,
const Array& transferList) = 0;
/// Using the structure clone algorithm, deserialize the object provided by \p
/// serialized into a JS value in the current runtime. \p serialized must be
/// created by serializeWithTransfer. If the current runtime does not support
/// the serialization scheme in \p serialized, then this method will throw and
/// \p serialized will remain unmodified. Otherwise, this will consume the
/// serialized data entirely and make the serialized objects in the current
/// runtime. Any transferred values in the serialized object will be owned by
/// the current runtime.
/// This method returns an Array containing the deserialized values, where
/// the first element is the value passed into serializeWithTransfer,
/// followed by all transferred values.
virtual Array deserializeWithTransfer(
std::unique_ptr<Serialized>& serialized) = 0;
protected:
~ISerialization() = default;
};
#endif // JSI_UNSTABLE
/// An interface that provides various functionalities of the JS runtime.
/// The APIs must not be called from multiple threads concurrently. It is the
/// user's responsibility ensure thread safety when using IRuntime.
/// Users should cast their runtime to IRuntime to access these APIs. However,
/// for backward compatibility, these APIs are also accessible via the Runtime
/// object directly.
class JSI_EXPORT IRuntime : public ICast {
public:
static constexpr jsi::UUID uuid{
0xc2e8e22e,
0xd7a6,
0x11f0,
0x8de9,
0x0242ac120002};
/// Evaluates the given JavaScript \c buffer. \c sourceURL is used
/// to annotate the stack trace if there is an exception. The
/// contents may be utf8-encoded JS source code, or binary bytecode
/// whose format is specific to the implementation. If the input
/// format is unknown, or evaluation causes an error, a JSIException
/// will be thrown.
/// Note this function should ONLY be used when there isn't another means
/// through the JSI API. For example, it will be much slower to use this to
/// call a global function than using the JSI APIs to read the function
/// property from the global object and then calling it explicitly.
virtual Value evaluateJavaScript(
const std::shared_ptr<const Buffer>& buffer,
const std::string& sourceURL) = 0;
/// Prepares to evaluate the given JavaScript \c buffer by processing it into
/// a form optimized for execution. This may include pre-parsing, compiling,
/// etc. If the input is invalid (for example, cannot be parsed), a
/// JSIException will be thrown. The resulting object is tied to the
/// particular concrete type of Runtime from which it was created. It may be
/// used (via evaluatePreparedJavaScript) in any Runtime of the same concrete
/// type.
/// The PreparedJavaScript object may be passed to multiple VM instances, so
/// they can all share and benefit from the prepared script.
/// As with evaluateJavaScript(), using JavaScript code should be avoided
/// when the JSI API is sufficient.
virtual std::shared_ptr<const PreparedJavaScript> prepareJavaScript(
const std::shared_ptr<const Buffer>& buffer,
std::string sourceURL) = 0;
/// Evaluates a PreparedJavaScript. If evaluation causes an error, a
/// JSIException will be thrown.
/// As with evaluateJavaScript(), using JavaScript code should be avoided
/// when the JSI API is sufficient.
virtual Value evaluatePreparedJavaScript(
const std::shared_ptr<const PreparedJavaScript>& js) = 0;
/// Queues a microtask in the JavaScript VM internal Microtask (a.k.a. Job in
/// ECMA262) queue, to be executed when the host drains microtasks in
/// its event loop implementation.
///
/// \param callback a function to be executed as a microtask.
virtual void queueMicrotask(const jsi::Function& callback) = 0;
/// Drain the JavaScript VM internal Microtask (a.k.a. Job in ECMA262) queue.
///
/// \param maxMicrotasksHint a hint to tell an implementation that it should
/// make a best effort not execute more than the given number. It's default
/// to -1 for infinity (unbounded execution).
/// \return true if the queue is drained or false if there is more work to do.
///
/// When there were exceptions thrown from the execution of microtasks,
/// implementations shall discard the exceptional jobs. An implementation may
/// \throw a \c JSError object to signal the hosts to handle. In that case, an
/// implementation may or may not suspend the draining.
///
/// Hosts may call this function again to resume the draining if it was
/// suspended due to either exceptions or the \p maxMicrotasksHint bound.
/// E.g. a host may repetitively invoke this function until the queue is
/// drained to implement the "microtask checkpoint" defined in WHATWG HTML
/// event loop: https://html.spec.whatwg.org/C#perform-a-microtask-checkpoint.
///
/// Note that error propagation is only a concern if a host needs to implement
/// `queueMicrotask`, a recent API that allows enqueueing arbitrary functions
/// (hence may throw) as microtasks. Exceptions from ECMA-262 Promise Jobs are
/// handled internally to VMs and are never propagated to hosts.
///
/// This API offers some queue management to hosts at its best effort due to
/// different behaviors and limitations imposed by different VMs and APIs. By
/// the time this is written, An implementation may swallow exceptions (JSC),
/// may not pause (V8), and may not support bounded executions.
virtual bool drainMicrotasks(int maxMicrotasksHint = -1) = 0;
/// \return the global object
virtual Object global() = 0;
/// \return a short printable description of the instance. It should
/// at least include some human-readable indication of the runtime
/// implementation. This should only be used by logging, debugging,
/// and other developer-facing callers.
virtual std::string description() = 0;
/// \return whether or not the underlying runtime supports debugging via the
/// Chrome remote debugging protocol.
///
/// NOTE: the API for determining whether a runtime is debuggable and
/// registering a runtime with the debugger is still in flux, so please don't
/// use this API unless you know what you're doing.
virtual bool isInspectable() = 0;
/// \return an interface to extract metrics from this \c Runtime. The default
/// implementation of this function returns an \c Instrumentation instance
/// which returns no metrics.
virtual Instrumentation& instrumentation() = 0;
/// Stores the pointer \p data with the \p dataUUID in the runtime. This can
/// be used to store some custom data within the runtime. When the runtime is
/// destroyed, or if an entry at an existing key is overwritten, the runtime
/// will release its ownership of the held object.
virtual void setRuntimeData(
const UUID& dataUUID,
const std::shared_ptr<void>& data) = 0;
/// Returns the data associated with the \p uuid in the runtime. If there's no
/// data associated with the uuid, return a null pointer.
virtual std::shared_ptr<void> getRuntimeData(const UUID& dataUUID) = 0;
/// Stores the pointer \p data with the \p uuid in the runtime. This can be
/// used to store some custom data within the runtime. When the runtime is
/// destroyed, or if an entry at an existing key is overwritten, the runtime
/// will release its ownership by calling \p deleter.
virtual void setRuntimeDataImpl(
const UUID& dataUUID,
const void* data,
void (*deleter)(const void* data)) = 0;
/// Returns the data associated with the \p uuid in the runtime. If there's no
/// data associated with the uuid, return a null pointer.
virtual const void* getRuntimeDataImpl(const UUID& dataUUID) = 0;
// Potential optimization: avoid the cloneFoo() virtual dispatch,
// and instead just fix the number of fields, and copy them, since
// in practice they are trivially copyable. Sufficient use of
// rvalue arguments/methods would also reduce the number of clones.
struct PointerValue {
virtual void invalidate() noexcept = 0;
protected:
virtual ~PointerValue() = default;
};
virtual PointerValue* cloneSymbol(const IRuntime::PointerValue* pv) = 0;
virtual PointerValue* cloneBigInt(const IRuntime::PointerValue* pv) = 0;
virtual PointerValue* cloneString(const IRuntime::PointerValue* pv) = 0;
virtual PointerValue* cloneObject(const IRuntime::PointerValue* pv) = 0;
virtual PointerValue* clonePropNameID(const IRuntime::PointerValue* pv) = 0;
virtual PropNameID createPropNameIDFromAscii(
const char* str,
size_t length) = 0;
virtual PropNameID createPropNameIDFromUtf8(
const uint8_t* utf8,
size_t length) = 0;
virtual PropNameID createPropNameIDFromUtf16(
const char16_t* utf16,
size_t length) = 0;
virtual PropNameID createPropNameIDFromString(const String& str) = 0;
virtual PropNameID createPropNameIDFromSymbol(const Symbol& sym) = 0;
virtual std::string utf8(const PropNameID&) = 0;
virtual bool compare(const PropNameID&, const PropNameID&) = 0;
virtual std::string symbolToString(const Symbol&) = 0;
virtual BigInt createBigIntFromInt64(int64_t) = 0;
virtual BigInt createBigIntFromUint64(uint64_t) = 0;
virtual bool bigintIsInt64(const BigInt&) = 0;
virtual bool bigintIsUint64(const BigInt&) = 0;
virtual uint64_t truncate(const BigInt&) = 0;
virtual String bigintToString(const BigInt&, int) = 0;
virtual String createStringFromAscii(const char* str, size_t length) = 0;
virtual String createStringFromUtf8(const uint8_t* utf8, size_t length) = 0;
virtual String createStringFromUtf16(
const char16_t* utf16,
size_t length) = 0;
virtual std::string utf8(const String&) = 0;
// \return a \c Value created from a utf8-encoded JSON string. The default
// implementation creates a \c String and invokes JSON.parse.
virtual Value createValueFromJsonUtf8(const uint8_t* json, size_t length) = 0;
virtual Object createObject() = 0;
virtual Object createObject(std::shared_ptr<HostObject> ho) = 0;
virtual std::shared_ptr<HostObject> getHostObject(const jsi::Object&) = 0;
virtual HostFunctionType& getHostFunction(const jsi::Function&) = 0;
// Creates a new Object with the custom prototype
virtual Object createObjectWithPrototype(const Value& prototype) = 0;
virtual bool hasNativeState(const jsi::Object&) = 0;
virtual std::shared_ptr<NativeState> getNativeState(const jsi::Object&) = 0;
virtual void setNativeState(
const jsi::Object&,
std::shared_ptr<NativeState> state) = 0;
virtual void setPrototypeOf(const Object& object, const Value& prototype) = 0;
virtual Value getPrototypeOf(const Object& object) = 0;
virtual Value getProperty(const Object&, const PropNameID& name) = 0;
virtual Value getProperty(const Object&, const String& name) = 0;
virtual Value getProperty(const Object&, const Value& name) = 0;
virtual bool hasProperty(const Object&, const PropNameID& name) = 0;
virtual bool hasProperty(const Object&, const String& name) = 0;
virtual bool hasProperty(const Object&, const Value& name) = 0;
virtual void setPropertyValue(
const Object&,
const PropNameID& name,
const Value& value) = 0;
virtual void
setPropertyValue(const Object&, const String& name, const Value& value) = 0;
virtual void
setPropertyValue(const Object&, const Value& name, const Value& value) = 0;
virtual void deleteProperty(const Object&, const PropNameID& name) = 0;
virtual void deleteProperty(const Object&, const String& name) = 0;
virtual void deleteProperty(const Object&, const Value& name) = 0;
virtual bool isArray(const Object&) const = 0;
virtual bool isArrayBuffer(const Object&) const = 0;
virtual bool isTypedArray(const Object&) const = 0;
virtual bool isUint8Array(const Object&) const = 0;
virtual bool isFunction(const Object&) const = 0;
virtual bool isHostObject(const jsi::Object&) const = 0;
virtual bool isHostFunction(const jsi::Function&) const = 0;
virtual Array getPropertyNames(const Object&) = 0;
virtual WeakObject createWeakObject(const Object&) = 0;
virtual Value lockWeakObject(const WeakObject&) = 0;
virtual Array createArray(size_t length) = 0;
virtual ArrayBuffer createArrayBuffer(
std::shared_ptr<MutableBuffer> buffer) = 0;
virtual size_t size(const Array&) = 0;
virtual size_t size(const ArrayBuffer&) = 0;
virtual uint8_t* data(const ArrayBuffer&) = 0;
virtual bool detached(const ArrayBuffer&) = 0;
virtual Value getValueAtIndex(const Array&, size_t i) = 0;
virtual void
setValueAtIndexImpl(const Array&, size_t i, const Value& value) = 0;
virtual size_t push(const Array&, const Value*, size_t) = 0;
virtual Function createFunctionFromHostFunction(
const PropNameID& name,
unsigned int paramCount,
HostFunctionType func) = 0;
virtual Value call(
const Function&,
const Value& jsThis,
const Value* args,
size_t count) = 0;
virtual Value
callAsConstructor(const Function&, const Value* args, size_t count) = 0;
// Private data for managing scopes.
struct ScopeState;
virtual ScopeState* pushScope() = 0;
virtual void popScope(ScopeState*) = 0;
virtual bool strictEquals(const Symbol& a, const Symbol& b) const = 0;
virtual bool strictEquals(const BigInt& a, const BigInt& b) const = 0;
virtual bool strictEquals(const String& a, const String& b) const = 0;
virtual bool strictEquals(const Object& a, const Object& b) const = 0;
virtual bool instanceOf(const Object& o, const Function& f) = 0;
/// See Object::setExternalMemoryPressure.
virtual void setExternalMemoryPressure(
const jsi::Object& obj,
size_t amount) = 0;
virtual std::u16string utf16(const String& str) = 0;
virtual std::u16string utf16(const PropNameID& sym) = 0;
/// Invokes the provided callback \p cb with the String content in \p str.
/// The callback must take in three arguments: bool ascii, const void* data,
/// and size_t num, respectively. \p ascii indicates whether the \p data
/// passed to the callback should be interpreted as a pointer to a sequence of
/// \p num ASCII characters or UTF16 characters. Depending on the internal
/// representation of the string, the function may invoke the callback
/// multiple times, with a different format on each invocation. The callback
/// must not access runtime functionality, as any operation on the runtime may
/// invalidate the data pointers.
virtual void getStringData(
const jsi::String& str,
void* ctx,
void (*cb)(void* ctx, bool ascii, const void* data, size_t num)) = 0;
/// Invokes the provided callback \p cb with the PropNameID content in \p sym.
/// The callback must take in three arguments: bool ascii, const void* data,
/// and size_t num, respectively. \p ascii indicates whether the \p data
/// passed to the callback should be interpreted as a pointer to a sequence of
/// \p num ASCII characters or UTF16 characters. Depending on the internal
/// representation of the string, the function may invoke the callback
/// multiple times, with a different format on each invocation. The callback
/// must not access runtime functionality, as any operation on the runtime may
/// invalidate the data pointers.
virtual void getPropNameIdData(
const jsi::PropNameID& sym,
void* ctx,
void (*cb)(void* ctx, bool ascii, const void* data, size_t num)) = 0;
/// If possible, returns the MutableBuffer representing \p arrayBuffer's
/// underlying data, else return a nullptr. Importantly, the returned
/// MutableBuffer directly points to \p arrayBuffer's data instead of copying
/// the data over. The data's lifetime is valid for the lifetime of
/// MutableBuffer, which is orthogonal from \p arrayBuffer.
virtual std::shared_ptr<MutableBuffer> tryGetMutableBuffer(
const jsi::ArrayBuffer& arrayBuffer) = 0;
/// \return the underlying buffer of the \p typedArray.
virtual ArrayBuffer buffer(const TypedArray& typedArray) = 0;
/// \return the 'byteOffset' property of the \p typedArray.
virtual size_t byteOffset(const TypedArray& typedArray) = 0;
/// \return the 'byteLength' property of the \p typedArray.
virtual size_t byteLength(const TypedArray& typedArray) = 0;
/// \return the 'length; property of the \p typedArray.
virtual size_t length(const TypedArray& typedArray) = 0;
/// Create a JS UInt8Array with length \p length.
virtual Uint8Array createUint8Array(size_t length) = 0;
/// Create a JS UInt8Array using the ArrayBuffer \p buffer starting at byte
/// offset \p offset and length \p length.
virtual Uint8Array
createUint8Array(const ArrayBuffer& buffer, size_t offset, size_t length) = 0;
/// Create a new Error object with the message property set to \p message.
virtual Value createError(const String& msg) = 0;
/// Create a new EvalError object with the message property set to \p message.
virtual Value createEvalError(const String& msg) = 0;
/// Create a new RangeError object with the message property set to \p
/// message.
virtual Value createRangeError(const String& msg) = 0;
/// Create a new ReferenceError object with the message property set to \p
/// message.
virtual Value createReferenceError(const String& msg) = 0;
/// Create a new SyntaxError object with the message property set to \p
/// message.
virtual Value createSyntaxError(const String& msg) = 0;
/// Create a new TypeError object with the message property set to \p message.
virtual Value createTypeError(const String& msg) = 0;
/// Create a new URIError object with the message property set to \p message.
virtual Value createURIError(const String& msg) = 0;
/// Returns the number of code units in the string, equivalent to 'length'
/// property of a JS string.
virtual size_t length(const String& str) = 0;
protected:
virtual ~IRuntime() = default;
};
/// Represents a JS runtime. Movable, but not copyable. Note that
/// this object may not be thread-aware, but cannot be used safely from
/// multiple threads at once. The application is responsible for
/// ensuring that it is used safely. This could mean using the
/// Runtime from a single thread, using a mutex, doing all work on a
/// serial queue, etc. This restriction applies to the methods of
/// this class, and any method in the API which take a Runtime& as an
/// argument. Destructors (all but ~Scope), operators, or other methods
/// which do not take Runtime& as an argument are safe to call from any
/// thread, but it is still forbidden to make write operations on a single
/// instance of any class from more than one thread. In addition, to
/// make shutdown safe, destruction of objects associated with the Runtime
/// must be destroyed before the Runtime is destroyed, or from the
/// destructor of a managed HostObject or HostFunction. Informally, this
/// means that the main source of unsafe behavior is to hold a jsi object
/// in a non-Runtime-managed object, and not clean it up before the Runtime
/// is shut down. If your lifecycle is such that avoiding this is hard,
/// you will probably need to do use your own locks.
class JSI_EXPORT Runtime : public IRuntime {
public:
virtual ~Runtime() override;
using IRuntime::getProperty;
using IRuntime::hasProperty;
using IRuntime::setPropertyValue;
ICast* castInterface(const UUID& uuid) override;
Instrumentation& instrumentation() override;
/// Stores the pointer \p data with the \p uuid in the runtime. This can be
/// used to store some custom data within the runtime. When the runtime is
/// destroyed, or if an entry at an existing key is overwritten, the runtime
/// will release its ownership of the held object.
void setRuntimeData(const UUID& uuid, const std::shared_ptr<void>& data)
override;
/// Returns the data associated with the \p uuid in the runtime. If there's no
/// data associated with the uuid, return a null pointer.
std::shared_ptr<void> getRuntimeData(const UUID& uuid) override;
Value getProperty(const Object&, const Value& name) override;
bool hasProperty(const Object&, const Value& name) override;
void setPropertyValue(const Object&, const Value& name, const Value& value)
override;
void deleteProperty(const Object&, const PropNameID& name) override;
void deleteProperty(const Object&, const String& name) override;
void deleteProperty(const Object&, const Value& name) override;
void setRuntimeDataImpl(
const UUID& uuid,
const void* data,
void (*deleter)(const void* data)) override;
const void* getRuntimeDataImpl(const UUID& uuid) override;
PropNameID createPropNameIDFromUtf16(const char16_t* utf16, size_t length)
override;
String createStringFromUtf16(const char16_t* utf16, size_t length) override;
Value createValueFromJsonUtf8(const uint8_t* json, size_t length) override;
Object createObjectWithPrototype(const Value& prototype) override;
void setPrototypeOf(const Object& object, const Value& prototype) override;
Value getPrototypeOf(const Object& object) override;
ScopeState* pushScope() override;
void popScope(ScopeState*) override;
std::u16string utf16(const String& str) override;
std::u16string utf16(const PropNameID& sym) override;
void getStringData(
const jsi::String& str,
void* ctx,
void (*cb)(void* ctx, bool ascii, const void* data, size_t num)) override;
void getPropNameIdData(
const jsi::PropNameID& sym,
void* ctx,
void (*cb)(void* ctx, bool ascii, const void* data, size_t num)) override;
size_t push(const Array&, const Value*, size_t) override;
std::shared_ptr<MutableBuffer> tryGetMutableBuffer(
const jsi::ArrayBuffer& arrayBuffer) override;
bool detached(const ArrayBuffer&) override;
ArrayBuffer buffer(const TypedArray& typedArray) override;
size_t byteOffset(const TypedArray& typedArray) override;
size_t byteLength(const TypedArray& typedArray) override;
size_t length(const TypedArray& typedArray) override;
bool isTypedArray(const Object&) const override;
bool isUint8Array(const Object&) const override;
Uint8Array createUint8Array(size_t length) override;
Uint8Array createUint8Array(
const ArrayBuffer& buffer,
size_t offset,
size_t length) override;
Value createError(const String& msg) override;
Value createEvalError(const String& msg) override;
Value createRangeError(const String& msg) override;
Value createReferenceError(const String& msg) override;
Value createSyntaxError(const String& msg) override;
Value createTypeError(const String& msg) override;
Value createURIError(const String& msg) override;
size_t length(const String& str) override;
protected:
friend class Pointer;
friend class PropNameID;
friend class Symbol;
friend class BigInt;
friend class String;
friend class Object;
friend class WeakObject;
friend class Array;
friend class ArrayBuffer;
friend class Function;
friend class Value;
friend class Scope;
friend class JSError;
// These exist so derived classes can access the private parts of
// Value, Symbol, String, and Object, which are all friends of Runtime.
template <typename T>
static T make(PointerValue* pv);
static PointerValue* getPointerValue(Pointer& pointer);
static const PointerValue* getPointerValue(const Pointer& pointer);
static const PointerValue* getPointerValue(const Value& value);
friend class ::FBJSRuntime;
template <typename Plain, typename Base>
friend class RuntimeDecorator;
};
// Base class for pointer-storing types.
class JSI_EXPORT Pointer {
protected:
explicit Pointer(Pointer&& other) noexcept : ptr_(other.ptr_) {
other.ptr_ = nullptr;
}
~Pointer() {
if (ptr_) {
ptr_->invalidate();
}
}
Pointer& operator=(Pointer&& other) noexcept;
friend class Runtime;
friend class Value;
explicit Pointer(Runtime::PointerValue* ptr) : ptr_(ptr) {}
typename Runtime::PointerValue* ptr_;
};
/// Represents something that can be a JS property key. Movable, not copyable.
class JSI_EXPORT PropNameID : public Pointer {
public:
using Pointer::Pointer;
PropNameID(IRuntime& runtime, const PropNameID& other)
: Pointer(runtime.clonePropNameID(other.ptr_)) {}
PropNameID(PropNameID&& other) = default;
PropNameID& operator=(PropNameID&& other) = default;
/// Create a JS property name id from ascii values. The data is
/// copied.
static PropNameID
forAscii(IRuntime& runtime, const char* str, size_t length) {
return runtime.createPropNameIDFromAscii(str, length);
}
/// Create a property name id from a nul-terminated C ascii name. The data is
/// copied.
static PropNameID forAscii(IRuntime& runtime, const char* str) {
return forAscii(runtime, str, strlen(str));
}
/// Create a PropNameID from a C++ string. The string is copied.
static PropNameID forAscii(IRuntime& runtime, const std::string& str) {
return forAscii(runtime, str.c_str(), str.size());
}
/// Create a PropNameID from utf8 values. The data is copied.
/// Results are undefined if \p utf8 contains invalid code points.
static PropNameID
forUtf8(IRuntime& runtime, const uint8_t* utf8, size_t length) {
return runtime.createPropNameIDFromUtf8(utf8, length);
}
/// Create a PropNameID from utf8-encoded octets stored in a
/// std::string. The string data is transformed and copied.
/// Results are undefined if \p utf8 contains invalid code points.
static PropNameID forUtf8(IRuntime& runtime, const std::string& utf8) {
return runtime.createPropNameIDFromUtf8(
reinterpret_cast<const uint8_t*>(utf8.data()), utf8.size());
}
/// Given a series of UTF-16 encoded code units, create a PropNameId. The
/// input may contain unpaired surrogates, which will be interpreted as a code
/// point of the same value.
static PropNameID
forUtf16(IRuntime& runtime, const char16_t* utf16, size_t length) {
return runtime.createPropNameIDFromUtf16(utf16, length);
}
/// Given a series of UTF-16 encoded code units stored inside std::u16string,
/// create a PropNameId. The input may contain unpaired surrogates, which
/// will be interpreted as a code point of the same value.
static PropNameID forUtf16(IRuntime& runtime, const std::u16string& str) {
return runtime.createPropNameIDFromUtf16(str.data(), str.size());
}
/// Create a PropNameID from a JS string.
static PropNameID forString(IRuntime& runtime, const jsi::String& str) {
return runtime.createPropNameIDFromString(str);
}
/// Create a PropNameID from a JS symbol.
static PropNameID forSymbol(IRuntime& runtime, const jsi::Symbol& sym) {
return runtime.createPropNameIDFromSymbol(sym);
}
// Creates a vector of PropNameIDs constructed from given arguments.
template <typename... Args>
static std::vector<PropNameID> names(IRuntime& runtime, Args&&... args);
// Creates a vector of given PropNameIDs.
template <size_t N>
static std::vector<PropNameID> names(PropNameID (&&propertyNames)[N]);
/// Copies the data in a PropNameID as utf8 into a C++ string.
std::string utf8(IRuntime& runtime) const {
return runtime.utf8(*this);
}
/// Copies the data in a PropNameID as utf16 into a C++ string.
std::u16string utf16(IRuntime& runtime) const {
return runtime.utf16(*this);
}
/// Invokes the user provided callback to process the content in PropNameId.
/// The callback must take in three arguments: bool ascii, const void* data,
/// and size_t num, respectively. \p ascii indicates whether the \p data
/// passed to the callback should be interpreted as a pointer to a sequence of
/// \p num ASCII characters or UTF16 characters. The function may invoke the
/// callback multiple times, with a different format on each invocation. The
/// callback must not access runtime functionality, as any operation on the
/// runtime may invalidate the data pointers.
template <typename CB>
void getPropNameIdData(IRuntime& runtime, CB& cb) const {
runtime.getPropNameIdData(
*this, &cb, [](void* ctx, bool ascii, const void* data, size_t num) {
(*((CB*)ctx))(ascii, data, num);
});
}
static bool compare(
IRuntime& runtime,
const jsi::PropNameID& a,
const jsi::PropNameID& b) {
return runtime.compare(a, b);
}
friend class Runtime;
friend class Value;
};
/// Represents a JS Symbol (es6). Movable, not copyable.
/// TODO T40778724: this is a limited implementation sufficient for
/// the debugger not to crash when a Symbol is a property in an Object
/// or element in an array. Complete support for creating will come
/// later.
class JSI_EXPORT Symbol : public Pointer {
public:
using Pointer::Pointer;
Symbol(Symbol&& other) = default;
Symbol& operator=(Symbol&& other) = default;
/// \return whether a and b refer to the same symbol.
static bool
strictEquals(IRuntime& runtime, const Symbol& a, const Symbol& b) {
return runtime.strictEquals(a, b);
}
/// Converts a Symbol into a C++ string as JS .toString would. The output
/// will look like \c Symbol(description) .
std::string toString(IRuntime& runtime) const {
return runtime.symbolToString(*this);
}
friend class Runtime;
friend class Value;
};
/// Represents a JS BigInt. Movable, not copyable.
class JSI_EXPORT BigInt : public Pointer {
public:
using Pointer::Pointer;
BigInt(BigInt&& other) = default;
BigInt& operator=(BigInt&& other) = default;
/// Create a BigInt representing the signed 64-bit \p value.
static BigInt fromInt64(IRuntime& runtime, int64_t value) {
return runtime.createBigIntFromInt64(value);
}