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