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