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