1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 /** \mainpage V8 API Reference Guide
6 *
7 * V8 is Google's open source JavaScript engine.
8 *
9 * This set of documents provides reference material generated from the
10 * V8 header file, include/v8.h.
11 *
12 * For other documentation see http://code.google.com/apis/v8/
13 */
14
15 #ifndef INCLUDE_V8_H_
16 #define INCLUDE_V8_H_
17
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 #include <memory>
22 #include <utility>
23 #include <vector>
24
25 #include "v8-version.h" // NOLINT(build/include)
26 #include "v8config.h" // NOLINT(build/include)
27
28 // We reserve the V8_* prefix for macros defined in V8 public API and
29 // assume there are no name conflicts with the embedder's code.
30
31 #ifdef V8_OS_WIN
32
33 // Setup for Windows DLL export/import. When building the V8 DLL the
34 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
35 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
36 // static library or building a program which uses the V8 static library neither
37 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
38 #ifdef BUILDING_V8_SHARED
39 # define V8_EXPORT __declspec(dllexport)
40 #elif USING_V8_SHARED
41 # define V8_EXPORT __declspec(dllimport)
42 #else
43 # define V8_EXPORT
44 #endif // BUILDING_V8_SHARED
45
46 #else // V8_OS_WIN
47
48 // Setup for Linux shared library export.
49 #if V8_HAS_ATTRIBUTE_VISIBILITY
50 # ifdef BUILDING_V8_SHARED
51 # define V8_EXPORT __attribute__ ((visibility("default")))
52 # else
53 # define V8_EXPORT
54 # endif
55 #else
56 # define V8_EXPORT
57 #endif
58
59 #endif // V8_OS_WIN
60
61 /**
62 * The v8 JavaScript engine.
63 */
64 namespace v8 {
65
66 class AccessorSignature;
67 class Array;
68 class ArrayBuffer;
69 class BigInt;
70 class BigIntObject;
71 class Boolean;
72 class BooleanObject;
73 class Context;
74 class Data;
75 class Date;
76 class External;
77 class Function;
78 class FunctionTemplate;
79 class HeapProfiler;
80 class ImplementationUtilities;
81 class Int32;
82 class Integer;
83 class Isolate;
84 template <class T>
85 class Maybe;
86 class Name;
87 class Number;
88 class NumberObject;
89 class Object;
90 class ObjectOperationDescriptor;
91 class ObjectTemplate;
92 class Platform;
93 class Primitive;
94 class Promise;
95 class PropertyDescriptor;
96 class Proxy;
97 class RawOperationDescriptor;
98 class Script;
99 class SharedArrayBuffer;
100 class Signature;
101 class StartupData;
102 class StackFrame;
103 class StackTrace;
104 class String;
105 class StringObject;
106 class Symbol;
107 class SymbolObject;
108 class PrimitiveArray;
109 class Private;
110 class Uint32;
111 class Utils;
112 class Value;
113 class WasmCompiledModule;
114 template <class T> class Local;
115 template <class T>
116 class MaybeLocal;
117 template <class T> class Eternal;
118 template<class T> class NonCopyablePersistentTraits;
119 template<class T> class PersistentBase;
120 template <class T, class M = NonCopyablePersistentTraits<T> >
121 class Persistent;
122 template <class T>
123 class Global;
124 template<class K, class V, class T> class PersistentValueMap;
125 template <class K, class V, class T>
126 class PersistentValueMapBase;
127 template <class K, class V, class T>
128 class GlobalValueMap;
129 template<class V, class T> class PersistentValueVector;
130 template<class T, class P> class WeakCallbackObject;
131 class FunctionTemplate;
132 class ObjectTemplate;
133 template<typename T> class FunctionCallbackInfo;
134 template<typename T> class PropertyCallbackInfo;
135 class StackTrace;
136 class StackFrame;
137 class Isolate;
138 class CallHandlerHelper;
139 class EscapableHandleScope;
140 template<typename T> class ReturnValue;
141
142 namespace internal {
143 class Arguments;
144 class DeferredHandles;
145 class Heap;
146 class HeapObject;
147 class Isolate;
148 class LocalEmbedderHeapTracer;
149 class NeverReadOnlySpaceObject;
150 class Object;
151 struct ScriptStreamingData;
152 template<typename T> class CustomArguments;
153 class PropertyCallbackArguments;
154 class FunctionCallbackArguments;
155 class GlobalHandles;
156
157 namespace wasm {
158 class NativeModule;
159 class StreamingDecoder;
160 } // namespace wasm
161
162 /**
163 * Configuration of tagging scheme.
164 */
165 const int kApiPointerSize = sizeof(void*); // NOLINT
166 const int kApiDoubleSize = sizeof(double); // NOLINT
167 const int kApiIntSize = sizeof(int); // NOLINT
168 const int kApiInt64Size = sizeof(int64_t); // NOLINT
169
170 // Tag information for HeapObject.
171 const int kHeapObjectTag = 1;
172 const int kWeakHeapObjectTag = 3;
173 const int kHeapObjectTagSize = 2;
174 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
175
176 // Tag information for Smi.
177 const int kSmiTag = 0;
178 const int kSmiTagSize = 1;
179 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
180
181 template <size_t tagged_ptr_size>
182 struct SmiTagging;
183
184 template <int kSmiShiftSize>
IntToSmi(int value)185 V8_INLINE internal::Object* IntToSmi(int value) {
186 int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
187 intptr_t tagged_value =
188 (static_cast<intptr_t>(value) << smi_shift_bits) | kSmiTag;
189 return reinterpret_cast<internal::Object*>(tagged_value);
190 }
191
192 // Smi constants for systems where tagged pointer is a 32-bit value.
193 template <>
194 struct SmiTagging<4> {
195 enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
196 static int SmiShiftSize() { return kSmiShiftSize; }
197 static int SmiValueSize() { return kSmiValueSize; }
198 V8_INLINE static int SmiToInt(const internal::Object* value) {
199 int shift_bits = kSmiTagSize + kSmiShiftSize;
200 // Throw away top 32 bits and shift down (requires >> to be sign extending).
201 return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
202 }
203 V8_INLINE static internal::Object* IntToSmi(int value) {
204 return internal::IntToSmi<kSmiShiftSize>(value);
205 }
206 V8_INLINE static constexpr bool IsValidSmi(intptr_t value) {
207 // To be representable as an tagged small integer, the two
208 // most-significant bits of 'value' must be either 00 or 11 due to
209 // sign-extension. To check this we add 01 to the two
210 // most-significant bits, and check if the most-significant bit is 0
211 //
212 // CAUTION: The original code below:
213 // bool result = ((value + 0x40000000) & 0x80000000) == 0;
214 // may lead to incorrect results according to the C language spec, and
215 // in fact doesn't work correctly with gcc4.1.1 in some cases: The
216 // compiler may produce undefined results in case of signed integer
217 // overflow. The computation must be done w/ unsigned ints.
218 return static_cast<uintptr_t>(value) + 0x40000000U < 0x80000000U;
219 }
220 };
221
222 // Smi constants for systems where tagged pointer is a 64-bit value.
223 template <>
224 struct SmiTagging<8> {
225 enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
226 static int SmiShiftSize() { return kSmiShiftSize; }
227 static int SmiValueSize() { return kSmiValueSize; }
228 V8_INLINE static int SmiToInt(const internal::Object* value) {
229 int shift_bits = kSmiTagSize + kSmiShiftSize;
230 // Shift down and throw away top 32 bits.
231 return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
232 }
233 V8_INLINE static internal::Object* IntToSmi(int value) {
234 return internal::IntToSmi<kSmiShiftSize>(value);
235 }
236 V8_INLINE static constexpr bool IsValidSmi(intptr_t value) {
237 // To be representable as a long smi, the value must be a 32-bit integer.
238 return (value == static_cast<int32_t>(value));
239 }
240 };
241
242 #if V8_COMPRESS_POINTERS
243 static_assert(
244 kApiPointerSize == kApiInt64Size,
245 "Pointer compression can be enabled only for 64-bit architectures");
246 typedef SmiTagging<4> PlatformSmiTagging;
247 #else
248 typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
249 #endif
250
251 const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
252 const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
253 const int kSmiMinValue = (static_cast<unsigned int>(-1)) << (kSmiValueSize - 1);
254 const int kSmiMaxValue = -(kSmiMinValue + 1);
255 constexpr bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
256 constexpr bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
257
258 } // namespace internal
259
260 namespace debug {
261 class ConsoleCallArguments;
262 } // namespace debug
263
264 // --- Handles ---
265
266 #define TYPE_CHECK(T, S) \
267 while (false) { \
268 *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
269 }
270
271 /**
272 * An object reference managed by the v8 garbage collector.
273 *
274 * All objects returned from v8 have to be tracked by the garbage
275 * collector so that it knows that the objects are still alive. Also,
276 * because the garbage collector may move objects, it is unsafe to
277 * point directly to an object. Instead, all objects are stored in
278 * handles which are known by the garbage collector and updated
279 * whenever an object moves. Handles should always be passed by value
280 * (except in cases like out-parameters) and they should never be
281 * allocated on the heap.
282 *
283 * There are two types of handles: local and persistent handles.
284 *
285 * Local handles are light-weight and transient and typically used in
286 * local operations. They are managed by HandleScopes. That means that a
287 * HandleScope must exist on the stack when they are created and that they are
288 * only valid inside of the HandleScope active during their creation.
289 * For passing a local handle to an outer HandleScope, an EscapableHandleScope
290 * and its Escape() method must be used.
291 *
292 * Persistent handles can be used when storing objects across several
293 * independent operations and have to be explicitly deallocated when they're no
294 * longer used.
295 *
296 * It is safe to extract the object stored in the handle by
297 * dereferencing the handle (for instance, to extract the Object* from
298 * a Local<Object>); the value will still be governed by a handle
299 * behind the scenes and the same rules apply to these values as to
300 * their handles.
301 */
302 template <class T>
303 class Local {
304 public:
305 V8_INLINE Local() : val_(0) {}
306 template <class S>
307 V8_INLINE Local(Local<S> that)
308 : val_(reinterpret_cast<T*>(*that)) {
309 /**
310 * This check fails when trying to convert between incompatible
311 * handles. For example, converting from a Local<String> to a
312 * Local<Number>.
313 */
314 TYPE_CHECK(T, S);
315 }
316
317 /**
318 * Returns true if the handle is empty.
319 */
320 V8_INLINE bool IsEmpty() const { return val_ == 0; }
321
322 /**
323 * Sets the handle to be empty. IsEmpty() will then return true.
324 */
325 V8_INLINE void Clear() { val_ = 0; }
326
327 V8_INLINE T* operator->() const { return val_; }
328
329 V8_INLINE T* operator*() const { return val_; }
330
331 /**
332 * Checks whether two handles are the same.
333 * Returns true if both are empty, or if the objects
334 * to which they refer are identical.
335 * The handles' references are not checked.
336 */
337 template <class S>
338 V8_INLINE bool operator==(const Local<S>& that) const {
339 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
340 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
341 if (a == 0) return b == 0;
342 if (b == 0) return false;
343 return *a == *b;
344 }
345
346 template <class S> V8_INLINE bool operator==(
347 const PersistentBase<S>& that) const {
348 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
349 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
350 if (a == 0) return b == 0;
351 if (b == 0) return false;
352 return *a == *b;
353 }
354
355 /**
356 * Checks whether two handles are different.
357 * Returns true if only one of the handles is empty, or if
358 * the objects to which they refer are different.
359 * The handles' references are not checked.
360 */
361 template <class S>
362 V8_INLINE bool operator!=(const Local<S>& that) const {
363 return !operator==(that);
364 }
365
366 template <class S> V8_INLINE bool operator!=(
367 const Persistent<S>& that) const {
368 return !operator==(that);
369 }
370
371 /**
372 * Cast a handle to a subclass, e.g. Local<Value> to Local<Object>.
373 * This is only valid if the handle actually refers to a value of the
374 * target type.
375 */
376 template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
377 #ifdef V8_ENABLE_CHECKS
378 // If we're going to perform the type check then we have to check
379 // that the handle isn't empty before doing the checked cast.
380 if (that.IsEmpty()) return Local<T>();
381 #endif
382 return Local<T>(T::Cast(*that));
383 }
384
385 /**
386 * Calling this is equivalent to Local<S>::Cast().
387 * In particular, this is only valid if the handle actually refers to a value
388 * of the target type.
389 */
390 template <class S>
391 V8_INLINE Local<S> As() const {
392 return Local<S>::Cast(*this);
393 }
394
395 /**
396 * Create a local handle for the content of another handle.
397 * The referee is kept alive by the local handle even when
398 * the original handle is destroyed/disposed.
399 */
400 V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
401 V8_INLINE static Local<T> New(Isolate* isolate,
402 const PersistentBase<T>& that);
403
404 private:
405 friend class Utils;
406 template<class F> friend class Eternal;
407 template<class F> friend class PersistentBase;
408 template<class F, class M> friend class Persistent;
409 template<class F> friend class Local;
410 template <class F>
411 friend class MaybeLocal;
412 template<class F> friend class FunctionCallbackInfo;
413 template<class F> friend class PropertyCallbackInfo;
414 friend class String;
415 friend class Object;
416 friend class Context;
417 friend class Isolate;
418 friend class Private;
419 template<class F> friend class internal::CustomArguments;
420 friend Local<Primitive> Undefined(Isolate* isolate);
421 friend Local<Primitive> Null(Isolate* isolate);
422 friend Local<Boolean> True(Isolate* isolate);
423 friend Local<Boolean> False(Isolate* isolate);
424 friend class HandleScope;
425 friend class EscapableHandleScope;
426 template <class F1, class F2, class F3>
427 friend class PersistentValueMapBase;
428 template<class F1, class F2> friend class PersistentValueVector;
429 template <class F>
430 friend class ReturnValue;
431
432 explicit V8_INLINE Local(T* that) : val_(that) {}
433 V8_INLINE static Local<T> New(Isolate* isolate, T* that);
434 T* val_;
435 };
436
437
438 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
439 // Handle is an alias for Local for historical reasons.
440 template <class T>
441 using Handle = Local<T>;
442 #endif
443
444
445 /**
446 * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
447 * the Local<> is empty before it can be used.
448 *
449 * If an API method returns a MaybeLocal<>, the API method can potentially fail
450 * either because an exception is thrown, or because an exception is pending,
451 * e.g. because a previous API call threw an exception that hasn't been caught
452 * yet, or because a TerminateExecution exception was thrown. In that case, an
453 * empty MaybeLocal is returned.
454 */
455 template <class T>
456 class MaybeLocal {
457 public:
458 V8_INLINE MaybeLocal() : val_(nullptr) {}
459 template <class S>
460 V8_INLINE MaybeLocal(Local<S> that)
461 : val_(reinterpret_cast<T*>(*that)) {
462 TYPE_CHECK(T, S);
463 }
464
465 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
466
467 /**
468 * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
469 * |false| is returned and |out| is left untouched.
470 */
471 template <class S>
472 V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local<S>* out) const {
473 out->val_ = IsEmpty() ? nullptr : this->val_;
474 return !IsEmpty();
475 }
476
477 /**
478 * Converts this MaybeLocal<> to a Local<>. If this MaybeLocal<> is empty,
479 * V8 will crash the process.
480 */
481 V8_INLINE Local<T> ToLocalChecked();
482
483 /**
484 * Converts this MaybeLocal<> to a Local<>, using a default value if this
485 * MaybeLocal<> is empty.
486 */
487 template <class S>
488 V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
489 return IsEmpty() ? default_value : Local<S>(val_);
490 }
491
492 private:
493 T* val_;
494 };
495
496 /**
497 * Eternal handles are set-once handles that live for the lifetime of the
498 * isolate.
499 */
500 template <class T> class Eternal {
501 public:
502 V8_INLINE Eternal() : val_(nullptr) {}
503 template <class S>
504 V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : val_(nullptr) {
505 Set(isolate, handle);
506 }
507 // Can only be safely called if already set.
508 V8_INLINE Local<T> Get(Isolate* isolate) const;
509 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
510 template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
511
512 private:
513 T* val_;
514 };
515
516
517 static const int kInternalFieldsInWeakCallback = 2;
518 static const int kEmbedderFieldsInWeakCallback = 2;
519
520 template <typename T>
521 class WeakCallbackInfo {
522 public:
523 typedef void (*Callback)(const WeakCallbackInfo<T>& data);
524
525 WeakCallbackInfo(Isolate* isolate, T* parameter,
526 void* embedder_fields[kEmbedderFieldsInWeakCallback],
527 Callback* callback)
528 : isolate_(isolate), parameter_(parameter), callback_(callback) {
529 for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
530 embedder_fields_[i] = embedder_fields[i];
531 }
532 }
533
534 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
535 V8_INLINE T* GetParameter() const { return parameter_; }
536 V8_INLINE void* GetInternalField(int index) const;
537
538 // When first called, the embedder MUST Reset() the Global which triggered the
539 // callback. The Global itself is unusable for anything else. No v8 other api
540 // calls may be called in the first callback. Should additional work be
541 // required, the embedder must set a second pass callback, which will be
542 // called after all the initial callbacks are processed.
543 // Calling SetSecondPassCallback on the second pass will immediately crash.
544 void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
545
546 private:
547 Isolate* isolate_;
548 T* parameter_;
549 Callback* callback_;
550 void* embedder_fields_[kEmbedderFieldsInWeakCallback];
551 };
552
553
554 // kParameter will pass a void* parameter back to the callback, kInternalFields
555 // will pass the first two internal fields back to the callback, kFinalizer
556 // will pass a void* parameter back, but is invoked before the object is
557 // actually collected, so it can be resurrected. In the last case, it is not
558 // possible to request a second pass callback.
559 enum class WeakCallbackType { kParameter, kInternalFields, kFinalizer };
560
561 /**
562 * An object reference that is independent of any handle scope. Where
563 * a Local handle only lives as long as the HandleScope in which it was
564 * allocated, a PersistentBase handle remains valid until it is explicitly
565 * disposed using Reset().
566 *
567 * A persistent handle contains a reference to a storage cell within
568 * the V8 engine which holds an object value and which is updated by
569 * the garbage collector whenever the object is moved. A new storage
570 * cell can be created using the constructor or PersistentBase::Reset and
571 * existing handles can be disposed using PersistentBase::Reset.
572 *
573 */
574 template <class T> class PersistentBase {
575 public:
576 /**
577 * If non-empty, destroy the underlying storage cell
578 * IsEmpty() will return true after this call.
579 */
580 V8_INLINE void Reset();
581 /**
582 * If non-empty, destroy the underlying storage cell
583 * and create a new one with the contents of other if other is non empty
584 */
585 template <class S>
586 V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
587
588 /**
589 * If non-empty, destroy the underlying storage cell
590 * and create a new one with the contents of other if other is non empty
591 */
592 template <class S>
593 V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
594
595 V8_INLINE bool IsEmpty() const { return val_ == NULL; }
596 V8_INLINE void Empty() { val_ = 0; }
597
598 V8_INLINE Local<T> Get(Isolate* isolate) const {
599 return Local<T>::New(isolate, *this);
600 }
601
602 template <class S>
603 V8_INLINE bool operator==(const PersistentBase<S>& that) const {
604 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
605 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
606 if (a == NULL) return b == NULL;
607 if (b == NULL) return false;
608 return *a == *b;
609 }
610
611 template <class S>
612 V8_INLINE bool operator==(const Local<S>& that) const {
613 internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
614 internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
615 if (a == NULL) return b == NULL;
616 if (b == NULL) return false;
617 return *a == *b;
618 }
619
620 template <class S>
621 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
622 return !operator==(that);
623 }
624
625 template <class S>
626 V8_INLINE bool operator!=(const Local<S>& that) const {
627 return !operator==(that);
628 }
629
630 /**
631 * Install a finalization callback on this object.
632 * NOTE: There is no guarantee as to *when* or even *if* the callback is
633 * invoked. The invocation is performed solely on a best effort basis.
634 * As always, GC-based finalization should *not* be relied upon for any
635 * critical form of resource management!
636 */
637 template <typename P>
638 V8_INLINE void SetWeak(P* parameter,
639 typename WeakCallbackInfo<P>::Callback callback,
640 WeakCallbackType type);
641
642 /**
643 * Turns this handle into a weak phantom handle without finalization callback.
644 * The handle will be reset automatically when the garbage collector detects
645 * that the object is no longer reachable.
646 * A related function Isolate::NumberOfPhantomHandleResetsSinceLastCall
647 * returns how many phantom handles were reset by the garbage collector.
648 */
649 V8_INLINE void SetWeak();
650
651 template<typename P>
652 V8_INLINE P* ClearWeak();
653
654 // TODO(dcarney): remove this.
655 V8_INLINE void ClearWeak() { ClearWeak<void>(); }
656
657 /**
658 * Annotates the strong handle with the given label, which is then used by the
659 * heap snapshot generator as a name of the edge from the root to the handle.
660 * The function does not take ownership of the label and assumes that the
661 * label is valid as long as the handle is valid.
662 */
663 V8_INLINE void AnnotateStrongRetainer(const char* label);
664
665 /**
666 * Allows the embedder to tell the v8 garbage collector that a certain object
667 * is alive. Only allowed when the embedder is asked to trace its heap by
668 * EmbedderHeapTracer.
669 */
670 V8_INLINE void RegisterExternalReference(Isolate* isolate) const;
671
672 /**
673 * Marks the reference to this object independent. Garbage collector is free
674 * to ignore any object groups containing this object. Weak callback for an
675 * independent handle should not assume that it will be preceded by a global
676 * GC prologue callback or followed by a global GC epilogue callback.
677 */
678 V8_DEPRECATE_SOON(
679 "Objects are always considered independent. "
680 "Use MarkActive to avoid collecting otherwise dead weak handles.",
681 V8_INLINE void MarkIndependent());
682
683 /**
684 * Marks the reference to this object as active. The scavenge garbage
685 * collection should not reclaim the objects marked as active, even if the
686 * object held by the handle is otherwise unreachable.
687 *
688 * This bit is cleared after the each garbage collection pass.
689 */
690 V8_INLINE void MarkActive();
691
692 V8_DEPRECATE_SOON("See MarkIndependent.",
693 V8_INLINE bool IsIndependent() const);
694
695 /** Checks if the handle holds the only reference to an object. */
696 V8_INLINE bool IsNearDeath() const;
697
698 /** Returns true if the handle's reference is weak. */
699 V8_INLINE bool IsWeak() const;
700
701 /**
702 * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
703 * description in v8-profiler.h for details.
704 */
705 V8_INLINE void SetWrapperClassId(uint16_t class_id);
706
707 /**
708 * Returns the class ID previously assigned to this handle or 0 if no class ID
709 * was previously assigned.
710 */
711 V8_INLINE uint16_t WrapperClassId() const;
712
713 PersistentBase(const PersistentBase& other) = delete; // NOLINT
714 void operator=(const PersistentBase&) = delete;
715
716 private:
717 friend class Isolate;
718 friend class Utils;
719 template<class F> friend class Local;
720 template<class F1, class F2> friend class Persistent;
721 template <class F>
722 friend class Global;
723 template<class F> friend class PersistentBase;
724 template<class F> friend class ReturnValue;
725 template <class F1, class F2, class F3>
726 friend class PersistentValueMapBase;
727 template<class F1, class F2> friend class PersistentValueVector;
728 friend class Object;
729
730 explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
731 V8_INLINE static T* New(Isolate* isolate, T* that);
732
733 T* val_;
734 };
735
736
737 /**
738 * Default traits for Persistent. This class does not allow
739 * use of the copy constructor or assignment operator.
740 * At present kResetInDestructor is not set, but that will change in a future
741 * version.
742 */
743 template<class T>
744 class NonCopyablePersistentTraits {
745 public:
746 typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
747 static const bool kResetInDestructor = false;
748 template<class S, class M>
749 V8_INLINE static void Copy(const Persistent<S, M>& source,
750 NonCopyablePersistent* dest) {
751 Uncompilable<Object>();
752 }
753 // TODO(dcarney): come up with a good compile error here.
754 template<class O> V8_INLINE static void Uncompilable() {
755 TYPE_CHECK(O, Primitive);
756 }
757 };
758
759
760 /**
761 * Helper class traits to allow copying and assignment of Persistent.
762 * This will clone the contents of storage cell, but not any of the flags, etc.
763 */
764 template<class T>
765 struct CopyablePersistentTraits {
766 typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
767 static const bool kResetInDestructor = true;
768 template<class S, class M>
769 static V8_INLINE void Copy(const Persistent<S, M>& source,
770 CopyablePersistent* dest) {
771 // do nothing, just allow copy
772 }
773 };
774
775
776 /**
777 * A PersistentBase which allows copy and assignment.
778 *
779 * Copy, assignment and destructor behavior is controlled by the traits
780 * class M.
781 *
782 * Note: Persistent class hierarchy is subject to future changes.
783 */
784 template <class T, class M> class Persistent : public PersistentBase<T> {
785 public:
786 /**
787 * A Persistent with no storage cell.
788 */
789 V8_INLINE Persistent() : PersistentBase<T>(0) { }
790 /**
791 * Construct a Persistent from a Local.
792 * When the Local is non-empty, a new storage cell is created
793 * pointing to the same object, and no flags are set.
794 */
795 template <class S>
796 V8_INLINE Persistent(Isolate* isolate, Local<S> that)
797 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
798 TYPE_CHECK(T, S);
799 }
800 /**
801 * Construct a Persistent from a Persistent.
802 * When the Persistent is non-empty, a new storage cell is created
803 * pointing to the same object, and no flags are set.
804 */
805 template <class S, class M2>
806 V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
807 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
808 TYPE_CHECK(T, S);
809 }
810 /**
811 * The copy constructors and assignment operator create a Persistent
812 * exactly as the Persistent constructor, but the Copy function from the
813 * traits class is called, allowing the setting of flags based on the
814 * copied Persistent.
815 */
816 V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
817 Copy(that);
818 }
819 template <class S, class M2>
820 V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
821 Copy(that);
822 }
823 V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
824 Copy(that);
825 return *this;
826 }
827 template <class S, class M2>
828 V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
829 Copy(that);
830 return *this;
831 }
832 /**
833 * The destructor will dispose the Persistent based on the
834 * kResetInDestructor flags in the traits class. Since not calling dispose
835 * can result in a memory leak, it is recommended to always set this flag.
836 */
837 V8_INLINE ~Persistent() {
838 if (M::kResetInDestructor) this->Reset();
839 }
840
841 // TODO(dcarney): this is pretty useless, fix or remove
842 template <class S>
843 V8_INLINE static Persistent<T>& Cast(const Persistent<S>& that) { // NOLINT
844 #ifdef V8_ENABLE_CHECKS
845 // If we're going to perform the type check then we have to check
846 // that the handle isn't empty before doing the checked cast.
847 if (!that.IsEmpty()) T::Cast(*that);
848 #endif
849 return reinterpret_cast<Persistent<T>&>(const_cast<Persistent<S>&>(that));
850 }
851
852 // TODO(dcarney): this is pretty useless, fix or remove
853 template <class S>
854 V8_INLINE Persistent<S>& As() const { // NOLINT
855 return Persistent<S>::Cast(*this);
856 }
857
858 private:
859 friend class Isolate;
860 friend class Utils;
861 template<class F> friend class Local;
862 template<class F1, class F2> friend class Persistent;
863 template<class F> friend class ReturnValue;
864
865 explicit V8_INLINE Persistent(T* that) : PersistentBase<T>(that) {}
866 V8_INLINE T* operator*() const { return this->val_; }
867 template<class S, class M2>
868 V8_INLINE void Copy(const Persistent<S, M2>& that);
869 };
870
871
872 /**
873 * A PersistentBase which has move semantics.
874 *
875 * Note: Persistent class hierarchy is subject to future changes.
876 */
877 template <class T>
878 class Global : public PersistentBase<T> {
879 public:
880 /**
881 * A Global with no storage cell.
882 */
883 V8_INLINE Global() : PersistentBase<T>(nullptr) {}
884 /**
885 * Construct a Global from a Local.
886 * When the Local is non-empty, a new storage cell is created
887 * pointing to the same object, and no flags are set.
888 */
889 template <class S>
890 V8_INLINE Global(Isolate* isolate, Local<S> that)
891 : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
892 TYPE_CHECK(T, S);
893 }
894 /**
895 * Construct a Global from a PersistentBase.
896 * When the Persistent is non-empty, a new storage cell is created
897 * pointing to the same object, and no flags are set.
898 */
899 template <class S>
900 V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
901 : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
902 TYPE_CHECK(T, S);
903 }
904 /**
905 * Move constructor.
906 */
907 V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) { // NOLINT
908 other.val_ = nullptr;
909 }
910 V8_INLINE ~Global() { this->Reset(); }
911 /**
912 * Move via assignment.
913 */
914 template <class S>
915 V8_INLINE Global& operator=(Global<S>&& rhs) { // NOLINT
916 TYPE_CHECK(T, S);
917 if (this != &rhs) {
918 this->Reset();
919 this->val_ = rhs.val_;
920 rhs.val_ = nullptr;
921 }
922 return *this;
923 }
924 /**
925 * Pass allows returning uniques from functions, etc.
926 */
927 Global Pass() { return static_cast<Global&&>(*this); } // NOLINT
928
929 /*
930 * For compatibility with Chromium's base::Bind (base::Passed).
931 */
932 typedef void MoveOnlyTypeForCPP03;
933
934 Global(const Global&) = delete;
935 void operator=(const Global&) = delete;
936
937 private:
938 template <class F>
939 friend class ReturnValue;
940 V8_INLINE T* operator*() const { return this->val_; }
941 };
942
943
944 // UniquePersistent is an alias for Global for historical reason.
945 template <class T>
946 using UniquePersistent = Global<T>;
947
948
949 /**
950 * A stack-allocated class that governs a number of local handles.
951 * After a handle scope has been created, all local handles will be
952 * allocated within that handle scope until either the handle scope is
953 * deleted or another handle scope is created. If there is already a
954 * handle scope and a new one is created, all allocations will take
955 * place in the new handle scope until it is deleted. After that,
956 * new handles will again be allocated in the original handle scope.
957 *
958 * After the handle scope of a local handle has been deleted the
959 * garbage collector will no longer track the object stored in the
960 * handle and may deallocate it. The behavior of accessing a handle
961 * for which the handle scope has been deleted is undefined.
962 */
963 class V8_EXPORT HandleScope {
964 public:
965 explicit HandleScope(Isolate* isolate);
966
967 ~HandleScope();
968
969 /**
970 * Counts the number of allocated handles.
971 */
972 static int NumberOfHandles(Isolate* isolate);
973
974 V8_INLINE Isolate* GetIsolate() const {
975 return reinterpret_cast<Isolate*>(isolate_);
976 }
977
978 HandleScope(const HandleScope&) = delete;
979 void operator=(const HandleScope&) = delete;
980
981 protected:
982 V8_INLINE HandleScope() {}
983
984 void Initialize(Isolate* isolate);
985
986 static internal::Object** CreateHandle(internal::Isolate* isolate,
987 internal::Object* value);
988
989 private:
990 // Declaring operator new and delete as deleted is not spec compliant.
991 // Therefore declare them private instead to disable dynamic alloc
992 void* operator new(size_t size);
993 void* operator new[](size_t size);
994 void operator delete(void*, size_t);
995 void operator delete[](void*, size_t);
996
997 // Uses heap_object to obtain the current Isolate.
998 static internal::Object** CreateHandle(
999 internal::NeverReadOnlySpaceObject* heap_object, internal::Object* value);
1000
1001 internal::Isolate* isolate_;
1002 internal::Object** prev_next_;
1003 internal::Object** prev_limit_;
1004
1005 // Local::New uses CreateHandle with an Isolate* parameter.
1006 template<class F> friend class Local;
1007
1008 // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
1009 // a HeapObject* in their shortcuts.
1010 friend class Object;
1011 friend class Context;
1012 };
1013
1014
1015 /**
1016 * A HandleScope which first allocates a handle in the current scope
1017 * which will be later filled with the escape value.
1018 */
1019 class V8_EXPORT EscapableHandleScope : public HandleScope {
1020 public:
1021 explicit EscapableHandleScope(Isolate* isolate);
1022 V8_INLINE ~EscapableHandleScope() {}
1023
1024 /**
1025 * Pushes the value into the previous scope and returns a handle to it.
1026 * Cannot be called twice.
1027 */
1028 template <class T>
1029 V8_INLINE Local<T> Escape(Local<T> value) {
1030 internal::Object** slot =
1031 Escape(reinterpret_cast<internal::Object**>(*value));
1032 return Local<T>(reinterpret_cast<T*>(slot));
1033 }
1034
1035 template <class T>
1036 V8_INLINE MaybeLocal<T> EscapeMaybe(MaybeLocal<T> value) {
1037 return Escape(value.FromMaybe(Local<T>()));
1038 }
1039
1040 EscapableHandleScope(const EscapableHandleScope&) = delete;
1041 void operator=(const EscapableHandleScope&) = delete;
1042
1043 private:
1044 // Declaring operator new and delete as deleted is not spec compliant.
1045 // Therefore declare them private instead to disable dynamic alloc
1046 void* operator new(size_t size);
1047 void* operator new[](size_t size);
1048 void operator delete(void*, size_t);
1049 void operator delete[](void*, size_t);
1050
1051 internal::Object** Escape(internal::Object** escape_value);
1052 internal::Object** escape_slot_;
1053 };
1054
1055 /**
1056 * A SealHandleScope acts like a handle scope in which no handle allocations
1057 * are allowed. It can be useful for debugging handle leaks.
1058 * Handles can be allocated within inner normal HandleScopes.
1059 */
1060 class V8_EXPORT SealHandleScope {
1061 public:
1062 explicit SealHandleScope(Isolate* isolate);
1063 ~SealHandleScope();
1064
1065 SealHandleScope(const SealHandleScope&) = delete;
1066 void operator=(const SealHandleScope&) = delete;
1067
1068 private:
1069 // Declaring operator new and delete as deleted is not spec compliant.
1070 // Therefore declare them private instead to disable dynamic alloc
1071 void* operator new(size_t size);
1072 void* operator new[](size_t size);
1073 void operator delete(void*, size_t);
1074 void operator delete[](void*, size_t);
1075
1076 internal::Isolate* const isolate_;
1077 internal::Object** prev_limit_;
1078 int prev_sealed_level_;
1079 };
1080
1081
1082 // --- Special objects ---
1083
1084
1085 /**
1086 * The superclass of values and API object templates.
1087 */
1088 class V8_EXPORT Data {
1089 private:
1090 Data();
1091 };
1092
1093 /**
1094 * A container type that holds relevant metadata for module loading.
1095 *
1096 * This is passed back to the embedder as part of
1097 * HostImportModuleDynamicallyCallback for module loading.
1098 */
1099 class V8_EXPORT ScriptOrModule {
1100 public:
1101 /**
1102 * The name that was passed by the embedder as ResourceName to the
1103 * ScriptOrigin. This can be either a v8::String or v8::Undefined.
1104 */
1105 Local<Value> GetResourceName();
1106
1107 /**
1108 * The options that were passed by the embedder as HostDefinedOptions to
1109 * the ScriptOrigin.
1110 */
1111 Local<PrimitiveArray> GetHostDefinedOptions();
1112 };
1113
1114 /**
1115 * An array to hold Primitive values. This is used by the embedder to
1116 * pass host defined options to the ScriptOptions during compilation.
1117 *
1118 * This is passed back to the embedder as part of
1119 * HostImportModuleDynamicallyCallback for module loading.
1120 *
1121 */
1122 class V8_EXPORT PrimitiveArray {
1123 public:
1124 static Local<PrimitiveArray> New(Isolate* isolate, int length);
1125 int Length() const;
1126 void Set(Isolate* isolate, int index, Local<Primitive> item);
1127 Local<Primitive> Get(Isolate* isolate, int index);
1128
1129 V8_DEPRECATED("Use Isolate version",
1130 void Set(int index, Local<Primitive> item));
1131 V8_DEPRECATED("Use Isolate version", Local<Primitive> Get(int index));
1132 };
1133
1134 /**
1135 * The optional attributes of ScriptOrigin.
1136 */
1137 class ScriptOriginOptions {
1138 public:
1139 V8_INLINE ScriptOriginOptions(bool is_shared_cross_origin = false,
1140 bool is_opaque = false, bool is_wasm = false,
1141 bool is_module = false)
1142 : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1143 (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1144 (is_module ? kIsModule : 0)) {}
1145 V8_INLINE ScriptOriginOptions(int flags)
1146 : flags_(flags &
1147 (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1148
1149 bool IsSharedCrossOrigin() const {
1150 return (flags_ & kIsSharedCrossOrigin) != 0;
1151 }
1152 bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1153 bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1154 bool IsModule() const { return (flags_ & kIsModule) != 0; }
1155
1156 int Flags() const { return flags_; }
1157
1158 private:
1159 enum {
1160 kIsSharedCrossOrigin = 1,
1161 kIsOpaque = 1 << 1,
1162 kIsWasm = 1 << 2,
1163 kIsModule = 1 << 3
1164 };
1165 const int flags_;
1166 };
1167
1168 /**
1169 * The origin, within a file, of a script.
1170 */
1171 class ScriptOrigin {
1172 public:
1173 V8_INLINE ScriptOrigin(
1174 Local<Value> resource_name,
1175 Local<Integer> resource_line_offset = Local<Integer>(),
1176 Local<Integer> resource_column_offset = Local<Integer>(),
1177 Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1178 Local<Integer> script_id = Local<Integer>(),
1179 Local<Value> source_map_url = Local<Value>(),
1180 Local<Boolean> resource_is_opaque = Local<Boolean>(),
1181 Local<Boolean> is_wasm = Local<Boolean>(),
1182 Local<Boolean> is_module = Local<Boolean>(),
1183 Local<PrimitiveArray> host_defined_options = Local<PrimitiveArray>());
1184
1185 V8_INLINE Local<Value> ResourceName() const;
1186 V8_INLINE Local<Integer> ResourceLineOffset() const;
1187 V8_INLINE Local<Integer> ResourceColumnOffset() const;
1188 V8_INLINE Local<Integer> ScriptID() const;
1189 V8_INLINE Local<Value> SourceMapUrl() const;
1190 V8_INLINE Local<PrimitiveArray> HostDefinedOptions() const;
1191 V8_INLINE ScriptOriginOptions Options() const { return options_; }
1192
1193 private:
1194 Local<Value> resource_name_;
1195 Local<Integer> resource_line_offset_;
1196 Local<Integer> resource_column_offset_;
1197 ScriptOriginOptions options_;
1198 Local<Integer> script_id_;
1199 Local<Value> source_map_url_;
1200 Local<PrimitiveArray> host_defined_options_;
1201 };
1202
1203 /**
1204 * A compiled JavaScript script, not yet tied to a Context.
1205 */
1206 class V8_EXPORT UnboundScript {
1207 public:
1208 /**
1209 * Binds the script to the currently entered context.
1210 */
1211 Local<Script> BindToCurrentContext();
1212
1213 int GetId();
1214 Local<Value> GetScriptName();
1215
1216 /**
1217 * Data read from magic sourceURL comments.
1218 */
1219 Local<Value> GetSourceURL();
1220 /**
1221 * Data read from magic sourceMappingURL comments.
1222 */
1223 Local<Value> GetSourceMappingURL();
1224
1225 /**
1226 * Returns zero based line number of the code_pos location in the script.
1227 * -1 will be returned if no information available.
1228 */
1229 int GetLineNumber(int code_pos);
1230
1231 static const int kNoScriptId = 0;
1232 };
1233
1234 /**
1235 * A compiled JavaScript module, not yet tied to a Context.
1236 */
1237 class V8_EXPORT UnboundModuleScript {
1238 // Only used as a container for code caching.
1239 };
1240
1241 /**
1242 * A location in JavaScript source.
1243 */
1244 class V8_EXPORT Location {
1245 public:
1246 int GetLineNumber() { return line_number_; }
1247 int GetColumnNumber() { return column_number_; }
1248
1249 Location(int line_number, int column_number)
1250 : line_number_(line_number), column_number_(column_number) {}
1251
1252 private:
1253 int line_number_;
1254 int column_number_;
1255 };
1256
1257 /**
1258 * A compiled JavaScript module.
1259 */
1260 class V8_EXPORT Module {
1261 public:
1262 /**
1263 * The different states a module can be in.
1264 *
1265 * This corresponds to the states used in ECMAScript except that "evaluated"
1266 * is split into kEvaluated and kErrored, indicating success and failure,
1267 * respectively.
1268 */
1269 enum Status {
1270 kUninstantiated,
1271 kInstantiating,
1272 kInstantiated,
1273 kEvaluating,
1274 kEvaluated,
1275 kErrored
1276 };
1277
1278 /**
1279 * Returns the module's current status.
1280 */
1281 Status GetStatus() const;
1282
1283 /**
1284 * For a module in kErrored status, this returns the corresponding exception.
1285 */
1286 Local<Value> GetException() const;
1287
1288 /**
1289 * Returns the number of modules requested by this module.
1290 */
1291 int GetModuleRequestsLength() const;
1292
1293 /**
1294 * Returns the ith module specifier in this module.
1295 * i must be < GetModuleRequestsLength() and >= 0.
1296 */
1297 Local<String> GetModuleRequest(int i) const;
1298
1299 /**
1300 * Returns the source location (line number and column number) of the ith
1301 * module specifier's first occurrence in this module.
1302 */
1303 Location GetModuleRequestLocation(int i) const;
1304
1305 /**
1306 * Returns the identity hash for this object.
1307 */
1308 int GetIdentityHash() const;
1309
1310 typedef MaybeLocal<Module> (*ResolveCallback)(Local<Context> context,
1311 Local<String> specifier,
1312 Local<Module> referrer);
1313
1314 /**
1315 * Instantiates the module and its dependencies.
1316 *
1317 * Returns an empty Maybe<bool> if an exception occurred during
1318 * instantiation. (In the case where the callback throws an exception, that
1319 * exception is propagated.)
1320 */
1321 V8_WARN_UNUSED_RESULT Maybe<bool> InstantiateModule(Local<Context> context,
1322 ResolveCallback callback);
1323
1324 /**
1325 * Evaluates the module and its dependencies.
1326 *
1327 * If status is kInstantiated, run the module's code. On success, set status
1328 * to kEvaluated and return the completion value; on failure, set status to
1329 * kErrored and propagate the thrown exception (which is then also available
1330 * via |GetException|).
1331 */
1332 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Evaluate(Local<Context> context);
1333
1334 /**
1335 * Returns the namespace object of this module.
1336 *
1337 * The module's status must be at least kInstantiated.
1338 */
1339 Local<Value> GetModuleNamespace();
1340
1341 /**
1342 * Returns the corresponding context-unbound module script.
1343 *
1344 * The module must be unevaluated, i.e. its status must not be kEvaluating,
1345 * kEvaluated or kErrored.
1346 */
1347 Local<UnboundModuleScript> GetUnboundModuleScript();
1348 };
1349
1350 /**
1351 * A compiled JavaScript script, tied to a Context which was active when the
1352 * script was compiled.
1353 */
1354 class V8_EXPORT Script {
1355 public:
1356 /**
1357 * A shorthand for ScriptCompiler::Compile().
1358 */
1359 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1360 Local<Context> context, Local<String> source,
1361 ScriptOrigin* origin = nullptr);
1362
1363 /**
1364 * Runs the script returning the resulting value. It will be run in the
1365 * context in which it was created (ScriptCompiler::CompileBound or
1366 * UnboundScript::BindToCurrentContext()).
1367 */
1368 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Run(Local<Context> context);
1369
1370 /**
1371 * Returns the corresponding context-unbound script.
1372 */
1373 Local<UnboundScript> GetUnboundScript();
1374 };
1375
1376
1377 /**
1378 * For compiling scripts.
1379 */
1380 class V8_EXPORT ScriptCompiler {
1381 public:
1382 /**
1383 * Compilation data that the embedder can cache and pass back to speed up
1384 * future compilations. The data is produced if the CompilerOptions passed to
1385 * the compilation functions in ScriptCompiler contains produce_data_to_cache
1386 * = true. The data to cache can then can be retrieved from
1387 * UnboundScript.
1388 */
1389 struct V8_EXPORT CachedData {
1390 enum BufferPolicy {
1391 BufferNotOwned,
1392 BufferOwned
1393 };
1394
1395 CachedData()
1396 : data(NULL),
1397 length(0),
1398 rejected(false),
1399 buffer_policy(BufferNotOwned) {}
1400
1401 // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1402 // data and guarantees that it stays alive until the CachedData object is
1403 // destroyed. If the policy is BufferOwned, the given data will be deleted
1404 // (with delete[]) when the CachedData object is destroyed.
1405 CachedData(const uint8_t* data, int length,
1406 BufferPolicy buffer_policy = BufferNotOwned);
1407 ~CachedData();
1408 // TODO(marja): Async compilation; add constructors which take a callback
1409 // which will be called when V8 no longer needs the data.
1410 const uint8_t* data;
1411 int length;
1412 bool rejected;
1413 BufferPolicy buffer_policy;
1414
1415 // Prevent copying.
1416 CachedData(const CachedData&) = delete;
1417 CachedData& operator=(const CachedData&) = delete;
1418 };
1419
1420 /**
1421 * Source code which can be then compiled to a UnboundScript or Script.
1422 */
1423 class Source {
1424 public:
1425 // Source takes ownership of CachedData.
1426 V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1427 CachedData* cached_data = NULL);
1428 V8_INLINE Source(Local<String> source_string,
1429 CachedData* cached_data = NULL);
1430 V8_INLINE ~Source();
1431
1432 // Ownership of the CachedData or its buffers is *not* transferred to the
1433 // caller. The CachedData object is alive as long as the Source object is
1434 // alive.
1435 V8_INLINE const CachedData* GetCachedData() const;
1436
1437 V8_INLINE const ScriptOriginOptions& GetResourceOptions() const;
1438
1439 // Prevent copying.
1440 Source(const Source&) = delete;
1441 Source& operator=(const Source&) = delete;
1442
1443 private:
1444 friend class ScriptCompiler;
1445
1446 Local<String> source_string;
1447
1448 // Origin information
1449 Local<Value> resource_name;
1450 Local<Integer> resource_line_offset;
1451 Local<Integer> resource_column_offset;
1452 ScriptOriginOptions resource_options;
1453 Local<Value> source_map_url;
1454 Local<PrimitiveArray> host_defined_options;
1455
1456 // Cached data from previous compilation (if a kConsume*Cache flag is
1457 // set), or hold newly generated cache data (kProduce*Cache flags) are
1458 // set when calling a compile method.
1459 CachedData* cached_data;
1460 };
1461
1462 /**
1463 * For streaming incomplete script data to V8. The embedder should implement a
1464 * subclass of this class.
1465 */
1466 class V8_EXPORT ExternalSourceStream {
1467 public:
1468 virtual ~ExternalSourceStream() {}
1469
1470 /**
1471 * V8 calls this to request the next chunk of data from the embedder. This
1472 * function will be called on a background thread, so it's OK to block and
1473 * wait for the data, if the embedder doesn't have data yet. Returns the
1474 * length of the data returned. When the data ends, GetMoreData should
1475 * return 0. Caller takes ownership of the data.
1476 *
1477 * When streaming UTF-8 data, V8 handles multi-byte characters split between
1478 * two data chunks, but doesn't handle multi-byte characters split between
1479 * more than two data chunks. The embedder can avoid this problem by always
1480 * returning at least 2 bytes of data.
1481 *
1482 * When streaming UTF-16 data, V8 does not handle characters split between
1483 * two data chunks. The embedder has to make sure that chunks have an even
1484 * length.
1485 *
1486 * If the embedder wants to cancel the streaming, they should make the next
1487 * GetMoreData call return 0. V8 will interpret it as end of data (and most
1488 * probably, parsing will fail). The streaming task will return as soon as
1489 * V8 has parsed the data it received so far.
1490 */
1491 virtual size_t GetMoreData(const uint8_t** src) = 0;
1492
1493 /**
1494 * V8 calls this method to set a 'bookmark' at the current position in
1495 * the source stream, for the purpose of (maybe) later calling
1496 * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1497 * calls to GetMoreData should return the same data as they did when
1498 * SetBookmark was called earlier.
1499 *
1500 * The embedder may return 'false' to indicate it cannot provide this
1501 * functionality.
1502 */
1503 virtual bool SetBookmark();
1504
1505 /**
1506 * V8 calls this to return to a previously set bookmark.
1507 */
1508 virtual void ResetToBookmark();
1509 };
1510
1511
1512 /**
1513 * Source code which can be streamed into V8 in pieces. It will be parsed
1514 * while streaming. It can be compiled after the streaming is complete.
1515 * StreamedSource must be kept alive while the streaming task is ran (see
1516 * ScriptStreamingTask below).
1517 */
1518 class V8_EXPORT StreamedSource {
1519 public:
1520 enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
1521
1522 StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1523 ~StreamedSource();
1524
1525 // Ownership of the CachedData or its buffers is *not* transferred to the
1526 // caller. The CachedData object is alive as long as the StreamedSource
1527 // object is alive.
1528 const CachedData* GetCachedData() const;
1529
1530 internal::ScriptStreamingData* impl() const { return impl_; }
1531
1532 // Prevent copying.
1533 StreamedSource(const StreamedSource&) = delete;
1534 StreamedSource& operator=(const StreamedSource&) = delete;
1535
1536 private:
1537 internal::ScriptStreamingData* impl_;
1538 };
1539
1540 /**
1541 * A streaming task which the embedder must run on a background thread to
1542 * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1543 */
1544 class ScriptStreamingTask {
1545 public:
1546 virtual ~ScriptStreamingTask() {}
1547 virtual void Run() = 0;
1548 };
1549
1550 enum CompileOptions {
1551 kNoCompileOptions = 0,
1552 kProduceParserCache,
1553 kConsumeParserCache,
1554 kProduceCodeCache,
1555 kProduceFullCodeCache,
1556 kConsumeCodeCache,
1557 kEagerCompile
1558 };
1559
1560 /**
1561 * The reason for which we are not requesting or providing a code cache.
1562 */
1563 enum NoCacheReason {
1564 kNoCacheNoReason = 0,
1565 kNoCacheBecauseCachingDisabled,
1566 kNoCacheBecauseNoResource,
1567 kNoCacheBecauseInlineScript,
1568 kNoCacheBecauseModule,
1569 kNoCacheBecauseStreamingSource,
1570 kNoCacheBecauseInspector,
1571 kNoCacheBecauseScriptTooSmall,
1572 kNoCacheBecauseCacheTooCold,
1573 kNoCacheBecauseV8Extension,
1574 kNoCacheBecauseExtensionModule,
1575 kNoCacheBecausePacScript,
1576 kNoCacheBecauseInDocumentWrite,
1577 kNoCacheBecauseResourceWithNoCacheHandler,
1578 kNoCacheBecauseDeferredProduceCodeCache
1579 };
1580
1581 /**
1582 * Compiles the specified script (context-independent).
1583 * Cached data as part of the source object can be optionally produced to be
1584 * consumed later to speed up compilation of identical source scripts.
1585 *
1586 * Note that when producing cached data, the source must point to NULL for
1587 * cached data. When consuming cached data, the cached data must have been
1588 * produced by the same version of V8.
1589 *
1590 * \param source Script source code.
1591 * \return Compiled script object (context independent; for running it must be
1592 * bound to a context).
1593 */
1594 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundScript(
1595 Isolate* isolate, Source* source,
1596 CompileOptions options = kNoCompileOptions,
1597 NoCacheReason no_cache_reason = kNoCacheNoReason);
1598
1599 /**
1600 * Compiles the specified script (bound to current context).
1601 *
1602 * \param source Script source code.
1603 * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1604 * using pre_data speeds compilation if it's done multiple times.
1605 * Owned by caller, no references are kept when this function returns.
1606 * \return Compiled script object, bound to the context that was active
1607 * when this function was called. When run it will always use this
1608 * context.
1609 */
1610 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1611 Local<Context> context, Source* source,
1612 CompileOptions options = kNoCompileOptions,
1613 NoCacheReason no_cache_reason = kNoCacheNoReason);
1614
1615 /**
1616 * Returns a task which streams script data into V8, or NULL if the script
1617 * cannot be streamed. The user is responsible for running the task on a
1618 * background thread and deleting it. When ran, the task starts parsing the
1619 * script, and it will request data from the StreamedSource as needed. When
1620 * ScriptStreamingTask::Run exits, all data has been streamed and the script
1621 * can be compiled (see Compile below).
1622 *
1623 * This API allows to start the streaming with as little data as possible, and
1624 * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1625 */
1626 static ScriptStreamingTask* StartStreamingScript(
1627 Isolate* isolate, StreamedSource* source,
1628 CompileOptions options = kNoCompileOptions);
1629
1630 /**
1631 * Compiles a streamed script (bound to current context).
1632 *
1633 * This can only be called after the streaming has finished
1634 * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1635 * during streaming, so the embedder needs to pass the full source here.
1636 */
1637 static V8_WARN_UNUSED_RESULT MaybeLocal<Script> Compile(
1638 Local<Context> context, StreamedSource* source,
1639 Local<String> full_source_string, const ScriptOrigin& origin);
1640
1641 /**
1642 * Return a version tag for CachedData for the current V8 version & flags.
1643 *
1644 * This value is meant only for determining whether a previously generated
1645 * CachedData instance is still valid; the tag has no other meaing.
1646 *
1647 * Background: The data carried by CachedData may depend on the exact
1648 * V8 version number or current compiler flags. This means that when
1649 * persisting CachedData, the embedder must take care to not pass in
1650 * data from another V8 version, or the same version with different
1651 * features enabled.
1652 *
1653 * The easiest way to do so is to clear the embedder's cache on any
1654 * such change.
1655 *
1656 * Alternatively, this tag can be stored alongside the cached data and
1657 * compared when it is being used.
1658 */
1659 static uint32_t CachedDataVersionTag();
1660
1661 /**
1662 * Compile an ES module, returning a Module that encapsulates
1663 * the compiled code.
1664 *
1665 * Corresponds to the ParseModule abstract operation in the
1666 * ECMAScript specification.
1667 */
1668 static V8_WARN_UNUSED_RESULT MaybeLocal<Module> CompileModule(
1669 Isolate* isolate, Source* source,
1670 CompileOptions options = kNoCompileOptions,
1671 NoCacheReason no_cache_reason = kNoCacheNoReason);
1672
1673 /**
1674 * Compile a function for a given context. This is equivalent to running
1675 *
1676 * with (obj) {
1677 * return function(args) { ... }
1678 * }
1679 *
1680 * It is possible to specify multiple context extensions (obj in the above
1681 * example).
1682 */
1683 static V8_WARN_UNUSED_RESULT MaybeLocal<Function> CompileFunctionInContext(
1684 Local<Context> context, Source* source, size_t arguments_count,
1685 Local<String> arguments[], size_t context_extension_count,
1686 Local<Object> context_extensions[],
1687 CompileOptions options = kNoCompileOptions,
1688 NoCacheReason no_cache_reason = kNoCacheNoReason);
1689
1690 /**
1691 * Creates and returns code cache for the specified unbound_script.
1692 * This will return nullptr if the script cannot be serialized. The
1693 * CachedData returned by this function should be owned by the caller.
1694 */
1695 static CachedData* CreateCodeCache(Local<UnboundScript> unbound_script);
1696
1697 /**
1698 * Creates and returns code cache for the specified unbound_module_script.
1699 * This will return nullptr if the script cannot be serialized. The
1700 * CachedData returned by this function should be owned by the caller.
1701 */
1702 static CachedData* CreateCodeCache(
1703 Local<UnboundModuleScript> unbound_module_script);
1704
1705 /**
1706 * Creates and returns code cache for the specified function that was
1707 * previously produced by CompileFunctionInContext.
1708 * This will return nullptr if the script cannot be serialized. The
1709 * CachedData returned by this function should be owned by the caller.
1710 */
1711 static CachedData* CreateCodeCacheForFunction(Local<Function> function);
1712
1713 private:
1714 static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1715 Isolate* isolate, Source* source, CompileOptions options,
1716 NoCacheReason no_cache_reason);
1717 };
1718
1719
1720 /**
1721 * An error message.
1722 */
1723 class V8_EXPORT Message {
1724 public:
1725 Local<String> Get() const;
1726
1727 /**
1728 * Return the isolate to which the Message belongs.
1729 */
1730 Isolate* GetIsolate() const;
1731
1732 V8_WARN_UNUSED_RESULT MaybeLocal<String> GetSourceLine(
1733 Local<Context> context) const;
1734
1735 /**
1736 * Returns the origin for the script from where the function causing the
1737 * error originates.
1738 */
1739 ScriptOrigin GetScriptOrigin() const;
1740
1741 /**
1742 * Returns the resource name for the script from where the function causing
1743 * the error originates.
1744 */
1745 Local<Value> GetScriptResourceName() const;
1746
1747 /**
1748 * Exception stack trace. By default stack traces are not captured for
1749 * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1750 * to change this option.
1751 */
1752 Local<StackTrace> GetStackTrace() const;
1753
1754 /**
1755 * Returns the number, 1-based, of the line where the error occurred.
1756 */
1757 V8_WARN_UNUSED_RESULT Maybe<int> GetLineNumber(Local<Context> context) const;
1758
1759 /**
1760 * Returns the index within the script of the first character where
1761 * the error occurred.
1762 */
1763 int GetStartPosition() const;
1764
1765 /**
1766 * Returns the index within the script of the last character where
1767 * the error occurred.
1768 */
1769 int GetEndPosition() const;
1770
1771 /**
1772 * Returns the error level of the message.
1773 */
1774 int ErrorLevel() const;
1775
1776 /**
1777 * Returns the index within the line of the first character where
1778 * the error occurred.
1779 */
1780 int GetStartColumn() const;
1781 V8_WARN_UNUSED_RESULT Maybe<int> GetStartColumn(Local<Context> context) const;
1782
1783 /**
1784 * Returns the index within the line of the last character where
1785 * the error occurred.
1786 */
1787 int GetEndColumn() const;
1788 V8_WARN_UNUSED_RESULT Maybe<int> GetEndColumn(Local<Context> context) const;
1789
1790 /**
1791 * Passes on the value set by the embedder when it fed the script from which
1792 * this Message was generated to V8.
1793 */
1794 bool IsSharedCrossOrigin() const;
1795 bool IsOpaque() const;
1796
1797 // TODO(1245381): Print to a string instead of on a FILE.
1798 static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1799
1800 static const int kNoLineNumberInfo = 0;
1801 static const int kNoColumnInfo = 0;
1802 static const int kNoScriptIdInfo = 0;
1803 };
1804
1805
1806 /**
1807 * Representation of a JavaScript stack trace. The information collected is a
1808 * snapshot of the execution stack and the information remains valid after
1809 * execution continues.
1810 */
1811 class V8_EXPORT StackTrace {
1812 public:
1813 /**
1814 * Flags that determine what information is placed captured for each
1815 * StackFrame when grabbing the current stack trace.
1816 * Note: these options are deprecated and we always collect all available
1817 * information (kDetailed).
1818 */
1819 enum StackTraceOptions {
1820 kLineNumber = 1,
1821 kColumnOffset = 1 << 1 | kLineNumber,
1822 kScriptName = 1 << 2,
1823 kFunctionName = 1 << 3,
1824 kIsEval = 1 << 4,
1825 kIsConstructor = 1 << 5,
1826 kScriptNameOrSourceURL = 1 << 6,
1827 kScriptId = 1 << 7,
1828 kExposeFramesAcrossSecurityOrigins = 1 << 8,
1829 kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
1830 kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
1831 };
1832
1833 /**
1834 * Returns a StackFrame at a particular index.
1835 */
1836 V8_DEPRECATED("Use Isolate version",
1837 Local<StackFrame> GetFrame(uint32_t index) const);
1838 Local<StackFrame> GetFrame(Isolate* isolate, uint32_t index) const;
1839
1840 /**
1841 * Returns the number of StackFrames.
1842 */
1843 int GetFrameCount() const;
1844
1845 /**
1846 * Grab a snapshot of the current JavaScript execution stack.
1847 *
1848 * \param frame_limit The maximum number of stack frames we want to capture.
1849 * \param options Enumerates the set of things we will capture for each
1850 * StackFrame.
1851 */
1852 static Local<StackTrace> CurrentStackTrace(
1853 Isolate* isolate, int frame_limit, StackTraceOptions options = kDetailed);
1854 };
1855
1856
1857 /**
1858 * A single JavaScript stack frame.
1859 */
1860 class V8_EXPORT StackFrame {
1861 public:
1862 /**
1863 * Returns the number, 1-based, of the line for the associate function call.
1864 * This method will return Message::kNoLineNumberInfo if it is unable to
1865 * retrieve the line number, or if kLineNumber was not passed as an option
1866 * when capturing the StackTrace.
1867 */
1868 int GetLineNumber() const;
1869
1870 /**
1871 * Returns the 1-based column offset on the line for the associated function
1872 * call.
1873 * This method will return Message::kNoColumnInfo if it is unable to retrieve
1874 * the column number, or if kColumnOffset was not passed as an option when
1875 * capturing the StackTrace.
1876 */
1877 int GetColumn() const;
1878
1879 /**
1880 * Returns the id of the script for the function for this StackFrame.
1881 * This method will return Message::kNoScriptIdInfo if it is unable to
1882 * retrieve the script id, or if kScriptId was not passed as an option when
1883 * capturing the StackTrace.
1884 */
1885 int GetScriptId() const;
1886
1887 /**
1888 * Returns the name of the resource that contains the script for the
1889 * function for this StackFrame.
1890 */
1891 Local<String> GetScriptName() const;
1892
1893 /**
1894 * Returns the name of the resource that contains the script for the
1895 * function for this StackFrame or sourceURL value if the script name
1896 * is undefined and its source ends with //# sourceURL=... string or
1897 * deprecated //@ sourceURL=... string.
1898 */
1899 Local<String> GetScriptNameOrSourceURL() const;
1900
1901 /**
1902 * Returns the name of the function associated with this stack frame.
1903 */
1904 Local<String> GetFunctionName() const;
1905
1906 /**
1907 * Returns whether or not the associated function is compiled via a call to
1908 * eval().
1909 */
1910 bool IsEval() const;
1911
1912 /**
1913 * Returns whether or not the associated function is called as a
1914 * constructor via "new".
1915 */
1916 bool IsConstructor() const;
1917
1918 /**
1919 * Returns whether or not the associated functions is defined in wasm.
1920 */
1921 bool IsWasm() const;
1922 };
1923
1924
1925 // A StateTag represents a possible state of the VM.
1926 enum StateTag {
1927 JS,
1928 GC,
1929 PARSER,
1930 BYTECODE_COMPILER,
1931 COMPILER,
1932 OTHER,
1933 EXTERNAL,
1934 IDLE
1935 };
1936
1937 // A RegisterState represents the current state of registers used
1938 // by the sampling profiler API.
1939 struct RegisterState {
1940 RegisterState() : pc(nullptr), sp(nullptr), fp(nullptr) {}
1941 void* pc; // Instruction pointer.
1942 void* sp; // Stack pointer.
1943 void* fp; // Frame pointer.
1944 };
1945
1946 // The output structure filled up by GetStackSample API function.
1947 struct SampleInfo {
1948 size_t frames_count; // Number of frames collected.
1949 StateTag vm_state; // Current VM state.
1950 void* external_callback_entry; // External callback address if VM is
1951 // executing an external callback.
1952 };
1953
1954 /**
1955 * A JSON Parser and Stringifier.
1956 */
1957 class V8_EXPORT JSON {
1958 public:
1959 /**
1960 * Tries to parse the string |json_string| and returns it as value if
1961 * successful.
1962 *
1963 * \param json_string The string to parse.
1964 * \return The corresponding value if successfully parsed.
1965 */
1966 static V8_DEPRECATE_SOON("Use the maybe version taking context",
1967 MaybeLocal<Value> Parse(Isolate* isolate,
1968 Local<String> json_string));
1969 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> Parse(
1970 Local<Context> context, Local<String> json_string);
1971
1972 /**
1973 * Tries to stringify the JSON-serializable object |json_object| and returns
1974 * it as string if successful.
1975 *
1976 * \param json_object The JSON-serializable object to stringify.
1977 * \return The corresponding string if successfully stringified.
1978 */
1979 static V8_WARN_UNUSED_RESULT MaybeLocal<String> Stringify(
1980 Local<Context> context, Local<Value> json_object,
1981 Local<String> gap = Local<String>());
1982 };
1983
1984 /**
1985 * Value serialization compatible with the HTML structured clone algorithm.
1986 * The format is backward-compatible (i.e. safe to store to disk).
1987 *
1988 * WARNING: This API is under development, and changes (including incompatible
1989 * changes to the API or wire format) may occur without notice until this
1990 * warning is removed.
1991 */
1992 class V8_EXPORT ValueSerializer {
1993 public:
1994 class V8_EXPORT Delegate {
1995 public:
1996 virtual ~Delegate() {}
1997
1998 /**
1999 * Handles the case where a DataCloneError would be thrown in the structured
2000 * clone spec. Other V8 embedders may throw some other appropriate exception
2001 * type.
2002 */
2003 virtual void ThrowDataCloneError(Local<String> message) = 0;
2004
2005 /**
2006 * The embedder overrides this method to write some kind of host object, if
2007 * possible. If not, a suitable exception should be thrown and
2008 * Nothing<bool>() returned.
2009 */
2010 virtual Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object);
2011
2012 /**
2013 * Called when the ValueSerializer is going to serialize a
2014 * SharedArrayBuffer object. The embedder must return an ID for the
2015 * object, using the same ID if this SharedArrayBuffer has already been
2016 * serialized in this buffer. When deserializing, this ID will be passed to
2017 * ValueDeserializer::GetSharedArrayBufferFromId as |clone_id|.
2018 *
2019 * If the object cannot be serialized, an
2020 * exception should be thrown and Nothing<uint32_t>() returned.
2021 */
2022 virtual Maybe<uint32_t> GetSharedArrayBufferId(
2023 Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer);
2024
2025 virtual Maybe<uint32_t> GetWasmModuleTransferId(
2026 Isolate* isolate, Local<WasmCompiledModule> module);
2027 /**
2028 * Allocates memory for the buffer of at least the size provided. The actual
2029 * size (which may be greater or equal) is written to |actual_size|. If no
2030 * buffer has been allocated yet, nullptr will be provided.
2031 *
2032 * If the memory cannot be allocated, nullptr should be returned.
2033 * |actual_size| will be ignored. It is assumed that |old_buffer| is still
2034 * valid in this case and has not been modified.
2035 *
2036 * The default implementation uses the stdlib's `realloc()` function.
2037 */
2038 virtual void* ReallocateBufferMemory(void* old_buffer, size_t size,
2039 size_t* actual_size);
2040
2041 /**
2042 * Frees a buffer allocated with |ReallocateBufferMemory|.
2043 *
2044 * The default implementation uses the stdlib's `free()` function.
2045 */
2046 virtual void FreeBufferMemory(void* buffer);
2047 };
2048
2049 explicit ValueSerializer(Isolate* isolate);
2050 ValueSerializer(Isolate* isolate, Delegate* delegate);
2051 ~ValueSerializer();
2052
2053 /**
2054 * Writes out a header, which includes the format version.
2055 */
2056 void WriteHeader();
2057
2058 /**
2059 * Serializes a JavaScript value into the buffer.
2060 */
2061 V8_WARN_UNUSED_RESULT Maybe<bool> WriteValue(Local<Context> context,
2062 Local<Value> value);
2063
2064 /**
2065 * Returns the stored data. This serializer should not be used once the buffer
2066 * is released. The contents are undefined if a previous write has failed.
2067 */
2068 V8_DEPRECATE_SOON("Use Release()", std::vector<uint8_t> ReleaseBuffer());
2069
2070 /**
2071 * Returns the stored data (allocated using the delegate's
2072 * ReallocateBufferMemory) and its size. This serializer should not be used
2073 * once the buffer is released. The contents are undefined if a previous write
2074 * has failed. Ownership of the buffer is transferred to the caller.
2075 */
2076 V8_WARN_UNUSED_RESULT std::pair<uint8_t*, size_t> Release();
2077
2078 /**
2079 * Marks an ArrayBuffer as havings its contents transferred out of band.
2080 * Pass the corresponding ArrayBuffer in the deserializing context to
2081 * ValueDeserializer::TransferArrayBuffer.
2082 */
2083 void TransferArrayBuffer(uint32_t transfer_id,
2084 Local<ArrayBuffer> array_buffer);
2085
2086 /**
2087 * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2088 */
2089 V8_DEPRECATE_SOON("Use Delegate::GetSharedArrayBufferId",
2090 void TransferSharedArrayBuffer(
2091 uint32_t transfer_id,
2092 Local<SharedArrayBuffer> shared_array_buffer));
2093
2094 /**
2095 * Indicate whether to treat ArrayBufferView objects as host objects,
2096 * i.e. pass them to Delegate::WriteHostObject. This should not be
2097 * called when no Delegate was passed.
2098 *
2099 * The default is not to treat ArrayBufferViews as host objects.
2100 */
2101 void SetTreatArrayBufferViewsAsHostObjects(bool mode);
2102
2103 /**
2104 * Write raw data in various common formats to the buffer.
2105 * Note that integer types are written in base-128 varint format, not with a
2106 * binary copy. For use during an override of Delegate::WriteHostObject.
2107 */
2108 void WriteUint32(uint32_t value);
2109 void WriteUint64(uint64_t value);
2110 void WriteDouble(double value);
2111 void WriteRawBytes(const void* source, size_t length);
2112
2113 private:
2114 ValueSerializer(const ValueSerializer&) = delete;
2115 void operator=(const ValueSerializer&) = delete;
2116
2117 struct PrivateData;
2118 PrivateData* private_;
2119 };
2120
2121 /**
2122 * Deserializes values from data written with ValueSerializer, or a compatible
2123 * implementation.
2124 *
2125 * WARNING: This API is under development, and changes (including incompatible
2126 * changes to the API or wire format) may occur without notice until this
2127 * warning is removed.
2128 */
2129 class V8_EXPORT ValueDeserializer {
2130 public:
2131 class V8_EXPORT Delegate {
2132 public:
2133 virtual ~Delegate() {}
2134
2135 /**
2136 * The embedder overrides this method to read some kind of host object, if
2137 * possible. If not, a suitable exception should be thrown and
2138 * MaybeLocal<Object>() returned.
2139 */
2140 virtual MaybeLocal<Object> ReadHostObject(Isolate* isolate);
2141
2142 /**
2143 * Get a WasmCompiledModule given a transfer_id previously provided
2144 * by ValueSerializer::GetWasmModuleTransferId
2145 */
2146 virtual MaybeLocal<WasmCompiledModule> GetWasmModuleFromId(
2147 Isolate* isolate, uint32_t transfer_id);
2148
2149 /**
2150 * Get a SharedArrayBuffer given a clone_id previously provided
2151 * by ValueSerializer::GetSharedArrayBufferId
2152 */
2153 virtual MaybeLocal<SharedArrayBuffer> GetSharedArrayBufferFromId(
2154 Isolate* isolate, uint32_t clone_id);
2155 };
2156
2157 ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size);
2158 ValueDeserializer(Isolate* isolate, const uint8_t* data, size_t size,
2159 Delegate* delegate);
2160 ~ValueDeserializer();
2161
2162 /**
2163 * Reads and validates a header (including the format version).
2164 * May, for example, reject an invalid or unsupported wire format.
2165 */
2166 V8_WARN_UNUSED_RESULT Maybe<bool> ReadHeader(Local<Context> context);
2167
2168 /**
2169 * Deserializes a JavaScript value from the buffer.
2170 */
2171 V8_WARN_UNUSED_RESULT MaybeLocal<Value> ReadValue(Local<Context> context);
2172
2173 /**
2174 * Accepts the array buffer corresponding to the one passed previously to
2175 * ValueSerializer::TransferArrayBuffer.
2176 */
2177 void TransferArrayBuffer(uint32_t transfer_id,
2178 Local<ArrayBuffer> array_buffer);
2179
2180 /**
2181 * Similar to TransferArrayBuffer, but for SharedArrayBuffer.
2182 * The id is not necessarily in the same namespace as unshared ArrayBuffer
2183 * objects.
2184 */
2185 void TransferSharedArrayBuffer(uint32_t id,
2186 Local<SharedArrayBuffer> shared_array_buffer);
2187
2188 /**
2189 * Must be called before ReadHeader to enable support for reading the legacy
2190 * wire format (i.e., which predates this being shipped).
2191 *
2192 * Don't use this unless you need to read data written by previous versions of
2193 * blink::ScriptValueSerializer.
2194 */
2195 void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format);
2196
2197 /**
2198 * Expect inline wasm in the data stream (rather than in-memory transfer)
2199 */
2200 void SetExpectInlineWasm(bool allow_inline_wasm);
2201
2202 /**
2203 * Reads the underlying wire format version. Likely mostly to be useful to
2204 * legacy code reading old wire format versions. Must be called after
2205 * ReadHeader.
2206 */
2207 uint32_t GetWireFormatVersion() const;
2208
2209 /**
2210 * Reads raw data in various common formats to the buffer.
2211 * Note that integer types are read in base-128 varint format, not with a
2212 * binary copy. For use during an override of Delegate::ReadHostObject.
2213 */
2214 V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t* value);
2215 V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t* value);
2216 V8_WARN_UNUSED_RESULT bool ReadDouble(double* value);
2217 V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void** data);
2218
2219 private:
2220 ValueDeserializer(const ValueDeserializer&) = delete;
2221 void operator=(const ValueDeserializer&) = delete;
2222
2223 struct PrivateData;
2224 PrivateData* private_;
2225 };
2226
2227
2228 // --- Value ---
2229
2230
2231 /**
2232 * The superclass of all JavaScript values and objects.
2233 */
2234 class V8_EXPORT Value : public Data {
2235 public:
2236 /**
2237 * Returns true if this value is the undefined value. See ECMA-262
2238 * 4.3.10.
2239 */
2240 V8_INLINE bool IsUndefined() const;
2241
2242 /**
2243 * Returns true if this value is the null value. See ECMA-262
2244 * 4.3.11.
2245 */
2246 V8_INLINE bool IsNull() const;
2247
2248 /**
2249 * Returns true if this value is either the null or the undefined value.
2250 * See ECMA-262
2251 * 4.3.11. and 4.3.12
2252 */
2253 V8_INLINE bool IsNullOrUndefined() const;
2254
2255 /**
2256 * Returns true if this value is true.
2257 */
2258 bool IsTrue() const;
2259
2260 /**
2261 * Returns true if this value is false.
2262 */
2263 bool IsFalse() const;
2264
2265 /**
2266 * Returns true if this value is a symbol or a string.
2267 */
2268 bool IsName() const;
2269
2270 /**
2271 * Returns true if this value is an instance of the String type.
2272 * See ECMA-262 8.4.
2273 */
2274 V8_INLINE bool IsString() const;
2275
2276 /**
2277 * Returns true if this value is a symbol.
2278 */
2279 bool IsSymbol() const;
2280
2281 /**
2282 * Returns true if this value is a function.
2283 */
2284 bool IsFunction() const;
2285
2286 /**
2287 * Returns true if this value is an array. Note that it will return false for
2288 * an Proxy for an array.
2289 */
2290 bool IsArray() const;
2291
2292 /**
2293 * Returns true if this value is an object.
2294 */
2295 bool IsObject() const;
2296
2297 /**
2298 * Returns true if this value is a bigint.
2299 */
2300 bool IsBigInt() const;
2301
2302 /**
2303 * Returns true if this value is boolean.
2304 */
2305 bool IsBoolean() const;
2306
2307 /**
2308 * Returns true if this value is a number.
2309 */
2310 bool IsNumber() const;
2311
2312 /**
2313 * Returns true if this value is external.
2314 */
2315 bool IsExternal() const;
2316
2317 /**
2318 * Returns true if this value is a 32-bit signed integer.
2319 */
2320 bool IsInt32() const;
2321
2322 /**
2323 * Returns true if this value is a 32-bit unsigned integer.
2324 */
2325 bool IsUint32() const;
2326
2327 /**
2328 * Returns true if this value is a Date.
2329 */
2330 bool IsDate() const;
2331
2332 /**
2333 * Returns true if this value is an Arguments object.
2334 */
2335 bool IsArgumentsObject() const;
2336
2337 /**
2338 * Returns true if this value is a BigInt object.
2339 */
2340 bool IsBigIntObject() const;
2341
2342 /**
2343 * Returns true if this value is a Boolean object.
2344 */
2345 bool IsBooleanObject() const;
2346
2347 /**
2348 * Returns true if this value is a Number object.
2349 */
2350 bool IsNumberObject() const;
2351
2352 /**
2353 * Returns true if this value is a String object.
2354 */
2355 bool IsStringObject() const;
2356
2357 /**
2358 * Returns true if this value is a Symbol object.
2359 */
2360 bool IsSymbolObject() const;
2361
2362 /**
2363 * Returns true if this value is a NativeError.
2364 */
2365 bool IsNativeError() const;
2366
2367 /**
2368 * Returns true if this value is a RegExp.
2369 */
2370 bool IsRegExp() const;
2371
2372 /**
2373 * Returns true if this value is an async function.
2374 */
2375 bool IsAsyncFunction() const;
2376
2377 /**
2378 * Returns true if this value is a Generator function.
2379 */
2380 bool IsGeneratorFunction() const;
2381
2382 /**
2383 * Returns true if this value is a Generator object (iterator).
2384 */
2385 bool IsGeneratorObject() const;
2386
2387 /**
2388 * Returns true if this value is a Promise.
2389 */
2390 bool IsPromise() const;
2391
2392 /**
2393 * Returns true if this value is a Map.
2394 */
2395 bool IsMap() const;
2396
2397 /**
2398 * Returns true if this value is a Set.
2399 */
2400 bool IsSet() const;
2401
2402 /**
2403 * Returns true if this value is a Map Iterator.
2404 */
2405 bool IsMapIterator() const;
2406
2407 /**
2408 * Returns true if this value is a Set Iterator.
2409 */
2410 bool IsSetIterator() const;
2411
2412 /**
2413 * Returns true if this value is a WeakMap.
2414 */
2415 bool IsWeakMap() const;
2416
2417 /**
2418 * Returns true if this value is a WeakSet.
2419 */
2420 bool IsWeakSet() const;
2421
2422 /**
2423 * Returns true if this value is an ArrayBuffer.
2424 */
2425 bool IsArrayBuffer() const;
2426
2427 /**
2428 * Returns true if this value is an ArrayBufferView.
2429 */
2430 bool IsArrayBufferView() const;
2431
2432 /**
2433 * Returns true if this value is one of TypedArrays.
2434 */
2435 bool IsTypedArray() const;
2436
2437 /**
2438 * Returns true if this value is an Uint8Array.
2439 */
2440 bool IsUint8Array() const;
2441
2442 /**
2443 * Returns true if this value is an Uint8ClampedArray.
2444 */
2445 bool IsUint8ClampedArray() const;
2446
2447 /**
2448 * Returns true if this value is an Int8Array.
2449 */
2450 bool IsInt8Array() const;
2451
2452 /**
2453 * Returns true if this value is an Uint16Array.
2454 */
2455 bool IsUint16Array() const;
2456
2457 /**
2458 * Returns true if this value is an Int16Array.
2459 */
2460 bool IsInt16Array() const;
2461
2462 /**
2463 * Returns true if this value is an Uint32Array.
2464 */
2465 bool IsUint32Array() const;
2466
2467 /**
2468 * Returns true if this value is an Int32Array.
2469 */
2470 bool IsInt32Array() const;
2471
2472 /**
2473 * Returns true if this value is a Float32Array.
2474 */
2475 bool IsFloat32Array() const;
2476
2477 /**
2478 * Returns true if this value is a Float64Array.
2479 */
2480 bool IsFloat64Array() const;
2481
2482 /**
2483 * Returns true if this value is a BigInt64Array.
2484 */
2485 bool IsBigInt64Array() const;
2486
2487 /**
2488 * Returns true if this value is a BigUint64Array.
2489 */
2490 bool IsBigUint64Array() const;
2491
2492 /**
2493 * Returns true if this value is a DataView.
2494 */
2495 bool IsDataView() const;
2496
2497 /**
2498 * Returns true if this value is a SharedArrayBuffer.
2499 * This is an experimental feature.
2500 */
2501 bool IsSharedArrayBuffer() const;
2502
2503 /**
2504 * Returns true if this value is a JavaScript Proxy.
2505 */
2506 bool IsProxy() const;
2507
2508 bool IsWebAssemblyCompiledModule() const;
2509
2510 /**
2511 * Returns true if the value is a Module Namespace Object.
2512 */
2513 bool IsModuleNamespaceObject() const;
2514
2515 V8_WARN_UNUSED_RESULT MaybeLocal<BigInt> ToBigInt(
2516 Local<Context> context) const;
2517 V8_WARN_UNUSED_RESULT MaybeLocal<Boolean> ToBoolean(
2518 Local<Context> context) const;
2519 V8_WARN_UNUSED_RESULT MaybeLocal<Number> ToNumber(
2520 Local<Context> context) const;
2521 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToString(
2522 Local<Context> context) const;
2523 V8_WARN_UNUSED_RESULT MaybeLocal<String> ToDetailString(
2524 Local<Context> context) const;
2525 V8_WARN_UNUSED_RESULT MaybeLocal<Object> ToObject(
2526 Local<Context> context) const;
2527 V8_WARN_UNUSED_RESULT MaybeLocal<Integer> ToInteger(
2528 Local<Context> context) const;
2529 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToUint32(
2530 Local<Context> context) const;
2531 V8_WARN_UNUSED_RESULT MaybeLocal<Int32> ToInt32(Local<Context> context) const;
2532
2533 V8_DEPRECATE_SOON("Use maybe version",
2534 Local<Boolean> ToBoolean(Isolate* isolate) const);
2535 V8_DEPRECATE_SOON("Use maybe version",
2536 Local<Number> ToNumber(Isolate* isolate) const);
2537 V8_DEPRECATE_SOON("Use maybe version",
2538 Local<String> ToString(Isolate* isolate) const);
2539 V8_DEPRECATE_SOON("Use maybe version",
2540 Local<Object> ToObject(Isolate* isolate) const);
2541 V8_DEPRECATE_SOON("Use maybe version",
2542 Local<Integer> ToInteger(Isolate* isolate) const);
2543 V8_DEPRECATE_SOON("Use maybe version",
2544 Local<Int32> ToInt32(Isolate* isolate) const);
2545
2546 inline V8_DEPRECATED("Use maybe version", Local<Boolean> ToBoolean() const);
2547 inline V8_DEPRECATED("Use maybe version", Local<String> ToString() const);
2548 inline V8_DEPRECATED("Use maybe version", Local<Object> ToObject() const);
2549 inline V8_DEPRECATED("Use maybe version", Local<Integer> ToInteger() const);
2550
2551 /**
2552 * Attempts to convert a string to an array index.
2553 * Returns an empty handle if the conversion fails.
2554 */
2555 V8_WARN_UNUSED_RESULT MaybeLocal<Uint32> ToArrayIndex(
2556 Local<Context> context) const;
2557
2558 V8_WARN_UNUSED_RESULT Maybe<bool> BooleanValue(Local<Context> context) const;
2559 V8_WARN_UNUSED_RESULT Maybe<double> NumberValue(Local<Context> context) const;
2560 V8_WARN_UNUSED_RESULT Maybe<int64_t> IntegerValue(
2561 Local<Context> context) const;
2562 V8_WARN_UNUSED_RESULT Maybe<uint32_t> Uint32Value(
2563 Local<Context> context) const;
2564 V8_WARN_UNUSED_RESULT Maybe<int32_t> Int32Value(Local<Context> context) const;
2565
2566 V8_DEPRECATED("Use maybe version", bool BooleanValue() const);
2567 V8_DEPRECATED("Use maybe version", double NumberValue() const);
2568 V8_DEPRECATED("Use maybe version", int64_t IntegerValue() const);
2569 V8_DEPRECATED("Use maybe version", uint32_t Uint32Value() const);
2570 V8_DEPRECATED("Use maybe version", int32_t Int32Value() const);
2571
2572 /** JS == */
2573 V8_DEPRECATED("Use maybe version", bool Equals(Local<Value> that) const);
2574 V8_WARN_UNUSED_RESULT Maybe<bool> Equals(Local<Context> context,
2575 Local<Value> that) const;
2576 bool StrictEquals(Local<Value> that) const;
2577 bool SameValue(Local<Value> that) const;
2578
2579 template <class T> V8_INLINE static Value* Cast(T* value);
2580
2581 Local<String> TypeOf(Isolate*);
2582
2583 Maybe<bool> InstanceOf(Local<Context> context, Local<Object> object);
2584
2585 private:
2586 V8_INLINE bool QuickIsUndefined() const;
2587 V8_INLINE bool QuickIsNull() const;
2588 V8_INLINE bool QuickIsNullOrUndefined() const;
2589 V8_INLINE bool QuickIsString() const;
2590 bool FullIsUndefined() const;
2591 bool FullIsNull() const;
2592 bool FullIsString() const;
2593 };
2594
2595
2596 /**
2597 * The superclass of primitive values. See ECMA-262 4.3.2.
2598 */
2599 class V8_EXPORT Primitive : public Value { };
2600
2601
2602 /**
2603 * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2604 * or false value.
2605 */
2606 class V8_EXPORT Boolean : public Primitive {
2607 public:
2608 bool Value() const;
2609 V8_INLINE static Boolean* Cast(v8::Value* obj);
2610 V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2611
2612 private:
2613 static void CheckCast(v8::Value* obj);
2614 };
2615
2616
2617 /**
2618 * A superclass for symbols and strings.
2619 */
2620 class V8_EXPORT Name : public Primitive {
2621 public:
2622 /**
2623 * Returns the identity hash for this object. The current implementation
2624 * uses an inline property on the object to store the identity hash.
2625 *
2626 * The return value will never be 0. Also, it is not guaranteed to be
2627 * unique.
2628 */
2629 int GetIdentityHash();
2630
2631 V8_INLINE static Name* Cast(Value* obj);
2632
2633 private:
2634 static void CheckCast(Value* obj);
2635 };
2636
2637 /**
2638 * A flag describing different modes of string creation.
2639 *
2640 * Aside from performance implications there are no differences between the two
2641 * creation modes.
2642 */
2643 enum class NewStringType {
2644 /**
2645 * Create a new string, always allocating new storage memory.
2646 */
2647 kNormal,
2648
2649 /**
2650 * Acts as a hint that the string should be created in the
2651 * old generation heap space and be deduplicated if an identical string
2652 * already exists.
2653 */
2654 kInternalized
2655 };
2656
2657 /**
2658 * A JavaScript string value (ECMA-262, 4.3.17).
2659 */
2660 class V8_EXPORT String : public Name {
2661 public:
2662 static constexpr int kMaxLength = internal::kApiPointerSize == 4
2663 ? (1 << 28) - 16
2664 : internal::kSmiMaxValue / 2 - 24;
2665
2666 enum Encoding {
2667 UNKNOWN_ENCODING = 0x1,
2668 TWO_BYTE_ENCODING = 0x0,
2669 ONE_BYTE_ENCODING = 0x8
2670 };
2671 /**
2672 * Returns the number of characters (UTF-16 code units) in this string.
2673 */
2674 int Length() const;
2675
2676 /**
2677 * Returns the number of bytes in the UTF-8 encoded
2678 * representation of this string.
2679 */
2680 V8_DEPRECATED("Use Isolate version instead", int Utf8Length() const);
2681
2682 int Utf8Length(Isolate* isolate) const;
2683
2684 /**
2685 * Returns whether this string is known to contain only one byte data,
2686 * i.e. ISO-8859-1 code points.
2687 * Does not read the string.
2688 * False negatives are possible.
2689 */
2690 bool IsOneByte() const;
2691
2692 /**
2693 * Returns whether this string contain only one byte data,
2694 * i.e. ISO-8859-1 code points.
2695 * Will read the entire string in some cases.
2696 */
2697 bool ContainsOnlyOneByte() const;
2698
2699 /**
2700 * Write the contents of the string to an external buffer.
2701 * If no arguments are given, expects the buffer to be large
2702 * enough to hold the entire string and NULL terminator. Copies
2703 * the contents of the string and the NULL terminator into the
2704 * buffer.
2705 *
2706 * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2707 * before the end of the buffer.
2708 *
2709 * Copies up to length characters into the output buffer.
2710 * Only null-terminates if there is enough space in the buffer.
2711 *
2712 * \param buffer The buffer into which the string will be copied.
2713 * \param start The starting position within the string at which
2714 * copying begins.
2715 * \param length The number of characters to copy from the string. For
2716 * WriteUtf8 the number of bytes in the buffer.
2717 * \param nchars_ref The number of characters written, can be NULL.
2718 * \param options Various options that might affect performance of this or
2719 * subsequent operations.
2720 * \return The number of characters copied to the buffer excluding the null
2721 * terminator. For WriteUtf8: The number of bytes copied to the buffer
2722 * including the null terminator (if written).
2723 */
2724 enum WriteOptions {
2725 NO_OPTIONS = 0,
2726 HINT_MANY_WRITES_EXPECTED = 1,
2727 NO_NULL_TERMINATION = 2,
2728 PRESERVE_ONE_BYTE_NULL = 4,
2729 // Used by WriteUtf8 to replace orphan surrogate code units with the
2730 // unicode replacement character. Needs to be set to guarantee valid UTF-8
2731 // output.
2732 REPLACE_INVALID_UTF8 = 8
2733 };
2734
2735 // 16-bit character codes.
2736 int Write(Isolate* isolate, uint16_t* buffer, int start = 0, int length = -1,
2737 int options = NO_OPTIONS) const;
2738 V8_DEPRECATED("Use Isolate* version",
2739 int Write(uint16_t* buffer, int start = 0, int length = -1,
2740 int options = NO_OPTIONS) const);
2741 // One byte characters.
2742 int WriteOneByte(Isolate* isolate, uint8_t* buffer, int start = 0,
2743 int length = -1, int options = NO_OPTIONS) const;
2744 V8_DEPRECATED("Use Isolate* version",
2745 int WriteOneByte(uint8_t* buffer, int start = 0,
2746 int length = -1, int options = NO_OPTIONS)
2747 const);
2748 // UTF-8 encoded characters.
2749 int WriteUtf8(Isolate* isolate, char* buffer, int length = -1,
2750 int* nchars_ref = NULL, int options = NO_OPTIONS) const;
2751 V8_DEPRECATED("Use Isolate* version",
2752 int WriteUtf8(char* buffer, int length = -1,
2753 int* nchars_ref = NULL, int options = NO_OPTIONS)
2754 const);
2755
2756 /**
2757 * A zero length string.
2758 */
2759 V8_INLINE static Local<String> Empty(Isolate* isolate);
2760
2761 /**
2762 * Returns true if the string is external
2763 */
2764 bool IsExternal() const;
2765
2766 /**
2767 * Returns true if the string is both external and one-byte.
2768 */
2769 bool IsExternalOneByte() const;
2770
2771 class V8_EXPORT ExternalStringResourceBase { // NOLINT
2772 public:
2773 virtual ~ExternalStringResourceBase() {}
2774
2775 virtual bool IsCompressible() const { return false; }
2776
2777 protected:
2778 ExternalStringResourceBase() {}
2779
2780 /**
2781 * Internally V8 will call this Dispose method when the external string
2782 * resource is no longer needed. The default implementation will use the
2783 * delete operator. This method can be overridden in subclasses to
2784 * control how allocated external string resources are disposed.
2785 */
2786 virtual void Dispose() { delete this; }
2787
2788 // Disallow copying and assigning.
2789 ExternalStringResourceBase(const ExternalStringResourceBase&) = delete;
2790 void operator=(const ExternalStringResourceBase&) = delete;
2791
2792 private:
2793 friend class internal::Heap;
2794 friend class v8::String;
2795 };
2796
2797 /**
2798 * An ExternalStringResource is a wrapper around a two-byte string
2799 * buffer that resides outside V8's heap. Implement an
2800 * ExternalStringResource to manage the life cycle of the underlying
2801 * buffer. Note that the string data must be immutable.
2802 */
2803 class V8_EXPORT ExternalStringResource
2804 : public ExternalStringResourceBase {
2805 public:
2806 /**
2807 * Override the destructor to manage the life cycle of the underlying
2808 * buffer.
2809 */
2810 virtual ~ExternalStringResource() {}
2811
2812 /**
2813 * The string data from the underlying buffer.
2814 */
2815 virtual const uint16_t* data() const = 0;
2816
2817 /**
2818 * The length of the string. That is, the number of two-byte characters.
2819 */
2820 virtual size_t length() const = 0;
2821
2822 protected:
2823 ExternalStringResource() {}
2824 };
2825
2826 /**
2827 * An ExternalOneByteStringResource is a wrapper around an one-byte
2828 * string buffer that resides outside V8's heap. Implement an
2829 * ExternalOneByteStringResource to manage the life cycle of the
2830 * underlying buffer. Note that the string data must be immutable
2831 * and that the data must be Latin-1 and not UTF-8, which would require
2832 * special treatment internally in the engine and do not allow efficient
2833 * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2834 */
2835
2836 class V8_EXPORT ExternalOneByteStringResource
2837 : public ExternalStringResourceBase {
2838 public:
2839 /**
2840 * Override the destructor to manage the life cycle of the underlying
2841 * buffer.
2842 */
2843 virtual ~ExternalOneByteStringResource() {}
2844 /** The string data from the underlying buffer.*/
2845 virtual const char* data() const = 0;
2846 /** The number of Latin-1 characters in the string.*/
2847 virtual size_t length() const = 0;
2848 protected:
2849 ExternalOneByteStringResource() {}
2850 };
2851
2852 /**
2853 * If the string is an external string, return the ExternalStringResourceBase
2854 * regardless of the encoding, otherwise return NULL. The encoding of the
2855 * string is returned in encoding_out.
2856 */
2857 V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
2858 Encoding* encoding_out) const;
2859
2860 /**
2861 * Get the ExternalStringResource for an external string. Returns
2862 * NULL if IsExternal() doesn't return true.
2863 */
2864 V8_INLINE ExternalStringResource* GetExternalStringResource() const;
2865
2866 /**
2867 * Get the ExternalOneByteStringResource for an external one-byte string.
2868 * Returns NULL if IsExternalOneByte() doesn't return true.
2869 */
2870 const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
2871
2872 V8_INLINE static String* Cast(v8::Value* obj);
2873
2874 // TODO(dcarney): remove with deprecation of New functions.
2875 enum NewStringType {
2876 kNormalString = static_cast<int>(v8::NewStringType::kNormal),
2877 kInternalizedString = static_cast<int>(v8::NewStringType::kInternalized)
2878 };
2879
2880 /** Allocates a new string from UTF-8 data.*/
2881 static V8_DEPRECATE_SOON(
2882 "Use maybe version",
2883 Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2884 NewStringType type = kNormalString,
2885 int length = -1));
2886
2887 /** Allocates a new string from UTF-8 data. Only returns an empty value when
2888 * length > kMaxLength. **/
2889 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromUtf8(
2890 Isolate* isolate, const char* data, v8::NewStringType type,
2891 int length = -1);
2892
2893 /** Allocates a new string from Latin-1 data. Only returns an empty value
2894 * when length > kMaxLength. **/
2895 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromOneByte(
2896 Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2897 int length = -1);
2898
2899 /** Allocates a new string from UTF-16 data.*/
2900 static V8_DEPRECATE_SOON(
2901 "Use maybe version",
2902 Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2903 NewStringType type = kNormalString,
2904 int length = -1));
2905
2906 /** Allocates a new string from UTF-16 data. Only returns an empty value when
2907 * length > kMaxLength. **/
2908 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewFromTwoByte(
2909 Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2910 int length = -1);
2911
2912 /**
2913 * Creates a new string by concatenating the left and the right strings
2914 * passed in as parameters.
2915 */
2916 static Local<String> Concat(Isolate* isolate, Local<String> left,
2917 Local<String> right);
2918 static V8_DEPRECATED("Use Isolate* version",
2919 Local<String> Concat(Local<String> left,
2920 Local<String> right));
2921
2922 /**
2923 * Creates a new external string using the data defined in the given
2924 * resource. When the external string is no longer live on V8's heap the
2925 * resource will be disposed by calling its Dispose method. The caller of
2926 * this function should not otherwise delete or modify the resource. Neither
2927 * should the underlying buffer be deallocated or modified except through the
2928 * destructor of the external string resource.
2929 */
2930 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalTwoByte(
2931 Isolate* isolate, ExternalStringResource* resource);
2932
2933 /**
2934 * Associate an external string resource with this string by transforming it
2935 * in place so that existing references to this string in the JavaScript heap
2936 * will use the external string resource. The external string resource's
2937 * character contents need to be equivalent to this string.
2938 * Returns true if the string has been changed to be an external string.
2939 * The string is not modified if the operation fails. See NewExternal for
2940 * information on the lifetime of the resource.
2941 */
2942 bool MakeExternal(ExternalStringResource* resource);
2943
2944 /**
2945 * Creates a new external string using the one-byte data defined in the given
2946 * resource. When the external string is no longer live on V8's heap the
2947 * resource will be disposed by calling its Dispose method. The caller of
2948 * this function should not otherwise delete or modify the resource. Neither
2949 * should the underlying buffer be deallocated or modified except through the
2950 * destructor of the external string resource.
2951 */
2952 static V8_DEPRECATE_SOON(
2953 "Use maybe version",
2954 Local<String> NewExternal(Isolate* isolate,
2955 ExternalOneByteStringResource* resource));
2956 static V8_WARN_UNUSED_RESULT MaybeLocal<String> NewExternalOneByte(
2957 Isolate* isolate, ExternalOneByteStringResource* resource);
2958
2959 /**
2960 * Associate an external string resource with this string by transforming it
2961 * in place so that existing references to this string in the JavaScript heap
2962 * will use the external string resource. The external string resource's
2963 * character contents need to be equivalent to this string.
2964 * Returns true if the string has been changed to be an external string.
2965 * The string is not modified if the operation fails. See NewExternal for
2966 * information on the lifetime of the resource.
2967 */
2968 bool MakeExternal(ExternalOneByteStringResource* resource);
2969
2970 /**
2971 * Returns true if this string can be made external.
2972 */
2973 bool CanMakeExternal();
2974
2975 /**
2976 * Returns true if the strings values are equal. Same as JS ==/===.
2977 */
2978 bool StringEquals(Local<String> str);
2979
2980 /**
2981 * Converts an object to a UTF-8-encoded character array. Useful if
2982 * you want to print the object. If conversion to a string fails
2983 * (e.g. due to an exception in the toString() method of the object)
2984 * then the length() method returns 0 and the * operator returns
2985 * NULL.
2986 */
2987 class V8_EXPORT Utf8Value {
2988 public:
2989 Utf8Value(Isolate* isolate, Local<v8::Value> obj);
2990 ~Utf8Value();
2991 char* operator*() { return str_; }
2992 const char* operator*() const { return str_; }
2993 int length() const { return length_; }
2994
2995 // Disallow copying and assigning.
2996 Utf8Value(const Utf8Value&) = delete;
2997 void operator=(const Utf8Value&) = delete;
2998
2999 private:
3000 char* str_;
3001 int length_;
3002 };
3003
3004 /**
3005 * Converts an object to a two-byte (UTF-16-encoded) string.
3006 * If conversion to a string fails (eg. due to an exception in the toString()
3007 * method of the object) then the length() method returns 0 and the * operator
3008 * returns NULL.
3009 */
3010 class V8_EXPORT Value {
3011 public:
3012 Value(Isolate* isolate, Local<v8::Value> obj);
3013 ~Value();
3014 uint16_t* operator*() { return str_; }
3015 const uint16_t* operator*() const { return str_; }
3016 int length() const { return length_; }
3017
3018 // Disallow copying and assigning.
3019 Value(const Value&) = delete;
3020 void operator=(const Value&) = delete;
3021
3022 private:
3023 uint16_t* str_;
3024 int length_;
3025 };
3026
3027 private:
3028 void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
3029 Encoding encoding) const;
3030 void VerifyExternalStringResource(ExternalStringResource* val) const;
3031 ExternalStringResource* GetExternalStringResourceSlow() const;
3032 ExternalStringResourceBase* GetExternalStringResourceBaseSlow(
3033 String::Encoding* encoding_out) const;
3034 const ExternalOneByteStringResource* GetExternalOneByteStringResourceSlow()
3035 const;
3036
3037 static void CheckCast(v8::Value* obj);
3038 };
3039
3040
3041 /**
3042 * A JavaScript symbol (ECMA-262 edition 6)
3043 */
3044 class V8_EXPORT Symbol : public Name {
3045 public:
3046 /**
3047 * Returns the print name string of the symbol, or undefined if none.
3048 */
3049 Local<Value> Name() const;
3050
3051 /**
3052 * Create a symbol. If name is not empty, it will be used as the description.
3053 */
3054 static Local<Symbol> New(Isolate* isolate,
3055 Local<String> name = Local<String>());
3056
3057 /**
3058 * Access global symbol registry.
3059 * Note that symbols created this way are never collected, so
3060 * they should only be used for statically fixed properties.
3061 * Also, there is only one global name space for the names used as keys.
3062 * To minimize the potential for clashes, use qualified names as keys.
3063 */
3064 static Local<Symbol> For(Isolate *isolate, Local<String> name);
3065
3066 /**
3067 * Retrieve a global symbol. Similar to |For|, but using a separate
3068 * registry that is not accessible by (and cannot clash with) JavaScript code.
3069 */
3070 static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
3071
3072 // Well-known symbols
3073 static Local<Symbol> GetHasInstance(Isolate* isolate);
3074 static Local<Symbol> GetIsConcatSpreadable(Isolate* isolate);
3075 static Local<Symbol> GetIterator(Isolate* isolate);
3076 static Local<Symbol> GetMatch(Isolate* isolate);
3077 static Local<Symbol> GetReplace(Isolate* isolate);
3078 static Local<Symbol> GetSearch(Isolate* isolate);
3079 static Local<Symbol> GetSplit(Isolate* isolate);
3080 static Local<Symbol> GetToPrimitive(Isolate* isolate);
3081 static Local<Symbol> GetToStringTag(Isolate* isolate);
3082 static Local<Symbol> GetUnscopables(Isolate* isolate);
3083
3084 V8_INLINE static Symbol* Cast(Value* obj);
3085
3086 private:
3087 Symbol();
3088 static void CheckCast(Value* obj);
3089 };
3090
3091
3092 /**
3093 * A private symbol
3094 *
3095 * This is an experimental feature. Use at your own risk.
3096 */
3097 class V8_EXPORT Private : public Data {
3098 public:
3099 /**
3100 * Returns the print name string of the private symbol, or undefined if none.
3101 */
3102 Local<Value> Name() const;
3103
3104 /**
3105 * Create a private symbol. If name is not empty, it will be the description.
3106 */
3107 static Local<Private> New(Isolate* isolate,
3108 Local<String> name = Local<String>());
3109
3110 /**
3111 * Retrieve a global private symbol. If a symbol with this name has not
3112 * been retrieved in the same isolate before, it is created.
3113 * Note that private symbols created this way are never collected, so
3114 * they should only be used for statically fixed properties.
3115 * Also, there is only one global name space for the names used as keys.
3116 * To minimize the potential for clashes, use qualified names as keys,
3117 * e.g., "Class#property".
3118 */
3119 static Local<Private> ForApi(Isolate* isolate, Local<String> name);
3120
3121 V8_INLINE static Private* Cast(Data* data);
3122
3123 private:
3124 Private();
3125
3126 static void CheckCast(Data* that);
3127 };
3128
3129
3130 /**
3131 * A JavaScript number value (ECMA-262, 4.3.20)
3132 */
3133 class V8_EXPORT Number : public Primitive {
3134 public:
3135 double Value() const;
3136 static Local<Number> New(Isolate* isolate, double value);
3137 V8_INLINE static Number* Cast(v8::Value* obj);
3138 private:
3139 Number();
3140 static void CheckCast(v8::Value* obj);
3141 };
3142
3143
3144 /**
3145 * A JavaScript value representing a signed integer.
3146 */
3147 class V8_EXPORT Integer : public Number {
3148 public:
3149 static Local<Integer> New(Isolate* isolate, int32_t value);
3150 static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
3151 int64_t Value() const;
3152 V8_INLINE static Integer* Cast(v8::Value* obj);
3153 private:
3154 Integer();
3155 static void CheckCast(v8::Value* obj);
3156 };
3157
3158
3159 /**
3160 * A JavaScript value representing a 32-bit signed integer.
3161 */
3162 class V8_EXPORT Int32 : public Integer {
3163 public:
3164 int32_t Value() const;
3165 V8_INLINE static Int32* Cast(v8::Value* obj);
3166
3167 private:
3168 Int32();
3169 static void CheckCast(v8::Value* obj);
3170 };
3171
3172
3173 /**
3174 * A JavaScript value representing a 32-bit unsigned integer.
3175 */
3176 class V8_EXPORT Uint32 : public Integer {
3177 public:
3178 uint32_t Value() const;
3179 V8_INLINE static Uint32* Cast(v8::Value* obj);
3180
3181 private:
3182 Uint32();
3183 static void CheckCast(v8::Value* obj);
3184 };
3185
3186 /**
3187 * A JavaScript BigInt value (https://tc39.github.io/proposal-bigint)
3188 */
3189 class V8_EXPORT BigInt : public Primitive {
3190 public:
3191 static Local<BigInt> New(Isolate* isolate, int64_t value);
3192 static Local<BigInt> NewFromUnsigned(Isolate* isolate, uint64_t value);
3193 /**
3194 * Creates a new BigInt object using a specified sign bit and a
3195 * specified list of digits/words.
3196 * The resulting number is calculated as:
3197 *
3198 * (-1)^sign_bit * (words[0] * (2^64)^0 + words[1] * (2^64)^1 + ...)
3199 */
3200 static MaybeLocal<BigInt> NewFromWords(Local<Context> context, int sign_bit,
3201 int word_count, const uint64_t* words);
3202
3203 /**
3204 * Returns the value of this BigInt as an unsigned 64-bit integer.
3205 * If `lossless` is provided, it will reflect whether the return value was
3206 * truncated or wrapped around. In particular, it is set to `false` if this
3207 * BigInt is negative.
3208 */
3209 uint64_t Uint64Value(bool* lossless = nullptr) const;
3210
3211 /**
3212 * Returns the value of this BigInt as a signed 64-bit integer.
3213 * If `lossless` is provided, it will reflect whether this BigInt was
3214 * truncated or not.
3215 */
3216 int64_t Int64Value(bool* lossless = nullptr) const;
3217
3218 /**
3219 * Returns the number of 64-bit words needed to store the result of
3220 * ToWordsArray().
3221 */
3222 int WordCount() const;
3223
3224 /**
3225 * Writes the contents of this BigInt to a specified memory location.
3226 * `sign_bit` must be provided and will be set to 1 if this BigInt is
3227 * negative.
3228 * `*word_count` has to be initialized to the length of the `words` array.
3229 * Upon return, it will be set to the actual number of words that would
3230 * be needed to store this BigInt (i.e. the return value of `WordCount()`).
3231 */
3232 void ToWordsArray(int* sign_bit, int* word_count, uint64_t* words) const;
3233
3234 V8_INLINE static BigInt* Cast(v8::Value* obj);
3235
3236 private:
3237 BigInt();
3238 static void CheckCast(v8::Value* obj);
3239 };
3240
3241 /**
3242 * PropertyAttribute.
3243 */
3244 enum PropertyAttribute {
3245 /** None. **/
3246 None = 0,
3247 /** ReadOnly, i.e., not writable. **/
3248 ReadOnly = 1 << 0,
3249 /** DontEnum, i.e., not enumerable. **/
3250 DontEnum = 1 << 1,
3251 /** DontDelete, i.e., not configurable. **/
3252 DontDelete = 1 << 2
3253 };
3254
3255 /**
3256 * Accessor[Getter|Setter] are used as callback functions when
3257 * setting|getting a particular property. See Object and ObjectTemplate's
3258 * method SetAccessor.
3259 */
3260 typedef void (*AccessorGetterCallback)(
3261 Local<String> property,
3262 const PropertyCallbackInfo<Value>& info);
3263 typedef void (*AccessorNameGetterCallback)(
3264 Local<Name> property,
3265 const PropertyCallbackInfo<Value>& info);
3266
3267
3268 typedef void (*AccessorSetterCallback)(
3269 Local<String> property,
3270 Local<Value> value,
3271 const PropertyCallbackInfo<void>& info);
3272 typedef void (*AccessorNameSetterCallback)(
3273 Local<Name> property,
3274 Local<Value> value,
3275 const PropertyCallbackInfo<void>& info);
3276
3277
3278 /**
3279 * Access control specifications.
3280 *
3281 * Some accessors should be accessible across contexts. These
3282 * accessors have an explicit access control parameter which specifies
3283 * the kind of cross-context access that should be allowed.
3284 *
3285 * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
3286 */
3287 enum AccessControl {
3288 DEFAULT = 0,
3289 ALL_CAN_READ = 1,
3290 ALL_CAN_WRITE = 1 << 1,
3291 PROHIBITS_OVERWRITING = 1 << 2
3292 };
3293
3294 /**
3295 * Property filter bits. They can be or'ed to build a composite filter.
3296 */
3297 enum PropertyFilter {
3298 ALL_PROPERTIES = 0,
3299 ONLY_WRITABLE = 1,
3300 ONLY_ENUMERABLE = 2,
3301 ONLY_CONFIGURABLE = 4,
3302 SKIP_STRINGS = 8,
3303 SKIP_SYMBOLS = 16
3304 };
3305
3306 /**
3307 * Options for marking whether callbacks may trigger JS-observable side effects.
3308 * Side-effect-free callbacks are whitelisted during debug evaluation with
3309 * throwOnSideEffect. It applies when calling a Function, FunctionTemplate,
3310 * or an Accessor's getter callback. For Interceptors, please see
3311 * PropertyHandlerFlags's kHasNoSideEffect.
3312 */
3313 enum class SideEffectType { kHasSideEffect, kHasNoSideEffect };
3314
3315 /**
3316 * Keys/Properties filter enums:
3317 *
3318 * KeyCollectionMode limits the range of collected properties. kOwnOnly limits
3319 * the collected properties to the given Object only. kIncludesPrototypes will
3320 * include all keys of the objects's prototype chain as well.
3321 */
3322 enum class KeyCollectionMode { kOwnOnly, kIncludePrototypes };
3323
3324 /**
3325 * kIncludesIndices allows for integer indices to be collected, while
3326 * kSkipIndices will exclude integer indices from being collected.
3327 */
3328 enum class IndexFilter { kIncludeIndices, kSkipIndices };
3329
3330 /**
3331 * kConvertToString will convert integer indices to strings.
3332 * kKeepNumbers will return numbers for integer indices.
3333 */
3334 enum class KeyConversionMode { kConvertToString, kKeepNumbers };
3335
3336 /**
3337 * Integrity level for objects.
3338 */
3339 enum class IntegrityLevel { kFrozen, kSealed };
3340
3341 /**
3342 * A JavaScript object (ECMA-262, 4.3.3)
3343 */
3344 class V8_EXPORT Object : public Value {
3345 public:
3346 V8_DEPRECATE_SOON("Use maybe version",
3347 bool Set(Local<Value> key, Local<Value> value));
3348 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context,
3349 Local<Value> key, Local<Value> value);
3350
3351 V8_DEPRECATE_SOON("Use maybe version",
3352 bool Set(uint32_t index, Local<Value> value));
3353 V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
3354 Local<Value> value);
3355
3356 // Implements CreateDataProperty (ECMA-262, 7.3.4).
3357 //
3358 // Defines a configurable, writable, enumerable property with the given value
3359 // on the object unless the property already exists and is not configurable
3360 // or the object is not extensible.
3361 //
3362 // Returns true on success.
3363 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
3364 Local<Name> key,
3365 Local<Value> value);
3366 V8_WARN_UNUSED_RESULT Maybe<bool> CreateDataProperty(Local<Context> context,
3367 uint32_t index,
3368 Local<Value> value);
3369
3370 // Implements DefineOwnProperty.
3371 //
3372 // In general, CreateDataProperty will be faster, however, does not allow
3373 // for specifying attributes.
3374 //
3375 // Returns true on success.
3376 V8_WARN_UNUSED_RESULT Maybe<bool> DefineOwnProperty(
3377 Local<Context> context, Local<Name> key, Local<Value> value,
3378 PropertyAttribute attributes = None);
3379
3380 // Implements Object.DefineProperty(O, P, Attributes), see Ecma-262 19.1.2.4.
3381 //
3382 // The defineProperty function is used to add an own property or
3383 // update the attributes of an existing own property of an object.
3384 //
3385 // Both data and accessor descriptors can be used.
3386 //
3387 // In general, CreateDataProperty is faster, however, does not allow
3388 // for specifying attributes or an accessor descriptor.
3389 //
3390 // The PropertyDescriptor can change when redefining a property.
3391 //
3392 // Returns true on success.
3393 V8_WARN_UNUSED_RESULT Maybe<bool> DefineProperty(
3394 Local<Context> context, Local<Name> key, PropertyDescriptor& descriptor);
3395
3396 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
3397 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
3398 Local<Value> key);
3399
3400 V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
3401 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
3402 uint32_t index);
3403
3404 /**
3405 * Gets the property attributes of a property which can be None or
3406 * any combination of ReadOnly, DontEnum and DontDelete. Returns
3407 * None when the property doesn't exist.
3408 */
3409 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetPropertyAttributes(
3410 Local<Context> context, Local<Value> key);
3411
3412 /**
3413 * Returns Object.getOwnPropertyDescriptor as per ES2016 section 19.1.2.6.
3414 */
3415 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetOwnPropertyDescriptor(
3416 Local<Context> context, Local<Name> key);
3417
3418 V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
3419 /**
3420 * Object::Has() calls the abstract operation HasProperty(O, P) described
3421 * in ECMA-262, 7.3.10. Has() returns
3422 * true, if the object has the property, either own or on the prototype chain.
3423 * Interceptors, i.e., PropertyQueryCallbacks, are called if present.
3424 *
3425 * Has() has the same side effects as JavaScript's `variable in object`.
3426 * For example, calling Has() on a revoked proxy will throw an exception.
3427 *
3428 * \note Has() converts the key to a name, which possibly calls back into
3429 * JavaScript.
3430 *
3431 * See also v8::Object::HasOwnProperty() and
3432 * v8::Object::HasRealNamedProperty().
3433 */
3434 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3435 Local<Value> key);
3436
3437 V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
3438 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3439 Local<Value> key);
3440
3441 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
3442
3443 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3444 uint32_t index);
3445
3446 /**
3447 * Note: SideEffectType affects the getter only, not the setter.
3448 */
3449 V8_WARN_UNUSED_RESULT Maybe<bool> SetAccessor(
3450 Local<Context> context, Local<Name> name,
3451 AccessorNameGetterCallback getter, AccessorNameSetterCallback setter = 0,
3452 MaybeLocal<Value> data = MaybeLocal<Value>(),
3453 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
3454 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3455
3456 void SetAccessorProperty(Local<Name> name, Local<Function> getter,
3457 Local<Function> setter = Local<Function>(),
3458 PropertyAttribute attribute = None,
3459 AccessControl settings = DEFAULT);
3460
3461 /**
3462 * Sets a native data property like Template::SetNativeDataProperty, but
3463 * this method sets on this object directly.
3464 */
3465 V8_WARN_UNUSED_RESULT Maybe<bool> SetNativeDataProperty(
3466 Local<Context> context, Local<Name> name,
3467 AccessorNameGetterCallback getter,
3468 AccessorNameSetterCallback setter = nullptr,
3469 Local<Value> data = Local<Value>(), PropertyAttribute attributes = None,
3470 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3471
3472 /**
3473 * Attempts to create a property with the given name which behaves like a data
3474 * property, except that the provided getter is invoked (and provided with the
3475 * data value) to supply its value the first time it is read. After the
3476 * property is accessed once, it is replaced with an ordinary data property.
3477 *
3478 * Analogous to Template::SetLazyDataProperty.
3479 */
3480 V8_WARN_UNUSED_RESULT Maybe<bool> SetLazyDataProperty(
3481 Local<Context> context, Local<Name> name,
3482 AccessorNameGetterCallback getter, Local<Value> data = Local<Value>(),
3483 PropertyAttribute attributes = None,
3484 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
3485
3486 /**
3487 * Functionality for private properties.
3488 * This is an experimental feature, use at your own risk.
3489 * Note: Private properties are not inherited. Do not rely on this, since it
3490 * may change.
3491 */
3492 Maybe<bool> HasPrivate(Local<Context> context, Local<Private> key);
3493 Maybe<bool> SetPrivate(Local<Context> context, Local<Private> key,
3494 Local<Value> value);
3495 Maybe<bool> DeletePrivate(Local<Context> context, Local<Private> key);
3496 MaybeLocal<Value> GetPrivate(Local<Context> context, Local<Private> key);
3497
3498 /**
3499 * Returns an array containing the names of the enumerable properties
3500 * of this object, including properties from prototype objects. The
3501 * array returned by this method contains the same values as would
3502 * be enumerated by a for-in statement over this object.
3503 */
3504 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
3505 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
3506 Local<Context> context);
3507 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetPropertyNames(
3508 Local<Context> context, KeyCollectionMode mode,
3509 PropertyFilter property_filter, IndexFilter index_filter,
3510 KeyConversionMode key_conversion = KeyConversionMode::kKeepNumbers);
3511
3512 /**
3513 * This function has the same functionality as GetPropertyNames but
3514 * the returned array doesn't contain the names of properties from
3515 * prototype objects.
3516 */
3517 V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
3518 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
3519 Local<Context> context);
3520
3521 /**
3522 * Returns an array containing the names of the filtered properties
3523 * of this object, including properties from prototype objects. The
3524 * array returned by this method contains the same values as would
3525 * be enumerated by a for-in statement over this object.
3526 */
3527 V8_WARN_UNUSED_RESULT MaybeLocal<Array> GetOwnPropertyNames(
3528 Local<Context> context, PropertyFilter filter,
3529 KeyConversionMode key_conversion = KeyConversionMode::kKeepNumbers);
3530
3531 /**
3532 * Get the prototype object. This does not skip objects marked to
3533 * be skipped by __proto__ and it does not consult the security
3534 * handler.
3535 */
3536 Local<Value> GetPrototype();
3537
3538 /**
3539 * Set the prototype object. This does not skip objects marked to
3540 * be skipped by __proto__ and it does not consult the security
3541 * handler.
3542 */
3543 V8_WARN_UNUSED_RESULT Maybe<bool> SetPrototype(Local<Context> context,
3544 Local<Value> prototype);
3545
3546 /**
3547 * Finds an instance of the given function template in the prototype
3548 * chain.
3549 */
3550 Local<Object> FindInstanceInPrototypeChain(Local<FunctionTemplate> tmpl);
3551
3552 /**
3553 * Call builtin Object.prototype.toString on this object.
3554 * This is different from Value::ToString() that may call
3555 * user-defined toString function. This one does not.
3556 */
3557 V8_WARN_UNUSED_RESULT MaybeLocal<String> ObjectProtoToString(
3558 Local<Context> context);
3559
3560 /**
3561 * Returns the name of the function invoked as a constructor for this object.
3562 */
3563 Local<String> GetConstructorName();
3564
3565 /**
3566 * Sets the integrity level of the object.
3567 */
3568 Maybe<bool> SetIntegrityLevel(Local<Context> context, IntegrityLevel level);
3569
3570 /** Gets the number of internal fields for this Object. */
3571 int InternalFieldCount();
3572
3573 /** Same as above, but works for Persistents */
3574 V8_INLINE static int InternalFieldCount(
3575 const PersistentBase<Object>& object) {
3576 return object.val_->InternalFieldCount();
3577 }
3578
3579 /** Gets the value from an internal field. */
3580 V8_INLINE Local<Value> GetInternalField(int index);
3581
3582 /** Sets the value in an internal field. */
3583 void SetInternalField(int index, Local<Value> value);
3584
3585 /**
3586 * Gets a 2-byte-aligned native pointer from an internal field. This field
3587 * must have been set by SetAlignedPointerInInternalField, everything else
3588 * leads to undefined behavior.
3589 */
3590 V8_INLINE void* GetAlignedPointerFromInternalField(int index);
3591
3592 /** Same as above, but works for Persistents */
3593 V8_INLINE static void* GetAlignedPointerFromInternalField(
3594 const PersistentBase<Object>& object, int index) {
3595 return object.val_->GetAlignedPointerFromInternalField(index);
3596 }
3597
3598 /**
3599 * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
3600 * a field, GetAlignedPointerFromInternalField must be used, everything else
3601 * leads to undefined behavior.
3602 */
3603 void SetAlignedPointerInInternalField(int index, void* value);
3604 void SetAlignedPointerInInternalFields(int argc, int indices[],
3605 void* values[]);
3606
3607 /**
3608 * HasOwnProperty() is like JavaScript's Object.prototype.hasOwnProperty().
3609 *
3610 * See also v8::Object::Has() and v8::Object::HasRealNamedProperty().
3611 */
3612 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
3613 Local<Name> key);
3614 V8_WARN_UNUSED_RESULT Maybe<bool> HasOwnProperty(Local<Context> context,
3615 uint32_t index);
3616 V8_DEPRECATE_SOON("Use maybe version",
3617 bool HasRealNamedProperty(Local<String> key));
3618 /**
3619 * Use HasRealNamedProperty() if you want to check if an object has an own
3620 * property without causing side effects, i.e., without calling interceptors.
3621 *
3622 * This function is similar to v8::Object::HasOwnProperty(), but it does not
3623 * call interceptors.
3624 *
3625 * \note Consider using non-masking interceptors, i.e., the interceptors are
3626 * not called if the receiver has the real named property. See
3627 * `v8::PropertyHandlerFlags::kNonMasking`.
3628 *
3629 * See also v8::Object::Has().
3630 */
3631 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedProperty(Local<Context> context,
3632 Local<Name> key);
3633 V8_DEPRECATE_SOON("Use maybe version",
3634 bool HasRealIndexedProperty(uint32_t index));
3635 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealIndexedProperty(
3636 Local<Context> context, uint32_t index);
3637 V8_DEPRECATE_SOON("Use maybe version",
3638 bool HasRealNamedCallbackProperty(Local<String> key));
3639 V8_WARN_UNUSED_RESULT Maybe<bool> HasRealNamedCallbackProperty(
3640 Local<Context> context, Local<Name> key);
3641
3642 /**
3643 * If result.IsEmpty() no real property was located in the prototype chain.
3644 * This means interceptors in the prototype chain are not called.
3645 */
3646 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedPropertyInPrototypeChain(
3647 Local<Context> context, Local<Name> key);
3648
3649 /**
3650 * Gets the property attributes of a real property in the prototype chain,
3651 * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
3652 * Interceptors in the prototype chain are not called.
3653 */
3654 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute>
3655 GetRealNamedPropertyAttributesInPrototypeChain(Local<Context> context,
3656 Local<Name> key);
3657
3658 /**
3659 * If result.IsEmpty() no real property was located on the object or
3660 * in the prototype chain.
3661 * This means interceptors in the prototype chain are not called.
3662 */
3663 V8_WARN_UNUSED_RESULT MaybeLocal<Value> GetRealNamedProperty(
3664 Local<Context> context, Local<Name> key);
3665
3666 /**
3667 * Gets the property attributes of a real property which can be
3668 * None or any combination of ReadOnly, DontEnum and DontDelete.
3669 * Interceptors in the prototype chain are not called.
3670 */
3671 V8_WARN_UNUSED_RESULT Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
3672 Local<Context> context, Local<Name> key);
3673
3674 /** Tests for a named lookup interceptor.*/
3675 bool HasNamedLookupInterceptor();
3676
3677 /** Tests for an index lookup interceptor.*/
3678 bool HasIndexedLookupInterceptor();
3679
3680 /**
3681 * Returns the identity hash for this object. The current implementation
3682 * uses a hidden property on the object to store the identity hash.
3683 *
3684 * The return value will never be 0. Also, it is not guaranteed to be
3685 * unique.
3686 */
3687 int GetIdentityHash();
3688
3689 /**
3690 * Clone this object with a fast but shallow copy. Values will point
3691 * to the same values as the original object.
3692 */
3693 // TODO(dcarney): take an isolate and optionally bail out?
3694 Local<Object> Clone();
3695
3696 /**
3697 * Returns the context in which the object was created.
3698 */
3699 Local<Context> CreationContext();
3700
3701 /** Same as above, but works for Persistents */
3702 V8_INLINE static Local<Context> CreationContext(
3703 const PersistentBase<Object>& object) {
3704 return object.val_->CreationContext();
3705 }
3706
3707 /**
3708 * Checks whether a callback is set by the
3709 * ObjectTemplate::SetCallAsFunctionHandler method.
3710 * When an Object is callable this method returns true.
3711 */
3712 bool IsCallable();
3713
3714 /**
3715 * True if this object is a constructor.
3716 */
3717 bool IsConstructor();
3718
3719 /**
3720 * Call an Object as a function if a callback is set by the
3721 * ObjectTemplate::SetCallAsFunctionHandler method.
3722 */
3723 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsFunction(Local<Context> context,
3724 Local<Value> recv,
3725 int argc,
3726 Local<Value> argv[]);
3727
3728 /**
3729 * Call an Object as a constructor if a callback is set by the
3730 * ObjectTemplate::SetCallAsFunctionHandler method.
3731 * Note: This method behaves like the Function::NewInstance method.
3732 */
3733 V8_WARN_UNUSED_RESULT MaybeLocal<Value> CallAsConstructor(
3734 Local<Context> context, int argc, Local<Value> argv[]);
3735
3736 /**
3737 * Return the isolate to which the Object belongs to.
3738 */
3739 Isolate* GetIsolate();
3740
3741 /**
3742 * If this object is a Set, Map, WeakSet or WeakMap, this returns a
3743 * representation of the elements of this object as an array.
3744 * If this object is a SetIterator or MapIterator, this returns all
3745 * elements of the underlying collection, starting at the iterator's current
3746 * position.
3747 * For other types, this will return an empty MaybeLocal<Array> (without
3748 * scheduling an exception).
3749 */
3750 MaybeLocal<Array> PreviewEntries(bool* is_key_value);
3751
3752 static Local<Object> New(Isolate* isolate);
3753
3754 V8_INLINE static Object* Cast(Value* obj);
3755
3756 private:
3757 Object();
3758 static void CheckCast(Value* obj);
3759 Local<Value> SlowGetInternalField(int index);
3760 void* SlowGetAlignedPointerFromInternalField(int index);
3761 };
3762
3763
3764 /**
3765 * An instance of the built-in array constructor (ECMA-262, 15.4.2).
3766 */
3767 class V8_EXPORT Array : public Object {
3768 public:
3769 uint32_t Length() const;
3770
3771 /**
3772 * Creates a JavaScript array with the given length. If the length
3773 * is negative the returned array will have length 0.
3774 */
3775 static Local<Array> New(Isolate* isolate, int length = 0);
3776
3777 V8_INLINE static Array* Cast(Value* obj);
3778 private:
3779 Array();
3780 static void CheckCast(Value* obj);
3781 };
3782
3783
3784 /**
3785 * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
3786 */
3787 class V8_EXPORT Map : public Object {
3788 public:
3789 size_t Size() const;
3790 void Clear();
3791 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Get(Local<Context> context,
3792 Local<Value> key);
3793 V8_WARN_UNUSED_RESULT MaybeLocal<Map> Set(Local<Context> context,
3794 Local<Value> key,
3795 Local<Value> value);
3796 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3797 Local<Value> key);
3798 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3799 Local<Value> key);
3800
3801 /**
3802 * Returns an array of length Size() * 2, where index N is the Nth key and
3803 * index N + 1 is the Nth value.
3804 */
3805 Local<Array> AsArray() const;
3806
3807 /**
3808 * Creates a new empty Map.
3809 */
3810 static Local<Map> New(Isolate* isolate);
3811
3812 V8_INLINE static Map* Cast(Value* obj);
3813
3814 private:
3815 Map();
3816 static void CheckCast(Value* obj);
3817 };
3818
3819
3820 /**
3821 * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3822 */
3823 class V8_EXPORT Set : public Object {
3824 public:
3825 size_t Size() const;
3826 void Clear();
3827 V8_WARN_UNUSED_RESULT MaybeLocal<Set> Add(Local<Context> context,
3828 Local<Value> key);
3829 V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context,
3830 Local<Value> key);
3831 V8_WARN_UNUSED_RESULT Maybe<bool> Delete(Local<Context> context,
3832 Local<Value> key);
3833
3834 /**
3835 * Returns an array of the keys in this Set.
3836 */
3837 Local<Array> AsArray() const;
3838
3839 /**
3840 * Creates a new empty Set.
3841 */
3842 static Local<Set> New(Isolate* isolate);
3843
3844 V8_INLINE static Set* Cast(Value* obj);
3845
3846 private:
3847 Set();
3848 static void CheckCast(Value* obj);
3849 };
3850
3851
3852 template<typename T>
3853 class ReturnValue {
3854 public:
3855 template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3856 : value_(that.value_) {
3857 TYPE_CHECK(T, S);
3858 }
3859 // Local setters
3860 template <typename S>
3861 V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3862 void Set(const Persistent<S>& handle));
3863 template <typename S>
3864 V8_INLINE void Set(const Global<S>& handle);
3865 template <typename S>
3866 V8_INLINE void Set(const Local<S> handle);
3867 // Fast primitive setters
3868 V8_INLINE void Set(bool value);
3869 V8_INLINE void Set(double i);
3870 V8_INLINE void Set(int32_t i);
3871 V8_INLINE void Set(uint32_t i);
3872 // Fast JS primitive setters
3873 V8_INLINE void SetNull();
3874 V8_INLINE void SetUndefined();
3875 V8_INLINE void SetEmptyString();
3876 // Convenience getter for Isolate
3877 V8_INLINE Isolate* GetIsolate() const;
3878
3879 // Pointer setter: Uncompilable to prevent inadvertent misuse.
3880 template <typename S>
3881 V8_INLINE void Set(S* whatever);
3882
3883 // Getter. Creates a new Local<> so it comes with a certain performance
3884 // hit. If the ReturnValue was not yet set, this will return the undefined
3885 // value.
3886 V8_INLINE Local<Value> Get() const;
3887
3888 private:
3889 template<class F> friend class ReturnValue;
3890 template<class F> friend class FunctionCallbackInfo;
3891 template<class F> friend class PropertyCallbackInfo;
3892 template <class F, class G, class H>
3893 friend class PersistentValueMapBase;
3894 V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3895 V8_INLINE internal::Object* GetDefaultValue();
3896 V8_INLINE explicit ReturnValue(internal::Object** slot);
3897 internal::Object** value_;
3898 };
3899
3900
3901 /**
3902 * The argument information given to function call callbacks. This
3903 * class provides access to information about the context of the call,
3904 * including the receiver, the number and values of arguments, and
3905 * the holder of the function.
3906 */
3907 template<typename T>
3908 class FunctionCallbackInfo {
3909 public:
3910 /** The number of available arguments. */
3911 V8_INLINE int Length() const;
3912 /** Accessor for the available arguments. */
3913 V8_INLINE Local<Value> operator[](int i) const;
3914 /** Returns the receiver. This corresponds to the "this" value. */
3915 V8_INLINE Local<Object> This() const;
3916 /**
3917 * If the callback was created without a Signature, this is the same
3918 * value as This(). If there is a signature, and the signature didn't match
3919 * This() but one of its hidden prototypes, this will be the respective
3920 * hidden prototype.
3921 *
3922 * Note that this is not the prototype of This() on which the accessor
3923 * referencing this callback was found (which in V8 internally is often
3924 * referred to as holder [sic]).
3925 */
3926 V8_INLINE Local<Object> Holder() const;
3927 /** For construct calls, this returns the "new.target" value. */
3928 V8_INLINE Local<Value> NewTarget() const;
3929 /** Indicates whether this is a regular call or a construct call. */
3930 V8_INLINE bool IsConstructCall() const;
3931 /** The data argument specified when creating the callback. */
3932 V8_INLINE Local<Value> Data() const;
3933 /** The current Isolate. */
3934 V8_INLINE Isolate* GetIsolate() const;
3935 /** The ReturnValue for the call. */
3936 V8_INLINE ReturnValue<T> GetReturnValue() const;
3937 // This shouldn't be public, but the arm compiler needs it.
3938 static const int kArgsLength = 6;
3939
3940 protected:
3941 friend class internal::FunctionCallbackArguments;
3942 friend class internal::CustomArguments<FunctionCallbackInfo>;
3943 friend class debug::ConsoleCallArguments;
3944 static const int kHolderIndex = 0;
3945 static const int kIsolateIndex = 1;
3946 static const int kReturnValueDefaultValueIndex = 2;
3947 static const int kReturnValueIndex = 3;
3948 static const int kDataIndex = 4;
3949 static const int kNewTargetIndex = 5;
3950
3951 V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3952 internal::Object** values, int length);
3953 internal::Object** implicit_args_;
3954 internal::Object** values_;
3955 int length_;
3956 };
3957
3958
3959 /**
3960 * The information passed to a property callback about the context
3961 * of the property access.
3962 */
3963 template<typename T>
3964 class PropertyCallbackInfo {
3965 public:
3966 /**
3967 * \return The isolate of the property access.
3968 */
3969 V8_INLINE Isolate* GetIsolate() const;
3970
3971 /**
3972 * \return The data set in the configuration, i.e., in
3973 * `NamedPropertyHandlerConfiguration` or
3974 * `IndexedPropertyHandlerConfiguration.`
3975 */
3976 V8_INLINE Local<Value> Data() const;
3977
3978 /**
3979 * \return The receiver. In many cases, this is the object on which the
3980 * property access was intercepted. When using
3981 * `Reflect.get`, `Function.prototype.call`, or similar functions, it is the
3982 * object passed in as receiver or thisArg.
3983 *
3984 * \code
3985 * void GetterCallback(Local<Name> name,
3986 * const v8::PropertyCallbackInfo<v8::Value>& info) {
3987 * auto context = info.GetIsolate()->GetCurrentContext();
3988 *
3989 * v8::Local<v8::Value> a_this =
3990 * info.This()
3991 * ->GetRealNamedProperty(context, v8_str("a"))
3992 * .ToLocalChecked();
3993 * v8::Local<v8::Value> a_holder =
3994 * info.Holder()
3995 * ->GetRealNamedProperty(context, v8_str("a"))
3996 * .ToLocalChecked();
3997 *
3998 * CHECK(v8_str("r")->Equals(context, a_this).FromJust());
3999 * CHECK(v8_str("obj")->Equals(context, a_holder).FromJust());
4000 *
4001 * info.GetReturnValue().Set(name);
4002 * }
4003 *
4004 * v8::Local<v8::FunctionTemplate> templ =
4005 * v8::FunctionTemplate::New(isolate);
4006 * templ->InstanceTemplate()->SetHandler(
4007 * v8::NamedPropertyHandlerConfiguration(GetterCallback));
4008 * LocalContext env;
4009 * env->Global()
4010 * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
4011 * .ToLocalChecked()
4012 * ->NewInstance(env.local())
4013 * .ToLocalChecked())
4014 * .FromJust();
4015 *
4016 * CompileRun("obj.a = 'obj'; var r = {a: 'r'}; Reflect.get(obj, 'x', r)");
4017 * \endcode
4018 */
4019 V8_INLINE Local<Object> This() const;
4020
4021 /**
4022 * \return The object in the prototype chain of the receiver that has the
4023 * interceptor. Suppose you have `x` and its prototype is `y`, and `y`
4024 * has an interceptor. Then `info.This()` is `x` and `info.Holder()` is `y`.
4025 * The Holder() could be a hidden object (the global object, rather
4026 * than the global proxy).
4027 *
4028 * \note For security reasons, do not pass the object back into the runtime.
4029 */
4030 V8_INLINE Local<Object> Holder() const;
4031
4032 /**
4033 * \return The return value of the callback.
4034 * Can be changed by calling Set().
4035 * \code
4036 * info.GetReturnValue().Set(...)
4037 * \endcode
4038 *
4039 */
4040 V8_INLINE ReturnValue<T> GetReturnValue() const;
4041
4042 /**
4043 * \return True if the intercepted function should throw if an error occurs.
4044 * Usually, `true` corresponds to `'use strict'`.
4045 *
4046 * \note Always `false` when intercepting `Reflect.set()`
4047 * independent of the language mode.
4048 */
4049 V8_INLINE bool ShouldThrowOnError() const;
4050
4051 // This shouldn't be public, but the arm compiler needs it.
4052 static const int kArgsLength = 7;
4053
4054 protected:
4055 friend class MacroAssembler;
4056 friend class internal::PropertyCallbackArguments;
4057 friend class internal::CustomArguments<PropertyCallbackInfo>;
4058 static const int kShouldThrowOnErrorIndex = 0;
4059 static const int kHolderIndex = 1;
4060 static const int kIsolateIndex = 2;
4061 static const int kReturnValueDefaultValueIndex = 3;
4062 static const int kReturnValueIndex = 4;
4063 static const int kDataIndex = 5;
4064 static const int kThisIndex = 6;
4065
4066 V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
4067 internal::Object** args_;
4068 };
4069
4070
4071 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
4072
4073 enum class ConstructorBehavior { kThrow, kAllow };
4074
4075 /**
4076 * A JavaScript function object (ECMA-262, 15.3).
4077 */
4078 class V8_EXPORT Function : public Object {
4079 public:
4080 /**
4081 * Create a function in the current execution context
4082 * for a given FunctionCallback.
4083 */
4084 static MaybeLocal<Function> New(
4085 Local<Context> context, FunctionCallback callback,
4086 Local<Value> data = Local<Value>(), int length = 0,
4087 ConstructorBehavior behavior = ConstructorBehavior::kAllow,
4088 SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
4089 static V8_DEPRECATE_SOON(
4090 "Use maybe version",
4091 Local<Function> New(Isolate* isolate, FunctionCallback callback,
4092 Local<Value> data = Local<Value>(), int length = 0));
4093
4094 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
4095 Local<Context> context, int argc, Local<Value> argv[]) const;
4096
4097 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(
4098 Local<Context> context) const {
4099 return NewInstance(context, 0, nullptr);
4100 }
4101
4102 /**
4103 * When side effect checks are enabled, passing kHasNoSideEffect allows the
4104 * constructor to be invoked without throwing. Calls made within the
4105 * constructor are still checked.
4106 */
4107 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstanceWithSideEffectType(
4108 Local<Context> context, int argc, Local<Value> argv[],
4109 SideEffectType side_effect_type = SideEffectType::kHasSideEffect) const;
4110
4111 V8_DEPRECATE_SOON("Use maybe version",
4112 Local<Value> Call(Local<Value> recv, int argc,
4113 Local<Value> argv[]));
4114 V8_WARN_UNUSED_RESULT MaybeLocal<Value> Call(Local<Context> context,
4115 Local<Value> recv, int argc,
4116 Local<Value> argv[]);
4117
4118 void SetName(Local<String> name);
4119 Local<Value> GetName() const;
4120
4121 /**
4122 * Name inferred from variable or property assignment of this function.
4123 * Used to facilitate debugging and profiling of JavaScript code written
4124 * in an OO style, where many functions are anonymous but are assigned
4125 * to object properties.
4126 */
4127 Local<Value> GetInferredName() const;
4128
4129 /**
4130 * displayName if it is set, otherwise name if it is configured, otherwise
4131 * function name, otherwise inferred name.
4132 */
4133 Local<Value> GetDebugName() const;
4134
4135 /**
4136 * User-defined name assigned to the "displayName" property of this function.
4137 * Used to facilitate debugging and profiling of JavaScript code.
4138 */
4139 Local<Value> GetDisplayName() const;
4140
4141 /**
4142 * Returns zero based line number of function body and
4143 * kLineOffsetNotFound if no information available.
4144 */
4145 int GetScriptLineNumber() const;
4146 /**
4147 * Returns zero based column number of function body and
4148 * kLineOffsetNotFound if no information available.
4149 */
4150 int GetScriptColumnNumber() const;
4151
4152 /**
4153 * Returns scriptId.
4154 */
4155 int ScriptId() const;
4156
4157 /**
4158 * Returns the original function if this function is bound, else returns
4159 * v8::Undefined.
4160 */
4161 Local<Value> GetBoundFunction() const;
4162
4163 ScriptOrigin GetScriptOrigin() const;
4164 V8_INLINE static Function* Cast(Value* obj);
4165 static const int kLineOffsetNotFound;
4166
4167 private:
4168 Function();
4169 static void CheckCast(Value* obj);
4170 };
4171
4172 #ifndef V8_PROMISE_INTERNAL_FIELD_COUNT
4173 // The number of required internal fields can be defined by embedder.
4174 #define V8_PROMISE_INTERNAL_FIELD_COUNT 0
4175 #endif
4176
4177 /**
4178 * An instance of the built-in Promise constructor (ES6 draft).
4179 */
4180 class V8_EXPORT Promise : public Object {
4181 public:
4182 /**
4183 * State of the promise. Each value corresponds to one of the possible values
4184 * of the [[PromiseState]] field.
4185 */
4186 enum PromiseState { kPending, kFulfilled, kRejected };
4187
4188 class V8_EXPORT Resolver : public Object {
4189 public:
4190 /**
4191 * Create a new resolver, along with an associated promise in pending state.
4192 */
4193 static V8_WARN_UNUSED_RESULT MaybeLocal<Resolver> New(
4194 Local<Context> context);
4195
4196 /**
4197 * Extract the associated promise.
4198 */
4199 Local<Promise> GetPromise();
4200
4201 /**
4202 * Resolve/reject the associated promise with a given value.
4203 * Ignored if the promise is no longer pending.
4204 */
4205 V8_WARN_UNUSED_RESULT Maybe<bool> Resolve(Local<Context> context,
4206 Local<Value> value);
4207
4208 V8_WARN_UNUSED_RESULT Maybe<bool> Reject(Local<Context> context,
4209 Local<Value> value);
4210
4211 V8_INLINE static Resolver* Cast(Value* obj);
4212
4213 private:
4214 Resolver();
4215 static void CheckCast(Value* obj);
4216 };
4217
4218 /**
4219 * Register a resolution/rejection handler with a promise.
4220 * The handler is given the respective resolution/rejection value as
4221 * an argument. If the promise is already resolved/rejected, the handler is
4222 * invoked at the end of turn.
4223 */
4224 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Catch(Local<Context> context,
4225 Local<Function> handler);
4226
4227 V8_WARN_UNUSED_RESULT MaybeLocal<Promise> Then(Local<Context> context,
4228 Local<Function> handler);
4229
4230 /**
4231 * Returns true if the promise has at least one derived promise, and
4232 * therefore resolve/reject handlers (including default handler).
4233 */
4234 bool HasHandler();
4235
4236 /**
4237 * Returns the content of the [[PromiseResult]] field. The Promise must not
4238 * be pending.
4239 */
4240 Local<Value> Result();
4241
4242 /**
4243 * Returns the value of the [[PromiseState]] field.
4244 */
4245 PromiseState State();
4246
4247 V8_INLINE static Promise* Cast(Value* obj);
4248
4249 static const int kEmbedderFieldCount = V8_PROMISE_INTERNAL_FIELD_COUNT;
4250
4251 private:
4252 Promise();
4253 static void CheckCast(Value* obj);
4254 };
4255
4256 /**
4257 * An instance of a Property Descriptor, see Ecma-262 6.2.4.
4258 *
4259 * Properties in a descriptor are present or absent. If you do not set
4260 * `enumerable`, `configurable`, and `writable`, they are absent. If `value`,
4261 * `get`, or `set` are absent, but you must specify them in the constructor, use
4262 * empty handles.
4263 *
4264 * Accessors `get` and `set` must be callable or undefined if they are present.
4265 *
4266 * \note Only query properties if they are present, i.e., call `x()` only if
4267 * `has_x()` returns true.
4268 *
4269 * \code
4270 * // var desc = {writable: false}
4271 * v8::PropertyDescriptor d(Local<Value>()), false);
4272 * d.value(); // error, value not set
4273 * if (d.has_writable()) {
4274 * d.writable(); // false
4275 * }
4276 *
4277 * // var desc = {value: undefined}
4278 * v8::PropertyDescriptor d(v8::Undefined(isolate));
4279 *
4280 * // var desc = {get: undefined}
4281 * v8::PropertyDescriptor d(v8::Undefined(isolate), Local<Value>()));
4282 * \endcode
4283 */
4284 class V8_EXPORT PropertyDescriptor {
4285 public:
4286 // GenericDescriptor
4287 PropertyDescriptor();
4288
4289 // DataDescriptor
4290 PropertyDescriptor(Local<Value> value);
4291
4292 // DataDescriptor with writable property
4293 PropertyDescriptor(Local<Value> value, bool writable);
4294
4295 // AccessorDescriptor
4296 PropertyDescriptor(Local<Value> get, Local<Value> set);
4297
4298 ~PropertyDescriptor();
4299
4300 Local<Value> value() const;
4301 bool has_value() const;
4302
4303 Local<Value> get() const;
4304 bool has_get() const;
4305 Local<Value> set() const;
4306 bool has_set() const;
4307
4308 void set_enumerable(bool enumerable);
4309 bool enumerable() const;
4310 bool has_enumerable() const;
4311
4312 void set_configurable(bool configurable);
4313 bool configurable() const;
4314 bool has_configurable() const;
4315
4316 bool writable() const;
4317 bool has_writable() const;
4318
4319 struct PrivateData;
4320 PrivateData* get_private() const { return private_; }
4321
4322 PropertyDescriptor(const PropertyDescriptor&) = delete;
4323 void operator=(const PropertyDescriptor&) = delete;
4324
4325 private:
4326 PrivateData* private_;
4327 };
4328
4329 /**
4330 * An instance of the built-in Proxy constructor (ECMA-262, 6th Edition,
4331 * 26.2.1).
4332 */
4333 class V8_EXPORT Proxy : public Object {
4334 public:
4335 Local<Value> GetTarget();
4336 Local<Value> GetHandler();
4337 bool IsRevoked();
4338 void Revoke();
4339
4340 /**
4341 * Creates a new Proxy for the target object.
4342 */
4343 static MaybeLocal<Proxy> New(Local<Context> context,
4344 Local<Object> local_target,
4345 Local<Object> local_handler);
4346
4347 V8_INLINE static Proxy* Cast(Value* obj);
4348
4349 private:
4350 Proxy();
4351 static void CheckCast(Value* obj);
4352 };
4353
4354 // TODO(mtrofin): rename WasmCompiledModule to WasmModuleObject, for
4355 // consistency with internal APIs.
4356 class V8_EXPORT WasmCompiledModule : public Object {
4357 public:
4358 typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> SerializedModule;
4359
4360 // The COMMA macro allows us to use ',' inside of the V8_DEPRECATED macro.
4361 #define COMMA ,
4362 V8_DEPRECATED(
4363 "Use BufferReference.",
4364 typedef std::pair<const uint8_t * COMMA size_t> CallerOwnedBuffer);
4365 #undef COMMA
4366
4367 /**
4368 * A unowned reference to a byte buffer.
4369 */
4370 struct BufferReference {
4371 const uint8_t* start;
4372 size_t size;
4373 BufferReference(const uint8_t* start, size_t size)
4374 : start(start), size(size) {}
4375 // Temporarily allow conversion to and from CallerOwnedBuffer.
4376 V8_DEPRECATED(
4377 "Use BufferReference directly.",
4378 inline BufferReference(CallerOwnedBuffer)); // NOLINT(runtime/explicit)
4379 V8_DEPRECATED("Use BufferReference directly.",
4380 inline operator CallerOwnedBuffer());
4381 };
4382
4383 /**
4384 * An opaque, native heap object for transferring wasm modules. It
4385 * supports move semantics, and does not support copy semantics.
4386 */
4387 class TransferrableModule final {
4388 public:
4389 TransferrableModule(TransferrableModule&& src) = default;
4390 TransferrableModule(const TransferrableModule& src) = delete;
4391
4392 TransferrableModule& operator=(TransferrableModule&& src) = default;
4393 TransferrableModule& operator=(const TransferrableModule& src) = delete;
4394
4395 private:
4396 typedef std::shared_ptr<internal::wasm::NativeModule> SharedModule;
4397 typedef std::pair<std::unique_ptr<const uint8_t[]>, size_t> OwnedBuffer;
4398 friend class WasmCompiledModule;
4399 explicit TransferrableModule(SharedModule shared_module)
4400 : shared_module_(std::move(shared_module)) {}
4401 TransferrableModule(OwnedBuffer serialized, OwnedBuffer bytes)
4402 : serialized_(std::move(serialized)), wire_bytes_(std::move(bytes)) {}
4403
4404 SharedModule shared_module_;
4405 OwnedBuffer serialized_ = {nullptr, 0};
4406 OwnedBuffer wire_bytes_ = {nullptr, 0};
4407 };
4408
4409 /**
4410 * Get an in-memory, non-persistable, and context-independent (meaning,
4411 * suitable for transfer to another Isolate and Context) representation
4412 * of this wasm compiled module.
4413 */
4414 TransferrableModule GetTransferrableModule();
4415
4416 /**
4417 * Efficiently re-create a WasmCompiledModule, without recompiling, from
4418 * a TransferrableModule.
4419 */
4420 static MaybeLocal<WasmCompiledModule> FromTransferrableModule(
4421 Isolate* isolate, const TransferrableModule&);
4422
4423 /**
4424 * Get the wasm-encoded bytes that were used to compile this module.
4425 */
4426 BufferReference GetWasmWireBytesRef();
4427 V8_DEPRECATED("Use GetWasmWireBytesRef version.",
4428 Local<String> GetWasmWireBytes());
4429
4430 /**
4431 * Serialize the compiled module. The serialized data does not include the
4432 * uncompiled bytes.
4433 */
4434 SerializedModule Serialize();
4435
4436 /**
4437 * If possible, deserialize the module, otherwise compile it from the provided
4438 * uncompiled bytes.
4439 */
4440 static MaybeLocal<WasmCompiledModule> DeserializeOrCompile(
4441 Isolate* isolate, BufferReference serialized_module,
4442 BufferReference wire_bytes);
4443 V8_INLINE static WasmCompiledModule* Cast(Value* obj);
4444
4445 private:
4446 static MaybeLocal<WasmCompiledModule> Deserialize(
4447 Isolate* isolate, BufferReference serialized_module,
4448 BufferReference wire_bytes);
4449 static MaybeLocal<WasmCompiledModule> Compile(Isolate* isolate,
4450 const uint8_t* start,
4451 size_t length);
4452 static BufferReference AsReference(
4453 const TransferrableModule::OwnedBuffer& buff) {
4454 return {buff.first.get(), buff.second};
4455 }
4456
4457 WasmCompiledModule();
4458 static void CheckCast(Value* obj);
4459 };
4460
4461 // TODO(clemensh): Remove after M70 branch.
4462 WasmCompiledModule::BufferReference::BufferReference(
4463 WasmCompiledModule::CallerOwnedBuffer buf)
4464 : BufferReference(buf.first, buf.second) {}
4465 WasmCompiledModule::BufferReference::
4466 operator WasmCompiledModule::CallerOwnedBuffer() {
4467 return {start, size};
4468 }
4469
4470 /**
4471 * The V8 interface for WebAssembly streaming compilation. When streaming
4472 * compilation is initiated, V8 passes a {WasmStreaming} object to the embedder
4473 * such that the embedder can pass the input butes for streaming compilation to
4474 * V8.
4475 */
4476 class V8_EXPORT WasmStreaming final {
4477 public:
4478 class WasmStreamingImpl;
4479
4480 WasmStreaming(std::unique_ptr<WasmStreamingImpl> impl);
4481
4482 ~WasmStreaming();
4483
4484 /**
4485 * Pass a new chunck of bytes to WebAssembly streaming compilation.
4486 * The buffer passed into {OnBytesReceived} is owned by the caller.
4487 */
4488 void OnBytesReceived(const uint8_t* bytes, size_t size);
4489
4490 /**
4491 * {Finish} should be called after all received bytes where passed to
4492 * {OnBytesReceived} to tell V8 that there will be no more bytes. {Finish}
4493 * does not have to be called after {Abort} has been called already.
4494 */
4495 void Finish();
4496
4497 /**
4498 * Abort streaming compilation. If {exception} has a value, then the promise
4499 * associated with streaming compilation is rejected with that value. If
4500 * {exception} does not have value, the promise does not get rejected.
4501 */
4502 void Abort(MaybeLocal<Value> exception);
4503
4504 /**
4505 * Unpacks a {WasmStreaming} object wrapped in a {Managed} for the embedder.
4506 * Since the embedder is on the other side of the API, it cannot unpack the
4507 * {Managed} itself.
4508 */
4509 static std::shared_ptr<WasmStreaming> Unpack(Isolate* isolate,
4510 Local<Value> value);
4511
4512 private:
4513 std::unique_ptr<WasmStreamingImpl> impl_;
4514 };
4515
4516 // TODO(mtrofin): when streaming compilation is done, we can rename this
4517 // to simply WasmModuleObjectBuilder
4518 class V8_EXPORT WasmModuleObjectBuilderStreaming final {
4519 public:
4520 explicit WasmModuleObjectBuilderStreaming(Isolate* isolate);
4521 /**
4522 * The buffer passed into OnBytesReceived is owned by the caller.
4523 */
4524 void OnBytesReceived(const uint8_t*, size_t size);
4525 void Finish();
4526 /**
4527 * Abort streaming compilation. If {exception} has a value, then the promise
4528 * associated with streaming compilation is rejected with that value. If
4529 * {exception} does not have value, the promise does not get rejected.
4530 */
4531 void Abort(MaybeLocal<Value> exception);
4532 Local<Promise> GetPromise();
4533
4534 ~WasmModuleObjectBuilderStreaming();
4535
4536 private:
4537 WasmModuleObjectBuilderStreaming(const WasmModuleObjectBuilderStreaming&) =
4538 delete;
4539 WasmModuleObjectBuilderStreaming(WasmModuleObjectBuilderStreaming&&) =
4540 default;
4541 WasmModuleObjectBuilderStreaming& operator=(
4542 const WasmModuleObjectBuilderStreaming&) = delete;
4543 WasmModuleObjectBuilderStreaming& operator=(
4544 WasmModuleObjectBuilderStreaming&&) = default;
4545 Isolate* isolate_ = nullptr;
4546
4547 #if V8_CC_MSVC
4548 /**
4549 * We don't need the static Copy API, so the default
4550 * NonCopyablePersistentTraits would be sufficient, however,
4551 * MSVC eagerly instantiates the Copy.
4552 * We ensure we don't use Copy, however, by compiling with the
4553 * defaults everywhere else.
4554 */
4555 Persistent<Promise, CopyablePersistentTraits<Promise>> promise_;
4556 #else
4557 Persistent<Promise> promise_;
4558 #endif
4559 std::shared_ptr<internal::wasm::StreamingDecoder> streaming_decoder_;
4560 };
4561
4562 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
4563 // The number of required internal fields can be defined by embedder.
4564 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
4565 #endif
4566
4567
4568 enum class ArrayBufferCreationMode { kInternalized, kExternalized };
4569
4570
4571 /**
4572 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
4573 */
4574 class V8_EXPORT ArrayBuffer : public Object {
4575 public:
4576 /**
4577 * A thread-safe allocator that V8 uses to allocate |ArrayBuffer|'s memory.
4578 * The allocator is a global V8 setting. It has to be set via
4579 * Isolate::CreateParams.
4580 *
4581 * Memory allocated through this allocator by V8 is accounted for as external
4582 * memory by V8. Note that V8 keeps track of the memory for all internalized
4583 * |ArrayBuffer|s. Responsibility for tracking external memory (using
4584 * Isolate::AdjustAmountOfExternalAllocatedMemory) is handed over to the
4585 * embedder upon externalization and taken over upon internalization (creating
4586 * an internalized buffer from an existing buffer).
4587 *
4588 * Note that it is unsafe to call back into V8 from any of the allocator
4589 * functions.
4590 */
4591 class V8_EXPORT Allocator { // NOLINT
4592 public:
4593 virtual ~Allocator() {}
4594
4595 /**
4596 * Allocate |length| bytes. Return NULL if allocation is not successful.
4597 * Memory should be initialized to zeroes.
4598 */
4599 virtual void* Allocate(size_t length) = 0;
4600
4601 /**
4602 * Allocate |length| bytes. Return NULL if allocation is not successful.
4603 * Memory does not have to be initialized.
4604 */
4605 virtual void* AllocateUninitialized(size_t length) = 0;
4606
4607 /**
4608 * Free the memory block of size |length|, pointed to by |data|.
4609 * That memory is guaranteed to be previously allocated by |Allocate|.
4610 */
4611 virtual void Free(void* data, size_t length) = 0;
4612
4613 /**
4614 * ArrayBuffer allocation mode. kNormal is a malloc/free style allocation,
4615 * while kReservation is for larger allocations with the ability to set
4616 * access permissions.
4617 */
4618 enum class AllocationMode { kNormal, kReservation };
4619
4620 /**
4621 * malloc/free based convenience allocator.
4622 *
4623 * Caller takes ownership, i.e. the returned object needs to be freed using
4624 * |delete allocator| once it is no longer in use.
4625 */
4626 static Allocator* NewDefaultAllocator();
4627 };
4628
4629 /**
4630 * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
4631 * returns an instance of this class, populated, with a pointer to data
4632 * and byte length.
4633 *
4634 * The Data pointer of ArrayBuffer::Contents must be freed using the provided
4635 * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
4636 * was allocated with ArraryBuffer::Allocator::Allocate.
4637 */
4638 class V8_EXPORT Contents { // NOLINT
4639 public:
4640 using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
4641
4642 Contents()
4643 : data_(nullptr),
4644 byte_length_(0),
4645 allocation_base_(nullptr),
4646 allocation_length_(0),
4647 allocation_mode_(Allocator::AllocationMode::kNormal),
4648 deleter_(nullptr),
4649 deleter_data_(nullptr) {}
4650
4651 void* AllocationBase() const { return allocation_base_; }
4652 size_t AllocationLength() const { return allocation_length_; }
4653 Allocator::AllocationMode AllocationMode() const {
4654 return allocation_mode_;
4655 }
4656
4657 void* Data() const { return data_; }
4658 size_t ByteLength() const { return byte_length_; }
4659 DeleterCallback Deleter() const { return deleter_; }
4660 void* DeleterData() const { return deleter_data_; }
4661
4662 private:
4663 Contents(void* data, size_t byte_length, void* allocation_base,
4664 size_t allocation_length,
4665 Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
4666 void* deleter_data);
4667
4668 void* data_;
4669 size_t byte_length_;
4670 void* allocation_base_;
4671 size_t allocation_length_;
4672 Allocator::AllocationMode allocation_mode_;
4673 DeleterCallback deleter_;
4674 void* deleter_data_;
4675
4676 friend class ArrayBuffer;
4677 };
4678
4679
4680 /**
4681 * Data length in bytes.
4682 */
4683 size_t ByteLength() const;
4684
4685 /**
4686 * Create a new ArrayBuffer. Allocate |byte_length| bytes.
4687 * Allocated memory will be owned by a created ArrayBuffer and
4688 * will be deallocated when it is garbage-collected,
4689 * unless the object is externalized.
4690 */
4691 static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
4692
4693 /**
4694 * Create a new ArrayBuffer over an existing memory block.
4695 * The created array buffer is by default immediately in externalized state.
4696 * In externalized state, the memory block will not be reclaimed when a
4697 * created ArrayBuffer is garbage-collected.
4698 * In internalized state, the memory block will be released using
4699 * |Allocator::Free| once all ArrayBuffers referencing it are collected by
4700 * the garbage collector.
4701 */
4702 static Local<ArrayBuffer> New(
4703 Isolate* isolate, void* data, size_t byte_length,
4704 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
4705
4706 /**
4707 * Returns true if ArrayBuffer is externalized, that is, does not
4708 * own its memory block.
4709 */
4710 bool IsExternal() const;
4711
4712 /**
4713 * Returns true if this ArrayBuffer may be neutered.
4714 */
4715 bool IsNeuterable() const;
4716
4717 /**
4718 * Neuters this ArrayBuffer and all its views (typed arrays).
4719 * Neutering sets the byte length of the buffer and all typed arrays to zero,
4720 * preventing JavaScript from ever accessing underlying backing store.
4721 * ArrayBuffer should have been externalized and must be neuterable.
4722 */
4723 void Neuter();
4724
4725 /**
4726 * Make this ArrayBuffer external. The pointer to underlying memory block
4727 * and byte length are returned as |Contents| structure. After ArrayBuffer
4728 * had been externalized, it does no longer own the memory block. The caller
4729 * should take steps to free memory when it is no longer needed.
4730 *
4731 * The Data pointer of ArrayBuffer::Contents must be freed using the provided
4732 * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
4733 * was allocated with ArraryBuffer::Allocator::Allocate.
4734 */
4735 Contents Externalize();
4736
4737 /**
4738 * Get a pointer to the ArrayBuffer's underlying memory block without
4739 * externalizing it. If the ArrayBuffer is not externalized, this pointer
4740 * will become invalid as soon as the ArrayBuffer gets garbage collected.
4741 *
4742 * The embedder should make sure to hold a strong reference to the
4743 * ArrayBuffer while accessing this pointer.
4744 */
4745 Contents GetContents();
4746
4747 V8_INLINE static ArrayBuffer* Cast(Value* obj);
4748
4749 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
4750 static const int kEmbedderFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
4751
4752 private:
4753 ArrayBuffer();
4754 static void CheckCast(Value* obj);
4755 };
4756
4757
4758 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
4759 // The number of required internal fields can be defined by embedder.
4760 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
4761 #endif
4762
4763
4764 /**
4765 * A base class for an instance of one of "views" over ArrayBuffer,
4766 * including TypedArrays and DataView (ES6 draft 15.13).
4767 */
4768 class V8_EXPORT ArrayBufferView : public Object {
4769 public:
4770 /**
4771 * Returns underlying ArrayBuffer.
4772 */
4773 Local<ArrayBuffer> Buffer();
4774 /**
4775 * Byte offset in |Buffer|.
4776 */
4777 size_t ByteOffset();
4778 /**
4779 * Size of a view in bytes.
4780 */
4781 size_t ByteLength();
4782
4783 /**
4784 * Copy the contents of the ArrayBufferView's buffer to an embedder defined
4785 * memory without additional overhead that calling ArrayBufferView::Buffer
4786 * might incur.
4787 *
4788 * Will write at most min(|byte_length|, ByteLength) bytes starting at
4789 * ByteOffset of the underlying buffer to the memory starting at |dest|.
4790 * Returns the number of bytes actually written.
4791 */
4792 size_t CopyContents(void* dest, size_t byte_length);
4793
4794 /**
4795 * Returns true if ArrayBufferView's backing ArrayBuffer has already been
4796 * allocated.
4797 */
4798 bool HasBuffer() const;
4799
4800 V8_INLINE static ArrayBufferView* Cast(Value* obj);
4801
4802 static const int kInternalFieldCount =
4803 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
4804 static const int kEmbedderFieldCount =
4805 V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
4806
4807 private:
4808 ArrayBufferView();
4809 static void CheckCast(Value* obj);
4810 };
4811
4812
4813 /**
4814 * A base class for an instance of TypedArray series of constructors
4815 * (ES6 draft 15.13.6).
4816 */
4817 class V8_EXPORT TypedArray : public ArrayBufferView {
4818 public:
4819 /*
4820 * The largest typed array size that can be constructed using New.
4821 */
4822 static constexpr size_t kMaxLength = internal::kSmiMaxValue;
4823
4824 /**
4825 * Number of elements in this typed array
4826 * (e.g. for Int16Array, |ByteLength|/2).
4827 */
4828 size_t Length();
4829
4830 V8_INLINE static TypedArray* Cast(Value* obj);
4831
4832 private:
4833 TypedArray();
4834 static void CheckCast(Value* obj);
4835 };
4836
4837
4838 /**
4839 * An instance of Uint8Array constructor (ES6 draft 15.13.6).
4840 */
4841 class V8_EXPORT Uint8Array : public TypedArray {
4842 public:
4843 static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
4844 size_t byte_offset, size_t length);
4845 static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4846 size_t byte_offset, size_t length);
4847 V8_INLINE static Uint8Array* Cast(Value* obj);
4848
4849 private:
4850 Uint8Array();
4851 static void CheckCast(Value* obj);
4852 };
4853
4854
4855 /**
4856 * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
4857 */
4858 class V8_EXPORT Uint8ClampedArray : public TypedArray {
4859 public:
4860 static Local<Uint8ClampedArray> New(Local<ArrayBuffer> array_buffer,
4861 size_t byte_offset, size_t length);
4862 static Local<Uint8ClampedArray> New(
4863 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
4864 size_t length);
4865 V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
4866
4867 private:
4868 Uint8ClampedArray();
4869 static void CheckCast(Value* obj);
4870 };
4871
4872 /**
4873 * An instance of Int8Array constructor (ES6 draft 15.13.6).
4874 */
4875 class V8_EXPORT Int8Array : public TypedArray {
4876 public:
4877 static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
4878 size_t byte_offset, size_t length);
4879 static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4880 size_t byte_offset, size_t length);
4881 V8_INLINE static Int8Array* Cast(Value* obj);
4882
4883 private:
4884 Int8Array();
4885 static void CheckCast(Value* obj);
4886 };
4887
4888
4889 /**
4890 * An instance of Uint16Array constructor (ES6 draft 15.13.6).
4891 */
4892 class V8_EXPORT Uint16Array : public TypedArray {
4893 public:
4894 static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
4895 size_t byte_offset, size_t length);
4896 static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4897 size_t byte_offset, size_t length);
4898 V8_INLINE static Uint16Array* Cast(Value* obj);
4899
4900 private:
4901 Uint16Array();
4902 static void CheckCast(Value* obj);
4903 };
4904
4905
4906 /**
4907 * An instance of Int16Array constructor (ES6 draft 15.13.6).
4908 */
4909 class V8_EXPORT Int16Array : public TypedArray {
4910 public:
4911 static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
4912 size_t byte_offset, size_t length);
4913 static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4914 size_t byte_offset, size_t length);
4915 V8_INLINE static Int16Array* Cast(Value* obj);
4916
4917 private:
4918 Int16Array();
4919 static void CheckCast(Value* obj);
4920 };
4921
4922
4923 /**
4924 * An instance of Uint32Array constructor (ES6 draft 15.13.6).
4925 */
4926 class V8_EXPORT Uint32Array : public TypedArray {
4927 public:
4928 static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
4929 size_t byte_offset, size_t length);
4930 static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4931 size_t byte_offset, size_t length);
4932 V8_INLINE static Uint32Array* Cast(Value* obj);
4933
4934 private:
4935 Uint32Array();
4936 static void CheckCast(Value* obj);
4937 };
4938
4939
4940 /**
4941 * An instance of Int32Array constructor (ES6 draft 15.13.6).
4942 */
4943 class V8_EXPORT Int32Array : public TypedArray {
4944 public:
4945 static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
4946 size_t byte_offset, size_t length);
4947 static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4948 size_t byte_offset, size_t length);
4949 V8_INLINE static Int32Array* Cast(Value* obj);
4950
4951 private:
4952 Int32Array();
4953 static void CheckCast(Value* obj);
4954 };
4955
4956
4957 /**
4958 * An instance of Float32Array constructor (ES6 draft 15.13.6).
4959 */
4960 class V8_EXPORT Float32Array : public TypedArray {
4961 public:
4962 static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
4963 size_t byte_offset, size_t length);
4964 static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4965 size_t byte_offset, size_t length);
4966 V8_INLINE static Float32Array* Cast(Value* obj);
4967
4968 private:
4969 Float32Array();
4970 static void CheckCast(Value* obj);
4971 };
4972
4973
4974 /**
4975 * An instance of Float64Array constructor (ES6 draft 15.13.6).
4976 */
4977 class V8_EXPORT Float64Array : public TypedArray {
4978 public:
4979 static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
4980 size_t byte_offset, size_t length);
4981 static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4982 size_t byte_offset, size_t length);
4983 V8_INLINE static Float64Array* Cast(Value* obj);
4984
4985 private:
4986 Float64Array();
4987 static void CheckCast(Value* obj);
4988 };
4989
4990 /**
4991 * An instance of BigInt64Array constructor.
4992 */
4993 class V8_EXPORT BigInt64Array : public TypedArray {
4994 public:
4995 static Local<BigInt64Array> New(Local<ArrayBuffer> array_buffer,
4996 size_t byte_offset, size_t length);
4997 static Local<BigInt64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
4998 size_t byte_offset, size_t length);
4999 V8_INLINE static BigInt64Array* Cast(Value* obj);
5000
5001 private:
5002 BigInt64Array();
5003 static void CheckCast(Value* obj);
5004 };
5005
5006 /**
5007 * An instance of BigUint64Array constructor.
5008 */
5009 class V8_EXPORT BigUint64Array : public TypedArray {
5010 public:
5011 static Local<BigUint64Array> New(Local<ArrayBuffer> array_buffer,
5012 size_t byte_offset, size_t length);
5013 static Local<BigUint64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
5014 size_t byte_offset, size_t length);
5015 V8_INLINE static BigUint64Array* Cast(Value* obj);
5016
5017 private:
5018 BigUint64Array();
5019 static void CheckCast(Value* obj);
5020 };
5021
5022 /**
5023 * An instance of DataView constructor (ES6 draft 15.13.7).
5024 */
5025 class V8_EXPORT DataView : public ArrayBufferView {
5026 public:
5027 static Local<DataView> New(Local<ArrayBuffer> array_buffer,
5028 size_t byte_offset, size_t length);
5029 static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
5030 size_t byte_offset, size_t length);
5031 V8_INLINE static DataView* Cast(Value* obj);
5032
5033 private:
5034 DataView();
5035 static void CheckCast(Value* obj);
5036 };
5037
5038
5039 /**
5040 * An instance of the built-in SharedArrayBuffer constructor.
5041 * This API is experimental and may change significantly.
5042 */
5043 class V8_EXPORT SharedArrayBuffer : public Object {
5044 public:
5045 /**
5046 * The contents of an |SharedArrayBuffer|. Externalization of
5047 * |SharedArrayBuffer| returns an instance of this class, populated, with a
5048 * pointer to data and byte length.
5049 *
5050 * The Data pointer of ArrayBuffer::Contents must be freed using the provided
5051 * deleter, which will call ArrayBuffer::Allocator::Free if the buffer
5052 * was allocated with ArraryBuffer::Allocator::Allocate.
5053 *
5054 * This API is experimental and may change significantly.
5055 */
5056 class V8_EXPORT Contents { // NOLINT
5057 public:
5058 using Allocator = v8::ArrayBuffer::Allocator;
5059 using DeleterCallback = void (*)(void* buffer, size_t length, void* info);
5060
5061 Contents()
5062 : data_(nullptr),
5063 byte_length_(0),
5064 allocation_base_(nullptr),
5065 allocation_length_(0),
5066 allocation_mode_(Allocator::AllocationMode::kNormal),
5067 deleter_(nullptr),
5068 deleter_data_(nullptr) {}
5069
5070 void* AllocationBase() const { return allocation_base_; }
5071 size_t AllocationLength() const { return allocation_length_; }
5072 Allocator::AllocationMode AllocationMode() const {
5073 return allocation_mode_;
5074 }
5075
5076 void* Data() const { return data_; }
5077 size_t ByteLength() const { return byte_length_; }
5078 DeleterCallback Deleter() const { return deleter_; }
5079 void* DeleterData() const { return deleter_data_; }
5080
5081 private:
5082 Contents(void* data, size_t byte_length, void* allocation_base,
5083 size_t allocation_length,
5084 Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
5085 void* deleter_data);
5086
5087 void* data_;
5088 size_t byte_length_;
5089 void* allocation_base_;
5090 size_t allocation_length_;
5091 Allocator::AllocationMode allocation_mode_;
5092 DeleterCallback deleter_;
5093 void* deleter_data_;
5094
5095 friend class SharedArrayBuffer;
5096 };
5097
5098 /**
5099 * Data length in bytes.
5100 */
5101 size_t ByteLength() const;
5102
5103 /**
5104 * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
5105 * Allocated memory will be owned by a created SharedArrayBuffer and
5106 * will be deallocated when it is garbage-collected,
5107 * unless the object is externalized.
5108 */
5109 static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
5110
5111 /**
5112 * Create a new SharedArrayBuffer over an existing memory block. The created
5113 * array buffer is immediately in externalized state unless otherwise
5114 * specified. The memory block will not be reclaimed when a created
5115 * SharedArrayBuffer is garbage-collected.
5116 */
5117 static Local<SharedArrayBuffer> New(
5118 Isolate* isolate, void* data, size_t byte_length,
5119 ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
5120
5121 /**
5122 * Returns true if SharedArrayBuffer is externalized, that is, does not
5123 * own its memory block.
5124 */
5125 bool IsExternal() const;
5126
5127 /**
5128 * Make this SharedArrayBuffer external. The pointer to underlying memory
5129 * block and byte length are returned as |Contents| structure. After
5130 * SharedArrayBuffer had been externalized, it does no longer own the memory
5131 * block. The caller should take steps to free memory when it is no longer
5132 * needed.
5133 *
5134 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5135 * by the allocator specified in
5136 * v8::Isolate::CreateParams::array_buffer_allocator.
5137 *
5138 */
5139 Contents Externalize();
5140
5141 /**
5142 * Get a pointer to the ArrayBuffer's underlying memory block without
5143 * externalizing it. If the ArrayBuffer is not externalized, this pointer
5144 * will become invalid as soon as the ArrayBuffer became garbage collected.
5145 *
5146 * The embedder should make sure to hold a strong reference to the
5147 * ArrayBuffer while accessing this pointer.
5148 *
5149 * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5150 * by the allocator specified in
5151 * v8::Isolate::CreateParams::array_buffer_allocator.
5152 */
5153 Contents GetContents();
5154
5155 V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
5156
5157 static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
5158
5159 private:
5160 SharedArrayBuffer();
5161 static void CheckCast(Value* obj);
5162 };
5163
5164
5165 /**
5166 * An instance of the built-in Date constructor (ECMA-262, 15.9).
5167 */
5168 class V8_EXPORT Date : public Object {
5169 public:
5170 static V8_DEPRECATE_SOON("Use maybe version.",
5171 Local<Value> New(Isolate* isolate, double time));
5172 static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
5173 double time);
5174
5175 /**
5176 * A specialization of Value::NumberValue that is more efficient
5177 * because we know the structure of this object.
5178 */
5179 double ValueOf() const;
5180
5181 V8_INLINE static Date* Cast(Value* obj);
5182
5183 /**
5184 * Notification that the embedder has changed the time zone,
5185 * daylight savings time, or other date / time configuration
5186 * parameters. V8 keeps a cache of various values used for
5187 * date / time computation. This notification will reset
5188 * those cached values for the current context so that date /
5189 * time configuration changes would be reflected in the Date
5190 * object.
5191 *
5192 * This API should not be called more than needed as it will
5193 * negatively impact the performance of date operations.
5194 */
5195 static void DateTimeConfigurationChangeNotification(Isolate* isolate);
5196
5197 private:
5198 static void CheckCast(Value* obj);
5199 };
5200
5201
5202 /**
5203 * A Number object (ECMA-262, 4.3.21).
5204 */
5205 class V8_EXPORT NumberObject : public Object {
5206 public:
5207 static Local<Value> New(Isolate* isolate, double value);
5208
5209 double ValueOf() const;
5210
5211 V8_INLINE static NumberObject* Cast(Value* obj);
5212
5213 private:
5214 static void CheckCast(Value* obj);
5215 };
5216
5217 /**
5218 * A BigInt object (https://tc39.github.io/proposal-bigint)
5219 */
5220 class V8_EXPORT BigIntObject : public Object {
5221 public:
5222 static Local<Value> New(Isolate* isolate, int64_t value);
5223
5224 Local<BigInt> ValueOf() const;
5225
5226 V8_INLINE static BigIntObject* Cast(Value* obj);
5227
5228 private:
5229 static void CheckCast(Value* obj);
5230 };
5231
5232 /**
5233 * A Boolean object (ECMA-262, 4.3.15).
5234 */
5235 class V8_EXPORT BooleanObject : public Object {
5236 public:
5237 static Local<Value> New(Isolate* isolate, bool value);
5238
5239 bool ValueOf() const;
5240
5241 V8_INLINE static BooleanObject* Cast(Value* obj);
5242
5243 private:
5244 static void CheckCast(Value* obj);
5245 };
5246
5247
5248 /**
5249 * A String object (ECMA-262, 4.3.18).
5250 */
5251 class V8_EXPORT StringObject : public Object {
5252 public:
5253 static Local<Value> New(Isolate* isolate, Local<String> value);
5254 static V8_DEPRECATED("Use Isolate* version",
5255 Local<Value> New(Local<String> value));
5256
5257 Local<String> ValueOf() const;
5258
5259 V8_INLINE static StringObject* Cast(Value* obj);
5260
5261 private:
5262 static void CheckCast(Value* obj);
5263 };
5264
5265
5266 /**
5267 * A Symbol object (ECMA-262 edition 6).
5268 */
5269 class V8_EXPORT SymbolObject : public Object {
5270 public:
5271 static Local<Value> New(Isolate* isolate, Local<Symbol> value);
5272
5273 Local<Symbol> ValueOf() const;
5274
5275 V8_INLINE static SymbolObject* Cast(Value* obj);
5276
5277 private:
5278 static void CheckCast(Value* obj);
5279 };
5280
5281
5282 /**
5283 * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
5284 */
5285 class V8_EXPORT RegExp : public Object {
5286 public:
5287 /**
5288 * Regular expression flag bits. They can be or'ed to enable a set
5289 * of flags.
5290 */
5291 enum Flags {
5292 kNone = 0,
5293 kGlobal = 1 << 0,
5294 kIgnoreCase = 1 << 1,
5295 kMultiline = 1 << 2,
5296 kSticky = 1 << 3,
5297 kUnicode = 1 << 4,
5298 kDotAll = 1 << 5,
5299 };
5300
5301 /**
5302 * Creates a regular expression from the given pattern string and
5303 * the flags bit field. May throw a JavaScript exception as
5304 * described in ECMA-262, 15.10.4.1.
5305 *
5306 * For example,
5307 * RegExp::New(v8::String::New("foo"),
5308 * static_cast<RegExp::Flags>(kGlobal | kMultiline))
5309 * is equivalent to evaluating "/foo/gm".
5310 */
5311 static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
5312 Local<String> pattern,
5313 Flags flags);
5314
5315 /**
5316 * Returns the value of the source property: a string representing
5317 * the regular expression.
5318 */
5319 Local<String> GetSource() const;
5320
5321 /**
5322 * Returns the flags bit field.
5323 */
5324 Flags GetFlags() const;
5325
5326 V8_INLINE static RegExp* Cast(Value* obj);
5327
5328 private:
5329 static void CheckCast(Value* obj);
5330 };
5331
5332
5333 /**
5334 * A JavaScript value that wraps a C++ void*. This type of value is mainly used
5335 * to associate C++ data structures with JavaScript objects.
5336 */
5337 class V8_EXPORT External : public Value {
5338 public:
5339 static Local<External> New(Isolate* isolate, void* value);
5340 V8_INLINE static External* Cast(Value* obj);
5341 void* Value() const;
5342 private:
5343 static void CheckCast(v8::Value* obj);
5344 };
5345
5346 #define V8_INTRINSICS_LIST(F) \
5347 F(ArrayProto_entries, array_entries_iterator) \
5348 F(ArrayProto_forEach, array_for_each_iterator) \
5349 F(ArrayProto_keys, array_keys_iterator) \
5350 F(ArrayProto_values, array_values_iterator) \
5351 F(ErrorPrototype, initial_error_prototype) \
5352 F(IteratorPrototype, initial_iterator_prototype)
5353
5354 enum Intrinsic {
5355 #define V8_DECL_INTRINSIC(name, iname) k##name,
5356 V8_INTRINSICS_LIST(V8_DECL_INTRINSIC)
5357 #undef V8_DECL_INTRINSIC
5358 };
5359
5360
5361 // --- Templates ---
5362
5363
5364 /**
5365 * The superclass of object and function templates.
5366 */
5367 class V8_EXPORT Template : public Data {
5368 public:
5369 /**
5370 * Adds a property to each instance created by this template.
5371 *
5372 * The property must be defined either as a primitive value, or a template.
5373 */
5374 void Set(Local<Name> name, Local<Data> value,
5375 PropertyAttribute attributes = None);
5376 void SetPrivate(Local<Private> name, Local<Data> value,
5377 PropertyAttribute attributes = None);
5378 V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
5379
5380 void SetAccessorProperty(
5381 Local<Name> name,
5382 Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
5383 Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
5384 PropertyAttribute attribute = None,
5385 AccessControl settings = DEFAULT);
5386
5387 /**
5388 * Whenever the property with the given name is accessed on objects
5389 * created from this Template the getter and setter callbacks
5390 * are called instead of getting and setting the property directly
5391 * on the JavaScript object.
5392 *
5393 * \param name The name of the property for which an accessor is added.
5394 * \param getter The callback to invoke when getting the property.
5395 * \param setter The callback to invoke when setting the property.
5396 * \param data A piece of data that will be passed to the getter and setter
5397 * callbacks whenever they are invoked.
5398 * \param settings Access control settings for the accessor. This is a bit
5399 * field consisting of one of more of
5400 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
5401 * The default is to not allow cross-context access.
5402 * ALL_CAN_READ means that all cross-context reads are allowed.
5403 * ALL_CAN_WRITE means that all cross-context writes are allowed.
5404 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
5405 * cross-context access.
5406 * \param attribute The attributes of the property for which an accessor
5407 * is added.
5408 * \param signature The signature describes valid receivers for the accessor
5409 * and is used to perform implicit instance checks against them. If the
5410 * receiver is incompatible (i.e. is not an instance of the constructor as
5411 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
5412 * thrown and no callback is invoked.
5413 */
5414 void SetNativeDataProperty(
5415 Local<String> name, AccessorGetterCallback getter,
5416 AccessorSetterCallback setter = 0,
5417 // TODO(dcarney): gcc can't handle Local below
5418 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5419 Local<AccessorSignature> signature = Local<AccessorSignature>(),
5420 AccessControl settings = DEFAULT,
5421 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
5422 void SetNativeDataProperty(
5423 Local<Name> name, AccessorNameGetterCallback getter,
5424 AccessorNameSetterCallback setter = 0,
5425 // TODO(dcarney): gcc can't handle Local below
5426 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5427 Local<AccessorSignature> signature = Local<AccessorSignature>(),
5428 AccessControl settings = DEFAULT,
5429 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
5430
5431 /**
5432 * Like SetNativeDataProperty, but V8 will replace the native data property
5433 * with a real data property on first access.
5434 */
5435 void SetLazyDataProperty(
5436 Local<Name> name, AccessorNameGetterCallback getter,
5437 Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5438 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
5439
5440 /**
5441 * During template instantiation, sets the value with the intrinsic property
5442 * from the correct context.
5443 */
5444 void SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
5445 PropertyAttribute attribute = None);
5446
5447 private:
5448 Template();
5449
5450 friend class ObjectTemplate;
5451 friend class FunctionTemplate;
5452 };
5453
5454 // TODO(dcarney): Replace GenericNamedPropertyFooCallback with just
5455 // NamedPropertyFooCallback.
5456
5457 /**
5458 * Interceptor for get requests on an object.
5459 *
5460 * Use `info.GetReturnValue().Set()` to set the return value of the
5461 * intercepted get request.
5462 *
5463 * \param property The name of the property for which the request was
5464 * intercepted.
5465 * \param info Information about the intercepted request, such as
5466 * isolate, receiver, return value, or whether running in `'use strict`' mode.
5467 * See `PropertyCallbackInfo`.
5468 *
5469 * \code
5470 * void GetterCallback(
5471 * Local<Name> name,
5472 * const v8::PropertyCallbackInfo<v8::Value>& info) {
5473 * info.GetReturnValue().Set(v8_num(42));
5474 * }
5475 *
5476 * v8::Local<v8::FunctionTemplate> templ =
5477 * v8::FunctionTemplate::New(isolate);
5478 * templ->InstanceTemplate()->SetHandler(
5479 * v8::NamedPropertyHandlerConfiguration(GetterCallback));
5480 * LocalContext env;
5481 * env->Global()
5482 * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
5483 * .ToLocalChecked()
5484 * ->NewInstance(env.local())
5485 * .ToLocalChecked())
5486 * .FromJust();
5487 * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
5488 * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
5489 * \endcode
5490 *
5491 * See also `ObjectTemplate::SetHandler`.
5492 */
5493 typedef void (*GenericNamedPropertyGetterCallback)(
5494 Local<Name> property, const PropertyCallbackInfo<Value>& info);
5495
5496 /**
5497 * Interceptor for set requests on an object.
5498 *
5499 * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5500 * or not. If the setter successfully intercepts the request, i.e., if the
5501 * request should not be further executed, call
5502 * `info.GetReturnValue().Set(value)`. If the setter
5503 * did not intercept the request, i.e., if the request should be handled as
5504 * if no interceptor is present, do not not call `Set()`.
5505 *
5506 * \param property The name of the property for which the request was
5507 * intercepted.
5508 * \param value The value which the property will have if the request
5509 * is not intercepted.
5510 * \param info Information about the intercepted request, such as
5511 * isolate, receiver, return value, or whether running in `'use strict'` mode.
5512 * See `PropertyCallbackInfo`.
5513 *
5514 * See also
5515 * `ObjectTemplate::SetHandler.`
5516 */
5517 typedef void (*GenericNamedPropertySetterCallback)(
5518 Local<Name> property, Local<Value> value,
5519 const PropertyCallbackInfo<Value>& info);
5520
5521 /**
5522 * Intercepts all requests that query the attributes of the
5523 * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
5524 * defineProperty().
5525 *
5526 * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
5527 * value is an integer encoding a `v8::PropertyAttribute`.
5528 *
5529 * \param property The name of the property for which the request was
5530 * intercepted.
5531 * \param info Information about the intercepted request, such as
5532 * isolate, receiver, return value, or whether running in `'use strict'` mode.
5533 * See `PropertyCallbackInfo`.
5534 *
5535 * \note Some functions query the property attributes internally, even though
5536 * they do not return the attributes. For example, `hasOwnProperty()` can
5537 * trigger this interceptor depending on the state of the object.
5538 *
5539 * See also
5540 * `ObjectTemplate::SetHandler.`
5541 */
5542 typedef void (*GenericNamedPropertyQueryCallback)(
5543 Local<Name> property, const PropertyCallbackInfo<Integer>& info);
5544
5545 /**
5546 * Interceptor for delete requests on an object.
5547 *
5548 * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5549 * or not. If the deleter successfully intercepts the request, i.e., if the
5550 * request should not be further executed, call
5551 * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
5552 * used as the return value of `delete`.
5553 *
5554 * \param property The name of the property for which the request was
5555 * intercepted.
5556 * \param info Information about the intercepted request, such as
5557 * isolate, receiver, return value, or whether running in `'use strict'` mode.
5558 * See `PropertyCallbackInfo`.
5559 *
5560 * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
5561 * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
5562 * if you are in strict mode.
5563 *
5564 * See also `ObjectTemplate::SetHandler.`
5565 */
5566 typedef void (*GenericNamedPropertyDeleterCallback)(
5567 Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
5568
5569 /**
5570 * Returns an array containing the names of the properties the named
5571 * property getter intercepts.
5572 *
5573 * Note: The values in the array must be of type v8::Name.
5574 */
5575 typedef void (*GenericNamedPropertyEnumeratorCallback)(
5576 const PropertyCallbackInfo<Array>& info);
5577
5578 /**
5579 * Interceptor for defineProperty requests on an object.
5580 *
5581 * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5582 * or not. If the definer successfully intercepts the request, i.e., if the
5583 * request should not be further executed, call
5584 * `info.GetReturnValue().Set(value)`. If the definer
5585 * did not intercept the request, i.e., if the request should be handled as
5586 * if no interceptor is present, do not not call `Set()`.
5587 *
5588 * \param property The name of the property for which the request was
5589 * intercepted.
5590 * \param desc The property descriptor which is used to define the
5591 * property if the request is not intercepted.
5592 * \param info Information about the intercepted request, such as
5593 * isolate, receiver, return value, or whether running in `'use strict'` mode.
5594 * See `PropertyCallbackInfo`.
5595 *
5596 * See also `ObjectTemplate::SetHandler`.
5597 */
5598 typedef void (*GenericNamedPropertyDefinerCallback)(
5599 Local<Name> property, const PropertyDescriptor& desc,
5600 const PropertyCallbackInfo<Value>& info);
5601
5602 /**
5603 * Interceptor for getOwnPropertyDescriptor requests on an object.
5604 *
5605 * Use `info.GetReturnValue().Set()` to set the return value of the
5606 * intercepted request. The return value must be an object that
5607 * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
5608 * `v8::Object::getOwnPropertyDescriptor`.
5609 *
5610 * \param property The name of the property for which the request was
5611 * intercepted.
5612 * \info Information about the intercepted request, such as
5613 * isolate, receiver, return value, or whether running in `'use strict'` mode.
5614 * See `PropertyCallbackInfo`.
5615 *
5616 * \note If GetOwnPropertyDescriptor is intercepted, it will
5617 * always return true, i.e., indicate that the property was found.
5618 *
5619 * See also `ObjectTemplate::SetHandler`.
5620 */
5621 typedef void (*GenericNamedPropertyDescriptorCallback)(
5622 Local<Name> property, const PropertyCallbackInfo<Value>& info);
5623
5624 /**
5625 * See `v8::GenericNamedPropertyGetterCallback`.
5626 */
5627 typedef void (*IndexedPropertyGetterCallback)(
5628 uint32_t index,
5629 const PropertyCallbackInfo<Value>& info);
5630
5631 /**
5632 * See `v8::GenericNamedPropertySetterCallback`.
5633 */
5634 typedef void (*IndexedPropertySetterCallback)(
5635 uint32_t index,
5636 Local<Value> value,
5637 const PropertyCallbackInfo<Value>& info);
5638
5639 /**
5640 * See `v8::GenericNamedPropertyQueryCallback`.
5641 */
5642 typedef void (*IndexedPropertyQueryCallback)(
5643 uint32_t index,
5644 const PropertyCallbackInfo<Integer>& info);
5645
5646 /**
5647 * See `v8::GenericNamedPropertyDeleterCallback`.
5648 */
5649 typedef void (*IndexedPropertyDeleterCallback)(
5650 uint32_t index,
5651 const PropertyCallbackInfo<Boolean>& info);
5652
5653 /**
5654 * Returns an array containing the indices of the properties the indexed
5655 * property getter intercepts.
5656 *
5657 * Note: The values in the array must be uint32_t.
5658 */
5659 typedef void (*IndexedPropertyEnumeratorCallback)(
5660 const PropertyCallbackInfo<Array>& info);
5661
5662 /**
5663 * See `v8::GenericNamedPropertyDefinerCallback`.
5664 */
5665 typedef void (*IndexedPropertyDefinerCallback)(
5666 uint32_t index, const PropertyDescriptor& desc,
5667 const PropertyCallbackInfo<Value>& info);
5668
5669 /**
5670 * See `v8::GenericNamedPropertyDescriptorCallback`.
5671 */
5672 typedef void (*IndexedPropertyDescriptorCallback)(
5673 uint32_t index, const PropertyCallbackInfo<Value>& info);
5674
5675 /**
5676 * Access type specification.
5677 */
5678 enum AccessType {
5679 ACCESS_GET,
5680 ACCESS_SET,
5681 ACCESS_HAS,
5682 ACCESS_DELETE,
5683 ACCESS_KEYS
5684 };
5685
5686
5687 /**
5688 * Returns true if the given context should be allowed to access the given
5689 * object.
5690 */
5691 typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
5692 Local<Object> accessed_object,
5693 Local<Value> data);
5694
5695 /**
5696 * A FunctionTemplate is used to create functions at runtime. There
5697 * can only be one function created from a FunctionTemplate in a
5698 * context. The lifetime of the created function is equal to the
5699 * lifetime of the context. So in case the embedder needs to create
5700 * temporary functions that can be collected using Scripts is
5701 * preferred.
5702 *
5703 * Any modification of a FunctionTemplate after first instantiation will trigger
5704 * a crash.
5705 *
5706 * A FunctionTemplate can have properties, these properties are added to the
5707 * function object when it is created.
5708 *
5709 * A FunctionTemplate has a corresponding instance template which is
5710 * used to create object instances when the function is used as a
5711 * constructor. Properties added to the instance template are added to
5712 * each object instance.
5713 *
5714 * A FunctionTemplate can have a prototype template. The prototype template
5715 * is used to create the prototype object of the function.
5716 *
5717 * The following example shows how to use a FunctionTemplate:
5718 *
5719 * \code
5720 * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
5721 * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
5722 *
5723 * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
5724 * proto_t->Set(isolate,
5725 * "proto_method",
5726 * v8::FunctionTemplate::New(isolate, InvokeCallback));
5727 * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
5728 *
5729 * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
5730 * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
5731 * InstanceAccessorCallback);
5732 * instance_t->SetHandler(
5733 * NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
5734 * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
5735 * Number::New(isolate, 3));
5736 *
5737 * v8::Local<v8::Function> function = t->GetFunction();
5738 * v8::Local<v8::Object> instance = function->NewInstance();
5739 * \endcode
5740 *
5741 * Let's use "function" as the JS variable name of the function object
5742 * and "instance" for the instance object created above. The function
5743 * and the instance will have the following properties:
5744 *
5745 * \code
5746 * func_property in function == true;
5747 * function.func_property == 1;
5748 *
5749 * function.prototype.proto_method() invokes 'InvokeCallback'
5750 * function.prototype.proto_const == 2;
5751 *
5752 * instance instanceof function == true;
5753 * instance.instance_accessor calls 'InstanceAccessorCallback'
5754 * instance.instance_property == 3;
5755 * \endcode
5756 *
5757 * A FunctionTemplate can inherit from another one by calling the
5758 * FunctionTemplate::Inherit method. The following graph illustrates
5759 * the semantics of inheritance:
5760 *
5761 * \code
5762 * FunctionTemplate Parent -> Parent() . prototype -> { }
5763 * ^ ^
5764 * | Inherit(Parent) | .__proto__
5765 * | |
5766 * FunctionTemplate Child -> Child() . prototype -> { }
5767 * \endcode
5768 *
5769 * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
5770 * object of the Child() function has __proto__ pointing to the
5771 * Parent() function's prototype object. An instance of the Child
5772 * function has all properties on Parent's instance templates.
5773 *
5774 * Let Parent be the FunctionTemplate initialized in the previous
5775 * section and create a Child FunctionTemplate by:
5776 *
5777 * \code
5778 * Local<FunctionTemplate> parent = t;
5779 * Local<FunctionTemplate> child = FunctionTemplate::New();
5780 * child->Inherit(parent);
5781 *
5782 * Local<Function> child_function = child->GetFunction();
5783 * Local<Object> child_instance = child_function->NewInstance();
5784 * \endcode
5785 *
5786 * The Child function and Child instance will have the following
5787 * properties:
5788 *
5789 * \code
5790 * child_func.prototype.__proto__ == function.prototype;
5791 * child_instance.instance_accessor calls 'InstanceAccessorCallback'
5792 * child_instance.instance_property == 3;
5793 * \endcode
5794 */
5795 class V8_EXPORT FunctionTemplate : public Template {
5796 public:
5797 /** Creates a function template.*/
5798 static Local<FunctionTemplate> New(
5799 Isolate* isolate, FunctionCallback callback = 0,
5800 Local<Value> data = Local<Value>(),
5801 Local<Signature> signature = Local<Signature>(), int length = 0,
5802 ConstructorBehavior behavior = ConstructorBehavior::kAllow,
5803 SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5804
5805 /** Get a template included in the snapshot by index. */
5806 static MaybeLocal<FunctionTemplate> FromSnapshot(Isolate* isolate,
5807 size_t index);
5808
5809 /**
5810 * Creates a function template backed/cached by a private property.
5811 */
5812 static Local<FunctionTemplate> NewWithCache(
5813 Isolate* isolate, FunctionCallback callback,
5814 Local<Private> cache_property, Local<Value> data = Local<Value>(),
5815 Local<Signature> signature = Local<Signature>(), int length = 0,
5816 SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5817
5818 /** Returns the unique function instance in the current execution context.*/
5819 V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
5820 V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
5821 Local<Context> context);
5822
5823 /**
5824 * Similar to Context::NewRemoteContext, this creates an instance that
5825 * isn't backed by an actual object.
5826 *
5827 * The InstanceTemplate of this FunctionTemplate must have access checks with
5828 * handlers installed.
5829 */
5830 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewRemoteInstance();
5831
5832 /**
5833 * Set the call-handler callback for a FunctionTemplate. This
5834 * callback is called whenever the function created from this
5835 * FunctionTemplate is called.
5836 */
5837 void SetCallHandler(
5838 FunctionCallback callback, Local<Value> data = Local<Value>(),
5839 SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5840
5841 /** Set the predefined length property for the FunctionTemplate. */
5842 void SetLength(int length);
5843
5844 /** Get the InstanceTemplate. */
5845 Local<ObjectTemplate> InstanceTemplate();
5846
5847 /**
5848 * Causes the function template to inherit from a parent function template.
5849 * This means the function's prototype.__proto__ is set to the parent
5850 * function's prototype.
5851 **/
5852 void Inherit(Local<FunctionTemplate> parent);
5853
5854 /**
5855 * A PrototypeTemplate is the template used to create the prototype object
5856 * of the function created by this template.
5857 */
5858 Local<ObjectTemplate> PrototypeTemplate();
5859
5860 /**
5861 * A PrototypeProviderTemplate is another function template whose prototype
5862 * property is used for this template. This is mutually exclusive with setting
5863 * a prototype template indirectly by calling PrototypeTemplate() or using
5864 * Inherit().
5865 **/
5866 void SetPrototypeProviderTemplate(Local<FunctionTemplate> prototype_provider);
5867
5868 /**
5869 * Set the class name of the FunctionTemplate. This is used for
5870 * printing objects created with the function created from the
5871 * FunctionTemplate as its constructor.
5872 */
5873 void SetClassName(Local<String> name);
5874
5875
5876 /**
5877 * When set to true, no access check will be performed on the receiver of a
5878 * function call. Currently defaults to true, but this is subject to change.
5879 */
5880 void SetAcceptAnyReceiver(bool value);
5881
5882 /**
5883 * Determines whether the __proto__ accessor ignores instances of
5884 * the function template. If instances of the function template are
5885 * ignored, __proto__ skips all instances and instead returns the
5886 * next object in the prototype chain.
5887 *
5888 * Call with a value of true to make the __proto__ accessor ignore
5889 * instances of the function template. Call with a value of false
5890 * to make the __proto__ accessor not ignore instances of the
5891 * function template. By default, instances of a function template
5892 * are not ignored.
5893 */
5894 void SetHiddenPrototype(bool value);
5895
5896 /**
5897 * Sets the ReadOnly flag in the attributes of the 'prototype' property
5898 * of functions created from this FunctionTemplate to true.
5899 */
5900 void ReadOnlyPrototype();
5901
5902 /**
5903 * Removes the prototype property from functions created from this
5904 * FunctionTemplate.
5905 */
5906 void RemovePrototype();
5907
5908 /**
5909 * Returns true if the given object is an instance of this function
5910 * template.
5911 */
5912 bool HasInstance(Local<Value> object);
5913
5914 V8_INLINE static FunctionTemplate* Cast(Data* data);
5915
5916 private:
5917 FunctionTemplate();
5918
5919 static void CheckCast(Data* that);
5920 friend class Context;
5921 friend class ObjectTemplate;
5922 };
5923
5924 /**
5925 * Configuration flags for v8::NamedPropertyHandlerConfiguration or
5926 * v8::IndexedPropertyHandlerConfiguration.
5927 */
5928 enum class PropertyHandlerFlags {
5929 /**
5930 * None.
5931 */
5932 kNone = 0,
5933
5934 /**
5935 * See ALL_CAN_READ above.
5936 */
5937 kAllCanRead = 1,
5938
5939 /** Will not call into interceptor for properties on the receiver or prototype
5940 * chain, i.e., only call into interceptor for properties that do not exist.
5941 * Currently only valid for named interceptors.
5942 */
5943 kNonMasking = 1 << 1,
5944
5945 /**
5946 * Will not call into interceptor for symbol lookup. Only meaningful for
5947 * named interceptors.
5948 */
5949 kOnlyInterceptStrings = 1 << 2,
5950
5951 /**
5952 * The getter, query, enumerator callbacks do not produce side effects.
5953 */
5954 kHasNoSideEffect = 1 << 3,
5955 };
5956
5957 struct NamedPropertyHandlerConfiguration {
5958 NamedPropertyHandlerConfiguration(
5959 GenericNamedPropertyGetterCallback getter,
5960 GenericNamedPropertySetterCallback setter,
5961 GenericNamedPropertyQueryCallback query,
5962 GenericNamedPropertyDeleterCallback deleter,
5963 GenericNamedPropertyEnumeratorCallback enumerator,
5964 GenericNamedPropertyDefinerCallback definer,
5965 GenericNamedPropertyDescriptorCallback descriptor,
5966 Local<Value> data = Local<Value>(),
5967 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
5968 : getter(getter),
5969 setter(setter),
5970 query(query),
5971 deleter(deleter),
5972 enumerator(enumerator),
5973 definer(definer),
5974 descriptor(descriptor),
5975 data(data),
5976 flags(flags) {}
5977
5978 NamedPropertyHandlerConfiguration(
5979 /** Note: getter is required */
5980 GenericNamedPropertyGetterCallback getter = 0,
5981 GenericNamedPropertySetterCallback setter = 0,
5982 GenericNamedPropertyQueryCallback query = 0,
5983 GenericNamedPropertyDeleterCallback deleter = 0,
5984 GenericNamedPropertyEnumeratorCallback enumerator = 0,
5985 Local<Value> data = Local<Value>(),
5986 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
5987 : getter(getter),
5988 setter(setter),
5989 query(query),
5990 deleter(deleter),
5991 enumerator(enumerator),
5992 definer(0),
5993 descriptor(0),
5994 data(data),
5995 flags(flags) {}
5996
5997 NamedPropertyHandlerConfiguration(
5998 GenericNamedPropertyGetterCallback getter,
5999 GenericNamedPropertySetterCallback setter,
6000 GenericNamedPropertyDescriptorCallback descriptor,
6001 GenericNamedPropertyDeleterCallback deleter,
6002 GenericNamedPropertyEnumeratorCallback enumerator,
6003 GenericNamedPropertyDefinerCallback definer,
6004 Local<Value> data = Local<Value>(),
6005 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6006 : getter(getter),
6007 setter(setter),
6008 query(0),
6009 deleter(deleter),
6010 enumerator(enumerator),
6011 definer(definer),
6012 descriptor(descriptor),
6013 data(data),
6014 flags(flags) {}
6015
6016 GenericNamedPropertyGetterCallback getter;
6017 GenericNamedPropertySetterCallback setter;
6018 GenericNamedPropertyQueryCallback query;
6019 GenericNamedPropertyDeleterCallback deleter;
6020 GenericNamedPropertyEnumeratorCallback enumerator;
6021 GenericNamedPropertyDefinerCallback definer;
6022 GenericNamedPropertyDescriptorCallback descriptor;
6023 Local<Value> data;
6024 PropertyHandlerFlags flags;
6025 };
6026
6027
6028 struct IndexedPropertyHandlerConfiguration {
6029 IndexedPropertyHandlerConfiguration(
6030 IndexedPropertyGetterCallback getter,
6031 IndexedPropertySetterCallback setter, IndexedPropertyQueryCallback query,
6032 IndexedPropertyDeleterCallback deleter,
6033 IndexedPropertyEnumeratorCallback enumerator,
6034 IndexedPropertyDefinerCallback definer,
6035 IndexedPropertyDescriptorCallback descriptor,
6036 Local<Value> data = Local<Value>(),
6037 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6038 : getter(getter),
6039 setter(setter),
6040 query(query),
6041 deleter(deleter),
6042 enumerator(enumerator),
6043 definer(definer),
6044 descriptor(descriptor),
6045 data(data),
6046 flags(flags) {}
6047
6048 IndexedPropertyHandlerConfiguration(
6049 /** Note: getter is required */
6050 IndexedPropertyGetterCallback getter = 0,
6051 IndexedPropertySetterCallback setter = 0,
6052 IndexedPropertyQueryCallback query = 0,
6053 IndexedPropertyDeleterCallback deleter = 0,
6054 IndexedPropertyEnumeratorCallback enumerator = 0,
6055 Local<Value> data = Local<Value>(),
6056 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6057 : getter(getter),
6058 setter(setter),
6059 query(query),
6060 deleter(deleter),
6061 enumerator(enumerator),
6062 definer(0),
6063 descriptor(0),
6064 data(data),
6065 flags(flags) {}
6066
6067 IndexedPropertyHandlerConfiguration(
6068 IndexedPropertyGetterCallback getter,
6069 IndexedPropertySetterCallback setter,
6070 IndexedPropertyDescriptorCallback descriptor,
6071 IndexedPropertyDeleterCallback deleter,
6072 IndexedPropertyEnumeratorCallback enumerator,
6073 IndexedPropertyDefinerCallback definer,
6074 Local<Value> data = Local<Value>(),
6075 PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6076 : getter(getter),
6077 setter(setter),
6078 query(0),
6079 deleter(deleter),
6080 enumerator(enumerator),
6081 definer(definer),
6082 descriptor(descriptor),
6083 data(data),
6084 flags(flags) {}
6085
6086 IndexedPropertyGetterCallback getter;
6087 IndexedPropertySetterCallback setter;
6088 IndexedPropertyQueryCallback query;
6089 IndexedPropertyDeleterCallback deleter;
6090 IndexedPropertyEnumeratorCallback enumerator;
6091 IndexedPropertyDefinerCallback definer;
6092 IndexedPropertyDescriptorCallback descriptor;
6093 Local<Value> data;
6094 PropertyHandlerFlags flags;
6095 };
6096
6097
6098 /**
6099 * An ObjectTemplate is used to create objects at runtime.
6100 *
6101 * Properties added to an ObjectTemplate are added to each object
6102 * created from the ObjectTemplate.
6103 */
6104 class V8_EXPORT ObjectTemplate : public Template {
6105 public:
6106 /** Creates an ObjectTemplate. */
6107 static Local<ObjectTemplate> New(
6108 Isolate* isolate,
6109 Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
6110
6111 /** Get a template included in the snapshot by index. */
6112 static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate,
6113 size_t index);
6114
6115 /** Creates a new instance of this template.*/
6116 V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
6117 V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
6118
6119 /**
6120 * Sets an accessor on the object template.
6121 *
6122 * Whenever the property with the given name is accessed on objects
6123 * created from this ObjectTemplate the getter and setter callbacks
6124 * are called instead of getting and setting the property directly
6125 * on the JavaScript object.
6126 *
6127 * \param name The name of the property for which an accessor is added.
6128 * \param getter The callback to invoke when getting the property.
6129 * \param setter The callback to invoke when setting the property.
6130 * \param data A piece of data that will be passed to the getter and setter
6131 * callbacks whenever they are invoked.
6132 * \param settings Access control settings for the accessor. This is a bit
6133 * field consisting of one of more of
6134 * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6135 * The default is to not allow cross-context access.
6136 * ALL_CAN_READ means that all cross-context reads are allowed.
6137 * ALL_CAN_WRITE means that all cross-context writes are allowed.
6138 * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6139 * cross-context access.
6140 * \param attribute The attributes of the property for which an accessor
6141 * is added.
6142 * \param signature The signature describes valid receivers for the accessor
6143 * and is used to perform implicit instance checks against them. If the
6144 * receiver is incompatible (i.e. is not an instance of the constructor as
6145 * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6146 * thrown and no callback is invoked.
6147 */
6148 void SetAccessor(
6149 Local<String> name, AccessorGetterCallback getter,
6150 AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
6151 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
6152 Local<AccessorSignature> signature = Local<AccessorSignature>(),
6153 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
6154 void SetAccessor(
6155 Local<Name> name, AccessorNameGetterCallback getter,
6156 AccessorNameSetterCallback setter = 0, Local<Value> data = Local<Value>(),
6157 AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
6158 Local<AccessorSignature> signature = Local<AccessorSignature>(),
6159 SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect);
6160
6161 /**
6162 * Sets a named property handler on the object template.
6163 *
6164 * Whenever a property whose name is a string or a symbol is accessed on
6165 * objects created from this object template, the provided callback is
6166 * invoked instead of accessing the property directly on the JavaScript
6167 * object.
6168 *
6169 * @param configuration The NamedPropertyHandlerConfiguration that defines the
6170 * callbacks to invoke when accessing a property.
6171 */
6172 void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
6173
6174 /**
6175 * Sets an indexed property handler on the object template.
6176 *
6177 * Whenever an indexed property is accessed on objects created from
6178 * this object template, the provided callback is invoked instead of
6179 * accessing the property directly on the JavaScript object.
6180 *
6181 * \param getter The callback to invoke when getting a property.
6182 * \param setter The callback to invoke when setting a property.
6183 * \param query The callback to invoke to check if an object has a property.
6184 * \param deleter The callback to invoke when deleting a property.
6185 * \param enumerator The callback to invoke to enumerate all the indexed
6186 * properties of an object.
6187 * \param data A piece of data that will be passed to the callbacks
6188 * whenever they are invoked.
6189 */
6190 // TODO(dcarney): deprecate
6191 void SetIndexedPropertyHandler(
6192 IndexedPropertyGetterCallback getter,
6193 IndexedPropertySetterCallback setter = 0,
6194 IndexedPropertyQueryCallback query = 0,
6195 IndexedPropertyDeleterCallback deleter = 0,
6196 IndexedPropertyEnumeratorCallback enumerator = 0,
6197 Local<Value> data = Local<Value>()) {
6198 SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
6199 deleter, enumerator, data));
6200 }
6201
6202 /**
6203 * Sets an indexed property handler on the object template.
6204 *
6205 * Whenever an indexed property is accessed on objects created from
6206 * this object template, the provided callback is invoked instead of
6207 * accessing the property directly on the JavaScript object.
6208 *
6209 * @param configuration The IndexedPropertyHandlerConfiguration that defines
6210 * the callbacks to invoke when accessing a property.
6211 */
6212 void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
6213
6214 /**
6215 * Sets the callback to be used when calling instances created from
6216 * this template as a function. If no callback is set, instances
6217 * behave like normal JavaScript objects that cannot be called as a
6218 * function.
6219 */
6220 void SetCallAsFunctionHandler(FunctionCallback callback,
6221 Local<Value> data = Local<Value>());
6222
6223 /**
6224 * Mark object instances of the template as undetectable.
6225 *
6226 * In many ways, undetectable objects behave as though they are not
6227 * there. They behave like 'undefined' in conditionals and when
6228 * printed. However, properties can be accessed and called as on
6229 * normal objects.
6230 */
6231 void MarkAsUndetectable();
6232
6233 /**
6234 * Sets access check callback on the object template and enables access
6235 * checks.
6236 *
6237 * When accessing properties on instances of this object template,
6238 * the access check callback will be called to determine whether or
6239 * not to allow cross-context access to the properties.
6240 */
6241 void SetAccessCheckCallback(AccessCheckCallback callback,
6242 Local<Value> data = Local<Value>());
6243
6244 /**
6245 * Like SetAccessCheckCallback but invokes an interceptor on failed access
6246 * checks instead of looking up all-can-read properties. You can only use
6247 * either this method or SetAccessCheckCallback, but not both at the same
6248 * time.
6249 */
6250 void SetAccessCheckCallbackAndHandler(
6251 AccessCheckCallback callback,
6252 const NamedPropertyHandlerConfiguration& named_handler,
6253 const IndexedPropertyHandlerConfiguration& indexed_handler,
6254 Local<Value> data = Local<Value>());
6255
6256 /**
6257 * Gets the number of internal fields for objects generated from
6258 * this template.
6259 */
6260 int InternalFieldCount();
6261
6262 /**
6263 * Sets the number of internal fields for objects generated from
6264 * this template.
6265 */
6266 void SetInternalFieldCount(int value);
6267
6268 /**
6269 * Returns true if the object will be an immutable prototype exotic object.
6270 */
6271 bool IsImmutableProto();
6272
6273 /**
6274 * Makes the ObjectTemplate for an immutable prototype exotic object, with an
6275 * immutable __proto__.
6276 */
6277 void SetImmutableProto();
6278
6279 V8_INLINE static ObjectTemplate* Cast(Data* data);
6280
6281 private:
6282 ObjectTemplate();
6283 static Local<ObjectTemplate> New(internal::Isolate* isolate,
6284 Local<FunctionTemplate> constructor);
6285 static void CheckCast(Data* that);
6286 friend class FunctionTemplate;
6287 };
6288
6289 /**
6290 * A Signature specifies which receiver is valid for a function.
6291 *
6292 * A receiver matches a given signature if the receiver (or any of its
6293 * hidden prototypes) was created from the signature's FunctionTemplate, or
6294 * from a FunctionTemplate that inherits directly or indirectly from the
6295 * signature's FunctionTemplate.
6296 */
6297 class V8_EXPORT Signature : public Data {
6298 public:
6299 static Local<Signature> New(
6300 Isolate* isolate,
6301 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
6302
6303 V8_INLINE static Signature* Cast(Data* data);
6304
6305 private:
6306 Signature();
6307
6308 static void CheckCast(Data* that);
6309 };
6310
6311
6312 /**
6313 * An AccessorSignature specifies which receivers are valid parameters
6314 * to an accessor callback.
6315 */
6316 class V8_EXPORT AccessorSignature : public Data {
6317 public:
6318 static Local<AccessorSignature> New(
6319 Isolate* isolate,
6320 Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
6321
6322 V8_INLINE static AccessorSignature* Cast(Data* data);
6323
6324 private:
6325 AccessorSignature();
6326
6327 static void CheckCast(Data* that);
6328 };
6329
6330
6331 // --- Extensions ---
6332 V8_DEPRECATE_SOON("Implementation detail", class)
6333 V8_EXPORT ExternalOneByteStringResourceImpl
6334 : public String::ExternalOneByteStringResource {
6335 public:
6336 ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
6337 ExternalOneByteStringResourceImpl(const char* data, size_t length)
6338 : data_(data), length_(length) {}
6339 const char* data() const { return data_; }
6340 size_t length() const { return length_; }
6341
6342 private:
6343 const char* data_;
6344 size_t length_;
6345 };
6346
6347 /**
6348 * Ignore
6349 */
6350 class V8_EXPORT Extension { // NOLINT
6351 public:
6352 // Note that the strings passed into this constructor must live as long
6353 // as the Extension itself.
6354 Extension(const char* name,
6355 const char* source = 0,
6356 int dep_count = 0,
6357 const char** deps = 0,
6358 int source_length = -1);
6359 virtual ~Extension() { delete source_; }
6360 virtual Local<FunctionTemplate> GetNativeFunctionTemplate(
6361 Isolate* isolate, Local<String> name) {
6362 return Local<FunctionTemplate>();
6363 }
6364
6365 const char* name() const { return name_; }
6366 size_t source_length() const { return source_length_; }
6367 const String::ExternalOneByteStringResource* source() const {
6368 return source_;
6369 }
6370 int dependency_count() { return dep_count_; }
6371 const char** dependencies() { return deps_; }
6372 void set_auto_enable(bool value) { auto_enable_ = value; }
6373 bool auto_enable() { return auto_enable_; }
6374
6375 // Disallow copying and assigning.
6376 Extension(const Extension&) = delete;
6377 void operator=(const Extension&) = delete;
6378
6379 private:
6380 const char* name_;
6381 size_t source_length_; // expected to initialize before source_
6382 String::ExternalOneByteStringResource* source_;
6383 int dep_count_;
6384 const char** deps_;
6385 bool auto_enable_;
6386 };
6387
6388
6389 void V8_EXPORT RegisterExtension(Extension* extension);
6390
6391
6392 // --- Statics ---
6393
6394 V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
6395 V8_INLINE Local<Primitive> Null(Isolate* isolate);
6396 V8_INLINE Local<Boolean> True(Isolate* isolate);
6397 V8_INLINE Local<Boolean> False(Isolate* isolate);
6398
6399 /**
6400 * A set of constraints that specifies the limits of the runtime's memory use.
6401 * You must set the heap size before initializing the VM - the size cannot be
6402 * adjusted after the VM is initialized.
6403 *
6404 * If you are using threads then you should hold the V8::Locker lock while
6405 * setting the stack limit and you must set a non-default stack limit separately
6406 * for each thread.
6407 *
6408 * The arguments for set_max_semi_space_size, set_max_old_space_size,
6409 * set_max_executable_size, set_code_range_size specify limits in MB.
6410 *
6411 * The argument for set_max_semi_space_size_in_kb is in KB.
6412 */
6413 class V8_EXPORT ResourceConstraints {
6414 public:
6415 ResourceConstraints();
6416
6417 /**
6418 * Configures the constraints with reasonable default values based on the
6419 * capabilities of the current device the VM is running on.
6420 *
6421 * \param physical_memory The total amount of physical memory on the current
6422 * device, in bytes.
6423 * \param virtual_memory_limit The amount of virtual memory on the current
6424 * device, in bytes, or zero, if there is no limit.
6425 */
6426 void ConfigureDefaults(uint64_t physical_memory,
6427 uint64_t virtual_memory_limit);
6428
6429 // Returns the max semi-space size in MB.
6430 V8_DEPRECATE_SOON("Use max_semi_space_size_in_kb()",
6431 size_t max_semi_space_size()) {
6432 return max_semi_space_size_in_kb_ / 1024;
6433 }
6434
6435 // Sets the max semi-space size in MB.
6436 V8_DEPRECATE_SOON("Use set_max_semi_space_size_in_kb(size_t limit_in_kb)",
6437 void set_max_semi_space_size(size_t limit_in_mb)) {
6438 max_semi_space_size_in_kb_ = limit_in_mb * 1024;
6439 }
6440
6441 // Returns the max semi-space size in KB.
6442 size_t max_semi_space_size_in_kb() const {
6443 return max_semi_space_size_in_kb_;
6444 }
6445
6446 // Sets the max semi-space size in KB.
6447 void set_max_semi_space_size_in_kb(size_t limit_in_kb) {
6448 max_semi_space_size_in_kb_ = limit_in_kb;
6449 }
6450
6451 size_t max_old_space_size() const { return max_old_space_size_; }
6452 void set_max_old_space_size(size_t limit_in_mb) {
6453 max_old_space_size_ = limit_in_mb;
6454 }
6455 V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
6456 size_t max_executable_size() const) {
6457 return max_executable_size_;
6458 }
6459 V8_DEPRECATE_SOON("max_executable_size_ is subsumed by max_old_space_size_",
6460 void set_max_executable_size(size_t limit_in_mb)) {
6461 max_executable_size_ = limit_in_mb;
6462 }
6463 uint32_t* stack_limit() const { return stack_limit_; }
6464 // Sets an address beyond which the VM's stack may not grow.
6465 void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
6466 size_t code_range_size() const { return code_range_size_; }
6467 void set_code_range_size(size_t limit_in_mb) {
6468 code_range_size_ = limit_in_mb;
6469 }
6470 size_t max_zone_pool_size() const { return max_zone_pool_size_; }
6471 void set_max_zone_pool_size(size_t bytes) { max_zone_pool_size_ = bytes; }
6472
6473 private:
6474 // max_semi_space_size_ is in KB
6475 size_t max_semi_space_size_in_kb_;
6476
6477 // The remaining limits are in MB
6478 size_t max_old_space_size_;
6479 size_t max_executable_size_;
6480 uint32_t* stack_limit_;
6481 size_t code_range_size_;
6482 size_t max_zone_pool_size_;
6483 };
6484
6485
6486 // --- Exceptions ---
6487
6488
6489 typedef void (*FatalErrorCallback)(const char* location, const char* message);
6490
6491 typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
6492
6493 typedef void (*DcheckErrorCallback)(const char* file, int line,
6494 const char* message);
6495
6496 typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
6497
6498 // --- Tracing ---
6499
6500 typedef void (*LogEventCallback)(const char* name, int event);
6501
6502 /**
6503 * Create new error objects by calling the corresponding error object
6504 * constructor with the message.
6505 */
6506 class V8_EXPORT Exception {
6507 public:
6508 static Local<Value> RangeError(Local<String> message);
6509 static Local<Value> ReferenceError(Local<String> message);
6510 static Local<Value> SyntaxError(Local<String> message);
6511 static Local<Value> TypeError(Local<String> message);
6512 static Local<Value> Error(Local<String> message);
6513
6514 /**
6515 * Creates an error message for the given exception.
6516 * Will try to reconstruct the original stack trace from the exception value,
6517 * or capture the current stack trace if not available.
6518 */
6519 static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
6520
6521 /**
6522 * Returns the original stack trace that was captured at the creation time
6523 * of a given exception, or an empty handle if not available.
6524 */
6525 static Local<StackTrace> GetStackTrace(Local<Value> exception);
6526 };
6527
6528
6529 // --- Counters Callbacks ---
6530
6531 typedef int* (*CounterLookupCallback)(const char* name);
6532
6533 typedef void* (*CreateHistogramCallback)(const char* name,
6534 int min,
6535 int max,
6536 size_t buckets);
6537
6538 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
6539
6540 // --- Enter/Leave Script Callback ---
6541 typedef void (*BeforeCallEnteredCallback)(Isolate*);
6542 typedef void (*CallCompletedCallback)(Isolate*);
6543
6544 /**
6545 * HostImportModuleDynamicallyCallback is called when we require the
6546 * embedder to load a module. This is used as part of the dynamic
6547 * import syntax.
6548 *
6549 * The referrer contains metadata about the script/module that calls
6550 * import.
6551 *
6552 * The specifier is the name of the module that should be imported.
6553 *
6554 * The embedder must compile, instantiate, evaluate the Module, and
6555 * obtain it's namespace object.
6556 *
6557 * The Promise returned from this function is forwarded to userland
6558 * JavaScript. The embedder must resolve this promise with the module
6559 * namespace object. In case of an exception, the embedder must reject
6560 * this promise with the exception. If the promise creation itself
6561 * fails (e.g. due to stack overflow), the embedder must propagate
6562 * that exception by returning an empty MaybeLocal.
6563 */
6564 typedef MaybeLocal<Promise> (*HostImportModuleDynamicallyCallback)(
6565 Local<Context> context, Local<ScriptOrModule> referrer,
6566 Local<String> specifier);
6567
6568 /**
6569 * HostInitializeImportMetaObjectCallback is called the first time import.meta
6570 * is accessed for a module. Subsequent access will reuse the same value.
6571 *
6572 * The method combines two implementation-defined abstract operations into one:
6573 * HostGetImportMetaProperties and HostFinalizeImportMeta.
6574 *
6575 * The embedder should use v8::Object::CreateDataProperty to add properties on
6576 * the meta object.
6577 */
6578 typedef void (*HostInitializeImportMetaObjectCallback)(Local<Context> context,
6579 Local<Module> module,
6580 Local<Object> meta);
6581
6582 /**
6583 * PromiseHook with type kInit is called when a new promise is
6584 * created. When a new promise is created as part of the chain in the
6585 * case of Promise.then or in the intermediate promises created by
6586 * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
6587 * otherwise we pass undefined.
6588 *
6589 * PromiseHook with type kResolve is called at the beginning of
6590 * resolve or reject function defined by CreateResolvingFunctions.
6591 *
6592 * PromiseHook with type kBefore is called at the beginning of the
6593 * PromiseReactionJob.
6594 *
6595 * PromiseHook with type kAfter is called right at the end of the
6596 * PromiseReactionJob.
6597 */
6598 enum class PromiseHookType { kInit, kResolve, kBefore, kAfter };
6599
6600 typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
6601 Local<Value> parent);
6602
6603 // --- Promise Reject Callback ---
6604 enum PromiseRejectEvent {
6605 kPromiseRejectWithNoHandler = 0,
6606 kPromiseHandlerAddedAfterReject = 1,
6607 kPromiseRejectAfterResolved = 2,
6608 kPromiseResolveAfterResolved = 3,
6609 };
6610
6611 class PromiseRejectMessage {
6612 public:
6613 PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
6614 Local<Value> value, Local<StackTrace> stack_trace)
6615 : promise_(promise),
6616 event_(event),
6617 value_(value),
6618 stack_trace_(stack_trace) {}
6619
6620 V8_INLINE Local<Promise> GetPromise() const { return promise_; }
6621 V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
6622 V8_INLINE Local<Value> GetValue() const { return value_; }
6623
6624 private:
6625 Local<Promise> promise_;
6626 PromiseRejectEvent event_;
6627 Local<Value> value_;
6628 Local<StackTrace> stack_trace_;
6629 };
6630
6631 typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
6632
6633 // --- Microtasks Callbacks ---
6634 typedef void (*MicrotasksCompletedCallback)(Isolate*);
6635 typedef void (*MicrotaskCallback)(void* data);
6636
6637
6638 /**
6639 * Policy for running microtasks:
6640 * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
6641 * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
6642 * - auto: microtasks are invoked when the script call depth decrements
6643 * to zero.
6644 */
6645 enum class MicrotasksPolicy { kExplicit, kScoped, kAuto };
6646
6647
6648 /**
6649 * This scope is used to control microtasks when kScopeMicrotasksInvocation
6650 * is used on Isolate. In this mode every non-primitive call to V8 should be
6651 * done inside some MicrotasksScope.
6652 * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
6653 * exits.
6654 * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
6655 * microtasks.
6656 */
6657 class V8_EXPORT MicrotasksScope {
6658 public:
6659 enum Type { kRunMicrotasks, kDoNotRunMicrotasks };
6660
6661 MicrotasksScope(Isolate* isolate, Type type);
6662 ~MicrotasksScope();
6663
6664 /**
6665 * Runs microtasks if no kRunMicrotasks scope is currently active.
6666 */
6667 static void PerformCheckpoint(Isolate* isolate);
6668
6669 /**
6670 * Returns current depth of nested kRunMicrotasks scopes.
6671 */
6672 static int GetCurrentDepth(Isolate* isolate);
6673
6674 /**
6675 * Returns true while microtasks are being executed.
6676 */
6677 static bool IsRunningMicrotasks(Isolate* isolate);
6678
6679 // Prevent copying.
6680 MicrotasksScope(const MicrotasksScope&) = delete;
6681 MicrotasksScope& operator=(const MicrotasksScope&) = delete;
6682
6683 private:
6684 internal::Isolate* const isolate_;
6685 bool run_;
6686 };
6687
6688
6689 // --- Failed Access Check Callback ---
6690 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
6691 AccessType type,
6692 Local<Value> data);
6693
6694 // --- AllowCodeGenerationFromStrings callbacks ---
6695
6696 /**
6697 * Callback to check if code generation from strings is allowed. See
6698 * Context::AllowCodeGenerationFromStrings.
6699 */
6700 typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context,
6701 Local<String> source);
6702
6703 // --- WebAssembly compilation callbacks ---
6704 typedef bool (*ExtensionCallback)(const FunctionCallbackInfo<Value>&);
6705
6706 typedef bool (*AllowWasmCodeGenerationCallback)(Local<Context> context,
6707 Local<String> source);
6708
6709 // --- Callback for APIs defined on v8-supported objects, but implemented
6710 // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
6711 typedef void (*ApiImplementationCallback)(const FunctionCallbackInfo<Value>&);
6712
6713 // --- Callback for WebAssembly.compileStreaming ---
6714 typedef void (*WasmStreamingCallback)(const FunctionCallbackInfo<Value>&);
6715
6716 // --- Callback for checking if WebAssembly threads are enabled ---
6717 typedef bool (*WasmThreadsEnabledCallback)(Local<Context> context);
6718
6719 // --- Garbage Collection Callbacks ---
6720
6721 /**
6722 * Applications can register callback functions which will be called before and
6723 * after certain garbage collection operations. Allocations are not allowed in
6724 * the callback functions, you therefore cannot manipulate objects (set or
6725 * delete properties for example) since it is possible such operations will
6726 * result in the allocation of objects.
6727 */
6728 enum GCType {
6729 kGCTypeScavenge = 1 << 0,
6730 kGCTypeMarkSweepCompact = 1 << 1,
6731 kGCTypeIncrementalMarking = 1 << 2,
6732 kGCTypeProcessWeakCallbacks = 1 << 3,
6733 kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact |
6734 kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks
6735 };
6736
6737 /**
6738 * GCCallbackFlags is used to notify additional information about the GC
6739 * callback.
6740 * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
6741 * constructing retained object infos.
6742 * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
6743 * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
6744 * is called synchronously without getting posted to an idle task.
6745 * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
6746 * in a phase where V8 is trying to collect all available garbage
6747 * (e.g., handling a low memory notification).
6748 * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
6749 * trigger an idle garbage collection.
6750 */
6751 enum GCCallbackFlags {
6752 kNoGCCallbackFlags = 0,
6753 kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
6754 kGCCallbackFlagForced = 1 << 2,
6755 kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3,
6756 kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4,
6757 kGCCallbackFlagCollectAllExternalMemory = 1 << 5,
6758 kGCCallbackScheduleIdleGarbageCollection = 1 << 6,
6759 };
6760
6761 typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
6762
6763 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
6764
6765 /**
6766 * This callback is invoked when the heap size is close to the heap limit and
6767 * V8 is likely to abort with out-of-memory error.
6768 * The callback can extend the heap limit by returning a value that is greater
6769 * than the current_heap_limit. The initial heap limit is the limit that was
6770 * set after heap setup.
6771 */
6772 typedef size_t (*NearHeapLimitCallback)(void* data, size_t current_heap_limit,
6773 size_t initial_heap_limit);
6774
6775 /**
6776 * Collection of V8 heap information.
6777 *
6778 * Instances of this class can be passed to v8::V8::HeapStatistics to
6779 * get heap statistics from V8.
6780 */
6781 class V8_EXPORT HeapStatistics {
6782 public:
6783 HeapStatistics();
6784 size_t total_heap_size() { return total_heap_size_; }
6785 size_t total_heap_size_executable() { return total_heap_size_executable_; }
6786 size_t total_physical_size() { return total_physical_size_; }
6787 size_t total_available_size() { return total_available_size_; }
6788 size_t used_heap_size() { return used_heap_size_; }
6789 size_t heap_size_limit() { return heap_size_limit_; }
6790 size_t malloced_memory() { return malloced_memory_; }
6791 size_t external_memory() { return external_memory_; }
6792 size_t peak_malloced_memory() { return peak_malloced_memory_; }
6793 size_t number_of_native_contexts() { return number_of_native_contexts_; }
6794 size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
6795
6796 /**
6797 * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
6798 * garbage with a bit pattern.
6799 */
6800 size_t does_zap_garbage() { return does_zap_garbage_; }
6801
6802 private:
6803 size_t total_heap_size_;
6804 size_t total_heap_size_executable_;
6805 size_t total_physical_size_;
6806 size_t total_available_size_;
6807 size_t used_heap_size_;
6808 size_t heap_size_limit_;
6809 size_t malloced_memory_;
6810 size_t external_memory_;
6811 size_t peak_malloced_memory_;
6812 bool does_zap_garbage_;
6813 size_t number_of_native_contexts_;
6814 size_t number_of_detached_contexts_;
6815
6816 friend class V8;
6817 friend class Isolate;
6818 };
6819
6820
6821 class V8_EXPORT HeapSpaceStatistics {
6822 public:
6823 HeapSpaceStatistics();
6824 const char* space_name() { return space_name_; }
6825 size_t space_size() { return space_size_; }
6826 size_t space_used_size() { return space_used_size_; }
6827 size_t space_available_size() { return space_available_size_; }
6828 size_t physical_space_size() { return physical_space_size_; }
6829
6830 private:
6831 const char* space_name_;
6832 size_t space_size_;
6833 size_t space_used_size_;
6834 size_t space_available_size_;
6835 size_t physical_space_size_;
6836
6837 friend class Isolate;
6838 };
6839
6840
6841 class V8_EXPORT HeapObjectStatistics {
6842 public:
6843 HeapObjectStatistics();
6844 const char* object_type() { return object_type_; }
6845 const char* object_sub_type() { return object_sub_type_; }
6846 size_t object_count() { return object_count_; }
6847 size_t object_size() { return object_size_; }
6848
6849 private:
6850 const char* object_type_;
6851 const char* object_sub_type_;
6852 size_t object_count_;
6853 size_t object_size_;
6854
6855 friend class Isolate;
6856 };
6857
6858 class V8_EXPORT HeapCodeStatistics {
6859 public:
6860 HeapCodeStatistics();
6861 size_t code_and_metadata_size() { return code_and_metadata_size_; }
6862 size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
6863 size_t external_script_source_size() { return external_script_source_size_; }
6864
6865 private:
6866 size_t code_and_metadata_size_;
6867 size_t bytecode_and_metadata_size_;
6868 size_t external_script_source_size_;
6869
6870 friend class Isolate;
6871 };
6872
6873 class RetainedObjectInfo;
6874
6875
6876 /**
6877 * FunctionEntryHook is the type of the profile entry hook called at entry to
6878 * any generated function when function-level profiling is enabled.
6879 *
6880 * \param function the address of the function that's being entered.
6881 * \param return_addr_location points to a location on stack where the machine
6882 * return address resides. This can be used to identify the caller of
6883 * \p function, and/or modified to divert execution when \p function exits.
6884 *
6885 * \note the entry hook must not cause garbage collection.
6886 */
6887 typedef void (*FunctionEntryHook)(uintptr_t function,
6888 uintptr_t return_addr_location);
6889
6890 /**
6891 * A JIT code event is issued each time code is added, moved or removed.
6892 *
6893 * \note removal events are not currently issued.
6894 */
6895 struct JitCodeEvent {
6896 enum EventType {
6897 CODE_ADDED,
6898 CODE_MOVED,
6899 CODE_REMOVED,
6900 CODE_ADD_LINE_POS_INFO,
6901 CODE_START_LINE_INFO_RECORDING,
6902 CODE_END_LINE_INFO_RECORDING
6903 };
6904 // Definition of the code position type. The "POSITION" type means the place
6905 // in the source code which are of interest when making stack traces to
6906 // pin-point the source location of a stack frame as close as possible.
6907 // The "STATEMENT_POSITION" means the place at the beginning of each
6908 // statement, and is used to indicate possible break locations.
6909 enum PositionType { POSITION, STATEMENT_POSITION };
6910
6911 // There are two different kinds of JitCodeEvents, one for JIT code generated
6912 // by the optimizing compiler, and one for byte code generated for the
6913 // interpreter. For JIT_CODE events, the |code_start| member of the event
6914 // points to the beginning of jitted assembly code, while for BYTE_CODE
6915 // events, |code_start| points to the first bytecode of the interpreted
6916 // function.
6917 enum CodeType { BYTE_CODE, JIT_CODE };
6918
6919 // Type of event.
6920 EventType type;
6921 CodeType code_type;
6922 // Start of the instructions.
6923 void* code_start;
6924 // Size of the instructions.
6925 size_t code_len;
6926 // Script info for CODE_ADDED event.
6927 Local<UnboundScript> script;
6928 // User-defined data for *_LINE_INFO_* event. It's used to hold the source
6929 // code line information which is returned from the
6930 // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
6931 // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
6932 void* user_data;
6933
6934 struct name_t {
6935 // Name of the object associated with the code, note that the string is not
6936 // zero-terminated.
6937 const char* str;
6938 // Number of chars in str.
6939 size_t len;
6940 };
6941
6942 struct line_info_t {
6943 // PC offset
6944 size_t offset;
6945 // Code position
6946 size_t pos;
6947 // The position type.
6948 PositionType position_type;
6949 };
6950
6951 union {
6952 // Only valid for CODE_ADDED.
6953 struct name_t name;
6954
6955 // Only valid for CODE_ADD_LINE_POS_INFO
6956 struct line_info_t line_info;
6957
6958 // New location of instructions. Only valid for CODE_MOVED.
6959 void* new_code_start;
6960 };
6961
6962 Isolate* isolate;
6963 };
6964
6965 /**
6966 * Option flags passed to the SetRAILMode function.
6967 * See documentation https://developers.google.com/web/tools/chrome-devtools/
6968 * profile/evaluate-performance/rail
6969 */
6970 enum RAILMode {
6971 // Response performance mode: In this mode very low virtual machine latency
6972 // is provided. V8 will try to avoid JavaScript execution interruptions.
6973 // Throughput may be throttled.
6974 PERFORMANCE_RESPONSE,
6975 // Animation performance mode: In this mode low virtual machine latency is
6976 // provided. V8 will try to avoid as many JavaScript execution interruptions
6977 // as possible. Throughput may be throttled. This is the default mode.
6978 PERFORMANCE_ANIMATION,
6979 // Idle performance mode: The embedder is idle. V8 can complete deferred work
6980 // in this mode.
6981 PERFORMANCE_IDLE,
6982 // Load performance mode: In this mode high throughput is provided. V8 may
6983 // turn off latency optimizations.
6984 PERFORMANCE_LOAD
6985 };
6986
6987 /**
6988 * Option flags passed to the SetJitCodeEventHandler function.
6989 */
6990 enum JitCodeEventOptions {
6991 kJitCodeEventDefault = 0,
6992 // Generate callbacks for already existent code.
6993 kJitCodeEventEnumExisting = 1
6994 };
6995
6996
6997 /**
6998 * Callback function passed to SetJitCodeEventHandler.
6999 *
7000 * \param event code add, move or removal event.
7001 */
7002 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
7003
7004
7005 /**
7006 * Interface for iterating through all external resources in the heap.
7007 */
7008 class V8_EXPORT ExternalResourceVisitor { // NOLINT
7009 public:
7010 virtual ~ExternalResourceVisitor() {}
7011 virtual void VisitExternalString(Local<String> string) {}
7012 };
7013
7014
7015 /**
7016 * Interface for iterating through all the persistent handles in the heap.
7017 */
7018 class V8_EXPORT PersistentHandleVisitor { // NOLINT
7019 public:
7020 virtual ~PersistentHandleVisitor() {}
7021 virtual void VisitPersistentHandle(Persistent<Value>* value,
7022 uint16_t class_id) {}
7023 };
7024
7025 /**
7026 * Memory pressure level for the MemoryPressureNotification.
7027 * kNone hints V8 that there is no memory pressure.
7028 * kModerate hints V8 to speed up incremental garbage collection at the cost of
7029 * of higher latency due to garbage collection pauses.
7030 * kCritical hints V8 to free memory as soon as possible. Garbage collection
7031 * pauses at this level will be large.
7032 */
7033 enum class MemoryPressureLevel { kNone, kModerate, kCritical };
7034
7035 /**
7036 * Interface for tracing through the embedder heap. During a V8 garbage
7037 * collection, V8 collects hidden fields of all potential wrappers, and at the
7038 * end of its marking phase iterates the collection and asks the embedder to
7039 * trace through its heap and use reporter to report each JavaScript object
7040 * reachable from any of the given wrappers.
7041 */
7042 class V8_EXPORT EmbedderHeapTracer {
7043 public:
7044 // Indicator for the stack state of the embedder.
7045 enum EmbedderStackState {
7046 kUnknown,
7047 kNonEmpty,
7048 kEmpty,
7049 };
7050
7051 enum ForceCompletionAction { FORCE_COMPLETION, DO_NOT_FORCE_COMPLETION };
7052
7053 struct AdvanceTracingActions {
7054 explicit AdvanceTracingActions(ForceCompletionAction force_completion_)
7055 : force_completion(force_completion_) {}
7056
7057 ForceCompletionAction force_completion;
7058 };
7059
7060 virtual ~EmbedderHeapTracer() = default;
7061
7062 /**
7063 * Called by v8 to register internal fields of found wrappers.
7064 *
7065 * The embedder is expected to store them somewhere and trace reachable
7066 * wrappers from them when called through |AdvanceTracing|.
7067 */
7068 virtual void RegisterV8References(
7069 const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
7070
7071 /**
7072 * Called at the beginning of a GC cycle.
7073 */
7074 virtual void TracePrologue() = 0;
7075
7076 /**
7077 * Called to make a tracing step in the embedder.
7078 *
7079 * The embedder is expected to trace its heap starting from wrappers reported
7080 * by RegisterV8References method, and report back all reachable wrappers.
7081 * Furthermore, the embedder is expected to stop tracing by the given
7082 * deadline.
7083 *
7084 * Returns true if there is still work to do.
7085 *
7086 * Note: Only one of the AdvanceTracing methods needs to be overriden by the
7087 * embedder.
7088 */
7089 V8_DEPRECATE_SOON("Use void AdvanceTracing(deadline_in_ms)",
7090 virtual bool AdvanceTracing(
7091 double deadline_in_ms, AdvanceTracingActions actions)) {
7092 return false;
7093 }
7094
7095 /**
7096 * Called to advance tracing in the embedder.
7097 *
7098 * The embedder is expected to trace its heap starting from wrappers reported
7099 * by RegisterV8References method, and report back all reachable wrappers.
7100 * Furthermore, the embedder is expected to stop tracing by the given
7101 * deadline. A deadline of infinity means that tracing should be finished.
7102 *
7103 * Returns |true| if tracing is done, and false otherwise.
7104 *
7105 * Note: Only one of the AdvanceTracing methods needs to be overriden by the
7106 * embedder.
7107 */
7108 virtual bool AdvanceTracing(double deadline_in_ms);
7109
7110 /*
7111 * Returns true if there no more tracing work to be done (see AdvanceTracing)
7112 * and false otherwise.
7113 */
7114 virtual bool IsTracingDone();
7115
7116 /**
7117 * Called at the end of a GC cycle.
7118 *
7119 * Note that allocation is *not* allowed within |TraceEpilogue|.
7120 */
7121 virtual void TraceEpilogue() = 0;
7122
7123 /**
7124 * Called upon entering the final marking pause. No more incremental marking
7125 * steps will follow this call.
7126 *
7127 * Note: Only one of the EnterFinalPause methods needs to be overriden by the
7128 * embedder.
7129 */
7130 V8_DEPRECATE_SOON("Use void EnterFinalPause(EmbedderStackState)",
7131 virtual void EnterFinalPause()) {}
7132 virtual void EnterFinalPause(EmbedderStackState stack_state);
7133
7134 /**
7135 * Called when tracing is aborted.
7136 *
7137 * The embedder is expected to throw away all intermediate data and reset to
7138 * the initial state.
7139 */
7140 virtual void AbortTracing() = 0;
7141
7142 /*
7143 * Called by the embedder to request immediate finalization of the currently
7144 * running tracing phase that has been started with TracePrologue and not
7145 * yet finished with TraceEpilogue.
7146 *
7147 * Will be a noop when currently not in tracing.
7148 *
7149 * This is an experimental feature.
7150 */
7151 void FinalizeTracing();
7152
7153 /*
7154 * Called by the embedder to immediately perform a full garbage collection.
7155 *
7156 * Should only be used in testing code.
7157 */
7158 void GarbageCollectionForTesting(EmbedderStackState stack_state);
7159
7160 /*
7161 * Returns the v8::Isolate this tracer is attached too and |nullptr| if it
7162 * is not attached to any v8::Isolate.
7163 */
7164 v8::Isolate* isolate() const { return isolate_; }
7165
7166 /**
7167 * Returns the number of wrappers that are still to be traced by the embedder.
7168 */
7169 V8_DEPRECATE_SOON("Use IsTracingDone",
7170 virtual size_t NumberOfWrappersToTrace()) {
7171 return 0;
7172 }
7173
7174 protected:
7175 v8::Isolate* isolate_ = nullptr;
7176
7177 friend class internal::LocalEmbedderHeapTracer;
7178 };
7179
7180 /**
7181 * Callback and supporting data used in SnapshotCreator to implement embedder
7182 * logic to serialize internal fields.
7183 */
7184 struct SerializeInternalFieldsCallback {
7185 typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
7186 void* data);
7187 SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
7188 void* data_arg = nullptr)
7189 : callback(function), data(data_arg) {}
7190 CallbackFunction callback;
7191 void* data;
7192 };
7193 // Note that these fields are called "internal fields" in the API and called
7194 // "embedder fields" within V8.
7195 typedef SerializeInternalFieldsCallback SerializeEmbedderFieldsCallback;
7196
7197 /**
7198 * Callback and supporting data used to implement embedder logic to deserialize
7199 * internal fields.
7200 */
7201 struct DeserializeInternalFieldsCallback {
7202 typedef void (*CallbackFunction)(Local<Object> holder, int index,
7203 StartupData payload, void* data);
7204 DeserializeInternalFieldsCallback(CallbackFunction function = nullptr,
7205 void* data_arg = nullptr)
7206 : callback(function), data(data_arg) {}
7207 void (*callback)(Local<Object> holder, int index, StartupData payload,
7208 void* data);
7209 void* data;
7210 };
7211 typedef DeserializeInternalFieldsCallback DeserializeEmbedderFieldsCallback;
7212
7213 /**
7214 * Isolate represents an isolated instance of the V8 engine. V8 isolates have
7215 * completely separate states. Objects from one isolate must not be used in
7216 * other isolates. The embedder can create multiple isolates and use them in
7217 * parallel in multiple threads. An isolate can be entered by at most one
7218 * thread at any given time. The Locker/Unlocker API must be used to
7219 * synchronize.
7220 */
7221 class V8_EXPORT Isolate {
7222 public:
7223 /**
7224 * Initial configuration parameters for a new Isolate.
7225 */
7226 struct CreateParams {
7227 CreateParams()
7228 : entry_hook(nullptr),
7229 code_event_handler(nullptr),
7230 snapshot_blob(nullptr),
7231 counter_lookup_callback(nullptr),
7232 create_histogram_callback(nullptr),
7233 add_histogram_sample_callback(nullptr),
7234 array_buffer_allocator(nullptr),
7235 external_references(nullptr),
7236 allow_atomics_wait(true),
7237 only_terminate_in_safe_scope(false) {}
7238
7239 /**
7240 * The optional entry_hook allows the host application to provide the
7241 * address of a function that's invoked on entry to every V8-generated
7242 * function. Note that entry_hook is invoked at the very start of each
7243 * generated function.
7244 * An entry_hook can only be provided in no-snapshot builds; in snapshot
7245 * builds it must be nullptr.
7246 */
7247 FunctionEntryHook entry_hook;
7248
7249 /**
7250 * Allows the host application to provide the address of a function that is
7251 * notified each time code is added, moved or removed.
7252 */
7253 JitCodeEventHandler code_event_handler;
7254
7255 /**
7256 * ResourceConstraints to use for the new Isolate.
7257 */
7258 ResourceConstraints constraints;
7259
7260 /**
7261 * Explicitly specify a startup snapshot blob. The embedder owns the blob.
7262 */
7263 StartupData* snapshot_blob;
7264
7265
7266 /**
7267 * Enables the host application to provide a mechanism for recording
7268 * statistics counters.
7269 */
7270 CounterLookupCallback counter_lookup_callback;
7271
7272 /**
7273 * Enables the host application to provide a mechanism for recording
7274 * histograms. The CreateHistogram function returns a
7275 * histogram which will later be passed to the AddHistogramSample
7276 * function.
7277 */
7278 CreateHistogramCallback create_histogram_callback;
7279 AddHistogramSampleCallback add_histogram_sample_callback;
7280
7281 /**
7282 * The ArrayBuffer::Allocator to use for allocating and freeing the backing
7283 * store of ArrayBuffers.
7284 */
7285 ArrayBuffer::Allocator* array_buffer_allocator;
7286
7287 /**
7288 * Specifies an optional nullptr-terminated array of raw addresses in the
7289 * embedder that V8 can match against during serialization and use for
7290 * deserialization. This array and its content must stay valid for the
7291 * entire lifetime of the isolate.
7292 */
7293 const intptr_t* external_references;
7294
7295 /**
7296 * Whether calling Atomics.wait (a function that may block) is allowed in
7297 * this isolate. This can also be configured via SetAllowAtomicsWait.
7298 */
7299 bool allow_atomics_wait;
7300
7301 /**
7302 * Termination is postponed when there is no active SafeForTerminationScope.
7303 */
7304 bool only_terminate_in_safe_scope;
7305 };
7306
7307
7308 /**
7309 * Stack-allocated class which sets the isolate for all operations
7310 * executed within a local scope.
7311 */
7312 class V8_EXPORT Scope {
7313 public:
7314 explicit Scope(Isolate* isolate) : isolate_(isolate) {
7315 isolate->Enter();
7316 }
7317
7318 ~Scope() { isolate_->Exit(); }
7319
7320 // Prevent copying of Scope objects.
7321 Scope(const Scope&) = delete;
7322 Scope& operator=(const Scope&) = delete;
7323
7324 private:
7325 Isolate* const isolate_;
7326 };
7327
7328
7329 /**
7330 * Assert that no Javascript code is invoked.
7331 */
7332 class V8_EXPORT DisallowJavascriptExecutionScope {
7333 public:
7334 enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
7335
7336 DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
7337 ~DisallowJavascriptExecutionScope();
7338
7339 // Prevent copying of Scope objects.
7340 DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
7341 delete;
7342 DisallowJavascriptExecutionScope& operator=(
7343 const DisallowJavascriptExecutionScope&) = delete;
7344
7345 private:
7346 bool on_failure_;
7347 void* internal_;
7348 };
7349
7350
7351 /**
7352 * Introduce exception to DisallowJavascriptExecutionScope.
7353 */
7354 class V8_EXPORT AllowJavascriptExecutionScope {
7355 public:
7356 explicit AllowJavascriptExecutionScope(Isolate* isolate);
7357 ~AllowJavascriptExecutionScope();
7358
7359 // Prevent copying of Scope objects.
7360 AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
7361 delete;
7362 AllowJavascriptExecutionScope& operator=(
7363 const AllowJavascriptExecutionScope&) = delete;
7364
7365 private:
7366 void* internal_throws_;
7367 void* internal_assert_;
7368 };
7369
7370 /**
7371 * Do not run microtasks while this scope is active, even if microtasks are
7372 * automatically executed otherwise.
7373 */
7374 class V8_EXPORT SuppressMicrotaskExecutionScope {
7375 public:
7376 explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
7377 ~SuppressMicrotaskExecutionScope();
7378
7379 // Prevent copying of Scope objects.
7380 SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
7381 delete;
7382 SuppressMicrotaskExecutionScope& operator=(
7383 const SuppressMicrotaskExecutionScope&) = delete;
7384
7385 private:
7386 internal::Isolate* const isolate_;
7387 };
7388
7389 /**
7390 * This scope allows terminations inside direct V8 API calls and forbid them
7391 * inside any recursice API calls without explicit SafeForTerminationScope.
7392 */
7393 class V8_EXPORT SafeForTerminationScope {
7394 public:
7395 explicit SafeForTerminationScope(v8::Isolate* isolate);
7396 ~SafeForTerminationScope();
7397
7398 // Prevent copying of Scope objects.
7399 SafeForTerminationScope(const SafeForTerminationScope&) = delete;
7400 SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete;
7401
7402 private:
7403 internal::Isolate* isolate_;
7404 bool prev_value_;
7405 };
7406
7407 /**
7408 * Types of garbage collections that can be requested via
7409 * RequestGarbageCollectionForTesting.
7410 */
7411 enum GarbageCollectionType {
7412 kFullGarbageCollection,
7413 kMinorGarbageCollection
7414 };
7415
7416 /**
7417 * Features reported via the SetUseCounterCallback callback. Do not change
7418 * assigned numbers of existing items; add new features to the end of this
7419 * list.
7420 */
7421 enum UseCounterFeature {
7422 kUseAsm = 0,
7423 kBreakIterator = 1,
7424 kLegacyConst = 2,
7425 kMarkDequeOverflow = 3,
7426 kStoreBufferOverflow = 4,
7427 kSlotsBufferOverflow = 5,
7428 kObjectObserve = 6,
7429 kForcedGC = 7,
7430 kSloppyMode = 8,
7431 kStrictMode = 9,
7432 kStrongMode = 10,
7433 kRegExpPrototypeStickyGetter = 11,
7434 kRegExpPrototypeToString = 12,
7435 kRegExpPrototypeUnicodeGetter = 13,
7436 kIntlV8Parse = 14,
7437 kIntlPattern = 15,
7438 kIntlResolved = 16,
7439 kPromiseChain = 17,
7440 kPromiseAccept = 18,
7441 kPromiseDefer = 19,
7442 kHtmlCommentInExternalScript = 20,
7443 kHtmlComment = 21,
7444 kSloppyModeBlockScopedFunctionRedefinition = 22,
7445 kForInInitializer = 23,
7446 kArrayProtectorDirtied = 24,
7447 kArraySpeciesModified = 25,
7448 kArrayPrototypeConstructorModified = 26,
7449 kArrayInstanceProtoModified = 27,
7450 kArrayInstanceConstructorModified = 28,
7451 kLegacyFunctionDeclaration = 29,
7452 kRegExpPrototypeSourceGetter = 30,
7453 kRegExpPrototypeOldFlagGetter = 31,
7454 kDecimalWithLeadingZeroInStrictMode = 32,
7455 kLegacyDateParser = 33,
7456 kDefineGetterOrSetterWouldThrow = 34,
7457 kFunctionConstructorReturnedUndefined = 35,
7458 kAssigmentExpressionLHSIsCallInSloppy = 36,
7459 kAssigmentExpressionLHSIsCallInStrict = 37,
7460 kPromiseConstructorReturnedUndefined = 38,
7461 kConstructorNonUndefinedPrimitiveReturn = 39,
7462 kLabeledExpressionStatement = 40,
7463 kLineOrParagraphSeparatorAsLineTerminator = 41,
7464 kIndexAccessor = 42,
7465 kErrorCaptureStackTrace = 43,
7466 kErrorPrepareStackTrace = 44,
7467 kErrorStackTraceLimit = 45,
7468 kWebAssemblyInstantiation = 46,
7469 kDeoptimizerDisableSpeculation = 47,
7470 kArrayPrototypeSortJSArrayModifiedPrototype = 48,
7471 kFunctionTokenOffsetTooLongForToString = 49,
7472 kWasmSharedMemory = 50,
7473 kWasmThreadOpcodes = 51,
7474
7475 // If you add new values here, you'll also need to update Chromium's:
7476 // web_feature.mojom, UseCounterCallback.cpp, and enums.xml. V8 changes to
7477 // this list need to be landed first, then changes on the Chromium side.
7478 kUseCounterFeatureCount // This enum value must be last.
7479 };
7480
7481 enum MessageErrorLevel {
7482 kMessageLog = (1 << 0),
7483 kMessageDebug = (1 << 1),
7484 kMessageInfo = (1 << 2),
7485 kMessageError = (1 << 3),
7486 kMessageWarning = (1 << 4),
7487 kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
7488 kMessageWarning,
7489 };
7490
7491 typedef void (*UseCounterCallback)(Isolate* isolate,
7492 UseCounterFeature feature);
7493
7494 /**
7495 * Allocates a new isolate but does not initialize it. Does not change the
7496 * currently entered isolate.
7497 *
7498 * Only Isolate::GetData() and Isolate::SetData(), which access the
7499 * embedder-controlled parts of the isolate, are allowed to be called on the
7500 * uninitialized isolate. To initialize the isolate, call
7501 * Isolate::Initialize().
7502 *
7503 * When an isolate is no longer used its resources should be freed
7504 * by calling Dispose(). Using the delete operator is not allowed.
7505 *
7506 * V8::Initialize() must have run prior to this.
7507 */
7508 static Isolate* Allocate();
7509
7510 /**
7511 * Initialize an Isolate previously allocated by Isolate::Allocate().
7512 */
7513 static void Initialize(Isolate* isolate, const CreateParams& params);
7514
7515 /**
7516 * Creates a new isolate. Does not change the currently entered
7517 * isolate.
7518 *
7519 * When an isolate is no longer used its resources should be freed
7520 * by calling Dispose(). Using the delete operator is not allowed.
7521 *
7522 * V8::Initialize() must have run prior to this.
7523 */
7524 static Isolate* New(const CreateParams& params);
7525
7526 /**
7527 * Returns the entered isolate for the current thread or NULL in
7528 * case there is no current isolate.
7529 *
7530 * This method must not be invoked before V8::Initialize() was invoked.
7531 */
7532 static Isolate* GetCurrent();
7533
7534 /**
7535 * Custom callback used by embedders to help V8 determine if it should abort
7536 * when it throws and no internal handler is predicted to catch the
7537 * exception. If --abort-on-uncaught-exception is used on the command line,
7538 * then V8 will abort if either:
7539 * - no custom callback is set.
7540 * - the custom callback set returns true.
7541 * Otherwise, the custom callback will not be called and V8 will not abort.
7542 */
7543 typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*);
7544 void SetAbortOnUncaughtExceptionCallback(
7545 AbortOnUncaughtExceptionCallback callback);
7546
7547 /**
7548 * This specifies the callback called by the upcoming dynamic
7549 * import() language feature to load modules.
7550 */
7551 void SetHostImportModuleDynamicallyCallback(
7552 HostImportModuleDynamicallyCallback callback);
7553
7554 /**
7555 * This specifies the callback called by the upcoming importa.meta
7556 * language feature to retrieve host-defined meta data for a module.
7557 */
7558 void SetHostInitializeImportMetaObjectCallback(
7559 HostInitializeImportMetaObjectCallback callback);
7560
7561 /**
7562 * Optional notification that the system is running low on memory.
7563 * V8 uses these notifications to guide heuristics.
7564 * It is allowed to call this function from another thread while
7565 * the isolate is executing long running JavaScript code.
7566 */
7567 void MemoryPressureNotification(MemoryPressureLevel level);
7568
7569 /**
7570 * Methods below this point require holding a lock (using Locker) in
7571 * a multi-threaded environment.
7572 */
7573
7574 /**
7575 * Sets this isolate as the entered one for the current thread.
7576 * Saves the previously entered one (if any), so that it can be
7577 * restored when exiting. Re-entering an isolate is allowed.
7578 */
7579 void Enter();
7580
7581 /**
7582 * Exits this isolate by restoring the previously entered one in the
7583 * current thread. The isolate may still stay the same, if it was
7584 * entered more than once.
7585 *
7586 * Requires: this == Isolate::GetCurrent().
7587 */
7588 void Exit();
7589
7590 /**
7591 * Disposes the isolate. The isolate must not be entered by any
7592 * thread to be disposable.
7593 */
7594 void Dispose();
7595
7596 /**
7597 * Dumps activated low-level V8 internal stats. This can be used instead
7598 * of performing a full isolate disposal.
7599 */
7600 void DumpAndResetStats();
7601
7602 /**
7603 * Discards all V8 thread-specific data for the Isolate. Should be used
7604 * if a thread is terminating and it has used an Isolate that will outlive
7605 * the thread -- all thread-specific data for an Isolate is discarded when
7606 * an Isolate is disposed so this call is pointless if an Isolate is about
7607 * to be Disposed.
7608 */
7609 void DiscardThreadSpecificMetadata();
7610
7611 /**
7612 * Associate embedder-specific data with the isolate. |slot| has to be
7613 * between 0 and GetNumberOfDataSlots() - 1.
7614 */
7615 V8_INLINE void SetData(uint32_t slot, void* data);
7616
7617 /**
7618 * Retrieve embedder-specific data from the isolate.
7619 * Returns NULL if SetData has never been called for the given |slot|.
7620 */
7621 V8_INLINE void* GetData(uint32_t slot);
7622
7623 /**
7624 * Returns the maximum number of available embedder data slots. Valid slots
7625 * are in the range of 0 - GetNumberOfDataSlots() - 1.
7626 */
7627 V8_INLINE static uint32_t GetNumberOfDataSlots();
7628
7629 /**
7630 * Return data that was previously attached to the isolate snapshot via
7631 * SnapshotCreator, and removes the reference to it.
7632 * Repeated call with the same index returns an empty MaybeLocal.
7633 */
7634 template <class T>
7635 V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
7636
7637 /**
7638 * Get statistics about the heap memory usage.
7639 */
7640 void GetHeapStatistics(HeapStatistics* heap_statistics);
7641
7642 /**
7643 * Returns the number of spaces in the heap.
7644 */
7645 size_t NumberOfHeapSpaces();
7646
7647 /**
7648 * Get the memory usage of a space in the heap.
7649 *
7650 * \param space_statistics The HeapSpaceStatistics object to fill in
7651 * statistics.
7652 * \param index The index of the space to get statistics from, which ranges
7653 * from 0 to NumberOfHeapSpaces() - 1.
7654 * \returns true on success.
7655 */
7656 bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7657 size_t index);
7658
7659 /**
7660 * Returns the number of types of objects tracked in the heap at GC.
7661 */
7662 size_t NumberOfTrackedHeapObjectTypes();
7663
7664 /**
7665 * Get statistics about objects in the heap.
7666 *
7667 * \param object_statistics The HeapObjectStatistics object to fill in
7668 * statistics of objects of given type, which were live in the previous GC.
7669 * \param type_index The index of the type of object to fill details about,
7670 * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
7671 * \returns true on success.
7672 */
7673 bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
7674 size_t type_index);
7675
7676 /**
7677 * Get statistics about code and its metadata in the heap.
7678 *
7679 * \param object_statistics The HeapCodeStatistics object to fill in
7680 * statistics of code, bytecode and their metadata.
7681 * \returns true on success.
7682 */
7683 bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
7684
7685 /**
7686 * Get a call stack sample from the isolate.
7687 * \param state Execution state.
7688 * \param frames Caller allocated buffer to store stack frames.
7689 * \param frames_limit Maximum number of frames to capture. The buffer must
7690 * be large enough to hold the number of frames.
7691 * \param sample_info The sample info is filled up by the function
7692 * provides number of actual captured stack frames and
7693 * the current VM state.
7694 * \note GetStackSample should only be called when the JS thread is paused or
7695 * interrupted. Otherwise the behavior is undefined.
7696 */
7697 void GetStackSample(const RegisterState& state, void** frames,
7698 size_t frames_limit, SampleInfo* sample_info);
7699
7700 /**
7701 * Adjusts the amount of registered external memory. Used to give V8 an
7702 * indication of the amount of externally allocated memory that is kept alive
7703 * by JavaScript objects. V8 uses this to decide when to perform global
7704 * garbage collections. Registering externally allocated memory will trigger
7705 * global garbage collections more often than it would otherwise in an attempt
7706 * to garbage collect the JavaScript objects that keep the externally
7707 * allocated memory alive.
7708 *
7709 * \param change_in_bytes the change in externally allocated memory that is
7710 * kept alive by JavaScript objects.
7711 * \returns the adjusted value.
7712 */
7713 V8_INLINE int64_t
7714 AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
7715
7716 /**
7717 * Returns the number of phantom handles without callbacks that were reset
7718 * by the garbage collector since the last call to this function.
7719 */
7720 size_t NumberOfPhantomHandleResetsSinceLastCall();
7721
7722 /**
7723 * Returns heap profiler for this isolate. Will return NULL until the isolate
7724 * is initialized.
7725 */
7726 HeapProfiler* GetHeapProfiler();
7727
7728 /**
7729 * Tells the VM whether the embedder is idle or not.
7730 */
7731 void SetIdle(bool is_idle);
7732
7733 /** Returns true if this isolate has a current context. */
7734 bool InContext();
7735
7736 /**
7737 * Returns the context of the currently running JavaScript, or the context
7738 * on the top of the stack if no JavaScript is running.
7739 */
7740 Local<Context> GetCurrentContext();
7741
7742 /** Returns the last context entered through V8's C++ API. */
7743 Local<Context> GetEnteredContext();
7744
7745 /**
7746 * Returns either the last context entered through V8's C++ API, or the
7747 * context of the currently running microtask while processing microtasks.
7748 * If a context is entered while executing a microtask, that context is
7749 * returned.
7750 */
7751 Local<Context> GetEnteredOrMicrotaskContext();
7752
7753 /**
7754 * Returns the Context that corresponds to the Incumbent realm in HTML spec.
7755 * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
7756 */
7757 Local<Context> GetIncumbentContext();
7758
7759 /**
7760 * Schedules an exception to be thrown when returning to JavaScript. When an
7761 * exception has been scheduled it is illegal to invoke any JavaScript
7762 * operation; the caller must return immediately and only after the exception
7763 * has been handled does it become legal to invoke JavaScript operations.
7764 */
7765 Local<Value> ThrowException(Local<Value> exception);
7766
7767 typedef void (*GCCallback)(Isolate* isolate, GCType type,
7768 GCCallbackFlags flags);
7769 typedef void (*GCCallbackWithData)(Isolate* isolate, GCType type,
7770 GCCallbackFlags flags, void* data);
7771
7772 /**
7773 * Enables the host application to receive a notification before a
7774 * garbage collection. Allocations are allowed in the callback function,
7775 * but the callback is not re-entrant: if the allocation inside it will
7776 * trigger the garbage collection, the callback won't be called again.
7777 * It is possible to specify the GCType filter for your callback. But it is
7778 * not possible to register the same callback function two times with
7779 * different GCType filters.
7780 */
7781 void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
7782 GCType gc_type_filter = kGCTypeAll);
7783 void AddGCPrologueCallback(GCCallback callback,
7784 GCType gc_type_filter = kGCTypeAll);
7785
7786 /**
7787 * This function removes callback which was installed by
7788 * AddGCPrologueCallback function.
7789 */
7790 void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
7791 void RemoveGCPrologueCallback(GCCallback callback);
7792
7793 /**
7794 * Sets the embedder heap tracer for the isolate.
7795 */
7796 void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
7797
7798 /**
7799 * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
7800 */
7801 enum class AtomicsWaitEvent {
7802 /** Indicates that this call is happening before waiting. */
7803 kStartWait,
7804 /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
7805 kWokenUp,
7806 /** `Atomics.wait()` finished because it timed out. */
7807 kTimedOut,
7808 /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
7809 kTerminatedExecution,
7810 /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
7811 kAPIStopped,
7812 /** `Atomics.wait()` did not wait, as the initial condition was not met. */
7813 kNotEqual
7814 };
7815
7816 /**
7817 * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
7818 * `Atomics.wait` call.
7819 */
7820 class V8_EXPORT AtomicsWaitWakeHandle {
7821 public:
7822 /**
7823 * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
7824 * with |kAPIStopped|.
7825 *
7826 * This function may be called from another thread. The caller has to ensure
7827 * through proper synchronization that it is not called after
7828 * the finishing |AtomicsWaitCallback|.
7829 *
7830 * Note that the ECMAScript specification does not plan for the possibility
7831 * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
7832 * call, so this may invalidate assumptions made by existing code.
7833 * The embedder may accordingly wish to schedule an exception in the
7834 * finishing |AtomicsWaitCallback|.
7835 */
7836 void Wake();
7837 };
7838
7839 /**
7840 * Embedder callback for `Atomics.wait()` that can be added through
7841 * |SetAtomicsWaitCallback|.
7842 *
7843 * This will be called just before starting to wait with the |event| value
7844 * |kStartWait| and after finishing waiting with one of the other
7845 * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
7846 *
7847 * |array_buffer| will refer to the underlying SharedArrayBuffer,
7848 * |offset_in_bytes| to the location of the waited-on memory address inside
7849 * the SharedArrayBuffer.
7850 *
7851 * |value| and |timeout_in_ms| will be the values passed to
7852 * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
7853 * will be `INFINITY`.
7854 *
7855 * In the |kStartWait| callback, |stop_handle| will be an object that
7856 * is only valid until the corresponding finishing callback and that
7857 * can be used to stop the wait process while it is happening.
7858 *
7859 * This callback may schedule exceptions, *unless* |event| is equal to
7860 * |kTerminatedExecution|.
7861 */
7862 typedef void (*AtomicsWaitCallback)(AtomicsWaitEvent event,
7863 Local<SharedArrayBuffer> array_buffer,
7864 size_t offset_in_bytes, int32_t value,
7865 double timeout_in_ms,
7866 AtomicsWaitWakeHandle* stop_handle,
7867 void* data);
7868
7869 /**
7870 * Set a new |AtomicsWaitCallback|. This overrides an earlier
7871 * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
7872 * this unsets the callback. |data| will be passed to the callback
7873 * as its last parameter.
7874 */
7875 void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
7876
7877 /**
7878 * Enables the host application to receive a notification after a
7879 * garbage collection. Allocations are allowed in the callback function,
7880 * but the callback is not re-entrant: if the allocation inside it will
7881 * trigger the garbage collection, the callback won't be called again.
7882 * It is possible to specify the GCType filter for your callback. But it is
7883 * not possible to register the same callback function two times with
7884 * different GCType filters.
7885 */
7886 void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
7887 GCType gc_type_filter = kGCTypeAll);
7888 void AddGCEpilogueCallback(GCCallback callback,
7889 GCType gc_type_filter = kGCTypeAll);
7890
7891 /**
7892 * This function removes callback which was installed by
7893 * AddGCEpilogueCallback function.
7894 */
7895 void RemoveGCEpilogueCallback(GCCallbackWithData callback,
7896 void* data = nullptr);
7897 void RemoveGCEpilogueCallback(GCCallback callback);
7898
7899 typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
7900
7901 /**
7902 * Set the callback that tells V8 how much memory is currently allocated
7903 * externally of the V8 heap. Ideally this memory is somehow connected to V8
7904 * objects and may get freed-up when the corresponding V8 objects get
7905 * collected by a V8 garbage collection.
7906 */
7907 void SetGetExternallyAllocatedMemoryInBytesCallback(
7908 GetExternallyAllocatedMemoryInBytesCallback callback);
7909
7910 /**
7911 * Forcefully terminate the current thread of JavaScript execution
7912 * in the given isolate.
7913 *
7914 * This method can be used by any thread even if that thread has not
7915 * acquired the V8 lock with a Locker object.
7916 */
7917 void TerminateExecution();
7918
7919 /**
7920 * Is V8 terminating JavaScript execution.
7921 *
7922 * Returns true if JavaScript execution is currently terminating
7923 * because of a call to TerminateExecution. In that case there are
7924 * still JavaScript frames on the stack and the termination
7925 * exception is still active.
7926 */
7927 bool IsExecutionTerminating();
7928
7929 /**
7930 * Resume execution capability in the given isolate, whose execution
7931 * was previously forcefully terminated using TerminateExecution().
7932 *
7933 * When execution is forcefully terminated using TerminateExecution(),
7934 * the isolate can not resume execution until all JavaScript frames
7935 * have propagated the uncatchable exception which is generated. This
7936 * method allows the program embedding the engine to handle the
7937 * termination event and resume execution capability, even if
7938 * JavaScript frames remain on the stack.
7939 *
7940 * This method can be used by any thread even if that thread has not
7941 * acquired the V8 lock with a Locker object.
7942 */
7943 void CancelTerminateExecution();
7944
7945 /**
7946 * Request V8 to interrupt long running JavaScript code and invoke
7947 * the given |callback| passing the given |data| to it. After |callback|
7948 * returns control will be returned to the JavaScript code.
7949 * There may be a number of interrupt requests in flight.
7950 * Can be called from another thread without acquiring a |Locker|.
7951 * Registered |callback| must not reenter interrupted Isolate.
7952 */
7953 void RequestInterrupt(InterruptCallback callback, void* data);
7954
7955 /**
7956 * Request garbage collection in this Isolate. It is only valid to call this
7957 * function if --expose_gc was specified.
7958 *
7959 * This should only be used for testing purposes and not to enforce a garbage
7960 * collection schedule. It has strong negative impact on the garbage
7961 * collection performance. Use IdleNotificationDeadline() or
7962 * LowMemoryNotification() instead to influence the garbage collection
7963 * schedule.
7964 */
7965 void RequestGarbageCollectionForTesting(GarbageCollectionType type);
7966
7967 /**
7968 * Set the callback to invoke for logging event.
7969 */
7970 void SetEventLogger(LogEventCallback that);
7971
7972 /**
7973 * Adds a callback to notify the host application right before a script
7974 * is about to run. If a script re-enters the runtime during executing, the
7975 * BeforeCallEnteredCallback is invoked for each re-entrance.
7976 * Executing scripts inside the callback will re-trigger the callback.
7977 */
7978 void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
7979
7980 /**
7981 * Removes callback that was installed by AddBeforeCallEnteredCallback.
7982 */
7983 void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
7984
7985 /**
7986 * Adds a callback to notify the host application when a script finished
7987 * running. If a script re-enters the runtime during executing, the
7988 * CallCompletedCallback is only invoked when the outer-most script
7989 * execution ends. Executing scripts inside the callback do not trigger
7990 * further callbacks.
7991 */
7992 void AddCallCompletedCallback(CallCompletedCallback callback);
7993
7994 /**
7995 * Removes callback that was installed by AddCallCompletedCallback.
7996 */
7997 void RemoveCallCompletedCallback(CallCompletedCallback callback);
7998
7999 /**
8000 * Set the PromiseHook callback for various promise lifecycle
8001 * events.
8002 */
8003 void SetPromiseHook(PromiseHook hook);
8004
8005 /**
8006 * Set callback to notify about promise reject with no handler, or
8007 * revocation of such a previous notification once the handler is added.
8008 */
8009 void SetPromiseRejectCallback(PromiseRejectCallback callback);
8010
8011 /**
8012 * Runs the Microtask Work Queue until empty
8013 * Any exceptions thrown by microtask callbacks are swallowed.
8014 */
8015 void RunMicrotasks();
8016
8017 /**
8018 * Enqueues the callback to the Microtask Work Queue
8019 */
8020 void EnqueueMicrotask(Local<Function> microtask);
8021
8022 /**
8023 * Enqueues the callback to the Microtask Work Queue
8024 */
8025 void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
8026
8027 /**
8028 * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
8029 */
8030 void SetMicrotasksPolicy(MicrotasksPolicy policy);
8031
8032 /**
8033 * Returns the policy controlling how Microtasks are invoked.
8034 */
8035 MicrotasksPolicy GetMicrotasksPolicy() const;
8036
8037 /**
8038 * Adds a callback to notify the host application after
8039 * microtasks were run. The callback is triggered by explicit RunMicrotasks
8040 * call or automatic microtasks execution (see SetAutorunMicrotasks).
8041 *
8042 * Callback will trigger even if microtasks were attempted to run,
8043 * but the microtasks queue was empty and no single microtask was actually
8044 * executed.
8045 *
8046 * Executing scriptsinside the callback will not re-trigger microtasks and
8047 * the callback.
8048 */
8049 void AddMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
8050
8051 /**
8052 * Removes callback that was installed by AddMicrotasksCompletedCallback.
8053 */
8054 void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallback callback);
8055
8056 /**
8057 * Sets a callback for counting the number of times a feature of V8 is used.
8058 */
8059 void SetUseCounterCallback(UseCounterCallback callback);
8060
8061 /**
8062 * Enables the host application to provide a mechanism for recording
8063 * statistics counters.
8064 */
8065 void SetCounterFunction(CounterLookupCallback);
8066
8067 /**
8068 * Enables the host application to provide a mechanism for recording
8069 * histograms. The CreateHistogram function returns a
8070 * histogram which will later be passed to the AddHistogramSample
8071 * function.
8072 */
8073 void SetCreateHistogramFunction(CreateHistogramCallback);
8074 void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
8075
8076 /**
8077 * Optional notification that the embedder is idle.
8078 * V8 uses the notification to perform garbage collection.
8079 * This call can be used repeatedly if the embedder remains idle.
8080 * Returns true if the embedder should stop calling IdleNotificationDeadline
8081 * until real work has been done. This indicates that V8 has done
8082 * as much cleanup as it will be able to do.
8083 *
8084 * The deadline_in_seconds argument specifies the deadline V8 has to finish
8085 * garbage collection work. deadline_in_seconds is compared with
8086 * MonotonicallyIncreasingTime() and should be based on the same timebase as
8087 * that function. There is no guarantee that the actual work will be done
8088 * within the time limit.
8089 */
8090 bool IdleNotificationDeadline(double deadline_in_seconds);
8091
8092 /**
8093 * Optional notification that the system is running low on memory.
8094 * V8 uses these notifications to attempt to free memory.
8095 */
8096 void LowMemoryNotification();
8097
8098 /**
8099 * Optional notification that a context has been disposed. V8 uses
8100 * these notifications to guide the GC heuristic. Returns the number
8101 * of context disposals - including this one - since the last time
8102 * V8 had a chance to clean up.
8103 *
8104 * The optional parameter |dependant_context| specifies whether the disposed
8105 * context was depending on state from other contexts or not.
8106 */
8107 int ContextDisposedNotification(bool dependant_context = true);
8108
8109 /**
8110 * Optional notification that the isolate switched to the foreground.
8111 * V8 uses these notifications to guide heuristics.
8112 */
8113 void IsolateInForegroundNotification();
8114
8115 /**
8116 * Optional notification that the isolate switched to the background.
8117 * V8 uses these notifications to guide heuristics.
8118 */
8119 void IsolateInBackgroundNotification();
8120
8121 /**
8122 * Optional notification which will enable the memory savings mode.
8123 * V8 uses this notification to guide heuristics which may result in a
8124 * smaller memory footprint at the cost of reduced runtime performance.
8125 */
8126 void EnableMemorySavingsMode();
8127
8128 /**
8129 * Optional notification which will disable the memory savings mode.
8130 */
8131 void DisableMemorySavingsMode();
8132
8133 /**
8134 * Optional notification to tell V8 the current performance requirements
8135 * of the embedder based on RAIL.
8136 * V8 uses these notifications to guide heuristics.
8137 * This is an unfinished experimental feature. Semantics and implementation
8138 * may change frequently.
8139 */
8140 void SetRAILMode(RAILMode rail_mode);
8141
8142 /**
8143 * Optional notification to tell V8 the current isolate is used for debugging
8144 * and requires higher heap limit.
8145 */
8146 void IncreaseHeapLimitForDebugging();
8147
8148 /**
8149 * Restores the original heap limit after IncreaseHeapLimitForDebugging().
8150 */
8151 void RestoreOriginalHeapLimit();
8152
8153 /**
8154 * Returns true if the heap limit was increased for debugging and the
8155 * original heap limit was not restored yet.
8156 */
8157 bool IsHeapLimitIncreasedForDebugging();
8158
8159 /**
8160 * Allows the host application to provide the address of a function that is
8161 * notified each time code is added, moved or removed.
8162 *
8163 * \param options options for the JIT code event handler.
8164 * \param event_handler the JIT code event handler, which will be invoked
8165 * each time code is added, moved or removed.
8166 * \note \p event_handler won't get notified of existent code.
8167 * \note since code removal notifications are not currently issued, the
8168 * \p event_handler may get notifications of code that overlaps earlier
8169 * code notifications. This happens when code areas are reused, and the
8170 * earlier overlapping code areas should therefore be discarded.
8171 * \note the events passed to \p event_handler and the strings they point to
8172 * are not guaranteed to live past each call. The \p event_handler must
8173 * copy strings and other parameters it needs to keep around.
8174 * \note the set of events declared in JitCodeEvent::EventType is expected to
8175 * grow over time, and the JitCodeEvent structure is expected to accrue
8176 * new members. The \p event_handler function must ignore event codes
8177 * it does not recognize to maintain future compatibility.
8178 * \note Use Isolate::CreateParams to get events for code executed during
8179 * Isolate setup.
8180 */
8181 void SetJitCodeEventHandler(JitCodeEventOptions options,
8182 JitCodeEventHandler event_handler);
8183
8184 /**
8185 * Modifies the stack limit for this Isolate.
8186 *
8187 * \param stack_limit An address beyond which the Vm's stack may not grow.
8188 *
8189 * \note If you are using threads then you should hold the V8::Locker lock
8190 * while setting the stack limit and you must set a non-default stack
8191 * limit separately for each thread.
8192 */
8193 void SetStackLimit(uintptr_t stack_limit);
8194
8195 /**
8196 * Returns a memory range that can potentially contain jitted code.
8197 *
8198 * On Win64, embedders are advised to install function table callbacks for
8199 * these ranges, as default SEH won't be able to unwind through jitted code.
8200 *
8201 * The first page of the code range is reserved for the embedder and is
8202 * committed, writable, and executable.
8203 *
8204 * Might be empty on other platforms.
8205 *
8206 * https://code.google.com/p/v8/issues/detail?id=3598
8207 */
8208 void GetCodeRange(void** start, size_t* length_in_bytes);
8209
8210 /** Set the callback to invoke in case of fatal errors. */
8211 void SetFatalErrorHandler(FatalErrorCallback that);
8212
8213 /** Set the callback to invoke in case of OOM errors. */
8214 void SetOOMErrorHandler(OOMErrorCallback that);
8215
8216 /**
8217 * Add a callback to invoke in case the heap size is close to the heap limit.
8218 * If multiple callbacks are added, only the most recently added callback is
8219 * invoked.
8220 */
8221 void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
8222
8223 /**
8224 * Remove the given callback and restore the heap limit to the
8225 * given limit. If the given limit is zero, then it is ignored.
8226 * If the current heap size is greater than the given limit,
8227 * then the heap limit is restored to the minimal limit that
8228 * is possible for the current heap size.
8229 */
8230 void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
8231 size_t heap_limit);
8232
8233 /**
8234 * Set the callback to invoke to check if code generation from
8235 * strings should be allowed.
8236 */
8237 void SetAllowCodeGenerationFromStringsCallback(
8238 AllowCodeGenerationFromStringsCallback callback);
8239
8240 /**
8241 * Set the callback to invoke to check if wasm code generation should
8242 * be allowed.
8243 */
8244 void SetAllowWasmCodeGenerationCallback(
8245 AllowWasmCodeGenerationCallback callback);
8246
8247 /**
8248 * Embedder over{ride|load} injection points for wasm APIs. The expectation
8249 * is that the embedder sets them at most once.
8250 */
8251 void SetWasmModuleCallback(ExtensionCallback callback);
8252 void SetWasmInstanceCallback(ExtensionCallback callback);
8253
8254 void SetWasmCompileStreamingCallback(ApiImplementationCallback callback);
8255
8256 void SetWasmStreamingCallback(WasmStreamingCallback callback);
8257
8258 void SetWasmThreadsEnabledCallback(WasmThreadsEnabledCallback callback);
8259
8260 /**
8261 * Check if V8 is dead and therefore unusable. This is the case after
8262 * fatal errors such as out-of-memory situations.
8263 */
8264 bool IsDead();
8265
8266 /**
8267 * Adds a message listener (errors only).
8268 *
8269 * The same message listener can be added more than once and in that
8270 * case it will be called more than once for each message.
8271 *
8272 * If data is specified, it will be passed to the callback when it is called.
8273 * Otherwise, the exception object will be passed to the callback instead.
8274 */
8275 bool AddMessageListener(MessageCallback that,
8276 Local<Value> data = Local<Value>());
8277
8278 /**
8279 * Adds a message listener.
8280 *
8281 * The same message listener can be added more than once and in that
8282 * case it will be called more than once for each message.
8283 *
8284 * If data is specified, it will be passed to the callback when it is called.
8285 * Otherwise, the exception object will be passed to the callback instead.
8286 *
8287 * A listener can listen for particular error levels by providing a mask.
8288 */
8289 bool AddMessageListenerWithErrorLevel(MessageCallback that,
8290 int message_levels,
8291 Local<Value> data = Local<Value>());
8292
8293 /**
8294 * Remove all message listeners from the specified callback function.
8295 */
8296 void RemoveMessageListeners(MessageCallback that);
8297
8298 /** Callback function for reporting failed access checks.*/
8299 void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
8300
8301 /**
8302 * Tells V8 to capture current stack trace when uncaught exception occurs
8303 * and report it to the message listeners. The option is off by default.
8304 */
8305 void SetCaptureStackTraceForUncaughtExceptions(
8306 bool capture, int frame_limit = 10,
8307 StackTrace::StackTraceOptions options = StackTrace::kOverview);
8308
8309 /**
8310 * Iterates through all external resources referenced from current isolate
8311 * heap. GC is not invoked prior to iterating, therefore there is no
8312 * guarantee that visited objects are still alive.
8313 */
8314 void VisitExternalResources(ExternalResourceVisitor* visitor);
8315
8316 /**
8317 * Iterates through all the persistent handles in the current isolate's heap
8318 * that have class_ids.
8319 */
8320 void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
8321
8322 /**
8323 * Iterates through all the persistent handles in the current isolate's heap
8324 * that have class_ids and are candidates to be marked as partially dependent
8325 * handles. This will visit handles to young objects created since the last
8326 * garbage collection but is free to visit an arbitrary superset of these
8327 * objects.
8328 */
8329 void VisitHandlesForPartialDependence(PersistentHandleVisitor* visitor);
8330
8331 /**
8332 * Iterates through all the persistent handles in the current isolate's heap
8333 * that have class_ids and are weak to be marked as inactive if there is no
8334 * pending activity for the handle.
8335 */
8336 void VisitWeakHandles(PersistentHandleVisitor* visitor);
8337
8338 /**
8339 * Check if this isolate is in use.
8340 * True if at least one thread Enter'ed this isolate.
8341 */
8342 bool IsInUse();
8343
8344 /**
8345 * Set whether calling Atomics.wait (a function that may block) is allowed in
8346 * this isolate. This can also be configured via
8347 * CreateParams::allow_atomics_wait.
8348 */
8349 void SetAllowAtomicsWait(bool allow);
8350
8351 Isolate() = delete;
8352 ~Isolate() = delete;
8353 Isolate(const Isolate&) = delete;
8354 Isolate& operator=(const Isolate&) = delete;
8355 // Deleting operator new and delete here is allowed as ctor and dtor is also
8356 // deleted.
8357 void* operator new(size_t size) = delete;
8358 void* operator new[](size_t size) = delete;
8359 void operator delete(void*, size_t) = delete;
8360 void operator delete[](void*, size_t) = delete;
8361
8362 private:
8363 template <class K, class V, class Traits>
8364 friend class PersistentValueMapBase;
8365
8366 internal::Object** GetDataFromSnapshotOnce(size_t index);
8367 void ReportExternalAllocationLimitReached();
8368 void CheckMemoryPressure();
8369 };
8370
8371 class V8_EXPORT StartupData {
8372 public:
8373 const char* data;
8374 int raw_size;
8375 };
8376
8377
8378 /**
8379 * EntropySource is used as a callback function when v8 needs a source
8380 * of entropy.
8381 */
8382 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
8383
8384 /**
8385 * ReturnAddressLocationResolver is used as a callback function when v8 is
8386 * resolving the location of a return address on the stack. Profilers that
8387 * change the return address on the stack can use this to resolve the stack
8388 * location to wherever the profiler stashed the original return address.
8389 *
8390 * \param return_addr_location A location on stack where a machine
8391 * return address resides.
8392 * \returns Either return_addr_location, or else a pointer to the profiler's
8393 * copy of the original return address.
8394 *
8395 * \note The resolver function must not cause garbage collection.
8396 */
8397 typedef uintptr_t (*ReturnAddressLocationResolver)(
8398 uintptr_t return_addr_location);
8399
8400
8401 /**
8402 * Container class for static utility functions.
8403 */
8404 class V8_EXPORT V8 {
8405 public:
8406 /**
8407 * Hand startup data to V8, in case the embedder has chosen to build
8408 * V8 with external startup data.
8409 *
8410 * Note:
8411 * - By default the startup data is linked into the V8 library, in which
8412 * case this function is not meaningful.
8413 * - If this needs to be called, it needs to be called before V8
8414 * tries to make use of its built-ins.
8415 * - To avoid unnecessary copies of data, V8 will point directly into the
8416 * given data blob, so pretty please keep it around until V8 exit.
8417 * - Compression of the startup blob might be useful, but needs to
8418 * handled entirely on the embedders' side.
8419 * - The call will abort if the data is invalid.
8420 */
8421 static void SetNativesDataBlob(StartupData* startup_blob);
8422 static void SetSnapshotDataBlob(StartupData* startup_blob);
8423
8424 /** Set the callback to invoke in case of Dcheck failures. */
8425 static void SetDcheckErrorHandler(DcheckErrorCallback that);
8426
8427
8428 /**
8429 * Sets V8 flags from a string.
8430 */
8431 static void SetFlagsFromString(const char* str, int length);
8432
8433 /**
8434 * Sets V8 flags from the command line.
8435 */
8436 static void SetFlagsFromCommandLine(int* argc,
8437 char** argv,
8438 bool remove_flags);
8439
8440 /** Get the version string. */
8441 static const char* GetVersion();
8442
8443 /**
8444 * Initializes V8. This function needs to be called before the first Isolate
8445 * is created. It always returns true.
8446 */
8447 static bool Initialize();
8448
8449 /**
8450 * Allows the host application to provide a callback which can be used
8451 * as a source of entropy for random number generators.
8452 */
8453 static void SetEntropySource(EntropySource source);
8454
8455 /**
8456 * Allows the host application to provide a callback that allows v8 to
8457 * cooperate with a profiler that rewrites return addresses on stack.
8458 */
8459 static void SetReturnAddressLocationResolver(
8460 ReturnAddressLocationResolver return_address_resolver);
8461
8462 /**
8463 * Releases any resources used by v8 and stops any utility threads
8464 * that may be running. Note that disposing v8 is permanent, it
8465 * cannot be reinitialized.
8466 *
8467 * It should generally not be necessary to dispose v8 before exiting
8468 * a process, this should happen automatically. It is only necessary
8469 * to use if the process needs the resources taken up by v8.
8470 */
8471 static bool Dispose();
8472
8473 /**
8474 * Initialize the ICU library bundled with V8. The embedder should only
8475 * invoke this method when using the bundled ICU. Returns true on success.
8476 *
8477 * If V8 was compiled with the ICU data in an external file, the location
8478 * of the data file has to be provided.
8479 */
8480 static bool InitializeICU(const char* icu_data_file = nullptr);
8481
8482 /**
8483 * Initialize the ICU library bundled with V8. The embedder should only
8484 * invoke this method when using the bundled ICU. If V8 was compiled with
8485 * the ICU data in an external file and when the default location of that
8486 * file should be used, a path to the executable must be provided.
8487 * Returns true on success.
8488 *
8489 * The default is a file called icudtl.dat side-by-side with the executable.
8490 *
8491 * Optionally, the location of the data file can be provided to override the
8492 * default.
8493 */
8494 static bool InitializeICUDefaultLocation(const char* exec_path,
8495 const char* icu_data_file = nullptr);
8496
8497 /**
8498 * Initialize the external startup data. The embedder only needs to
8499 * invoke this method when external startup data was enabled in a build.
8500 *
8501 * If V8 was compiled with the startup data in an external file, then
8502 * V8 needs to be given those external files during startup. There are
8503 * three ways to do this:
8504 * - InitializeExternalStartupData(const char*)
8505 * This will look in the given directory for files "natives_blob.bin"
8506 * and "snapshot_blob.bin" - which is what the default build calls them.
8507 * - InitializeExternalStartupData(const char*, const char*)
8508 * As above, but will directly use the two given file names.
8509 * - Call SetNativesDataBlob, SetNativesDataBlob.
8510 * This will read the blobs from the given data structures and will
8511 * not perform any file IO.
8512 */
8513 static void InitializeExternalStartupData(const char* directory_path);
8514 static void InitializeExternalStartupData(const char* natives_blob,
8515 const char* snapshot_blob);
8516 /**
8517 * Sets the v8::Platform to use. This should be invoked before V8 is
8518 * initialized.
8519 */
8520 static void InitializePlatform(Platform* platform);
8521
8522 /**
8523 * Clears all references to the v8::Platform. This should be invoked after
8524 * V8 was disposed.
8525 */
8526 static void ShutdownPlatform();
8527
8528 #if V8_OS_POSIX
8529 /**
8530 * Give the V8 signal handler a chance to handle a fault.
8531 *
8532 * This function determines whether a memory access violation can be recovered
8533 * by V8. If so, it will return true and modify context to return to a code
8534 * fragment that can recover from the fault. Otherwise, TryHandleSignal will
8535 * return false.
8536 *
8537 * The parameters to this function correspond to those passed to a Linux
8538 * signal handler.
8539 *
8540 * \param signal_number The signal number.
8541 *
8542 * \param info A pointer to the siginfo_t structure provided to the signal
8543 * handler.
8544 *
8545 * \param context The third argument passed to the Linux signal handler, which
8546 * points to a ucontext_t structure.
8547 */
8548 static bool TryHandleSignal(int signal_number, void* info, void* context);
8549 #endif // V8_OS_POSIX
8550
8551 /**
8552 * Enable the default signal handler rather than using one provided by the
8553 * embedder.
8554 */
8555 V8_DEPRECATE_SOON("Use EnableWebAssemblyTrapHandler",
8556 static bool RegisterDefaultSignalHandler());
8557
8558 /**
8559 * Activate trap-based bounds checking for WebAssembly.
8560 *
8561 * \param use_v8_signal_handler Whether V8 should install its own signal
8562 * handler or rely on the embedder's.
8563 */
8564 static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
8565
8566 private:
8567 V8();
8568
8569 static internal::Object** GlobalizeReference(internal::Isolate* isolate,
8570 internal::Object** handle);
8571 static internal::Object** CopyPersistent(internal::Object** handle);
8572 static void DisposeGlobal(internal::Object** global_handle);
8573 static void MakeWeak(internal::Object** location, void* data,
8574 WeakCallbackInfo<void>::Callback weak_callback,
8575 WeakCallbackType type);
8576 static void MakeWeak(internal::Object** location, void* data,
8577 // Must be 0 or -1.
8578 int internal_field_index1,
8579 // Must be 1 or -1.
8580 int internal_field_index2,
8581 WeakCallbackInfo<void>::Callback weak_callback);
8582 static void MakeWeak(internal::Object*** location_addr);
8583 static void* ClearWeak(internal::Object** location);
8584 static void AnnotateStrongRetainer(internal::Object** location,
8585 const char* label);
8586 static Value* Eternalize(Isolate* isolate, Value* handle);
8587
8588 static void RegisterExternallyReferencedObject(internal::Object** object,
8589 internal::Isolate* isolate);
8590
8591 template <class K, class V, class T>
8592 friend class PersistentValueMapBase;
8593
8594 static void FromJustIsNothing();
8595 static void ToLocalEmpty();
8596 static void InternalFieldOutOfBounds(int index);
8597 template <class T> friend class Local;
8598 template <class T>
8599 friend class MaybeLocal;
8600 template <class T>
8601 friend class Maybe;
8602 template <class T>
8603 friend class WeakCallbackInfo;
8604 template <class T> friend class Eternal;
8605 template <class T> friend class PersistentBase;
8606 template <class T, class M> friend class Persistent;
8607 friend class Context;
8608 };
8609
8610 /**
8611 * Helper class to create a snapshot data blob.
8612 */
8613 class V8_EXPORT SnapshotCreator {
8614 public:
8615 enum class FunctionCodeHandling { kClear, kKeep };
8616
8617 /**
8618 * Initialize and enter an isolate, and set it up for serialization.
8619 * The isolate is either created from scratch or from an existing snapshot.
8620 * The caller keeps ownership of the argument snapshot.
8621 * \param existing_blob existing snapshot from which to create this one.
8622 * \param external_references a null-terminated array of external references
8623 * that must be equivalent to CreateParams::external_references.
8624 */
8625 SnapshotCreator(Isolate* isolate,
8626 const intptr_t* external_references = nullptr,
8627 StartupData* existing_blob = nullptr);
8628
8629 /**
8630 * Create and enter an isolate, and set it up for serialization.
8631 * The isolate is either created from scratch or from an existing snapshot.
8632 * The caller keeps ownership of the argument snapshot.
8633 * \param existing_blob existing snapshot from which to create this one.
8634 * \param external_references a null-terminated array of external references
8635 * that must be equivalent to CreateParams::external_references.
8636 */
8637 SnapshotCreator(const intptr_t* external_references = nullptr,
8638 StartupData* existing_blob = nullptr);
8639
8640 ~SnapshotCreator();
8641
8642 /**
8643 * \returns the isolate prepared by the snapshot creator.
8644 */
8645 Isolate* GetIsolate();
8646
8647 /**
8648 * Set the default context to be included in the snapshot blob.
8649 * The snapshot will not contain the global proxy, and we expect one or a
8650 * global object template to create one, to be provided upon deserialization.
8651 *
8652 * \param callback optional callback to serialize internal fields.
8653 */
8654 void SetDefaultContext(Local<Context> context,
8655 SerializeInternalFieldsCallback callback =
8656 SerializeInternalFieldsCallback());
8657
8658 /**
8659 * Add additional context to be included in the snapshot blob.
8660 * The snapshot will include the global proxy.
8661 *
8662 * \param callback optional callback to serialize internal fields.
8663 *
8664 * \returns the index of the context in the snapshot blob.
8665 */
8666 size_t AddContext(Local<Context> context,
8667 SerializeInternalFieldsCallback callback =
8668 SerializeInternalFieldsCallback());
8669
8670 /**
8671 * Add a template to be included in the snapshot blob.
8672 * \returns the index of the template in the snapshot blob.
8673 */
8674 size_t AddTemplate(Local<Template> template_obj);
8675
8676 /**
8677 * Attach arbitrary V8::Data to the context snapshot, which can be retrieved
8678 * via Context::GetDataFromSnapshot after deserialization. This data does not
8679 * survive when a new snapshot is created from an existing snapshot.
8680 * \returns the index for retrieval.
8681 */
8682 template <class T>
8683 V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
8684
8685 /**
8686 * Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
8687 * via Isolate::GetDataFromSnapshot after deserialization. This data does not
8688 * survive when a new snapshot is created from an existing snapshot.
8689 * \returns the index for retrieval.
8690 */
8691 template <class T>
8692 V8_INLINE size_t AddData(Local<T> object);
8693
8694 /**
8695 * Created a snapshot data blob.
8696 * This must not be called from within a handle scope.
8697 * \param function_code_handling whether to include compiled function code
8698 * in the snapshot.
8699 * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
8700 * caller acquires ownership of the data array in the return value.
8701 */
8702 StartupData CreateBlob(FunctionCodeHandling function_code_handling);
8703
8704 // Disallow copying and assigning.
8705 SnapshotCreator(const SnapshotCreator&) = delete;
8706 void operator=(const SnapshotCreator&) = delete;
8707
8708 private:
8709 size_t AddData(Local<Context> context, internal::Object* object);
8710 size_t AddData(internal::Object* object);
8711
8712 void* data_;
8713 };
8714
8715 /**
8716 * A simple Maybe type, representing an object which may or may not have a
8717 * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
8718 *
8719 * If an API method returns a Maybe<>, the API method can potentially fail
8720 * either because an exception is thrown, or because an exception is pending,
8721 * e.g. because a previous API call threw an exception that hasn't been caught
8722 * yet, or because a TerminateExecution exception was thrown. In that case, a
8723 * "Nothing" value is returned.
8724 */
8725 template <class T>
8726 class Maybe {
8727 public:
8728 V8_INLINE bool IsNothing() const { return !has_value_; }
8729 V8_INLINE bool IsJust() const { return has_value_; }
8730
8731 /**
8732 * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
8733 */
8734 V8_INLINE T ToChecked() const { return FromJust(); }
8735
8736 /**
8737 * Converts this Maybe<> to a value of type T. If this Maybe<> is
8738 * nothing (empty), |false| is returned and |out| is left untouched.
8739 */
8740 V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
8741 if (V8_LIKELY(IsJust())) *out = value_;
8742 return IsJust();
8743 }
8744
8745 /**
8746 * Converts this Maybe<> to a value of type T. If this Maybe<> is
8747 * nothing (empty), V8 will crash the process.
8748 */
8749 V8_INLINE T FromJust() const {
8750 if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
8751 return value_;
8752 }
8753
8754 /**
8755 * Converts this Maybe<> to a value of type T, using a default value if this
8756 * Maybe<> is nothing (empty).
8757 */
8758 V8_INLINE T FromMaybe(const T& default_value) const {
8759 return has_value_ ? value_ : default_value;
8760 }
8761
8762 V8_INLINE bool operator==(const Maybe& other) const {
8763 return (IsJust() == other.IsJust()) &&
8764 (!IsJust() || FromJust() == other.FromJust());
8765 }
8766
8767 V8_INLINE bool operator!=(const Maybe& other) const {
8768 return !operator==(other);
8769 }
8770
8771 private:
8772 Maybe() : has_value_(false) {}
8773 explicit Maybe(const T& t) : has_value_(true), value_(t) {}
8774
8775 bool has_value_;
8776 T value_;
8777
8778 template <class U>
8779 friend Maybe<U> Nothing();
8780 template <class U>
8781 friend Maybe<U> Just(const U& u);
8782 };
8783
8784 template <class T>
8785 inline Maybe<T> Nothing() {
8786 return Maybe<T>();
8787 }
8788
8789 template <class T>
8790 inline Maybe<T> Just(const T& t) {
8791 return Maybe<T>(t);
8792 }
8793
8794 // A template specialization of Maybe<T> for the case of T = void.
8795 template <>
8796 class Maybe<void> {
8797 public:
8798 V8_INLINE bool IsNothing() const { return !is_valid_; }
8799 V8_INLINE bool IsJust() const { return is_valid_; }
8800
8801 V8_INLINE bool operator==(const Maybe& other) const {
8802 return IsJust() == other.IsJust();
8803 }
8804
8805 V8_INLINE bool operator!=(const Maybe& other) const {
8806 return !operator==(other);
8807 }
8808
8809 private:
8810 struct JustTag {};
8811
8812 Maybe() : is_valid_(false) {}
8813 explicit Maybe(JustTag) : is_valid_(true) {}
8814
8815 bool is_valid_;
8816
8817 template <class U>
8818 friend Maybe<U> Nothing();
8819 friend Maybe<void> JustVoid();
8820 };
8821
8822 inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
8823
8824 /**
8825 * An external exception handler.
8826 */
8827 class V8_EXPORT TryCatch {
8828 public:
8829 /**
8830 * Creates a new try/catch block and registers it with v8. Note that
8831 * all TryCatch blocks should be stack allocated because the memory
8832 * location itself is compared against JavaScript try/catch blocks.
8833 */
8834 explicit TryCatch(Isolate* isolate);
8835
8836 /**
8837 * Unregisters and deletes this try/catch block.
8838 */
8839 ~TryCatch();
8840
8841 /**
8842 * Returns true if an exception has been caught by this try/catch block.
8843 */
8844 bool HasCaught() const;
8845
8846 /**
8847 * For certain types of exceptions, it makes no sense to continue execution.
8848 *
8849 * If CanContinue returns false, the correct action is to perform any C++
8850 * cleanup needed and then return. If CanContinue returns false and
8851 * HasTerminated returns true, it is possible to call
8852 * CancelTerminateExecution in order to continue calling into the engine.
8853 */
8854 bool CanContinue() const;
8855
8856 /**
8857 * Returns true if an exception has been caught due to script execution
8858 * being terminated.
8859 *
8860 * There is no JavaScript representation of an execution termination
8861 * exception. Such exceptions are thrown when the TerminateExecution
8862 * methods are called to terminate a long-running script.
8863 *
8864 * If such an exception has been thrown, HasTerminated will return true,
8865 * indicating that it is possible to call CancelTerminateExecution in order
8866 * to continue calling into the engine.
8867 */
8868 bool HasTerminated() const;
8869
8870 /**
8871 * Throws the exception caught by this TryCatch in a way that avoids
8872 * it being caught again by this same TryCatch. As with ThrowException
8873 * it is illegal to execute any JavaScript operations after calling
8874 * ReThrow; the caller must return immediately to where the exception
8875 * is caught.
8876 */
8877 Local<Value> ReThrow();
8878
8879 /**
8880 * Returns the exception caught by this try/catch block. If no exception has
8881 * been caught an empty handle is returned.
8882 *
8883 * The returned handle is valid until this TryCatch block has been destroyed.
8884 */
8885 Local<Value> Exception() const;
8886
8887 /**
8888 * Returns the .stack property of the thrown object. If no .stack
8889 * property is present an empty handle is returned.
8890 */
8891 V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
8892 Local<Context> context) const;
8893
8894 /**
8895 * Returns the message associated with this exception. If there is
8896 * no message associated an empty handle is returned.
8897 *
8898 * The returned handle is valid until this TryCatch block has been
8899 * destroyed.
8900 */
8901 Local<v8::Message> Message() const;
8902
8903 /**
8904 * Clears any exceptions that may have been caught by this try/catch block.
8905 * After this method has been called, HasCaught() will return false. Cancels
8906 * the scheduled exception if it is caught and ReThrow() is not called before.
8907 *
8908 * It is not necessary to clear a try/catch block before using it again; if
8909 * another exception is thrown the previously caught exception will just be
8910 * overwritten. However, it is often a good idea since it makes it easier
8911 * to determine which operation threw a given exception.
8912 */
8913 void Reset();
8914
8915 /**
8916 * Set verbosity of the external exception handler.
8917 *
8918 * By default, exceptions that are caught by an external exception
8919 * handler are not reported. Call SetVerbose with true on an
8920 * external exception handler to have exceptions caught by the
8921 * handler reported as if they were not caught.
8922 */
8923 void SetVerbose(bool value);
8924
8925 /**
8926 * Returns true if verbosity is enabled.
8927 */
8928 bool IsVerbose() const;
8929
8930 /**
8931 * Set whether or not this TryCatch should capture a Message object
8932 * which holds source information about where the exception
8933 * occurred. True by default.
8934 */
8935 void SetCaptureMessage(bool value);
8936
8937 /**
8938 * There are cases when the raw address of C++ TryCatch object cannot be
8939 * used for comparisons with addresses into the JS stack. The cases are:
8940 * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
8941 * 2) Address sanitizer allocates local C++ object in the heap when
8942 * UseAfterReturn mode is enabled.
8943 * This method returns address that can be used for comparisons with
8944 * addresses into the JS stack. When neither simulator nor ASAN's
8945 * UseAfterReturn is enabled, then the address returned will be the address
8946 * of the C++ try catch handler itself.
8947 */
8948 static void* JSStackComparableAddress(TryCatch* handler) {
8949 if (handler == NULL) return NULL;
8950 return handler->js_stack_comparable_address_;
8951 }
8952
8953 TryCatch(const TryCatch&) = delete;
8954 void operator=(const TryCatch&) = delete;
8955
8956 private:
8957 // Declaring operator new and delete as deleted is not spec compliant.
8958 // Therefore declare them private instead to disable dynamic alloc
8959 void* operator new(size_t size);
8960 void* operator new[](size_t size);
8961 void operator delete(void*, size_t);
8962 void operator delete[](void*, size_t);
8963
8964 void ResetInternal();
8965
8966 internal::Isolate* isolate_;
8967 TryCatch* next_;
8968 void* exception_;
8969 void* message_obj_;
8970 void* js_stack_comparable_address_;
8971 bool is_verbose_ : 1;
8972 bool can_continue_ : 1;
8973 bool capture_message_ : 1;
8974 bool rethrow_ : 1;
8975 bool has_terminated_ : 1;
8976
8977 friend class internal::Isolate;
8978 };
8979
8980
8981 // --- Context ---
8982
8983
8984 /**
8985 * A container for extension names.
8986 */
8987 class V8_EXPORT ExtensionConfiguration {
8988 public:
8989 ExtensionConfiguration() : name_count_(0), names_(NULL) { }
8990 ExtensionConfiguration(int name_count, const char* names[])
8991 : name_count_(name_count), names_(names) { }
8992
8993 const char** begin() const { return &names_[0]; }
8994 const char** end() const { return &names_[name_count_]; }
8995
8996 private:
8997 const int name_count_;
8998 const char** names_;
8999 };
9000
9001 /**
9002 * A sandboxed execution context with its own set of built-in objects
9003 * and functions.
9004 */
9005 class V8_EXPORT Context {
9006 public:
9007 /**
9008 * Returns the global proxy object.
9009 *
9010 * Global proxy object is a thin wrapper whose prototype points to actual
9011 * context's global object with the properties like Object, etc. This is done
9012 * that way for security reasons (for more details see
9013 * https://wiki.mozilla.org/Gecko:SplitWindow).
9014 *
9015 * Please note that changes to global proxy object prototype most probably
9016 * would break VM---v8 expects only global object as a prototype of global
9017 * proxy object.
9018 */
9019 Local<Object> Global();
9020
9021 /**
9022 * Detaches the global object from its context before
9023 * the global object can be reused to create a new context.
9024 */
9025 void DetachGlobal();
9026
9027 /**
9028 * Creates a new context and returns a handle to the newly allocated
9029 * context.
9030 *
9031 * \param isolate The isolate in which to create the context.
9032 *
9033 * \param extensions An optional extension configuration containing
9034 * the extensions to be installed in the newly created context.
9035 *
9036 * \param global_template An optional object template from which the
9037 * global object for the newly created context will be created.
9038 *
9039 * \param global_object An optional global object to be reused for
9040 * the newly created context. This global object must have been
9041 * created by a previous call to Context::New with the same global
9042 * template. The state of the global object will be completely reset
9043 * and only object identify will remain.
9044 */
9045 static Local<Context> New(
9046 Isolate* isolate, ExtensionConfiguration* extensions = NULL,
9047 MaybeLocal<ObjectTemplate> global_template = MaybeLocal<ObjectTemplate>(),
9048 MaybeLocal<Value> global_object = MaybeLocal<Value>(),
9049 DeserializeInternalFieldsCallback internal_fields_deserializer =
9050 DeserializeInternalFieldsCallback());
9051
9052 /**
9053 * Create a new context from a (non-default) context snapshot. There
9054 * is no way to provide a global object template since we do not create
9055 * a new global object from template, but we can reuse a global object.
9056 *
9057 * \param isolate See v8::Context::New.
9058 *
9059 * \param context_snapshot_index The index of the context snapshot to
9060 * deserialize from. Use v8::Context::New for the default snapshot.
9061 *
9062 * \param embedder_fields_deserializer Optional callback to deserialize
9063 * internal fields. It should match the SerializeInternalFieldCallback used
9064 * to serialize.
9065 *
9066 * \param extensions See v8::Context::New.
9067 *
9068 * \param global_object See v8::Context::New.
9069 */
9070
9071 static MaybeLocal<Context> FromSnapshot(
9072 Isolate* isolate, size_t context_snapshot_index,
9073 DeserializeInternalFieldsCallback embedder_fields_deserializer =
9074 DeserializeInternalFieldsCallback(),
9075 ExtensionConfiguration* extensions = nullptr,
9076 MaybeLocal<Value> global_object = MaybeLocal<Value>());
9077
9078 /**
9079 * Returns an global object that isn't backed by an actual context.
9080 *
9081 * The global template needs to have access checks with handlers installed.
9082 * If an existing global object is passed in, the global object is detached
9083 * from its context.
9084 *
9085 * Note that this is different from a detached context where all accesses to
9086 * the global proxy will fail. Instead, the access check handlers are invoked.
9087 *
9088 * It is also not possible to detach an object returned by this method.
9089 * Instead, the access check handlers need to return nothing to achieve the
9090 * same effect.
9091 *
9092 * It is possible, however, to create a new context from the global object
9093 * returned by this method.
9094 */
9095 static MaybeLocal<Object> NewRemoteContext(
9096 Isolate* isolate, Local<ObjectTemplate> global_template,
9097 MaybeLocal<Value> global_object = MaybeLocal<Value>());
9098
9099 /**
9100 * Sets the security token for the context. To access an object in
9101 * another context, the security tokens must match.
9102 */
9103 void SetSecurityToken(Local<Value> token);
9104
9105 /** Restores the security token to the default value. */
9106 void UseDefaultSecurityToken();
9107
9108 /** Returns the security token of this context.*/
9109 Local<Value> GetSecurityToken();
9110
9111 /**
9112 * Enter this context. After entering a context, all code compiled
9113 * and run is compiled and run in this context. If another context
9114 * is already entered, this old context is saved so it can be
9115 * restored when the new context is exited.
9116 */
9117 void Enter();
9118
9119 /**
9120 * Exit this context. Exiting the current context restores the
9121 * context that was in place when entering the current context.
9122 */
9123 void Exit();
9124
9125 /** Returns an isolate associated with a current context. */
9126 Isolate* GetIsolate();
9127
9128 /**
9129 * The field at kDebugIdIndex used to be reserved for the inspector.
9130 * It now serves no purpose.
9131 */
9132 enum EmbedderDataFields { kDebugIdIndex = 0 };
9133
9134 /**
9135 * Return the number of fields allocated for embedder data.
9136 */
9137 uint32_t GetNumberOfEmbedderDataFields();
9138
9139 /**
9140 * Gets the embedder data with the given index, which must have been set by a
9141 * previous call to SetEmbedderData with the same index.
9142 */
9143 V8_INLINE Local<Value> GetEmbedderData(int index);
9144
9145 /**
9146 * Gets the binding object used by V8 extras. Extra natives get a reference
9147 * to this object and can use it to "export" functionality by adding
9148 * properties. Extra natives can also "import" functionality by accessing
9149 * properties added by the embedder using the V8 API.
9150 */
9151 Local<Object> GetExtrasBindingObject();
9152
9153 /**
9154 * Sets the embedder data with the given index, growing the data as
9155 * needed. Note that index 0 currently has a special meaning for Chrome's
9156 * debugger.
9157 */
9158 void SetEmbedderData(int index, Local<Value> value);
9159
9160 /**
9161 * Gets a 2-byte-aligned native pointer from the embedder data with the given
9162 * index, which must have been set by a previous call to
9163 * SetAlignedPointerInEmbedderData with the same index. Note that index 0
9164 * currently has a special meaning for Chrome's debugger.
9165 */
9166 V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
9167
9168 /**
9169 * Sets a 2-byte-aligned native pointer in the embedder data with the given
9170 * index, growing the data as needed. Note that index 0 currently has a
9171 * special meaning for Chrome's debugger.
9172 */
9173 void SetAlignedPointerInEmbedderData(int index, void* value);
9174
9175 /**
9176 * Control whether code generation from strings is allowed. Calling
9177 * this method with false will disable 'eval' and the 'Function'
9178 * constructor for code running in this context. If 'eval' or the
9179 * 'Function' constructor are used an exception will be thrown.
9180 *
9181 * If code generation from strings is not allowed the
9182 * V8::AllowCodeGenerationFromStrings callback will be invoked if
9183 * set before blocking the call to 'eval' or the 'Function'
9184 * constructor. If that callback returns true, the call will be
9185 * allowed, otherwise an exception will be thrown. If no callback is
9186 * set an exception will be thrown.
9187 */
9188 void AllowCodeGenerationFromStrings(bool allow);
9189
9190 /**
9191 * Returns true if code generation from strings is allowed for the context.
9192 * For more details see AllowCodeGenerationFromStrings(bool) documentation.
9193 */
9194 bool IsCodeGenerationFromStringsAllowed();
9195
9196 /**
9197 * Sets the error description for the exception that is thrown when
9198 * code generation from strings is not allowed and 'eval' or the 'Function'
9199 * constructor are called.
9200 */
9201 void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
9202
9203 /**
9204 * Return data that was previously attached to the context snapshot via
9205 * SnapshotCreator, and removes the reference to it.
9206 * Repeated call with the same index returns an empty MaybeLocal.
9207 */
9208 template <class T>
9209 V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
9210
9211 /**
9212 * Stack-allocated class which sets the execution context for all
9213 * operations executed within a local scope.
9214 */
9215 class Scope {
9216 public:
9217 explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
9218 context_->Enter();
9219 }
9220 V8_INLINE ~Scope() { context_->Exit(); }
9221
9222 private:
9223 Local<Context> context_;
9224 };
9225
9226 /**
9227 * Stack-allocated class to support the backup incumbent settings object
9228 * stack.
9229 * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
9230 */
9231 class V8_EXPORT BackupIncumbentScope {
9232 public:
9233 /**
9234 * |backup_incumbent_context| is pushed onto the backup incumbent settings
9235 * object stack.
9236 */
9237 explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
9238 ~BackupIncumbentScope();
9239
9240 private:
9241 friend class internal::Isolate;
9242
9243 Local<Context> backup_incumbent_context_;
9244 const BackupIncumbentScope* prev_ = nullptr;
9245 };
9246
9247 private:
9248 friend class Value;
9249 friend class Script;
9250 friend class Object;
9251 friend class Function;
9252
9253 internal::Object** GetDataFromSnapshotOnce(size_t index);
9254 Local<Value> SlowGetEmbedderData(int index);
9255 void* SlowGetAlignedPointerFromEmbedderData(int index);
9256 };
9257
9258
9259 /**
9260 * Multiple threads in V8 are allowed, but only one thread at a time is allowed
9261 * to use any given V8 isolate, see the comments in the Isolate class. The
9262 * definition of 'using a V8 isolate' includes accessing handles or holding onto
9263 * object pointers obtained from V8 handles while in the particular V8 isolate.
9264 * It is up to the user of V8 to ensure, perhaps with locking, that this
9265 * constraint is not violated. In addition to any other synchronization
9266 * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
9267 * used to signal thread switches to V8.
9268 *
9269 * v8::Locker is a scoped lock object. While it's active, i.e. between its
9270 * construction and destruction, the current thread is allowed to use the locked
9271 * isolate. V8 guarantees that an isolate can be locked by at most one thread at
9272 * any time. In other words, the scope of a v8::Locker is a critical section.
9273 *
9274 * Sample usage:
9275 * \code
9276 * ...
9277 * {
9278 * v8::Locker locker(isolate);
9279 * v8::Isolate::Scope isolate_scope(isolate);
9280 * ...
9281 * // Code using V8 and isolate goes here.
9282 * ...
9283 * } // Destructor called here
9284 * \endcode
9285 *
9286 * If you wish to stop using V8 in a thread A you can do this either by
9287 * destroying the v8::Locker object as above or by constructing a v8::Unlocker
9288 * object:
9289 *
9290 * \code
9291 * {
9292 * isolate->Exit();
9293 * v8::Unlocker unlocker(isolate);
9294 * ...
9295 * // Code not using V8 goes here while V8 can run in another thread.
9296 * ...
9297 * } // Destructor called here.
9298 * isolate->Enter();
9299 * \endcode
9300 *
9301 * The Unlocker object is intended for use in a long-running callback from V8,
9302 * where you want to release the V8 lock for other threads to use.
9303 *
9304 * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
9305 * given thread. This can be useful if you have code that can be called either
9306 * from code that holds the lock or from code that does not. The Unlocker is
9307 * not recursive so you can not have several Unlockers on the stack at once, and
9308 * you can not use an Unlocker in a thread that is not inside a Locker's scope.
9309 *
9310 * An unlocker will unlock several lockers if it has to and reinstate the
9311 * correct depth of locking on its destruction, e.g.:
9312 *
9313 * \code
9314 * // V8 not locked.
9315 * {
9316 * v8::Locker locker(isolate);
9317 * Isolate::Scope isolate_scope(isolate);
9318 * // V8 locked.
9319 * {
9320 * v8::Locker another_locker(isolate);
9321 * // V8 still locked (2 levels).
9322 * {
9323 * isolate->Exit();
9324 * v8::Unlocker unlocker(isolate);
9325 * // V8 not locked.
9326 * }
9327 * isolate->Enter();
9328 * // V8 locked again (2 levels).
9329 * }
9330 * // V8 still locked (1 level).
9331 * }
9332 * // V8 Now no longer locked.
9333 * \endcode
9334 */
9335 class V8_EXPORT Unlocker {
9336 public:
9337 /**
9338 * Initialize Unlocker for a given Isolate.
9339 */
9340 V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
9341
9342 ~Unlocker();
9343 private:
9344 void Initialize(Isolate* isolate);
9345
9346 internal::Isolate* isolate_;
9347 };
9348
9349
9350 class V8_EXPORT Locker {
9351 public:
9352 /**
9353 * Initialize Locker for a given Isolate.
9354 */
9355 V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
9356
9357 ~Locker();
9358
9359 /**
9360 * Returns whether or not the locker for a given isolate, is locked by the
9361 * current thread.
9362 */
9363 static bool IsLocked(Isolate* isolate);
9364
9365 /**
9366 * Returns whether v8::Locker is being used by this V8 instance.
9367 */
9368 static bool IsActive();
9369
9370 // Disallow copying and assigning.
9371 Locker(const Locker&) = delete;
9372 void operator=(const Locker&) = delete;
9373
9374 private:
9375 void Initialize(Isolate* isolate);
9376
9377 bool has_lock_;
9378 bool top_level_;
9379 internal::Isolate* isolate_;
9380 };
9381
9382
9383 // --- Implementation ---
9384
9385
9386 namespace internal {
9387
9388 /**
9389 * This class exports constants and functionality from within v8 that
9390 * is necessary to implement inline functions in the v8 api. Don't
9391 * depend on functions and constants defined here.
9392 */
9393 class Internals {
9394 public:
9395 // These values match non-compiler-dependent values defined within
9396 // the implementation of v8.
9397 static const int kHeapObjectMapOffset = 0;
9398 static const int kMapInstanceTypeOffset = 1 * kApiPointerSize + kApiIntSize;
9399 static const int kStringResourceOffset = 3 * kApiPointerSize;
9400
9401 static const int kOddballKindOffset = 4 * kApiPointerSize + kApiDoubleSize;
9402 static const int kForeignAddressOffset = kApiPointerSize;
9403 static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
9404 static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
9405 static const int kContextHeaderSize = 2 * kApiPointerSize;
9406 static const int kContextEmbedderDataIndex = 5;
9407 static const int kFullStringRepresentationMask = 0x0f;
9408 static const int kStringEncodingMask = 0x8;
9409 static const int kExternalTwoByteRepresentationTag = 0x02;
9410 static const int kExternalOneByteRepresentationTag = 0x0a;
9411
9412 static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
9413 static const int kExternalMemoryOffset = 4 * kApiPointerSize;
9414 static const int kExternalMemoryLimitOffset =
9415 kExternalMemoryOffset + kApiInt64Size;
9416 static const int kExternalMemoryAtLastMarkCompactOffset =
9417 kExternalMemoryLimitOffset + kApiInt64Size;
9418 static const int kIsolateRootsOffset = kExternalMemoryLimitOffset +
9419 kApiInt64Size + kApiInt64Size +
9420 kApiPointerSize + kApiPointerSize;
9421 static const int kUndefinedValueRootIndex = 4;
9422 static const int kTheHoleValueRootIndex = 5;
9423 static const int kNullValueRootIndex = 6;
9424 static const int kTrueValueRootIndex = 7;
9425 static const int kFalseValueRootIndex = 8;
9426 static const int kEmptyStringRootIndex = 9;
9427
9428 static const int kNodeClassIdOffset = 1 * kApiPointerSize;
9429 static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
9430 static const int kNodeStateMask = 0x7;
9431 static const int kNodeStateIsWeakValue = 2;
9432 static const int kNodeStateIsPendingValue = 3;
9433 static const int kNodeStateIsNearDeathValue = 4;
9434 static const int kNodeIsIndependentShift = 3;
9435 static const int kNodeIsActiveShift = 4;
9436
9437 static const int kFirstNonstringType = 0x80;
9438 static const int kOddballType = 0x83;
9439 static const int kForeignType = 0x87;
9440 static const int kJSSpecialApiObjectType = 0x410;
9441 static const int kJSApiObjectType = 0x420;
9442 static const int kJSObjectType = 0x421;
9443
9444 static const int kUndefinedOddballKind = 5;
9445 static const int kNullOddballKind = 3;
9446
9447 static const uint32_t kNumIsolateDataSlots = 4;
9448
9449 V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
9450 V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
9451 #ifdef V8_ENABLE_CHECKS
9452 CheckInitializedImpl(isolate);
9453 #endif
9454 }
9455
9456 V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
9457 return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
9458 kHeapObjectTag);
9459 }
9460
9461 V8_INLINE static int SmiValue(const internal::Object* value) {
9462 return PlatformSmiTagging::SmiToInt(value);
9463 }
9464
9465 V8_INLINE static internal::Object* IntToSmi(int value) {
9466 return PlatformSmiTagging::IntToSmi(value);
9467 }
9468
9469 V8_INLINE static constexpr bool IsValidSmi(intptr_t value) {
9470 return PlatformSmiTagging::IsValidSmi(value);
9471 }
9472
9473 V8_INLINE static int GetInstanceType(const internal::Object* obj) {
9474 typedef internal::Object O;
9475 O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
9476 return ReadField<uint16_t>(map, kMapInstanceTypeOffset);
9477 }
9478
9479 V8_INLINE static int GetOddballKind(const internal::Object* obj) {
9480 typedef internal::Object O;
9481 return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
9482 }
9483
9484 V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
9485 int representation = (instance_type & kFullStringRepresentationMask);
9486 return representation == kExternalTwoByteRepresentationTag;
9487 }
9488
9489 V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
9490 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9491 return *addr & static_cast<uint8_t>(1U << shift);
9492 }
9493
9494 V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
9495 bool value, int shift) {
9496 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9497 uint8_t mask = static_cast<uint8_t>(1U << shift);
9498 *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
9499 }
9500
9501 V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
9502 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9503 return *addr & kNodeStateMask;
9504 }
9505
9506 V8_INLINE static void UpdateNodeState(internal::Object** obj,
9507 uint8_t value) {
9508 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
9509 *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
9510 }
9511
9512 V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
9513 uint32_t slot,
9514 void* data) {
9515 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) +
9516 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
9517 *reinterpret_cast<void**>(addr) = data;
9518 }
9519
9520 V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
9521 uint32_t slot) {
9522 const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
9523 kIsolateEmbedderDataOffset + slot * kApiPointerSize;
9524 return *reinterpret_cast<void* const*>(addr);
9525 }
9526
9527 V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
9528 int index) {
9529 uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
9530 return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
9531 }
9532
9533 template <typename T>
9534 V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
9535 const uint8_t* addr =
9536 reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
9537 return *reinterpret_cast<const T*>(addr);
9538 }
9539
9540 template <typename T>
9541 V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
9542 typedef internal::Object O;
9543 typedef internal::Internals I;
9544 O* ctx = *reinterpret_cast<O* const*>(context);
9545 int embedder_data_offset = I::kContextHeaderSize +
9546 (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
9547 O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
9548 int value_offset =
9549 I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
9550 return I::ReadField<T>(embedder_data, value_offset);
9551 }
9552 };
9553
9554 // Only perform cast check for types derived from v8::Data since
9555 // other types do not implement the Cast method.
9556 template <bool PerformCheck>
9557 struct CastCheck {
9558 template <class T>
9559 static void Perform(T* data);
9560 };
9561
9562 template <>
9563 template <class T>
9564 void CastCheck<true>::Perform(T* data) {
9565 T::Cast(data);
9566 }
9567
9568 template <>
9569 template <class T>
9570 void CastCheck<false>::Perform(T* data) {}
9571
9572 template <class T>
9573 V8_INLINE void PerformCastCheck(T* data) {
9574 CastCheck<std::is_base_of<Data, T>::value>::Perform(data);
9575 }
9576
9577 } // namespace internal
9578
9579
9580 template <class T>
9581 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
9582 return New(isolate, that.val_);
9583 }
9584
9585 template <class T>
9586 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
9587 return New(isolate, that.val_);
9588 }
9589
9590
9591 template <class T>
9592 Local<T> Local<T>::New(Isolate* isolate, T* that) {
9593 if (that == NULL) return Local<T>();
9594 T* that_ptr = that;
9595 internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
9596 return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
9597 reinterpret_cast<internal::Isolate*>(isolate), *p)));
9598 }
9599
9600
9601 template<class T>
9602 template<class S>
9603 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
9604 TYPE_CHECK(T, S);
9605 val_ = reinterpret_cast<T*>(
9606 V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
9607 }
9608
9609 template <class T>
9610 Local<T> Eternal<T>::Get(Isolate* isolate) const {
9611 // The eternal handle will never go away, so as with the roots, we don't even
9612 // need to open a handle.
9613 return Local<T>(val_);
9614 }
9615
9616
9617 template <class T>
9618 Local<T> MaybeLocal<T>::ToLocalChecked() {
9619 if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
9620 return Local<T>(val_);
9621 }
9622
9623
9624 template <class T>
9625 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
9626 #ifdef V8_ENABLE_CHECKS
9627 if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
9628 V8::InternalFieldOutOfBounds(index);
9629 }
9630 #endif
9631 return embedder_fields_[index];
9632 }
9633
9634
9635 template <class T>
9636 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
9637 if (that == NULL) return NULL;
9638 internal::Object** p = reinterpret_cast<internal::Object**>(that);
9639 return reinterpret_cast<T*>(
9640 V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
9641 p));
9642 }
9643
9644
9645 template <class T, class M>
9646 template <class S, class M2>
9647 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
9648 TYPE_CHECK(T, S);
9649 this->Reset();
9650 if (that.IsEmpty()) return;
9651 internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
9652 this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
9653 M::Copy(that, this);
9654 }
9655
9656 template <class T>
9657 bool PersistentBase<T>::IsIndependent() const {
9658 typedef internal::Internals I;
9659 if (this->IsEmpty()) return false;
9660 return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
9661 I::kNodeIsIndependentShift);
9662 }
9663
9664 template <class T>
9665 bool PersistentBase<T>::IsNearDeath() const {
9666 typedef internal::Internals I;
9667 if (this->IsEmpty()) return false;
9668 uint8_t node_state =
9669 I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
9670 return node_state == I::kNodeStateIsNearDeathValue ||
9671 node_state == I::kNodeStateIsPendingValue;
9672 }
9673
9674
9675 template <class T>
9676 bool PersistentBase<T>::IsWeak() const {
9677 typedef internal::Internals I;
9678 if (this->IsEmpty()) return false;
9679 return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
9680 I::kNodeStateIsWeakValue;
9681 }
9682
9683
9684 template <class T>
9685 void PersistentBase<T>::Reset() {
9686 if (this->IsEmpty()) return;
9687 V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
9688 val_ = 0;
9689 }
9690
9691
9692 template <class T>
9693 template <class S>
9694 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
9695 TYPE_CHECK(T, S);
9696 Reset();
9697 if (other.IsEmpty()) return;
9698 this->val_ = New(isolate, other.val_);
9699 }
9700
9701
9702 template <class T>
9703 template <class S>
9704 void PersistentBase<T>::Reset(Isolate* isolate,
9705 const PersistentBase<S>& other) {
9706 TYPE_CHECK(T, S);
9707 Reset();
9708 if (other.IsEmpty()) return;
9709 this->val_ = New(isolate, other.val_);
9710 }
9711
9712
9713 template <class T>
9714 template <typename P>
9715 V8_INLINE void PersistentBase<T>::SetWeak(
9716 P* parameter, typename WeakCallbackInfo<P>::Callback callback,
9717 WeakCallbackType type) {
9718 typedef typename WeakCallbackInfo<void>::Callback Callback;
9719 V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
9720 reinterpret_cast<Callback>(callback), type);
9721 }
9722
9723 template <class T>
9724 void PersistentBase<T>::SetWeak() {
9725 V8::MakeWeak(reinterpret_cast<internal::Object***>(&this->val_));
9726 }
9727
9728 template <class T>
9729 template <typename P>
9730 P* PersistentBase<T>::ClearWeak() {
9731 return reinterpret_cast<P*>(
9732 V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
9733 }
9734
9735 template <class T>
9736 void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
9737 V8::AnnotateStrongRetainer(reinterpret_cast<internal::Object**>(this->val_),
9738 label);
9739 }
9740
9741 template <class T>
9742 void PersistentBase<T>::RegisterExternalReference(Isolate* isolate) const {
9743 if (IsEmpty()) return;
9744 V8::RegisterExternallyReferencedObject(
9745 reinterpret_cast<internal::Object**>(this->val_),
9746 reinterpret_cast<internal::Isolate*>(isolate));
9747 }
9748
9749 template <class T>
9750 void PersistentBase<T>::MarkIndependent() {
9751 typedef internal::Internals I;
9752 if (this->IsEmpty()) return;
9753 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
9754 I::kNodeIsIndependentShift);
9755 }
9756
9757 template <class T>
9758 void PersistentBase<T>::MarkActive() {
9759 typedef internal::Internals I;
9760 if (this->IsEmpty()) return;
9761 I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_), true,
9762 I::kNodeIsActiveShift);
9763 }
9764
9765
9766 template <class T>
9767 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
9768 typedef internal::Internals I;
9769 if (this->IsEmpty()) return;
9770 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
9771 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9772 *reinterpret_cast<uint16_t*>(addr) = class_id;
9773 }
9774
9775
9776 template <class T>
9777 uint16_t PersistentBase<T>::WrapperClassId() const {
9778 typedef internal::Internals I;
9779 if (this->IsEmpty()) return 0;
9780 internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
9781 uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9782 return *reinterpret_cast<uint16_t*>(addr);
9783 }
9784
9785
9786 template<typename T>
9787 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
9788
9789 template<typename T>
9790 template<typename S>
9791 void ReturnValue<T>::Set(const Persistent<S>& handle) {
9792 TYPE_CHECK(T, S);
9793 if (V8_UNLIKELY(handle.IsEmpty())) {
9794 *value_ = GetDefaultValue();
9795 } else {
9796 *value_ = *reinterpret_cast<internal::Object**>(*handle);
9797 }
9798 }
9799
9800 template <typename T>
9801 template <typename S>
9802 void ReturnValue<T>::Set(const Global<S>& handle) {
9803 TYPE_CHECK(T, S);
9804 if (V8_UNLIKELY(handle.IsEmpty())) {
9805 *value_ = GetDefaultValue();
9806 } else {
9807 *value_ = *reinterpret_cast<internal::Object**>(*handle);
9808 }
9809 }
9810
9811 template <typename T>
9812 template <typename S>
9813 void ReturnValue<T>::Set(const Local<S> handle) {
9814 TYPE_CHECK(T, S);
9815 if (V8_UNLIKELY(handle.IsEmpty())) {
9816 *value_ = GetDefaultValue();
9817 } else {
9818 *value_ = *reinterpret_cast<internal::Object**>(*handle);
9819 }
9820 }
9821
9822 template<typename T>
9823 void ReturnValue<T>::Set(double i) {
9824 TYPE_CHECK(T, Number);
9825 Set(Number::New(GetIsolate(), i));
9826 }
9827
9828 template<typename T>
9829 void ReturnValue<T>::Set(int32_t i) {
9830 TYPE_CHECK(T, Integer);
9831 typedef internal::Internals I;
9832 if (V8_LIKELY(I::IsValidSmi(i))) {
9833 *value_ = I::IntToSmi(i);
9834 return;
9835 }
9836 Set(Integer::New(GetIsolate(), i));
9837 }
9838
9839 template<typename T>
9840 void ReturnValue<T>::Set(uint32_t i) {
9841 TYPE_CHECK(T, Integer);
9842 // Can't simply use INT32_MAX here for whatever reason.
9843 bool fits_into_int32_t = (i & (1U << 31)) == 0;
9844 if (V8_LIKELY(fits_into_int32_t)) {
9845 Set(static_cast<int32_t>(i));
9846 return;
9847 }
9848 Set(Integer::NewFromUnsigned(GetIsolate(), i));
9849 }
9850
9851 template<typename T>
9852 void ReturnValue<T>::Set(bool value) {
9853 TYPE_CHECK(T, Boolean);
9854 typedef internal::Internals I;
9855 int root_index;
9856 if (value) {
9857 root_index = I::kTrueValueRootIndex;
9858 } else {
9859 root_index = I::kFalseValueRootIndex;
9860 }
9861 *value_ = *I::GetRoot(GetIsolate(), root_index);
9862 }
9863
9864 template<typename T>
9865 void ReturnValue<T>::SetNull() {
9866 TYPE_CHECK(T, Primitive);
9867 typedef internal::Internals I;
9868 *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
9869 }
9870
9871 template<typename T>
9872 void ReturnValue<T>::SetUndefined() {
9873 TYPE_CHECK(T, Primitive);
9874 typedef internal::Internals I;
9875 *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
9876 }
9877
9878 template<typename T>
9879 void ReturnValue<T>::SetEmptyString() {
9880 TYPE_CHECK(T, String);
9881 typedef internal::Internals I;
9882 *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
9883 }
9884
9885 template <typename T>
9886 Isolate* ReturnValue<T>::GetIsolate() const {
9887 // Isolate is always the pointer below the default value on the stack.
9888 return *reinterpret_cast<Isolate**>(&value_[-2]);
9889 }
9890
9891 template <typename T>
9892 Local<Value> ReturnValue<T>::Get() const {
9893 typedef internal::Internals I;
9894 if (*value_ == *I::GetRoot(GetIsolate(), I::kTheHoleValueRootIndex))
9895 return Local<Value>(*Undefined(GetIsolate()));
9896 return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
9897 }
9898
9899 template <typename T>
9900 template <typename S>
9901 void ReturnValue<T>::Set(S* whatever) {
9902 // Uncompilable to prevent inadvertent misuse.
9903 TYPE_CHECK(S*, Primitive);
9904 }
9905
9906 template<typename T>
9907 internal::Object* ReturnValue<T>::GetDefaultValue() {
9908 // Default value is always the pointer below value_ on the stack.
9909 return value_[-1];
9910 }
9911
9912 template <typename T>
9913 FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
9914 internal::Object** values,
9915 int length)
9916 : implicit_args_(implicit_args), values_(values), length_(length) {}
9917
9918 template<typename T>
9919 Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
9920 if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
9921 return Local<Value>(reinterpret_cast<Value*>(values_ - i));
9922 }
9923
9924
9925 template<typename T>
9926 Local<Object> FunctionCallbackInfo<T>::This() const {
9927 return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
9928 }
9929
9930
9931 template<typename T>
9932 Local<Object> FunctionCallbackInfo<T>::Holder() const {
9933 return Local<Object>(reinterpret_cast<Object*>(
9934 &implicit_args_[kHolderIndex]));
9935 }
9936
9937 template <typename T>
9938 Local<Value> FunctionCallbackInfo<T>::NewTarget() const {
9939 return Local<Value>(
9940 reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
9941 }
9942
9943 template <typename T>
9944 Local<Value> FunctionCallbackInfo<T>::Data() const {
9945 return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
9946 }
9947
9948
9949 template<typename T>
9950 Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
9951 return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
9952 }
9953
9954
9955 template<typename T>
9956 ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
9957 return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
9958 }
9959
9960
9961 template<typename T>
9962 bool FunctionCallbackInfo<T>::IsConstructCall() const {
9963 return !NewTarget()->IsUndefined();
9964 }
9965
9966
9967 template<typename T>
9968 int FunctionCallbackInfo<T>::Length() const {
9969 return length_;
9970 }
9971
9972 ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
9973 Local<Integer> resource_line_offset,
9974 Local<Integer> resource_column_offset,
9975 Local<Boolean> resource_is_shared_cross_origin,
9976 Local<Integer> script_id,
9977 Local<Value> source_map_url,
9978 Local<Boolean> resource_is_opaque,
9979 Local<Boolean> is_wasm, Local<Boolean> is_module,
9980 Local<PrimitiveArray> host_defined_options)
9981 : resource_name_(resource_name),
9982 resource_line_offset_(resource_line_offset),
9983 resource_column_offset_(resource_column_offset),
9984 options_(!resource_is_shared_cross_origin.IsEmpty() &&
9985 resource_is_shared_cross_origin->IsTrue(),
9986 !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
9987 !is_wasm.IsEmpty() && is_wasm->IsTrue(),
9988 !is_module.IsEmpty() && is_module->IsTrue()),
9989 script_id_(script_id),
9990 source_map_url_(source_map_url),
9991 host_defined_options_(host_defined_options) {}
9992
9993 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
9994
9995 Local<PrimitiveArray> ScriptOrigin::HostDefinedOptions() const {
9996 return host_defined_options_;
9997 }
9998
9999 Local<Integer> ScriptOrigin::ResourceLineOffset() const {
10000 return resource_line_offset_;
10001 }
10002
10003
10004 Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
10005 return resource_column_offset_;
10006 }
10007
10008
10009 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
10010
10011
10012 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
10013
10014 ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
10015 CachedData* data)
10016 : source_string(string),
10017 resource_name(origin.ResourceName()),
10018 resource_line_offset(origin.ResourceLineOffset()),
10019 resource_column_offset(origin.ResourceColumnOffset()),
10020 resource_options(origin.Options()),
10021 source_map_url(origin.SourceMapUrl()),
10022 host_defined_options(origin.HostDefinedOptions()),
10023 cached_data(data) {}
10024
10025 ScriptCompiler::Source::Source(Local<String> string,
10026 CachedData* data)
10027 : source_string(string), cached_data(data) {}
10028
10029
10030 ScriptCompiler::Source::~Source() {
10031 delete cached_data;
10032 }
10033
10034
10035 const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
10036 const {
10037 return cached_data;
10038 }
10039
10040 const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const {
10041 return resource_options;
10042 }
10043
10044 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
10045 return value ? True(isolate) : False(isolate);
10046 }
10047
10048 void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
10049 Set(String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
10050 .ToLocalChecked(),
10051 value);
10052 }
10053
10054 FunctionTemplate* FunctionTemplate::Cast(Data* data) {
10055 #ifdef V8_ENABLE_CHECKS
10056 CheckCast(data);
10057 #endif
10058 return reinterpret_cast<FunctionTemplate*>(data);
10059 }
10060
10061 ObjectTemplate* ObjectTemplate::Cast(Data* data) {
10062 #ifdef V8_ENABLE_CHECKS
10063 CheckCast(data);
10064 #endif
10065 return reinterpret_cast<ObjectTemplate*>(data);
10066 }
10067
10068 Signature* Signature::Cast(Data* data) {
10069 #ifdef V8_ENABLE_CHECKS
10070 CheckCast(data);
10071 #endif
10072 return reinterpret_cast<Signature*>(data);
10073 }
10074
10075 AccessorSignature* AccessorSignature::Cast(Data* data) {
10076 #ifdef V8_ENABLE_CHECKS
10077 CheckCast(data);
10078 #endif
10079 return reinterpret_cast<AccessorSignature*>(data);
10080 }
10081
10082 Local<Value> Object::GetInternalField(int index) {
10083 #ifndef V8_ENABLE_CHECKS
10084 typedef internal::Object O;
10085 typedef internal::Internals I;
10086 O* obj = *reinterpret_cast<O**>(this);
10087 // Fast path: If the object is a plain JSObject, which is the common case, we
10088 // know where to find the internal fields and can return the value directly.
10089 auto instance_type = I::GetInstanceType(obj);
10090 if (instance_type == I::kJSObjectType ||
10091 instance_type == I::kJSApiObjectType ||
10092 instance_type == I::kJSSpecialApiObjectType) {
10093 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
10094 O* value = I::ReadField<O*>(obj, offset);
10095 O** result = HandleScope::CreateHandle(
10096 reinterpret_cast<internal::NeverReadOnlySpaceObject*>(obj), value);
10097 return Local<Value>(reinterpret_cast<Value*>(result));
10098 }
10099 #endif
10100 return SlowGetInternalField(index);
10101 }
10102
10103
10104 void* Object::GetAlignedPointerFromInternalField(int index) {
10105 #ifndef V8_ENABLE_CHECKS
10106 typedef internal::Object O;
10107 typedef internal::Internals I;
10108 O* obj = *reinterpret_cast<O**>(this);
10109 // Fast path: If the object is a plain JSObject, which is the common case, we
10110 // know where to find the internal fields and can return the value directly.
10111 auto instance_type = I::GetInstanceType(obj);
10112 if (V8_LIKELY(instance_type == I::kJSObjectType ||
10113 instance_type == I::kJSApiObjectType ||
10114 instance_type == I::kJSSpecialApiObjectType)) {
10115 int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
10116 return I::ReadField<void*>(obj, offset);
10117 }
10118 #endif
10119 return SlowGetAlignedPointerFromInternalField(index);
10120 }
10121
10122 String* String::Cast(v8::Value* value) {
10123 #ifdef V8_ENABLE_CHECKS
10124 CheckCast(value);
10125 #endif
10126 return static_cast<String*>(value);
10127 }
10128
10129
10130 Local<String> String::Empty(Isolate* isolate) {
10131 typedef internal::Object* S;
10132 typedef internal::Internals I;
10133 I::CheckInitialized(isolate);
10134 S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
10135 return Local<String>(reinterpret_cast<String*>(slot));
10136 }
10137
10138
10139 String::ExternalStringResource* String::GetExternalStringResource() const {
10140 typedef internal::Object O;
10141 typedef internal::Internals I;
10142 O* obj = *reinterpret_cast<O* const*>(this);
10143
10144 ExternalStringResource* result;
10145 if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
10146 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
10147 result = reinterpret_cast<String::ExternalStringResource*>(value);
10148 } else {
10149 result = GetExternalStringResourceSlow();
10150 }
10151 #ifdef V8_ENABLE_CHECKS
10152 VerifyExternalStringResource(result);
10153 #endif
10154 return result;
10155 }
10156
10157
10158 String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
10159 String::Encoding* encoding_out) const {
10160 typedef internal::Object O;
10161 typedef internal::Internals I;
10162 O* obj = *reinterpret_cast<O* const*>(this);
10163 int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
10164 *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
10165 ExternalStringResourceBase* resource;
10166 if (type == I::kExternalOneByteRepresentationTag ||
10167 type == I::kExternalTwoByteRepresentationTag) {
10168 void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
10169 resource = static_cast<ExternalStringResourceBase*>(value);
10170 } else {
10171 resource = GetExternalStringResourceBaseSlow(encoding_out);
10172 }
10173 #ifdef V8_ENABLE_CHECKS
10174 VerifyExternalStringResourceBase(resource, *encoding_out);
10175 #endif
10176 return resource;
10177 }
10178
10179
10180 bool Value::IsUndefined() const {
10181 #ifdef V8_ENABLE_CHECKS
10182 return FullIsUndefined();
10183 #else
10184 return QuickIsUndefined();
10185 #endif
10186 }
10187
10188 bool Value::QuickIsUndefined() const {
10189 typedef internal::Object O;
10190 typedef internal::Internals I;
10191 O* obj = *reinterpret_cast<O* const*>(this);
10192 if (!I::HasHeapObjectTag(obj)) return false;
10193 if (I::GetInstanceType(obj) != I::kOddballType) return false;
10194 return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
10195 }
10196
10197
10198 bool Value::IsNull() const {
10199 #ifdef V8_ENABLE_CHECKS
10200 return FullIsNull();
10201 #else
10202 return QuickIsNull();
10203 #endif
10204 }
10205
10206 bool Value::QuickIsNull() const {
10207 typedef internal::Object O;
10208 typedef internal::Internals I;
10209 O* obj = *reinterpret_cast<O* const*>(this);
10210 if (!I::HasHeapObjectTag(obj)) return false;
10211 if (I::GetInstanceType(obj) != I::kOddballType) return false;
10212 return (I::GetOddballKind(obj) == I::kNullOddballKind);
10213 }
10214
10215 bool Value::IsNullOrUndefined() const {
10216 #ifdef V8_ENABLE_CHECKS
10217 return FullIsNull() || FullIsUndefined();
10218 #else
10219 return QuickIsNullOrUndefined();
10220 #endif
10221 }
10222
10223 bool Value::QuickIsNullOrUndefined() const {
10224 typedef internal::Object O;
10225 typedef internal::Internals I;
10226 O* obj = *reinterpret_cast<O* const*>(this);
10227 if (!I::HasHeapObjectTag(obj)) return false;
10228 if (I::GetInstanceType(obj) != I::kOddballType) return false;
10229 int kind = I::GetOddballKind(obj);
10230 return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
10231 }
10232
10233 bool Value::IsString() const {
10234 #ifdef V8_ENABLE_CHECKS
10235 return FullIsString();
10236 #else
10237 return QuickIsString();
10238 #endif
10239 }
10240
10241 bool Value::QuickIsString() const {
10242 typedef internal::Object O;
10243 typedef internal::Internals I;
10244 O* obj = *reinterpret_cast<O* const*>(this);
10245 if (!I::HasHeapObjectTag(obj)) return false;
10246 return (I::GetInstanceType(obj) < I::kFirstNonstringType);
10247 }
10248
10249
10250 template <class T> Value* Value::Cast(T* value) {
10251 return static_cast<Value*>(value);
10252 }
10253
10254 Local<Boolean> Value::ToBoolean() const {
10255 return ToBoolean(Isolate::GetCurrent()->GetCurrentContext())
10256 .FromMaybe(Local<Boolean>());
10257 }
10258
10259 Local<String> Value::ToString() const {
10260 return ToString(Isolate::GetCurrent()->GetCurrentContext())
10261 .FromMaybe(Local<String>());
10262 }
10263
10264 Local<Object> Value::ToObject() const {
10265 return ToObject(Isolate::GetCurrent()->GetCurrentContext())
10266 .FromMaybe(Local<Object>());
10267 }
10268
10269 Local<Integer> Value::ToInteger() const {
10270 return ToInteger(Isolate::GetCurrent()->GetCurrentContext())
10271 .FromMaybe(Local<Integer>());
10272 }
10273
10274 Boolean* Boolean::Cast(v8::Value* value) {
10275 #ifdef V8_ENABLE_CHECKS
10276 CheckCast(value);
10277 #endif
10278 return static_cast<Boolean*>(value);
10279 }
10280
10281
10282 Name* Name::Cast(v8::Value* value) {
10283 #ifdef V8_ENABLE_CHECKS
10284 CheckCast(value);
10285 #endif
10286 return static_cast<Name*>(value);
10287 }
10288
10289
10290 Symbol* Symbol::Cast(v8::Value* value) {
10291 #ifdef V8_ENABLE_CHECKS
10292 CheckCast(value);
10293 #endif
10294 return static_cast<Symbol*>(value);
10295 }
10296
10297
10298 Private* Private::Cast(Data* data) {
10299 #ifdef V8_ENABLE_CHECKS
10300 CheckCast(data);
10301 #endif
10302 return reinterpret_cast<Private*>(data);
10303 }
10304
10305
10306 Number* Number::Cast(v8::Value* value) {
10307 #ifdef V8_ENABLE_CHECKS
10308 CheckCast(value);
10309 #endif
10310 return static_cast<Number*>(value);
10311 }
10312
10313
10314 Integer* Integer::Cast(v8::Value* value) {
10315 #ifdef V8_ENABLE_CHECKS
10316 CheckCast(value);
10317 #endif
10318 return static_cast<Integer*>(value);
10319 }
10320
10321
10322 Int32* Int32::Cast(v8::Value* value) {
10323 #ifdef V8_ENABLE_CHECKS
10324 CheckCast(value);
10325 #endif
10326 return static_cast<Int32*>(value);
10327 }
10328
10329
10330 Uint32* Uint32::Cast(v8::Value* value) {
10331 #ifdef V8_ENABLE_CHECKS
10332 CheckCast(value);
10333 #endif
10334 return static_cast<Uint32*>(value);
10335 }
10336
10337 BigInt* BigInt::Cast(v8::Value* value) {
10338 #ifdef V8_ENABLE_CHECKS
10339 CheckCast(value);
10340 #endif
10341 return static_cast<BigInt*>(value);
10342 }
10343
10344 Date* Date::Cast(v8::Value* value) {
10345 #ifdef V8_ENABLE_CHECKS
10346 CheckCast(value);
10347 #endif
10348 return static_cast<Date*>(value);
10349 }
10350
10351
10352 StringObject* StringObject::Cast(v8::Value* value) {
10353 #ifdef V8_ENABLE_CHECKS
10354 CheckCast(value);
10355 #endif
10356 return static_cast<StringObject*>(value);
10357 }
10358
10359
10360 SymbolObject* SymbolObject::Cast(v8::Value* value) {
10361 #ifdef V8_ENABLE_CHECKS
10362 CheckCast(value);
10363 #endif
10364 return static_cast<SymbolObject*>(value);
10365 }
10366
10367
10368 NumberObject* NumberObject::Cast(v8::Value* value) {
10369 #ifdef V8_ENABLE_CHECKS
10370 CheckCast(value);
10371 #endif
10372 return static_cast<NumberObject*>(value);
10373 }
10374
10375 BigIntObject* BigIntObject::Cast(v8::Value* value) {
10376 #ifdef V8_ENABLE_CHECKS
10377 CheckCast(value);
10378 #endif
10379 return static_cast<BigIntObject*>(value);
10380 }
10381
10382 BooleanObject* BooleanObject::Cast(v8::Value* value) {
10383 #ifdef V8_ENABLE_CHECKS
10384 CheckCast(value);
10385 #endif
10386 return static_cast<BooleanObject*>(value);
10387 }
10388
10389
10390 RegExp* RegExp::Cast(v8::Value* value) {
10391 #ifdef V8_ENABLE_CHECKS
10392 CheckCast(value);
10393 #endif
10394 return static_cast<RegExp*>(value);
10395 }
10396
10397
10398 Object* Object::Cast(v8::Value* value) {
10399 #ifdef V8_ENABLE_CHECKS
10400 CheckCast(value);
10401 #endif
10402 return static_cast<Object*>(value);
10403 }
10404
10405
10406 Array* Array::Cast(v8::Value* value) {
10407 #ifdef V8_ENABLE_CHECKS
10408 CheckCast(value);
10409 #endif
10410 return static_cast<Array*>(value);
10411 }
10412
10413
10414 Map* Map::Cast(v8::Value* value) {
10415 #ifdef V8_ENABLE_CHECKS
10416 CheckCast(value);
10417 #endif
10418 return static_cast<Map*>(value);
10419 }
10420
10421
10422 Set* Set::Cast(v8::Value* value) {
10423 #ifdef V8_ENABLE_CHECKS
10424 CheckCast(value);
10425 #endif
10426 return static_cast<Set*>(value);
10427 }
10428
10429
10430 Promise* Promise::Cast(v8::Value* value) {
10431 #ifdef V8_ENABLE_CHECKS
10432 CheckCast(value);
10433 #endif
10434 return static_cast<Promise*>(value);
10435 }
10436
10437
10438 Proxy* Proxy::Cast(v8::Value* value) {
10439 #ifdef V8_ENABLE_CHECKS
10440 CheckCast(value);
10441 #endif
10442 return static_cast<Proxy*>(value);
10443 }
10444
10445 WasmCompiledModule* WasmCompiledModule::Cast(v8::Value* value) {
10446 #ifdef V8_ENABLE_CHECKS
10447 CheckCast(value);
10448 #endif
10449 return static_cast<WasmCompiledModule*>(value);
10450 }
10451
10452 Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
10453 #ifdef V8_ENABLE_CHECKS
10454 CheckCast(value);
10455 #endif
10456 return static_cast<Promise::Resolver*>(value);
10457 }
10458
10459
10460 ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
10461 #ifdef V8_ENABLE_CHECKS
10462 CheckCast(value);
10463 #endif
10464 return static_cast<ArrayBuffer*>(value);
10465 }
10466
10467
10468 ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
10469 #ifdef V8_ENABLE_CHECKS
10470 CheckCast(value);
10471 #endif
10472 return static_cast<ArrayBufferView*>(value);
10473 }
10474
10475
10476 TypedArray* TypedArray::Cast(v8::Value* value) {
10477 #ifdef V8_ENABLE_CHECKS
10478 CheckCast(value);
10479 #endif
10480 return static_cast<TypedArray*>(value);
10481 }
10482
10483
10484 Uint8Array* Uint8Array::Cast(v8::Value* value) {
10485 #ifdef V8_ENABLE_CHECKS
10486 CheckCast(value);
10487 #endif
10488 return static_cast<Uint8Array*>(value);
10489 }
10490
10491
10492 Int8Array* Int8Array::Cast(v8::Value* value) {
10493 #ifdef V8_ENABLE_CHECKS
10494 CheckCast(value);
10495 #endif
10496 return static_cast<Int8Array*>(value);
10497 }
10498
10499
10500 Uint16Array* Uint16Array::Cast(v8::Value* value) {
10501 #ifdef V8_ENABLE_CHECKS
10502 CheckCast(value);
10503 #endif
10504 return static_cast<Uint16Array*>(value);
10505 }
10506
10507
10508 Int16Array* Int16Array::Cast(v8::Value* value) {
10509 #ifdef V8_ENABLE_CHECKS
10510 CheckCast(value);
10511 #endif
10512 return static_cast<Int16Array*>(value);
10513 }
10514
10515
10516 Uint32Array* Uint32Array::Cast(v8::Value* value) {
10517 #ifdef V8_ENABLE_CHECKS
10518 CheckCast(value);
10519 #endif
10520 return static_cast<Uint32Array*>(value);
10521 }
10522
10523
10524 Int32Array* Int32Array::Cast(v8::Value* value) {
10525 #ifdef V8_ENABLE_CHECKS
10526 CheckCast(value);
10527 #endif
10528 return static_cast<Int32Array*>(value);
10529 }
10530
10531
10532 Float32Array* Float32Array::Cast(v8::Value* value) {
10533 #ifdef V8_ENABLE_CHECKS
10534 CheckCast(value);
10535 #endif
10536 return static_cast<Float32Array*>(value);
10537 }
10538
10539
10540 Float64Array* Float64Array::Cast(v8::Value* value) {
10541 #ifdef V8_ENABLE_CHECKS
10542 CheckCast(value);
10543 #endif
10544 return static_cast<Float64Array*>(value);
10545 }
10546
10547 BigInt64Array* BigInt64Array::Cast(v8::Value* value) {
10548 #ifdef V8_ENABLE_CHECKS
10549 CheckCast(value);
10550 #endif
10551 return static_cast<BigInt64Array*>(value);
10552 }
10553
10554 BigUint64Array* BigUint64Array::Cast(v8::Value* value) {
10555 #ifdef V8_ENABLE_CHECKS
10556 CheckCast(value);
10557 #endif
10558 return static_cast<BigUint64Array*>(value);
10559 }
10560
10561 Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
10562 #ifdef V8_ENABLE_CHECKS
10563 CheckCast(value);
10564 #endif
10565 return static_cast<Uint8ClampedArray*>(value);
10566 }
10567
10568
10569 DataView* DataView::Cast(v8::Value* value) {
10570 #ifdef V8_ENABLE_CHECKS
10571 CheckCast(value);
10572 #endif
10573 return static_cast<DataView*>(value);
10574 }
10575
10576
10577 SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
10578 #ifdef V8_ENABLE_CHECKS
10579 CheckCast(value);
10580 #endif
10581 return static_cast<SharedArrayBuffer*>(value);
10582 }
10583
10584
10585 Function* Function::Cast(v8::Value* value) {
10586 #ifdef V8_ENABLE_CHECKS
10587 CheckCast(value);
10588 #endif
10589 return static_cast<Function*>(value);
10590 }
10591
10592
10593 External* External::Cast(v8::Value* value) {
10594 #ifdef V8_ENABLE_CHECKS
10595 CheckCast(value);
10596 #endif
10597 return static_cast<External*>(value);
10598 }
10599
10600
10601 template<typename T>
10602 Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
10603 return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
10604 }
10605
10606
10607 template<typename T>
10608 Local<Value> PropertyCallbackInfo<T>::Data() const {
10609 return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
10610 }
10611
10612
10613 template<typename T>
10614 Local<Object> PropertyCallbackInfo<T>::This() const {
10615 return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
10616 }
10617
10618
10619 template<typename T>
10620 Local<Object> PropertyCallbackInfo<T>::Holder() const {
10621 return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
10622 }
10623
10624
10625 template<typename T>
10626 ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
10627 return ReturnValue<T>(&args_[kReturnValueIndex]);
10628 }
10629
10630 template <typename T>
10631 bool PropertyCallbackInfo<T>::ShouldThrowOnError() const {
10632 typedef internal::Internals I;
10633 return args_[kShouldThrowOnErrorIndex] != I::IntToSmi(0);
10634 }
10635
10636
10637 Local<Primitive> Undefined(Isolate* isolate) {
10638 typedef internal::Object* S;
10639 typedef internal::Internals I;
10640 I::CheckInitialized(isolate);
10641 S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
10642 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10643 }
10644
10645
10646 Local<Primitive> Null(Isolate* isolate) {
10647 typedef internal::Object* S;
10648 typedef internal::Internals I;
10649 I::CheckInitialized(isolate);
10650 S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
10651 return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10652 }
10653
10654
10655 Local<Boolean> True(Isolate* isolate) {
10656 typedef internal::Object* S;
10657 typedef internal::Internals I;
10658 I::CheckInitialized(isolate);
10659 S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
10660 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10661 }
10662
10663
10664 Local<Boolean> False(Isolate* isolate) {
10665 typedef internal::Object* S;
10666 typedef internal::Internals I;
10667 I::CheckInitialized(isolate);
10668 S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
10669 return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10670 }
10671
10672
10673 void Isolate::SetData(uint32_t slot, void* data) {
10674 typedef internal::Internals I;
10675 I::SetEmbedderData(this, slot, data);
10676 }
10677
10678
10679 void* Isolate::GetData(uint32_t slot) {
10680 typedef internal::Internals I;
10681 return I::GetEmbedderData(this, slot);
10682 }
10683
10684
10685 uint32_t Isolate::GetNumberOfDataSlots() {
10686 typedef internal::Internals I;
10687 return I::kNumIsolateDataSlots;
10688 }
10689
10690 template <class T>
10691 MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
10692 T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
10693 if (data) internal::PerformCastCheck(data);
10694 return Local<T>(data);
10695 }
10696
10697 int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
10698 int64_t change_in_bytes) {
10699 typedef internal::Internals I;
10700 const int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
10701 int64_t* external_memory = reinterpret_cast<int64_t*>(
10702 reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
10703 int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
10704 reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
10705 int64_t* external_memory_at_last_mc =
10706 reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
10707 I::kExternalMemoryAtLastMarkCompactOffset);
10708 const int64_t amount = *external_memory + change_in_bytes;
10709
10710 *external_memory = amount;
10711
10712 int64_t allocation_diff_since_last_mc =
10713 *external_memory_at_last_mc - *external_memory;
10714 allocation_diff_since_last_mc = allocation_diff_since_last_mc < 0
10715 ? -allocation_diff_since_last_mc
10716 : allocation_diff_since_last_mc;
10717 if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
10718 CheckMemoryPressure();
10719 }
10720
10721 if (change_in_bytes < 0) {
10722 *external_memory_limit += change_in_bytes;
10723 }
10724
10725 if (change_in_bytes > 0 && amount > *external_memory_limit) {
10726 ReportExternalAllocationLimitReached();
10727 }
10728 return *external_memory;
10729 }
10730
10731 Local<Value> Context::GetEmbedderData(int index) {
10732 #ifndef V8_ENABLE_CHECKS
10733 typedef internal::Object O;
10734 typedef internal::Internals I;
10735 auto* context = *reinterpret_cast<internal::NeverReadOnlySpaceObject**>(this);
10736 O** result =
10737 HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
10738 return Local<Value>(reinterpret_cast<Value*>(result));
10739 #else
10740 return SlowGetEmbedderData(index);
10741 #endif
10742 }
10743
10744
10745 void* Context::GetAlignedPointerFromEmbedderData(int index) {
10746 #ifndef V8_ENABLE_CHECKS
10747 typedef internal::Internals I;
10748 return I::ReadEmbedderData<void*>(this, index);
10749 #else
10750 return SlowGetAlignedPointerFromEmbedderData(index);
10751 #endif
10752 }
10753
10754 template <class T>
10755 MaybeLocal<T> Context::GetDataFromSnapshotOnce(size_t index) {
10756 T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
10757 if (data) internal::PerformCastCheck(data);
10758 return Local<T>(data);
10759 }
10760
10761 template <class T>
10762 size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
10763 T* object_ptr = *object;
10764 internal::Object** p = reinterpret_cast<internal::Object**>(object_ptr);
10765 return AddData(context, *p);
10766 }
10767
10768 template <class T>
10769 size_t SnapshotCreator::AddData(Local<T> object) {
10770 T* object_ptr = *object;
10771 internal::Object** p = reinterpret_cast<internal::Object**>(object_ptr);
10772 return AddData(*p);
10773 }
10774
10775 /**
10776 * \example shell.cc
10777 * A simple shell that takes a list of expressions on the
10778 * command-line and executes them.
10779 */
10780
10781
10782 /**
10783 * \example process.cc
10784 */
10785
10786
10787 } // namespace v8
10788
10789
10790 #undef TYPE_CHECK
10791
10792
10793 #endif // INCLUDE_V8_H_
10794