v8  4.5.103 (node 4.8.7)
V8 is Google's open source JavaScript engine
v8.h
Go to the documentation of this file.
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 V8_H_
16 #define V8_H_
17 
18 #include <stddef.h>
19 #include <stdint.h>
20 #include <stdio.h>
21 
22 #include "v8-version.h"
23 #include "v8config.h"
24 
25 // We reserve the V8_* prefix for macros defined in V8 public API and
26 // assume there are no name conflicts with the embedder's code.
27 
28 #ifdef V8_OS_WIN
29 
30 // Setup for Windows DLL export/import. When building the V8 DLL the
31 // BUILDING_V8_SHARED needs to be defined. When building a program which uses
32 // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
33 // static library or building a program which uses the V8 static library neither
34 // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
35 #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
36 #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the
37  build configuration to ensure that at most one of these is set
38 #endif
39 
40 #ifdef BUILDING_V8_SHARED
41 # define V8_EXPORT __declspec(dllexport)
42 #elif USING_V8_SHARED
43 # define V8_EXPORT __declspec(dllimport)
44 #else
45 # define V8_EXPORT
46 #endif // BUILDING_V8_SHARED
47 
48 #else // V8_OS_WIN
49 
50 // Setup for Linux shared library export.
51 #if V8_HAS_ATTRIBUTE_VISIBILITY && defined(V8_SHARED)
52 # ifdef BUILDING_V8_SHARED
53 # define V8_EXPORT __attribute__ ((visibility("default")))
54 # else
55 # define V8_EXPORT
56 # endif
57 #else
58 # define V8_EXPORT
59 #endif
60 
61 #endif // V8_OS_WIN
62 
63 /**
64  * The v8 JavaScript engine.
65  */
66 namespace v8 {
67 
68 class AccessorSignature;
69 class Array;
70 class Boolean;
71 class BooleanObject;
72 class Context;
73 class CpuProfiler;
74 class Data;
75 class Date;
76 class External;
77 class Function;
78 class FunctionTemplate;
79 class HeapProfiler;
80 class ImplementationUtilities;
81 class Int32;
82 class Integer;
83 class Isolate;
84 template <class T>
85 class Maybe;
86 class Name;
87 class Number;
88 class NumberObject;
89 class Object;
90 class ObjectOperationDescriptor;
91 class ObjectTemplate;
92 class Platform;
93 class Primitive;
94 class Promise;
95 class RawOperationDescriptor;
96 class Script;
97 class SharedArrayBuffer;
98 class Signature;
99 class StartupData;
100 class StackFrame;
101 class StackTrace;
102 class String;
103 class StringObject;
104 class Symbol;
105 class SymbolObject;
106 class Uint32;
107 class Utils;
108 class Value;
109 template <class T> class Local;
110 template <class T>
111 class MaybeLocal;
112 template <class T> class Eternal;
113 template<class T> class NonCopyablePersistentTraits;
114 template<class T> class PersistentBase;
115 template<class T,
116  class M = NonCopyablePersistentTraits<T> > class Persistent;
117 template <class T>
118 class Global;
119 template<class K, class V, class T> class PersistentValueMap;
120 template <class K, class V, class T>
122 template <class K, class V, class T>
123 class GlobalValueMap;
124 template<class V, class T> class PersistentValueVector;
125 template<class T, class P> class WeakCallbackObject;
126 class FunctionTemplate;
127 class ObjectTemplate;
128 class Data;
129 template<typename T> class FunctionCallbackInfo;
130 template<typename T> class PropertyCallbackInfo;
131 class StackTrace;
132 class StackFrame;
133 class Isolate;
134 class CallHandlerHelper;
136 template<typename T> class ReturnValue;
137 
138 namespace internal {
139 class Arguments;
140 class Heap;
141 class HeapObject;
142 class Isolate;
143 class Object;
144 struct StreamedSource;
145 template<typename T> class CustomArguments;
146 class PropertyCallbackArguments;
147 class FunctionCallbackArguments;
148 class GlobalHandles;
149 }
150 
151 
152 /**
153  * General purpose unique identifier.
154  */
155 class UniqueId {
156  public:
157  explicit UniqueId(intptr_t data)
158  : data_(data) {}
159 
160  bool operator==(const UniqueId& other) const {
161  return data_ == other.data_;
162  }
163 
164  bool operator!=(const UniqueId& other) const {
165  return data_ != other.data_;
166  }
167 
168  bool operator<(const UniqueId& other) const {
169  return data_ < other.data_;
170  }
171 
172  private:
173  intptr_t data_;
174 };
175 
176 // --- Handles ---
177 
178 #define TYPE_CHECK(T, S)
179  while (false) {
180  *(static_cast<T* volatile*>(0)) = static_cast<S*>(0);
181  }
182 
183 
184 /**
185  * An object reference managed by the v8 garbage collector.
186  *
187  * All objects returned from v8 have to be tracked by the garbage
188  * collector so that it knows that the objects are still alive. Also,
189  * because the garbage collector may move objects, it is unsafe to
190  * point directly to an object. Instead, all objects are stored in
191  * handles which are known by the garbage collector and updated
192  * whenever an object moves. Handles should always be passed by value
193  * (except in cases like out-parameters) and they should never be
194  * allocated on the heap.
195  *
196  * There are two types of handles: local and persistent handles.
197  * Local handles are light-weight and transient and typically used in
198  * local operations. They are managed by HandleScopes. Persistent
199  * handles can be used when storing objects across several independent
200  * operations and have to be explicitly deallocated when they're no
201  * longer used.
202  *
203  * It is safe to extract the object stored in the handle by
204  * dereferencing the handle (for instance, to extract the Object* from
205  * a Local<Object>); the value will still be governed by a handle
206  * behind the scenes and the same rules apply to these values as to
207  * their handles.
208  */
209 template <class T>
210 class Local {
211  public:
212  V8_INLINE Local() : val_(0) {}
213  template <class S>
215  : val_(reinterpret_cast<T*>(*that)) {
216  /**
217  * This check fails when trying to convert between incompatible
218  * handles. For example, converting from a Local<String> to a
219  * Local<Number>.
220  */
221  TYPE_CHECK(T, S);
222  }
223 
224  /**
225  * Returns true if the handle is empty.
226  */
227  V8_INLINE bool IsEmpty() const { return val_ == 0; }
228 
229  /**
230  * Sets the handle to be empty. IsEmpty() will then return true.
231  */
232  V8_INLINE void Clear() { val_ = 0; }
233 
234  V8_INLINE T* operator->() const { return val_; }
235 
236  V8_INLINE T* operator*() const { return val_; }
237 
238  /**
239  * Checks whether two handles are the same.
240  * Returns true if both are empty, or if the objects
241  * to which they refer are identical.
242  * The handles' references are not checked.
243  */
244  template <class S>
245  V8_INLINE bool operator==(const Local<S>& that) const {
246  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
247  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
248  if (a == 0) return b == 0;
249  if (b == 0) return false;
250  return *a == *b;
251  }
252 
253  template <class S> V8_INLINE bool operator==(
254  const PersistentBase<S>& that) const {
255  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
256  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
257  if (a == 0) return b == 0;
258  if (b == 0) return false;
259  return *a == *b;
260  }
261 
262  /**
263  * Checks whether two handles are different.
264  * Returns true if only one of the handles is empty, or if
265  * the objects to which they refer are different.
266  * The handles' references are not checked.
267  */
268  template <class S>
269  V8_INLINE bool operator!=(const Local<S>& that) const {
270  return !operator==(that);
271  }
272 
273  template <class S> V8_INLINE bool operator!=(
274  const Persistent<S>& that) const {
275  return !operator==(that);
276  }
277 
278  template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
279 #ifdef V8_ENABLE_CHECKS
280  // If we're going to perform the type check then we have to check
281  // that the handle isn't empty before doing the checked cast.
282  if (that.IsEmpty()) return Local<T>();
283 #endif
284  return Local<T>(T::Cast(*that));
285  }
286 
287 
288  template <class S> V8_INLINE Local<S> As() {
289  return Local<S>::Cast(*this);
290  }
291 
292  /**
293  * Create a local handle for the content of another handle.
294  * The referee is kept alive by the local handle even when
295  * the original handle is destroyed/disposed.
296  */
297  V8_INLINE static Local<T> New(Isolate* isolate, Local<T> that);
298  V8_INLINE static Local<T> New(Isolate* isolate,
299  const PersistentBase<T>& that);
300 
301  private:
302  friend class Utils;
303  template<class F> friend class Eternal;
304  template<class F> friend class PersistentBase;
305  template<class F, class M> friend class Persistent;
306  template<class F> friend class Local;
307  template <class F>
308  friend class MaybeLocal;
309  template<class F> friend class FunctionCallbackInfo;
310  template<class F> friend class PropertyCallbackInfo;
311  friend class String;
312  friend class Object;
313  friend class Context;
314  template<class F> friend class internal::CustomArguments;
315  friend Local<Primitive> Undefined(Isolate* isolate);
316  friend Local<Primitive> Null(Isolate* isolate);
317  friend Local<Boolean> True(Isolate* isolate);
318  friend Local<Boolean> False(Isolate* isolate);
319  friend class HandleScope;
320  friend class EscapableHandleScope;
321  template <class F1, class F2, class F3>
323  template<class F1, class F2> friend class PersistentValueVector;
324 
325  template <class S>
326  V8_INLINE Local(S* that)
327  : val_(that) {}
328  V8_INLINE static Local<T> New(Isolate* isolate, T* that);
329  T* val_;
330 };
331 
332 
333 #if !defined(V8_IMMINENT_DEPRECATION_WARNINGS)
334 // Local is an alias for Local for historical reasons.
335 template <class T>
336 using Handle = Local<T>;
337 #endif
338 
339 
340 /**
341  * A MaybeLocal<> is a wrapper around Local<> that enforces a check whether
342  * the Local<> is empty before it can be used.
343  *
344  * If an API method returns a MaybeLocal<>, the API method can potentially fail
345  * either because an exception is thrown, or because an exception is pending,
346  * e.g. because a previous API call threw an exception that hasn't been caught
347  * yet, or because a TerminateExecution exception was thrown. In that case, an
348  * empty MaybeLocal is returned.
349  */
350 template <class T>
351 class MaybeLocal {
352  public:
353  V8_INLINE MaybeLocal() : val_(nullptr) {}
354  template <class S>
356  : val_(reinterpret_cast<T*>(*that)) {
357  TYPE_CHECK(T, S);
358  }
359 
360  V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
361 
362  template <class S>
364  out->val_ = IsEmpty() ? nullptr : this->val_;
365  return !IsEmpty();
366  }
367 
368  // Will crash if the MaybeLocal<> is empty.
370 
371  template <class S>
372  V8_INLINE Local<S> FromMaybe(Local<S> default_value) const {
373  return IsEmpty() ? default_value : Local<S>(val_);
374  }
375 
376  private:
377  T* val_;
378 };
379 
380 
381 // Eternal handles are set-once handles that live for the life of the isolate.
382 template <class T> class Eternal {
383  public:
384  V8_INLINE Eternal() : index_(kInitialValue) { }
385  template<class S>
386  V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
387  Set(isolate, handle);
388  }
389  // Can only be safely called if already set.
390  V8_INLINE Local<T> Get(Isolate* isolate);
391  V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
392  template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
393 
394  private:
395  static const int kInitialValue = -1;
396  int index_;
397 };
398 
399 
400 static const int kInternalFieldsInWeakCallback = 2;
401 
402 
403 template <typename T>
405  public:
406  typedef void (*Callback)(const WeakCallbackInfo<T>& data);
407 
408  WeakCallbackInfo(Isolate* isolate, T* parameter,
409  void* internal_fields[kInternalFieldsInWeakCallback],
410  Callback* callback)
411  : isolate_(isolate), parameter_(parameter), callback_(callback) {
412  for (int i = 0; i < kInternalFieldsInWeakCallback; ++i) {
413  internal_fields_[i] = internal_fields[i];
414  }
415  }
416 
417  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
418  V8_INLINE T* GetParameter() const { return parameter_; }
419  V8_INLINE void* GetInternalField(int index) const;
420 
421  V8_INLINE V8_DEPRECATE_SOON("use indexed version",
422  void* GetInternalField1() const) {
423  return internal_fields_[0];
424  }
425  V8_INLINE V8_DEPRECATE_SOON("use indexed version",
426  void* GetInternalField2() const) {
427  return internal_fields_[1];
428  }
429 
430  bool IsFirstPass() const { return callback_ != nullptr; }
431 
432  // When first called, the embedder MUST Reset() the Global which triggered the
433  // callback. The Global itself is unusable for anything else. No v8 other api
434  // calls may be called in the first callback. Should additional work be
435  // required, the embedder must set a second pass callback, which will be
436  // called after all the initial callbacks are processed.
437  // Calling SetSecondPassCallback on the second pass will immediately crash.
438  void SetSecondPassCallback(Callback callback) const { *callback_ = callback; }
439 
440  private:
441  Isolate* isolate_;
442  T* parameter_;
443  Callback* callback_;
444  void* internal_fields_[kInternalFieldsInWeakCallback];
445 };
446 
447 
448 template <class T, class P>
450  public:
451  typedef void (*Callback)(const WeakCallbackData<T, P>& data);
452 
453  WeakCallbackData(Isolate* isolate, P* parameter, Local<T> handle)
454  : isolate_(isolate), parameter_(parameter), handle_(handle) {}
455 
456  V8_INLINE Isolate* GetIsolate() const { return isolate_; }
457  V8_INLINE P* GetParameter() const { return parameter_; }
458  V8_INLINE Local<T> GetValue() const { return handle_; }
459 
460  private:
461  Isolate* isolate_;
462  P* parameter_;
463  Local<T> handle_;
464 };
465 
466 
467 // TODO(dcarney): delete this with WeakCallbackData
468 template <class T>
469 using PhantomCallbackData = WeakCallbackInfo<T>;
470 
471 
473 
474 
475 /**
476  * An object reference that is independent of any handle scope. Where
477  * a Local handle only lives as long as the HandleScope in which it was
478  * allocated, a PersistentBase handle remains valid until it is explicitly
479  * disposed.
480  *
481  * A persistent handle contains a reference to a storage cell within
482  * the v8 engine which holds an object value and which is updated by
483  * the garbage collector whenever the object is moved. A new storage
484  * cell can be created using the constructor or PersistentBase::Reset and
485  * existing handles can be disposed using PersistentBase::Reset.
486  *
487  */
488 template <class T> class PersistentBase {
489  public:
490  /**
491  * If non-empty, destroy the underlying storage cell
492  * IsEmpty() will return true after this call.
493  */
494  V8_INLINE void Reset();
495  /**
496  * If non-empty, destroy the underlying storage cell
497  * and create a new one with the contents of other if other is non empty
498  */
499  template <class S>
500  V8_INLINE void Reset(Isolate* isolate, const Local<S>& other);
501 
502  /**
503  * If non-empty, destroy the underlying storage cell
504  * and create a new one with the contents of other if other is non empty
505  */
506  template <class S>
507  V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
508 
509  V8_INLINE bool IsEmpty() const { return val_ == NULL; }
510  V8_INLINE void Empty() { val_ = 0; }
511 
512  template <class S>
513  V8_INLINE bool operator==(const PersistentBase<S>& that) const {
514  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
515  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
516  if (a == NULL) return b == NULL;
517  if (b == NULL) return false;
518  return *a == *b;
519  }
520 
521  template <class S>
522  V8_INLINE bool operator==(const Local<S>& that) const {
523  internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
524  internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
525  if (a == NULL) return b == NULL;
526  if (b == NULL) return false;
527  return *a == *b;
528  }
529 
530  template <class S>
531  V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
532  return !operator==(that);
533  }
534 
535  template <class S>
536  V8_INLINE bool operator!=(const Local<S>& that) const {
537  return !operator==(that);
538  }
539 
540  /**
541  * Install a finalization callback on this object.
542  * NOTE: There is no guarantee as to *when* or even *if* the callback is
543  * invoked. The invocation is performed solely on a best effort basis.
544  * As always, GC-based finalization should *not* be relied upon for any
545  * critical form of resource management!
546  */
547  template <typename P>
549  "use WeakCallbackInfo version",
550  void SetWeak(P* parameter,
551  typename WeakCallbackData<T, P>::Callback callback));
552 
553  template <typename S, typename P>
555  "use WeakCallbackInfo version",
556  void SetWeak(P* parameter,
557  typename WeakCallbackData<S, P>::Callback callback));
558 
559  // Phantom persistents work like weak persistents, except that the pointer to
560  // the object being collected is not available in the finalization callback.
561  // This enables the garbage collector to collect the object and any objects
562  // it references transitively in one GC cycle. At the moment you can either
563  // specify a parameter for the callback or the location of two internal
564  // fields in the dying object.
565  template <typename P>
567  "use SetWeak",
568  void SetPhantom(P* parameter,
569  typename WeakCallbackInfo<P>::Callback callback,
570  int internal_field_index1 = -1,
571  int internal_field_index2 = -1));
572 
573  template <typename P>
574  V8_INLINE void SetWeak(P* parameter,
575  typename WeakCallbackInfo<P>::Callback callback,
576  WeakCallbackType type);
577 
578  template<typename P>
580 
581  // TODO(dcarney): remove this.
582  V8_INLINE void ClearWeak() { ClearWeak<void>(); }
583 
584  /**
585  * Marks the reference to this object independent. Garbage collector is free
586  * to ignore any object groups containing this object. Weak callback for an
587  * independent handle should not assume that it will be preceded by a global
588  * GC prologue callback or followed by a global GC epilogue callback.
589  */
590  V8_INLINE void MarkIndependent();
591 
592  /**
593  * Marks the reference to this object partially dependent. Partially dependent
594  * handles only depend on other partially dependent handles and these
595  * dependencies are provided through object groups. It provides a way to build
596  * smaller object groups for young objects that represent only a subset of all
597  * external dependencies. This mark is automatically cleared after each
598  * garbage collection.
599  */
601 
602  V8_INLINE bool IsIndependent() const;
603 
604  /** Checks if the handle holds the only reference to an object. */
605  V8_INLINE bool IsNearDeath() const;
606 
607  /** Returns true if the handle's reference is weak. */
608  V8_INLINE bool IsWeak() const;
609 
610  /**
611  * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
612  * description in v8-profiler.h for details.
613  */
614  V8_INLINE void SetWrapperClassId(uint16_t class_id);
615 
616  /**
617  * Returns the class ID previously assigned to this handle or 0 if no class ID
618  * was previously assigned.
619  */
620  V8_INLINE uint16_t WrapperClassId() const;
621 
622  private:
623  friend class Isolate;
624  friend class Utils;
625  template<class F> friend class Local;
626  template<class F1, class F2> friend class Persistent;
627  template <class F>
628  friend class Global;
629  template<class F> friend class PersistentBase;
630  template<class F> friend class ReturnValue;
631  template <class F1, class F2, class F3>
633  template<class F1, class F2> friend class PersistentValueVector;
634  friend class Object;
635 
636  explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
637  PersistentBase(PersistentBase& other) = delete; // NOLINT
638  void operator=(PersistentBase&) = delete;
639  V8_INLINE static T* New(Isolate* isolate, T* that);
640 
641  T* val_;
642 };
643 
644 
645 /**
646  * Default traits for Persistent. This class does not allow
647  * use of the copy constructor or assignment operator.
648  * At present kResetInDestructor is not set, but that will change in a future
649  * version.
650  */
651 template<class T>
652 class NonCopyablePersistentTraits {
653  public:
654  typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
655  static const bool kResetInDestructor = false;
656  template<class S, class M>
657  V8_INLINE static void Copy(const Persistent<S, M>& source,
658  NonCopyablePersistent* dest) {
659  Uncompilable<Object>();
660  }
661  // TODO(dcarney): come up with a good compile error here.
662  template<class O> V8_INLINE static void Uncompilable() {
663  TYPE_CHECK(O, Primitive);
664  }
665 };
666 
667 
668 /**
669  * Helper class traits to allow copying and assignment of Persistent.
670  * This will clone the contents of storage cell, but not any of the flags, etc.
671  */
672 template<class T>
675  static const bool kResetInDestructor = true;
676  template<class S, class M>
677  static V8_INLINE void Copy(const Persistent<S, M>& source,
678  CopyablePersistent* dest) {
679  // do nothing, just allow copy
680  }
681 };
682 
683 
684 /**
685  * A PersistentBase which allows copy and assignment.
686  *
687  * Copy, assignment and destructor bevavior is controlled by the traits
688  * class M.
689  *
690  * Note: Persistent class hierarchy is subject to future changes.
691  */
692 template <class T, class M> class Persistent : public PersistentBase<T> {
693  public:
694  /**
695  * A Persistent with no storage cell.
696  */
698  /**
699  * Construct a Persistent from a Local.
700  * When the Local is non-empty, a new storage cell is created
701  * pointing to the same object, and no flags are set.
702  */
703  template <class S>
704  V8_INLINE Persistent(Isolate* isolate, Local<S> that)
705  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
706  TYPE_CHECK(T, S);
707  }
708  /**
709  * Construct a Persistent from a Persistent.
710  * When the Persistent is non-empty, a new storage cell is created
711  * pointing to the same object, and no flags are set.
712  */
713  template <class S, class M2>
714  V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
715  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
716  TYPE_CHECK(T, S);
717  }
718  /**
719  * The copy constructors and assignment operator create a Persistent
720  * exactly as the Persistent constructor, but the Copy function from the
721  * traits class is called, allowing the setting of flags based on the
722  * copied Persistent.
723  */
725  Copy(that);
726  }
727  template <class S, class M2>
728  V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
729  Copy(that);
730  }
731  V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
732  Copy(that);
733  return *this;
734  }
735  template <class S, class M2>
736  V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
737  Copy(that);
738  return *this;
739  }
740  /**
741  * The destructor will dispose the Persistent based on the
742  * kResetInDestructor flags in the traits class. Since not calling dispose
743  * can result in a memory leak, it is recommended to always set this flag.
744  */
746  if (M::kResetInDestructor) this->Reset();
747  }
748 
749  // TODO(dcarney): this is pretty useless, fix or remove
750  template <class S>
751  V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
752 #ifdef V8_ENABLE_CHECKS
753  // If we're going to perform the type check then we have to check
754  // that the handle isn't empty before doing the checked cast.
755  if (!that.IsEmpty()) T::Cast(*that);
756 #endif
757  return reinterpret_cast<Persistent<T>&>(that);
758  }
759 
760  // TODO(dcarney): this is pretty useless, fix or remove
761  template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
762  return Persistent<S>::Cast(*this);
763  }
764 
765  private:
766  friend class Isolate;
767  friend class Utils;
768  template<class F> friend class Local;
769  template<class F1, class F2> friend class Persistent;
770  template<class F> friend class ReturnValue;
771 
772  template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
773  V8_INLINE T* operator*() const { return this->val_; }
774  template<class S, class M2>
775  V8_INLINE void Copy(const Persistent<S, M2>& that);
776 };
777 
778 
779 /**
780  * A PersistentBase which has move semantics.
781  *
782  * Note: Persistent class hierarchy is subject to future changes.
783  */
784 template <class T>
785 class Global : public PersistentBase<T> {
786  public:
787  /**
788  * A Global with no storage cell.
789  */
790  V8_INLINE Global() : PersistentBase<T>(nullptr) {}
791  /**
792  * Construct a Global from a Local.
793  * When the Local is non-empty, a new storage cell is created
794  * pointing to the same object, and no flags are set.
795  */
796  template <class S>
797  V8_INLINE Global(Isolate* isolate, Local<S> that)
798  : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
799  TYPE_CHECK(T, S);
800  }
801  /**
802  * Construct a Global from a PersistentBase.
803  * When the Persistent is non-empty, a new storage cell is created
804  * pointing to the same object, and no flags are set.
805  */
806  template <class S>
807  V8_INLINE Global(Isolate* isolate, const PersistentBase<S>& that)
808  : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
809  TYPE_CHECK(T, S);
810  }
811  /**
812  * Move constructor.
813  */
814  V8_INLINE Global(Global&& other) : PersistentBase<T>(other.val_) {
815  other.val_ = nullptr;
816  }
817  V8_INLINE ~Global() { this->Reset(); }
818  /**
819  * Move via assignment.
820  */
821  template <class S>
823  TYPE_CHECK(T, S);
824  if (this != &rhs) {
825  this->Reset();
826  this->val_ = rhs.val_;
827  rhs.val_ = nullptr;
828  }
829  return *this;
830  }
831  /**
832  * Pass allows returning uniques from functions, etc.
833  */
834  Global Pass() { return static_cast<Global&&>(*this); }
835 
836  /*
837  * For compatibility with Chromium's base::Bind (base::Passed).
838  */
839  typedef void MoveOnlyTypeForCPP03;
840 
841  private:
842  template <class F>
843  friend class ReturnValue;
844  Global(Global&) = delete;
845  void operator=(Global&) = delete;
846  V8_INLINE T* operator*() const { return this->val_; }
847 };
848 
849 
850 // UniquePersistent is an alias for Global for historical reason.
851 template <class T>
852 using UniquePersistent = Global<T>;
853 
854 
855  /**
856  * A stack-allocated class that governs a number of local handles.
857  * After a handle scope has been created, all local handles will be
858  * allocated within that handle scope until either the handle scope is
859  * deleted or another handle scope is created. If there is already a
860  * handle scope and a new one is created, all allocations will take
861  * place in the new handle scope until it is deleted. After that,
862  * new handles will again be allocated in the original handle scope.
863  *
864  * After the handle scope of a local handle has been deleted the
865  * garbage collector will no longer track the object stored in the
866  * handle and may deallocate it. The behavior of accessing a handle
867  * for which the handle scope has been deleted is undefined.
868  */
870  public:
871  HandleScope(Isolate* isolate);
872 
874 
875  /**
876  * Counts the number of allocated handles.
877  */
878  static int NumberOfHandles(Isolate* isolate);
879 
881  return reinterpret_cast<Isolate*>(isolate_);
882  }
883 
884  protected:
886 
887  void Initialize(Isolate* isolate);
888 
889  static internal::Object** CreateHandle(internal::Isolate* isolate,
890  internal::Object* value);
891 
892  private:
893  // Uses heap_object to obtain the current Isolate.
894  static internal::Object** CreateHandle(internal::HeapObject* heap_object,
895  internal::Object* value);
896 
897  // Make it hard to create heap-allocated or illegal handle scopes by
898  // disallowing certain operations.
899  HandleScope(const HandleScope&);
900  void operator=(const HandleScope&);
901  void* operator new(size_t size);
902  void operator delete(void*, size_t);
903 
904  internal::Isolate* isolate_;
905  internal::Object** prev_next_;
906  internal::Object** prev_limit_;
907 
908  // Local::New uses CreateHandle with an Isolate* parameter.
909  template<class F> friend class Local;
910 
911  // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
912  // a HeapObject* in their shortcuts.
913  friend class Object;
914  friend class Context;
915 };
916 
917 
918 /**
919  * A HandleScope which first allocates a handle in the current scope
920  * which will be later filled with the escape value.
921  */
923  public:
926 
927  /**
928  * Pushes the value into the previous scope and returns a handle to it.
929  * Cannot be called twice.
930  */
931  template <class T>
932  V8_INLINE Local<T> Escape(Local<T> value) {
933  internal::Object** slot =
934  Escape(reinterpret_cast<internal::Object**>(*value));
935  return Local<T>(reinterpret_cast<T*>(slot));
936  }
937 
938  private:
939  internal::Object** Escape(internal::Object** escape_value);
940 
941  // Make it hard to create heap-allocated or illegal handle scopes by
942  // disallowing certain operations.
943  EscapableHandleScope(const EscapableHandleScope&);
944  void operator=(const EscapableHandleScope&);
945  void* operator new(size_t size);
946  void operator delete(void*, size_t);
947 
948  internal::Object** escape_slot_;
949 };
950 
952  public:
955 
956  private:
957  // Make it hard to create heap-allocated or illegal handle scopes by
958  // disallowing certain operations.
959  SealHandleScope(const SealHandleScope&);
960  void operator=(const SealHandleScope&);
961  void* operator new(size_t size);
962  void operator delete(void*, size_t);
963 
964  internal::Isolate* isolate_;
965  int prev_level_;
966  internal::Object** prev_limit_;
967 };
968 
969 
970 // --- Special objects ---
971 
972 
973 /**
974  * The superclass of values and API object templates.
975  */
977  private:
978  Data();
979 };
980 
981 
982 /**
983  * The optional attributes of ScriptOrigin.
984  */
986  public:
987  V8_INLINE ScriptOriginOptions(bool is_embedder_debug_script = false,
988  bool is_shared_cross_origin = false,
989  bool is_opaque = false)
990  : flags_((is_embedder_debug_script ? kIsEmbedderDebugScript : 0) |
991  (is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
992  (is_opaque ? kIsOpaque : 0)) {}
994  : flags_(flags &
995  (kIsEmbedderDebugScript | kIsSharedCrossOrigin | kIsOpaque)) {}
996  bool IsEmbedderDebugScript() const {
997  return (flags_ & kIsEmbedderDebugScript) != 0;
998  }
999  bool IsSharedCrossOrigin() const {
1000  return (flags_ & kIsSharedCrossOrigin) != 0;
1001  }
1002  bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1003  int Flags() const { return flags_; }
1004 
1005  private:
1006  enum {
1007  kIsEmbedderDebugScript = 1,
1008  kIsSharedCrossOrigin = 1 << 1,
1009  kIsOpaque = 1 << 2
1010  };
1011  const int flags_;
1012 };
1013 
1014 /**
1015  * The origin, within a file, of a script.
1016  */
1018  public:
1020  Local<Value> resource_name,
1021  Local<Integer> resource_line_offset = Local<Integer>(),
1022  Local<Integer> resource_column_offset = Local<Integer>(),
1023  Local<Boolean> resource_is_shared_cross_origin = Local<Boolean>(),
1024  Local<Integer> script_id = Local<Integer>(),
1025  Local<Boolean> resource_is_embedder_debug_script = Local<Boolean>(),
1026  Local<Value> source_map_url = Local<Value>(),
1027  Local<Boolean> resource_is_opaque = Local<Boolean>());
1028  V8_INLINE Local<Value> ResourceName() const;
1031  /**
1032  * Returns true for embedder's debugger scripts
1033  */
1034  V8_INLINE Local<Integer> ScriptID() const;
1035  V8_INLINE Local<Value> SourceMapUrl() const;
1036  V8_INLINE ScriptOriginOptions Options() const { return options_; }
1037 
1038  private:
1039  Local<Value> resource_name_;
1040  Local<Integer> resource_line_offset_;
1041  Local<Integer> resource_column_offset_;
1042  ScriptOriginOptions options_;
1043  Local<Integer> script_id_;
1044  Local<Value> source_map_url_;
1045 };
1046 
1047 
1048 /**
1049  * A compiled JavaScript script, not yet tied to a Context.
1050  */
1052  public:
1053  /**
1054  * Binds the script to the currently entered context.
1055  */
1057 
1058  int GetId();
1060 
1061  /**
1062  * Data read from magic sourceURL comments.
1063  */
1065  /**
1066  * Data read from magic sourceMappingURL comments.
1067  */
1069 
1070  /**
1071  * Returns zero based line number of the code_pos location in the script.
1072  * -1 will be returned if no information available.
1073  */
1074  int GetLineNumber(int code_pos);
1075 
1076  static const int kNoScriptId = 0;
1077 };
1078 
1079 
1080 /**
1081  * A compiled JavaScript script, tied to a Context which was active when the
1082  * script was compiled.
1083  */
1085  public:
1086  /**
1087  * A shorthand for ScriptCompiler::Compile().
1088  */
1090  "Use maybe version",
1091  Local<Script> Compile(Local<String> source,
1092  ScriptOrigin* origin = nullptr));
1094  Local<Context> context, Local<String> source,
1095  ScriptOrigin* origin = nullptr);
1096 
1097  static Local<Script> V8_DEPRECATE_SOON("Use maybe version",
1098  Compile(Local<String> source,
1099  Local<String> file_name));
1100 
1101  /**
1102  * Runs the script returning the resulting value. It will be run in the
1103  * context in which it was created (ScriptCompiler::CompileBound or
1104  * UnboundScript::BindToCurrentContext()).
1105  */
1106  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Run());
1108 
1109  /**
1110  * Returns the corresponding context-unbound script.
1111  */
1113 
1114  V8_DEPRECATED("Use GetUnboundScript()->GetId()",
1115  int GetId()) {
1117  }
1118 };
1119 
1120 
1121 /**
1122  * For compiling scripts.
1123  */
1125  public:
1126  /**
1127  * Compilation data that the embedder can cache and pass back to speed up
1128  * future compilations. The data is produced if the CompilerOptions passed to
1129  * the compilation functions in ScriptCompiler contains produce_data_to_cache
1130  * = true. The data to cache can then can be retrieved from
1131  * UnboundScript.
1132  */
1136  BufferOwned
1137  };
1138 
1140  : data(NULL),
1141  length(0),
1142  rejected(false),
1144 
1145  // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
1146  // data and guarantees that it stays alive until the CachedData object is
1147  // destroyed. If the policy is BufferOwned, the given data will be deleted
1148  // (with delete[]) when the CachedData object is destroyed.
1149  CachedData(const uint8_t* data, int length,
1150  BufferPolicy buffer_policy = BufferNotOwned);
1152  // TODO(marja): Async compilation; add constructors which take a callback
1153  // which will be called when V8 no longer needs the data.
1154  const uint8_t* data;
1155  int length;
1156  bool rejected;
1158 
1159  private:
1160  // Prevent copying. Not implemented.
1161  CachedData(const CachedData&);
1162  CachedData& operator=(const CachedData&);
1163  };
1164 
1165  /**
1166  * Source code which can be then compiled to a UnboundScript or Script.
1167  */
1168  class Source {
1169  public:
1170  // Source takes ownership of CachedData.
1171  V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
1172  CachedData* cached_data = NULL);
1173  V8_INLINE Source(Local<String> source_string,
1174  CachedData* cached_data = NULL);
1175  V8_INLINE ~Source();
1176 
1177  // Ownership of the CachedData or its buffers is *not* transferred to the
1178  // caller. The CachedData object is alive as long as the Source object is
1179  // alive.
1180  V8_INLINE const CachedData* GetCachedData() const;
1181 
1182  private:
1183  friend class ScriptCompiler;
1184  // Prevent copying. Not implemented.
1185  Source(const Source&);
1186  Source& operator=(const Source&);
1187 
1188  Local<String> source_string;
1189 
1190  // Origin information
1191  Local<Value> resource_name;
1192  Local<Integer> resource_line_offset;
1193  Local<Integer> resource_column_offset;
1194  ScriptOriginOptions resource_options;
1195  Local<Value> source_map_url;
1196 
1197  // Cached data from previous compilation (if a kConsume*Cache flag is
1198  // set), or hold newly generated cache data (kProduce*Cache flags) are
1199  // set when calling a compile method.
1200  CachedData* cached_data;
1201  };
1202 
1203  /**
1204  * For streaming incomplete script data to V8. The embedder should implement a
1205  * subclass of this class.
1206  */
1208  public:
1209  virtual ~ExternalSourceStream() {}
1210 
1211  /**
1212  * V8 calls this to request the next chunk of data from the embedder. This
1213  * function will be called on a background thread, so it's OK to block and
1214  * wait for the data, if the embedder doesn't have data yet. Returns the
1215  * length of the data returned. When the data ends, GetMoreData should
1216  * return 0. Caller takes ownership of the data.
1217  *
1218  * When streaming UTF-8 data, V8 handles multi-byte characters split between
1219  * two data chunks, but doesn't handle multi-byte characters split between
1220  * more than two data chunks. The embedder can avoid this problem by always
1221  * returning at least 2 bytes of data.
1222  *
1223  * If the embedder wants to cancel the streaming, they should make the next
1224  * GetMoreData call return 0. V8 will interpret it as end of data (and most
1225  * probably, parsing will fail). The streaming task will return as soon as
1226  * V8 has parsed the data it received so far.
1227  */
1228  virtual size_t GetMoreData(const uint8_t** src) = 0;
1229 
1230  /**
1231  * V8 calls this method to set a 'bookmark' at the current position in
1232  * the source stream, for the purpose of (maybe) later calling
1233  * ResetToBookmark. If ResetToBookmark is called later, then subsequent
1234  * calls to GetMoreData should return the same data as they did when
1235  * SetBookmark was called earlier.
1236  *
1237  * The embedder may return 'false' to indicate it cannot provide this
1238  * functionality.
1239  */
1240  virtual bool SetBookmark();
1241 
1242  /**
1243  * V8 calls this to return to a previously set bookmark.
1244  */
1245  virtual void ResetToBookmark();
1246  };
1247 
1248 
1249  /**
1250  * Source code which can be streamed into V8 in pieces. It will be parsed
1251  * while streaming. It can be compiled after the streaming is complete.
1252  * StreamedSource must be kept alive while the streaming task is ran (see
1253  * ScriptStreamingTask below).
1254  */
1256  public:
1258 
1259  StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
1261 
1262  // Ownership of the CachedData or its buffers is *not* transferred to the
1263  // caller. The CachedData object is alive as long as the StreamedSource
1264  // object is alive.
1265  const CachedData* GetCachedData() const;
1266 
1267  internal::StreamedSource* impl() const { return impl_; }
1268 
1269  private:
1270  // Prevent copying. Not implemented.
1271  StreamedSource(const StreamedSource&);
1272  StreamedSource& operator=(const StreamedSource&);
1273 
1274  internal::StreamedSource* impl_;
1275  };
1276 
1277  /**
1278  * A streaming task which the embedder must run on a background thread to
1279  * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
1280  */
1282  public:
1283  virtual ~ScriptStreamingTask() {}
1284  virtual void Run() = 0;
1285  };
1286 
1293  };
1294 
1295  /**
1296  * Compiles the specified script (context-independent).
1297  * Cached data as part of the source object can be optionally produced to be
1298  * consumed later to speed up compilation of identical source scripts.
1299  *
1300  * Note that when producing cached data, the source must point to NULL for
1301  * cached data. When consuming cached data, the cached data must have been
1302  * produced by the same version of V8.
1303  *
1304  * \param source Script source code.
1305  * \return Compiled script object (context independent; for running it must be
1306  * bound to a context).
1307  */
1308  static V8_DEPRECATE_SOON("Use maybe version",
1309  Local<UnboundScript> CompileUnbound(
1310  Isolate* isolate, Source* source,
1311  CompileOptions options = kNoCompileOptions));
1313  Isolate* isolate, Source* source,
1314  CompileOptions options = kNoCompileOptions);
1315 
1316  /**
1317  * Compiles the specified script (bound to current context).
1318  *
1319  * \param source Script source code.
1320  * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
1321  * using pre_data speeds compilation if it's done multiple times.
1322  * Owned by caller, no references are kept when this function returns.
1323  * \return Compiled script object, bound to the context that was active
1324  * when this function was called. When run it will always use this
1325  * context.
1326  */
1328  "Use maybe version",
1329  Local<Script> Compile(Isolate* isolate, Source* source,
1330  CompileOptions options = kNoCompileOptions));
1332  Local<Context> context, Source* source,
1333  CompileOptions options = kNoCompileOptions);
1334 
1335  /**
1336  * Returns a task which streams script data into V8, or NULL if the script
1337  * cannot be streamed. The user is responsible for running the task on a
1338  * background thread and deleting it. When ran, the task starts parsing the
1339  * script, and it will request data from the StreamedSource as needed. When
1340  * ScriptStreamingTask::Run exits, all data has been streamed and the script
1341  * can be compiled (see Compile below).
1342  *
1343  * This API allows to start the streaming with as little data as possible, and
1344  * the remaining data (for example, the ScriptOrigin) is passed to Compile.
1345  */
1347  Isolate* isolate, StreamedSource* source,
1348  CompileOptions options = kNoCompileOptions);
1349 
1350  /**
1351  * Compiles a streamed script (bound to current context).
1352  *
1353  * This can only be called after the streaming has finished
1354  * (ScriptStreamingTask has been run). V8 doesn't construct the source string
1355  * during streaming, so the embedder needs to pass the full source here.
1356  */
1358  "Use maybe version",
1359  Local<Script> Compile(Isolate* isolate, StreamedSource* source,
1360  Local<String> full_source_string,
1361  const ScriptOrigin& origin));
1363  Local<Context> context, StreamedSource* source,
1364  Local<String> full_source_string, const ScriptOrigin& origin);
1365 
1366  /**
1367  * Return a version tag for CachedData for the current V8 version & flags.
1368  *
1369  * This value is meant only for determining whether a previously generated
1370  * CachedData instance is still valid; the tag has no other meaing.
1371  *
1372  * Background: The data carried by CachedData may depend on the exact
1373  * V8 version number or currently compiler flags. This means when
1374  * persisting CachedData, the embedder must take care to not pass in
1375  * data from another V8 version, or the same version with different
1376  * features enabled.
1377  *
1378  * The easiest way to do so is to clear the embedder's cache on any
1379  * such change.
1380  *
1381  * Alternatively, this tag can be stored alongside the cached data and
1382  * compared when it is being used.
1383  */
1384  static uint32_t CachedDataVersionTag();
1385 
1386  /**
1387  * Compile an ES6 module.
1388  *
1389  * This is an experimental feature.
1390  *
1391  * TODO(adamk): Script is likely the wrong return value for this;
1392  * should return some new Module type.
1393  */
1395  "Use maybe version",
1396  Local<Script> CompileModule(Isolate* isolate, Source* source,
1397  CompileOptions options = kNoCompileOptions));
1399  Local<Context> context, Source* source,
1400  CompileOptions options = kNoCompileOptions);
1401 
1402  /**
1403  * Compile a function for a given context. This is equivalent to running
1404  *
1405  * with (obj) {
1406  * return function(args) { ... }
1407  * }
1408  *
1409  * It is possible to specify multiple context extensions (obj in the above
1410  * example).
1411  */
1412  static V8_DEPRECATE_SOON("Use maybe version",
1413  Local<Function> CompileFunctionInContext(
1414  Isolate* isolate, Source* source,
1415  Local<Context> context, size_t arguments_count,
1416  Local<String> arguments[],
1417  size_t context_extension_count,
1418  Local<Object> context_extensions[]));
1420  Local<Context> context, Source* source, size_t arguments_count,
1421  Local<String> arguments[], size_t context_extension_count,
1422  Local<Object> context_extensions[]);
1423 
1424  private:
1425  static V8_WARN_UNUSED_RESULT MaybeLocal<UnboundScript> CompileUnboundInternal(
1426  Isolate* isolate, Source* source, CompileOptions options, bool is_module);
1427 };
1428 
1429 
1430 /**
1431  * An error message.
1432  */
1434  public:
1435  Local<String> Get() const;
1436 
1437  V8_DEPRECATE_SOON("Use maybe version", Local<String> GetSourceLine() const);
1439  Local<Context> context) const;
1440 
1441  /**
1442  * Returns the origin for the script from where the function causing the
1443  * error originates.
1444  */
1446 
1447  /**
1448  * Returns the resource name for the script from where the function causing
1449  * the error originates.
1450  */
1452 
1453  /**
1454  * Exception stack trace. By default stack traces are not captured for
1455  * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
1456  * to change this option.
1457  */
1459 
1460  /**
1461  * Returns the number, 1-based, of the line where the error occurred.
1462  */
1463  V8_DEPRECATE_SOON("Use maybe version", int GetLineNumber() const);
1465 
1466  /**
1467  * Returns the index within the script of the first character where
1468  * the error occurred.
1469  */
1470  int GetStartPosition() const;
1471 
1472  /**
1473  * Returns the index within the script of the last character where
1474  * the error occurred.
1475  */
1476  int GetEndPosition() const;
1477 
1478  /**
1479  * Returns the index within the line of the first character where
1480  * the error occurred.
1481  */
1482  V8_DEPRECATE_SOON("Use maybe version", int GetStartColumn() const);
1484 
1485  /**
1486  * Returns the index within the line of the last character where
1487  * the error occurred.
1488  */
1489  V8_DEPRECATE_SOON("Use maybe version", int GetEndColumn() const);
1491 
1492  /**
1493  * Passes on the value set by the embedder when it fed the script from which
1494  * this Message was generated to V8.
1495  */
1496  bool IsSharedCrossOrigin() const;
1497  bool IsOpaque() const;
1498 
1499  // TODO(1245381): Print to a string instead of on a FILE.
1500  static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
1501 
1502  static const int kNoLineNumberInfo = 0;
1503  static const int kNoColumnInfo = 0;
1504  static const int kNoScriptIdInfo = 0;
1505 };
1506 
1507 
1508 /**
1509  * Representation of a JavaScript stack trace. The information collected is a
1510  * snapshot of the execution stack and the information remains valid after
1511  * execution continues.
1512  */
1514  public:
1515  /**
1516  * Flags that determine what information is placed captured for each
1517  * StackFrame when grabbing the current stack trace.
1518  */
1522  kScriptName = 1 << 2,
1523  kFunctionName = 1 << 3,
1524  kIsEval = 1 << 4,
1525  kIsConstructor = 1 << 5,
1527  kScriptId = 1 << 7,
1531  };
1532 
1533  /**
1534  * Returns a StackFrame at a particular index.
1535  */
1536  Local<StackFrame> GetFrame(uint32_t index) const;
1537 
1538  /**
1539  * Returns the number of StackFrames.
1540  */
1541  int GetFrameCount() const;
1542 
1543  /**
1544  * Returns StackTrace as a v8::Array that contains StackFrame objects.
1545  */
1547 
1548  /**
1549  * Grab a snapshot of the current JavaScript execution stack.
1550  *
1551  * \param frame_limit The maximum number of stack frames we want to capture.
1552  * \param options Enumerates the set of things we will capture for each
1553  * StackFrame.
1554  */
1556  Isolate* isolate,
1557  int frame_limit,
1558  StackTraceOptions options = kOverview);
1559 };
1560 
1561 
1562 /**
1563  * A single JavaScript stack frame.
1564  */
1566  public:
1567  /**
1568  * Returns the number, 1-based, of the line for the associate function call.
1569  * This method will return Message::kNoLineNumberInfo if it is unable to
1570  * retrieve the line number, or if kLineNumber was not passed as an option
1571  * when capturing the StackTrace.
1572  */
1573  int GetLineNumber() const;
1574 
1575  /**
1576  * Returns the 1-based column offset on the line for the associated function
1577  * call.
1578  * This method will return Message::kNoColumnInfo if it is unable to retrieve
1579  * the column number, or if kColumnOffset was not passed as an option when
1580  * capturing the StackTrace.
1581  */
1582  int GetColumn() const;
1583 
1584  /**
1585  * Returns the id of the script for the function for this StackFrame.
1586  * This method will return Message::kNoScriptIdInfo if it is unable to
1587  * retrieve the script id, or if kScriptId was not passed as an option when
1588  * capturing the StackTrace.
1589  */
1590  int GetScriptId() const;
1591 
1592  /**
1593  * Returns the name of the resource that contains the script for the
1594  * function for this StackFrame.
1595  */
1597 
1598  /**
1599  * Returns the name of the resource that contains the script for the
1600  * function for this StackFrame or sourceURL value if the script name
1601  * is undefined and its source ends with //# sourceURL=... string or
1602  * deprecated //@ sourceURL=... string.
1603  */
1605 
1606  /**
1607  * Returns the name of the function associated with this stack frame.
1608  */
1610 
1611  /**
1612  * Returns whether or not the associated function is compiled via a call to
1613  * eval().
1614  */
1615  bool IsEval() const;
1616 
1617  /**
1618  * Returns whether or not the associated function is called as a
1619  * constructor via "new".
1620  */
1621  bool IsConstructor() const;
1622 };
1623 
1624 
1625 // A StateTag represents a possible state of the VM.
1627 
1628 
1629 // A RegisterState represents the current state of registers used
1630 // by the sampling profiler API.
1632  RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
1633  void* pc; // Instruction pointer.
1634  void* sp; // Stack pointer.
1635  void* fp; // Frame pointer.
1636 };
1637 
1638 
1639 // The output structure filled up by GetStackSample API function.
1640 struct SampleInfo {
1643 };
1644 
1645 
1646 /**
1647  * A JSON Parser.
1648  */
1650  public:
1651  /**
1652  * Tries to parse the string |json_string| and returns it as value if
1653  * successful.
1654  *
1655  * \param json_string The string to parse.
1656  * \return The corresponding value if successfully parsed.
1657  */
1658  static V8_DEPRECATE_SOON("Use maybe version",
1659  Local<Value> Parse(Local<String> json_string));
1661  Isolate* isolate, Local<String> json_string);
1662 };
1663 
1664 
1665 /**
1666  * A map whose keys are referenced weakly. It is similar to JavaScript WeakMap
1667  * but can be created without entering a v8::Context and hence shouldn't
1668  * escape to JavaScript.
1669  */
1670 class V8_EXPORT NativeWeakMap : public Data {
1671  public:
1672  static Local<NativeWeakMap> New(Isolate* isolate);
1673  void Set(Local<Value> key, Local<Value> value);
1675  bool Has(Local<Value> key);
1676  bool Delete(Local<Value> key);
1677 };
1678 
1679 
1680 // --- Value ---
1681 
1682 
1683 /**
1684  * The superclass of all JavaScript values and objects.
1685  */
1686 class V8_EXPORT Value : public Data {
1687  public:
1688  /**
1689  * Returns true if this value is the undefined value. See ECMA-262
1690  * 4.3.10.
1691  */
1692  V8_INLINE bool IsUndefined() const;
1693 
1694  /**
1695  * Returns true if this value is the null value. See ECMA-262
1696  * 4.3.11.
1697  */
1698  V8_INLINE bool IsNull() const;
1699 
1700  /**
1701  * Returns true if this value is true.
1702  */
1703  bool IsTrue() const;
1704 
1705  /**
1706  * Returns true if this value is false.
1707  */
1708  bool IsFalse() const;
1709 
1710  /**
1711  * Returns true if this value is a symbol or a string.
1712  * This is an experimental feature.
1713  */
1714  bool IsName() const;
1715 
1716  /**
1717  * Returns true if this value is an instance of the String type.
1718  * See ECMA-262 8.4.
1719  */
1720  V8_INLINE bool IsString() const;
1721 
1722  /**
1723  * Returns true if this value is a symbol.
1724  * This is an experimental feature.
1725  */
1726  bool IsSymbol() const;
1727 
1728  /**
1729  * Returns true if this value is a function.
1730  */
1731  bool IsFunction() const;
1732 
1733  /**
1734  * Returns true if this value is an array.
1735  */
1736  bool IsArray() const;
1737 
1738  /**
1739  * Returns true if this value is an object.
1740  */
1741  bool IsObject() const;
1742 
1743  /**
1744  * Returns true if this value is boolean.
1745  */
1746  bool IsBoolean() const;
1747 
1748  /**
1749  * Returns true if this value is a number.
1750  */
1751  bool IsNumber() const;
1752 
1753  /**
1754  * Returns true if this value is external.
1755  */
1756  bool IsExternal() const;
1757 
1758  /**
1759  * Returns true if this value is a 32-bit signed integer.
1760  */
1761  bool IsInt32() const;
1762 
1763  /**
1764  * Returns true if this value is a 32-bit unsigned integer.
1765  */
1766  bool IsUint32() const;
1767 
1768  /**
1769  * Returns true if this value is a Date.
1770  */
1771  bool IsDate() const;
1772 
1773  /**
1774  * Returns true if this value is an Arguments object.
1775  */
1776  bool IsArgumentsObject() const;
1777 
1778  /**
1779  * Returns true if this value is a Boolean object.
1780  */
1781  bool IsBooleanObject() const;
1782 
1783  /**
1784  * Returns true if this value is a Number object.
1785  */
1786  bool IsNumberObject() const;
1787 
1788  /**
1789  * Returns true if this value is a String object.
1790  */
1791  bool IsStringObject() const;
1792 
1793  /**
1794  * Returns true if this value is a Symbol object.
1795  * This is an experimental feature.
1796  */
1797  bool IsSymbolObject() const;
1798 
1799  /**
1800  * Returns true if this value is a NativeError.
1801  */
1802  bool IsNativeError() const;
1803 
1804  /**
1805  * Returns true if this value is a RegExp.
1806  */
1807  bool IsRegExp() const;
1808 
1809  /**
1810  * Returns true if this value is a Generator function.
1811  * This is an experimental feature.
1812  */
1813  bool IsGeneratorFunction() const;
1814 
1815  /**
1816  * Returns true if this value is a Generator object (iterator).
1817  * This is an experimental feature.
1818  */
1819  bool IsGeneratorObject() const;
1820 
1821  /**
1822  * Returns true if this value is a Promise.
1823  * This is an experimental feature.
1824  */
1825  bool IsPromise() const;
1826 
1827  /**
1828  * Returns true if this value is a Map.
1829  */
1830  bool IsMap() const;
1831 
1832  /**
1833  * Returns true if this value is a Set.
1834  */
1835  bool IsSet() const;
1836 
1837  /**
1838  * Returns true if this value is a Map Iterator.
1839  */
1840  bool IsMapIterator() const;
1841 
1842  /**
1843  * Returns true if this value is a Set Iterator.
1844  */
1845  bool IsSetIterator() const;
1846 
1847  /**
1848  * Returns true if this value is a WeakMap.
1849  */
1850  bool IsWeakMap() const;
1851 
1852  /**
1853  * Returns true if this value is a WeakSet.
1854  */
1855  bool IsWeakSet() const;
1856 
1857  /**
1858  * Returns true if this value is an ArrayBuffer.
1859  * This is an experimental feature.
1860  */
1861  bool IsArrayBuffer() const;
1862 
1863  /**
1864  * Returns true if this value is an ArrayBufferView.
1865  * This is an experimental feature.
1866  */
1867  bool IsArrayBufferView() const;
1868 
1869  /**
1870  * Returns true if this value is one of TypedArrays.
1871  * This is an experimental feature.
1872  */
1873  bool IsTypedArray() const;
1874 
1875  /**
1876  * Returns true if this value is an Uint8Array.
1877  * This is an experimental feature.
1878  */
1879  bool IsUint8Array() const;
1880 
1881  /**
1882  * Returns true if this value is an Uint8ClampedArray.
1883  * This is an experimental feature.
1884  */
1885  bool IsUint8ClampedArray() const;
1886 
1887  /**
1888  * Returns true if this value is an Int8Array.
1889  * This is an experimental feature.
1890  */
1891  bool IsInt8Array() const;
1892 
1893  /**
1894  * Returns true if this value is an Uint16Array.
1895  * This is an experimental feature.
1896  */
1897  bool IsUint16Array() const;
1898 
1899  /**
1900  * Returns true if this value is an Int16Array.
1901  * This is an experimental feature.
1902  */
1903  bool IsInt16Array() const;
1904 
1905  /**
1906  * Returns true if this value is an Uint32Array.
1907  * This is an experimental feature.
1908  */
1909  bool IsUint32Array() const;
1910 
1911  /**
1912  * Returns true if this value is an Int32Array.
1913  * This is an experimental feature.
1914  */
1915  bool IsInt32Array() const;
1916 
1917  /**
1918  * Returns true if this value is a Float32Array.
1919  * This is an experimental feature.
1920  */
1921  bool IsFloat32Array() const;
1922 
1923  /**
1924  * Returns true if this value is a Float64Array.
1925  * This is an experimental feature.
1926  */
1927  bool IsFloat64Array() const;
1928 
1929  /**
1930  * Returns true if this value is a SIMD Float32x4.
1931  * This is an experimental feature.
1932  */
1933  bool IsFloat32x4() const;
1934 
1935  /**
1936  * Returns true if this value is a DataView.
1937  * This is an experimental feature.
1938  */
1939  bool IsDataView() const;
1940 
1941  /**
1942  * Returns true if this value is a SharedArrayBuffer.
1943  * This is an experimental feature.
1944  */
1945  bool IsSharedArrayBuffer() const;
1946 
1947 
1949  Local<Context> context) const;
1951  Local<Context> context) const;
1953  Local<Context> context) const;
1955  Local<Context> context) const;
1957  Local<Context> context) const;
1959  Local<Context> context) const;
1961  Local<Context> context) const;
1963 
1964  V8_DEPRECATE_SOON("Use maybe version",
1965  Local<Boolean> ToBoolean(Isolate* isolate) const);
1966  V8_DEPRECATE_SOON("Use maybe version",
1967  Local<Number> ToNumber(Isolate* isolate) const);
1968  V8_DEPRECATE_SOON("Use maybe version",
1969  Local<String> ToString(Isolate* isolate) const);
1970  V8_DEPRECATE_SOON("Use maybe version",
1971  Local<String> ToDetailString(Isolate* isolate) const);
1972  V8_DEPRECATE_SOON("Use maybe version",
1973  Local<Object> ToObject(Isolate* isolate) const);
1974  V8_DEPRECATE_SOON("Use maybe version",
1975  Local<Integer> ToInteger(Isolate* isolate) const);
1976  V8_DEPRECATE_SOON("Use maybe version",
1977  Local<Uint32> ToUint32(Isolate* isolate) const);
1978  V8_DEPRECATE_SOON("Use maybe version",
1979  Local<Int32> ToInt32(Isolate* isolate) const);
1980 
1981  inline V8_DEPRECATE_SOON("Use maybe version",
1982  Local<Boolean> ToBoolean() const);
1983  inline V8_DEPRECATE_SOON("Use maybe version", Local<Number> ToNumber() const);
1984  inline V8_DEPRECATE_SOON("Use maybe version", Local<String> ToString() const);
1985  inline V8_DEPRECATE_SOON("Use maybe version",
1986  Local<String> ToDetailString() const);
1987  inline V8_DEPRECATE_SOON("Use maybe version", Local<Object> ToObject() const);
1988  inline V8_DEPRECATE_SOON("Use maybe version",
1989  Local<Integer> ToInteger() const);
1990  inline V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToUint32() const);
1991  inline V8_DEPRECATE_SOON("Use maybe version", Local<Int32> ToInt32() const);
1992 
1993  /**
1994  * Attempts to convert a string to an array index.
1995  * Returns an empty handle if the conversion fails.
1996  */
1997  V8_DEPRECATE_SOON("Use maybe version", Local<Uint32> ToArrayIndex() const);
1999  Local<Context> context) const;
2000 
2004  Local<Context> context) const;
2006  Local<Context> context) const;
2008 
2009  V8_DEPRECATE_SOON("Use maybe version", bool BooleanValue() const);
2010  V8_DEPRECATE_SOON("Use maybe version", double NumberValue() const);
2011  V8_DEPRECATE_SOON("Use maybe version", int64_t IntegerValue() const);
2012  V8_DEPRECATE_SOON("Use maybe version", uint32_t Uint32Value() const);
2013  V8_DEPRECATE_SOON("Use maybe version", int32_t Int32Value() const);
2014 
2015  /** JS == */
2016  V8_DEPRECATE_SOON("Use maybe version", bool Equals(Local<Value> that) const);
2018  Local<Value> that) const;
2019  bool StrictEquals(Local<Value> that) const;
2020  bool SameValue(Local<Value> that) const;
2021 
2022  template <class T> V8_INLINE static Value* Cast(T* value);
2023 
2024  private:
2025  V8_INLINE bool QuickIsUndefined() const;
2026  V8_INLINE bool QuickIsNull() const;
2027  V8_INLINE bool QuickIsString() const;
2028  bool FullIsUndefined() const;
2029  bool FullIsNull() const;
2030  bool FullIsString() const;
2031 };
2032 
2033 
2034 /**
2035  * The superclass of primitive values. See ECMA-262 4.3.2.
2036  */
2037 class V8_EXPORT Primitive : public Value { };
2038 
2039 
2040 /**
2041  * A primitive boolean value (ECMA-262, 4.3.14). Either the true
2042  * or false value.
2043  */
2044 class V8_EXPORT Boolean : public Primitive {
2045  public:
2046  bool Value() const;
2047  V8_INLINE static Boolean* Cast(v8::Value* obj);
2048  V8_INLINE static Local<Boolean> New(Isolate* isolate, bool value);
2049 
2050  private:
2051  static void CheckCast(v8::Value* obj);
2052 };
2053 
2054 
2055 /**
2056  * A superclass for symbols and strings.
2057  */
2058 class V8_EXPORT Name : public Primitive {
2059  public:
2060  /**
2061  * Returns the identity hash for this object. The current implementation
2062  * uses an inline property on the object to store the identity hash.
2063  *
2064  * The return value will never be 0. Also, it is not guaranteed to be
2065  * unique.
2066  */
2068 
2069  V8_INLINE static Name* Cast(v8::Value* obj);
2070  private:
2071  static void CheckCast(v8::Value* obj);
2072 };
2073 
2074 
2076 
2077 
2078 /**
2079  * A JavaScript string value (ECMA-262, 4.3.17).
2080  */
2081 class V8_EXPORT String : public Name {
2082  public:
2083  static const int kMaxLength = (1 << 28) - 16;
2084 
2085  enum Encoding {
2088  ONE_BYTE_ENCODING = 0x4
2089  };
2090  /**
2091  * Returns the number of characters in this string.
2092  */
2093  int Length() const;
2094 
2095  /**
2096  * Returns the number of bytes in the UTF-8 encoded
2097  * representation of this string.
2098  */
2099  int Utf8Length() const;
2100 
2101  /**
2102  * Returns whether this string is known to contain only one byte data.
2103  * Does not read the string.
2104  * False negatives are possible.
2105  */
2106  bool IsOneByte() const;
2107 
2108  /**
2109  * Returns whether this string contain only one byte data.
2110  * Will read the entire string in some cases.
2111  */
2112  bool ContainsOnlyOneByte() const;
2113 
2114  /**
2115  * Write the contents of the string to an external buffer.
2116  * If no arguments are given, expects the buffer to be large
2117  * enough to hold the entire string and NULL terminator. Copies
2118  * the contents of the string and the NULL terminator into the
2119  * buffer.
2120  *
2121  * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
2122  * before the end of the buffer.
2123  *
2124  * Copies up to length characters into the output buffer.
2125  * Only null-terminates if there is enough space in the buffer.
2126  *
2127  * \param buffer The buffer into which the string will be copied.
2128  * \param start The starting position within the string at which
2129  * copying begins.
2130  * \param length The number of characters to copy from the string. For
2131  * WriteUtf8 the number of bytes in the buffer.
2132  * \param nchars_ref The number of characters written, can be NULL.
2133  * \param options Various options that might affect performance of this or
2134  * subsequent operations.
2135  * \return The number of characters copied to the buffer excluding the null
2136  * terminator. For WriteUtf8: The number of bytes copied to the buffer
2137  * including the null terminator (if written).
2138  */
2144  // Used by WriteUtf8 to replace orphan surrogate code units with the
2145  // unicode replacement character. Needs to be set to guarantee valid UTF-8
2146  // output.
2148  };
2149 
2150  // 16-bit character codes.
2151  int Write(uint16_t* buffer,
2152  int start = 0,
2153  int length = -1,
2154  int options = NO_OPTIONS) const;
2155  // One byte characters.
2156  int WriteOneByte(uint8_t* buffer,
2157  int start = 0,
2158  int length = -1,
2159  int options = NO_OPTIONS) const;
2160  // UTF-8 encoded characters.
2161  int WriteUtf8(char* buffer,
2162  int length = -1,
2163  int* nchars_ref = NULL,
2164  int options = NO_OPTIONS) const;
2165 
2166  /**
2167  * A zero length string.
2168  */
2169  V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
2170 
2171  /**
2172  * Returns true if the string is external
2173  */
2174  bool IsExternal() const;
2175 
2176  /**
2177  * Returns true if the string is both external and one-byte.
2178  */
2179  bool IsExternalOneByte() const;
2180 
2182  public:
2184 
2185  protected:
2187 
2188  /**
2189  * Internally V8 will call this Dispose method when the external string
2190  * resource is no longer needed. The default implementation will use the
2191  * delete operator. This method can be overridden in subclasses to
2192  * control how allocated external string resources are disposed.
2193  */
2194  virtual void Dispose() { delete this; }
2195 
2196  private:
2197  // Disallow copying and assigning.
2198  ExternalStringResourceBase(const ExternalStringResourceBase&);
2199  void operator=(const ExternalStringResourceBase&);
2200 
2201  friend class v8::internal::Heap;
2202  };
2203 
2204  /**
2205  * An ExternalStringResource is a wrapper around a two-byte string
2206  * buffer that resides outside V8's heap. Implement an
2207  * ExternalStringResource to manage the life cycle of the underlying
2208  * buffer. Note that the string data must be immutable.
2209  */
2211  : public ExternalStringResourceBase {
2212  public:
2213  /**
2214  * Override the destructor to manage the life cycle of the underlying
2215  * buffer.
2216  */
2218 
2219  /**
2220  * The string data from the underlying buffer.
2221  */
2222  virtual const uint16_t* data() const = 0;
2223 
2224  /**
2225  * The length of the string. That is, the number of two-byte characters.
2226  */
2227  virtual size_t length() const = 0;
2228 
2229  protected:
2231  };
2232 
2233  /**
2234  * An ExternalOneByteStringResource is a wrapper around an one-byte
2235  * string buffer that resides outside V8's heap. Implement an
2236  * ExternalOneByteStringResource to manage the life cycle of the
2237  * underlying buffer. Note that the string data must be immutable
2238  * and that the data must be Latin-1 and not UTF-8, which would require
2239  * special treatment internally in the engine and do not allow efficient
2240  * indexing. Use String::New or convert to 16 bit data for non-Latin1.
2241  */
2242 
2244  : public ExternalStringResourceBase {
2245  public:
2246  /**
2247  * Override the destructor to manage the life cycle of the underlying
2248  * buffer.
2249  */
2251  /** The string data from the underlying buffer.*/
2252  virtual const char* data() const = 0;
2253  /** The number of Latin-1 characters in the string.*/
2254  virtual size_t length() const = 0;
2255  protected:
2257  };
2258 
2259  /**
2260  * If the string is an external string, return the ExternalStringResourceBase
2261  * regardless of the encoding, otherwise return NULL. The encoding of the
2262  * string is returned in encoding_out.
2263  */
2265  Encoding* encoding_out) const;
2266 
2267  /**
2268  * Get the ExternalStringResource for an external string. Returns
2269  * NULL if IsExternal() doesn't return true.
2270  */
2272 
2273  /**
2274  * Get the ExternalOneByteStringResource for an external one-byte string.
2275  * Returns NULL if IsExternalOneByte() doesn't return true.
2276  */
2278 
2279  V8_INLINE static String* Cast(v8::Value* obj);
2280 
2281  // TODO(dcarney): remove with deprecation of New functions.
2285  };
2286 
2287  /** Allocates a new string from UTF-8 data.*/
2289  "Use maybe version",
2290  Local<String> NewFromUtf8(Isolate* isolate, const char* data,
2292  int length = -1));
2293 
2294  /** Allocates a new string from UTF-8 data. Only returns an empty value when
2295  * length > kMaxLength. **/
2297  Isolate* isolate, const char* data, v8::NewStringType type,
2298  int length = -1);
2299 
2300  /** Allocates a new string from Latin-1 data.*/
2302  "Use maybe version",
2303  Local<String> NewFromOneByte(Isolate* isolate, const uint8_t* data,
2305  int length = -1));
2306 
2307  /** Allocates a new string from Latin-1 data. Only returns an empty value
2308  * when length > kMaxLength. **/
2310  Isolate* isolate, const uint8_t* data, v8::NewStringType type,
2311  int length = -1);
2312 
2313  /** Allocates a new string from UTF-16 data.*/
2315  "Use maybe version",
2316  Local<String> NewFromTwoByte(Isolate* isolate, const uint16_t* data,
2318  int length = -1));
2319 
2320  /** Allocates a new string from UTF-16 data. Only returns an empty value when
2321  * length > kMaxLength. **/
2323  Isolate* isolate, const uint16_t* data, v8::NewStringType type,
2324  int length = -1);
2325 
2326  /**
2327  * Creates a new string by concatenating the left and the right strings
2328  * passed in as parameters.
2329  */
2330  static Local<String> Concat(Local<String> left, Local<String> right);
2331 
2332  /**
2333  * Creates a new external string using the data defined in the given
2334  * resource. When the external string is no longer live on V8's heap the
2335  * resource will be disposed by calling its Dispose method. The caller of
2336  * this function should not otherwise delete or modify the resource. Neither
2337  * should the underlying buffer be deallocated or modified except through the
2338  * destructor of the external string resource.
2339  */
2341  "Use maybe version",
2342  Local<String> NewExternal(Isolate* isolate,
2343  ExternalStringResource* resource));
2345  Isolate* isolate, ExternalStringResource* resource);
2346 
2347  /**
2348  * Associate an external string resource with this string by transforming it
2349  * in place so that existing references to this string in the JavaScript heap
2350  * will use the external string resource. The external string resource's
2351  * character contents need to be equivalent to this string.
2352  * Returns true if the string has been changed to be an external string.
2353  * The string is not modified if the operation fails. See NewExternal for
2354  * information on the lifetime of the resource.
2355  */
2357 
2358  /**
2359  * Creates a new external string using the one-byte data defined in the given
2360  * resource. When the external string is no longer live on V8's heap the
2361  * resource will be disposed by calling its Dispose method. The caller of
2362  * this function should not otherwise delete or modify the resource. Neither
2363  * should the underlying buffer be deallocated or modified except through the
2364  * destructor of the external string resource.
2365  */
2367  "Use maybe version",
2368  Local<String> NewExternal(Isolate* isolate,
2369  ExternalOneByteStringResource* resource));
2371  Isolate* isolate, ExternalOneByteStringResource* resource);
2372 
2373  /**
2374  * Associate an external string resource with this string by transforming it
2375  * in place so that existing references to this string in the JavaScript heap
2376  * will use the external string resource. The external string resource's
2377  * character contents need to be equivalent to this string.
2378  * Returns true if the string has been changed to be an external string.
2379  * The string is not modified if the operation fails. See NewExternal for
2380  * information on the lifetime of the resource.
2381  */
2383 
2384  /**
2385  * Returns true if this string can be made external.
2386  */
2388 
2389  /**
2390  * Converts an object to a UTF-8-encoded character array. Useful if
2391  * you want to print the object. If conversion to a string fails
2392  * (e.g. due to an exception in the toString() method of the object)
2393  * then the length() method returns 0 and the * operator returns
2394  * NULL.
2395  */
2397  public:
2398  explicit Utf8Value(Local<v8::Value> obj);
2400  char* operator*() { return str_; }
2401  const char* operator*() const { return str_; }
2402  int length() const { return length_; }
2403  private:
2404  char* str_;
2405  int length_;
2406 
2407  // Disallow copying and assigning.
2408  Utf8Value(const Utf8Value&);
2409  void operator=(const Utf8Value&);
2410  };
2411 
2412  /**
2413  * Converts an object to a two-byte string.
2414  * If conversion to a string fails (eg. due to an exception in the toString()
2415  * method of the object) then the length() method returns 0 and the * operator
2416  * returns NULL.
2417  */
2419  public:
2420  explicit Value(Local<v8::Value> obj);
2421  ~Value();
2422  uint16_t* operator*() { return str_; }
2423  const uint16_t* operator*() const { return str_; }
2424  int length() const { return length_; }
2425  private:
2426  uint16_t* str_;
2427  int length_;
2428 
2429  // Disallow copying and assigning.
2430  Value(const Value&);
2431  void operator=(const Value&);
2432  };
2433 
2434  private:
2435  void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
2436  Encoding encoding) const;
2437  void VerifyExternalStringResource(ExternalStringResource* val) const;
2438  static void CheckCast(v8::Value* obj);
2439 };
2440 
2441 
2442 /**
2443  * A JavaScript symbol (ECMA-262 edition 6)
2444  *
2445  * This is an experimental feature. Use at your own risk.
2446  */
2447 class V8_EXPORT Symbol : public Name {
2448  public:
2449  // Returns the print name string of the symbol, or undefined if none.
2450  Local<Value> Name() const;
2451 
2452  // Create a symbol. If name is not empty, it will be used as the description.
2453  static Local<Symbol> New(
2454  Isolate *isolate, Local<String> name = Local<String>());
2455 
2456  // Access global symbol registry.
2457  // Note that symbols created this way are never collected, so
2458  // they should only be used for statically fixed properties.
2459  // Also, there is only one global name space for the names used as keys.
2460  // To minimize the potential for clashes, use qualified names as keys.
2461  static Local<Symbol> For(Isolate *isolate, Local<String> name);
2462 
2463  // Retrieve a global symbol. Similar to |For|, but using a separate
2464  // registry that is not accessible by (and cannot clash with) JavaScript code.
2465  static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
2466 
2467  // Well-known symbols
2468  static Local<Symbol> GetIterator(Isolate* isolate);
2469  static Local<Symbol> GetUnscopables(Isolate* isolate);
2470  static Local<Symbol> GetToStringTag(Isolate* isolate);
2471 
2472  V8_INLINE static Symbol* Cast(v8::Value* obj);
2473 
2474  private:
2475  Symbol();
2476  static void CheckCast(v8::Value* obj);
2477 };
2478 
2479 
2480 /**
2481  * A JavaScript number value (ECMA-262, 4.3.20)
2482  */
2483 class V8_EXPORT Number : public Primitive {
2484  public:
2485  double Value() const;
2486  static Local<Number> New(Isolate* isolate, double value);
2487  V8_INLINE static Number* Cast(v8::Value* obj);
2488  private:
2489  Number();
2490  static void CheckCast(v8::Value* obj);
2491 };
2492 
2493 
2494 /**
2495  * A JavaScript value representing a signed integer.
2496  */
2497 class V8_EXPORT Integer : public Number {
2498  public:
2499  static Local<Integer> New(Isolate* isolate, int32_t value);
2500  static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
2501  int64_t Value() const;
2502  V8_INLINE static Integer* Cast(v8::Value* obj);
2503  private:
2504  Integer();
2505  static void CheckCast(v8::Value* obj);
2506 };
2507 
2508 
2509 /**
2510  * A JavaScript value representing a 32-bit signed integer.
2511  */
2512 class V8_EXPORT Int32 : public Integer {
2513  public:
2514  int32_t Value() const;
2515  V8_INLINE static Int32* Cast(v8::Value* obj);
2516 
2517  private:
2518  Int32();
2519  static void CheckCast(v8::Value* obj);
2520 };
2521 
2522 
2523 /**
2524  * A JavaScript value representing a 32-bit unsigned integer.
2525  */
2526 class V8_EXPORT Uint32 : public Integer {
2527  public:
2528  uint32_t Value() const;
2529  V8_INLINE static Uint32* Cast(v8::Value* obj);
2530 
2531  private:
2532  Uint32();
2533  static void CheckCast(v8::Value* obj);
2534 };
2535 
2536 
2538  None = 0,
2539  ReadOnly = 1 << 0,
2540  DontEnum = 1 << 1,
2541  DontDelete = 1 << 2
2542 };
2543 
2544 /**
2545  * Accessor[Getter|Setter] are used as callback functions when
2546  * setting|getting a particular property. See Object and ObjectTemplate's
2547  * method SetAccessor.
2548  */
2549 typedef void (*AccessorGetterCallback)(
2550  Local<String> property,
2551  const PropertyCallbackInfo<Value>& info);
2553  Local<Name> property,
2554  const PropertyCallbackInfo<Value>& info);
2555 
2556 
2557 typedef void (*AccessorSetterCallback)(
2558  Local<String> property,
2559  Local<Value> value,
2560  const PropertyCallbackInfo<void>& info);
2562  Local<Name> property,
2563  Local<Value> value,
2564  const PropertyCallbackInfo<void>& info);
2565 
2566 
2567 /**
2568  * Access control specifications.
2569  *
2570  * Some accessors should be accessible across contexts. These
2571  * accessors have an explicit access control parameter which specifies
2572  * the kind of cross-context access that should be allowed.
2573  *
2574  * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
2575  */
2577  DEFAULT = 0,
2579  ALL_CAN_WRITE = 1 << 1,
2580  PROHIBITS_OVERWRITING = 1 << 2
2581 };
2582 
2583 
2584 /**
2585  * A JavaScript object (ECMA-262, 4.3.3)
2586  */
2587 class V8_EXPORT Object : public Value {
2588  public:
2589  V8_DEPRECATE_SOON("Use maybe version",
2590  bool Set(Local<Value> key, Local<Value> value));
2592  Local<Value> key, Local<Value> value);
2593 
2594  V8_DEPRECATE_SOON("Use maybe version",
2595  bool Set(uint32_t index, Local<Value> value));
2596  V8_WARN_UNUSED_RESULT Maybe<bool> Set(Local<Context> context, uint32_t index,
2597  Local<Value> value);
2598 
2599  // Implements CreateDataProperty (ECMA-262, 7.3.4).
2600  //
2601  // Defines a configurable, writable, enumerable property with the given value
2602  // on the object unless the property already exists and is not configurable
2603  // or the object is not extensible.
2604  //
2605  // Returns true on success.
2607  Local<Name> key,
2608  Local<Value> value);
2610  uint32_t index,
2611  Local<Value> value);
2612 
2613  // Implements DefineOwnProperty.
2614  //
2615  // In general, CreateDataProperty will be faster, however, does not allow
2616  // for specifying attributes.
2617  //
2618  // Returns true on success.
2620  Local<Context> context, Local<Name> key, Local<Value> value,
2621  PropertyAttribute attributes = None);
2622 
2623  // Sets an own property on this object bypassing interceptors and
2624  // overriding accessors or read-only properties.
2625  //
2626  // Note that if the object has an interceptor the property will be set
2627  // locally, but since the interceptor takes precedence the local property
2628  // will only be returned if the interceptor doesn't return a value.
2629  //
2630  // Note also that this only works for named properties.
2631  V8_DEPRECATE_SOON("Use CreateDataProperty",
2632  bool ForceSet(Local<Value> key, Local<Value> value,
2633  PropertyAttribute attribs = None));
2634  V8_DEPRECATE_SOON("Use CreateDataProperty",
2635  Maybe<bool> ForceSet(Local<Context> context,
2636  Local<Value> key, Local<Value> value,
2637  PropertyAttribute attribs = None));
2638 
2639  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(Local<Value> key));
2641  Local<Value> key);
2642 
2643  V8_DEPRECATE_SOON("Use maybe version", Local<Value> Get(uint32_t index));
2645  uint32_t index);
2646 
2647  /**
2648  * Gets the property attributes of a property which can be None or
2649  * any combination of ReadOnly, DontEnum and DontDelete. Returns
2650  * None when the property doesn't exist.
2651  */
2652  V8_DEPRECATE_SOON("Use maybe version",
2653  PropertyAttribute GetPropertyAttributes(Local<Value> key));
2655  Local<Context> context, Local<Value> key);
2656 
2657  /**
2658  * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
2659  */
2660  V8_DEPRECATE_SOON("Use maybe version",
2661  Local<Value> GetOwnPropertyDescriptor(Local<String> key));
2663  Local<Context> context, Local<String> key);
2664 
2665  V8_DEPRECATE_SOON("Use maybe version", bool Has(Local<Value> key));
2667  Local<Value> key);
2668 
2669  V8_DEPRECATE_SOON("Use maybe version", bool Delete(Local<Value> key));
2670  // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2671  Maybe<bool> Delete(Local<Context> context, Local<Value> key);
2672 
2673  V8_DEPRECATE_SOON("Use maybe version", bool Has(uint32_t index));
2674  V8_WARN_UNUSED_RESULT Maybe<bool> Has(Local<Context> context, uint32_t index);
2675 
2676  V8_DEPRECATE_SOON("Use maybe version", bool Delete(uint32_t index));
2677  // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2678  Maybe<bool> Delete(Local<Context> context, uint32_t index);
2679 
2680  V8_DEPRECATE_SOON("Use maybe version",
2681  bool SetAccessor(Local<String> name,
2682  AccessorGetterCallback getter,
2683  AccessorSetterCallback setter = 0,
2684  Local<Value> data = Local<Value>(),
2685  AccessControl settings = DEFAULT,
2686  PropertyAttribute attribute = None));
2687  V8_DEPRECATE_SOON("Use maybe version",
2688  bool SetAccessor(Local<Name> name,
2690  AccessorNameSetterCallback setter = 0,
2691  Local<Value> data = Local<Value>(),
2692  AccessControl settings = DEFAULT,
2693  PropertyAttribute attribute = None));
2694  // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
2695  Maybe<bool> SetAccessor(Local<Context> context, Local<Name> name,
2697  AccessorNameSetterCallback setter = 0,
2699  AccessControl settings = DEFAULT,
2700  PropertyAttribute attribute = None);
2701 
2703  Local<Function> setter = Local<Function>(),
2704  PropertyAttribute attribute = None,
2705  AccessControl settings = DEFAULT);
2706 
2707  /**
2708  * Returns an array containing the names of the enumerable properties
2709  * of this object, including properties from prototype objects. The
2710  * array returned by this method contains the same values as would
2711  * be enumerated by a for-in statement over this object.
2712  */
2713  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetPropertyNames());
2715  Local<Context> context);
2716 
2717  /**
2718  * This function has the same functionality as GetPropertyNames but
2719  * the returned array doesn't contain the names of properties from
2720  * prototype objects.
2721  */
2722  V8_DEPRECATE_SOON("Use maybe version", Local<Array> GetOwnPropertyNames());
2724  Local<Context> context);
2725 
2726  /**
2727  * Get the prototype object. This does not skip objects marked to
2728  * be skipped by __proto__ and it does not consult the security
2729  * handler.
2730  */
2732 
2733  /**
2734  * Set the prototype object. This does not skip objects marked to
2735  * be skipped by __proto__ and it does not consult the security
2736  * handler.
2737  */
2738  V8_DEPRECATE_SOON("Use maybe version",
2739  bool SetPrototype(Local<Value> prototype));
2741  Local<Value> prototype);
2742 
2743  /**
2744  * Finds an instance of the given function template in the prototype
2745  * chain.
2746  */
2748 
2749  /**
2750  * Call builtin Object.prototype.toString on this object.
2751  * This is different from Value::ToString() that may call
2752  * user-defined toString function. This one does not.
2753  */
2754  V8_DEPRECATE_SOON("Use maybe version", Local<String> ObjectProtoToString());
2756  Local<Context> context);
2757 
2758  /**
2759  * Returns the name of the function invoked as a constructor for this object.
2760  */
2762 
2763  /** Gets the number of internal fields for this Object. */
2765 
2766  /** Same as above, but works for Persistents */
2768  const PersistentBase<Object>& object) {
2769  return object.val_->InternalFieldCount();
2770  }
2771 
2772  /** Gets the value from an internal field. */
2773  V8_INLINE Local<Value> GetInternalField(int index);
2774 
2775  /** Sets the value in an internal field. */
2776  void SetInternalField(int index, Local<Value> value);
2777 
2778  /**
2779  * Gets a 2-byte-aligned native pointer from an internal field. This field
2780  * must have been set by SetAlignedPointerInInternalField, everything else
2781  * leads to undefined behavior.
2782  */
2784 
2785  /** Same as above, but works for Persistents */
2787  const PersistentBase<Object>& object, int index) {
2788  return object.val_->GetAlignedPointerFromInternalField(index);
2789  }
2790 
2791  /**
2792  * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
2793  * a field, GetAlignedPointerFromInternalField must be used, everything else
2794  * leads to undefined behavior.
2795  */
2796  void SetAlignedPointerInInternalField(int index, void* value);
2797 
2798  // Testers for local properties.
2799  V8_DEPRECATE_SOON("Use maybe version",
2800  bool HasOwnProperty(Local<String> key));
2802  Local<Name> key);
2803  V8_DEPRECATE_SOON("Use maybe version",
2804  bool HasRealNamedProperty(Local<String> key));
2806  Local<Name> key);
2807  V8_DEPRECATE_SOON("Use maybe version",
2808  bool HasRealIndexedProperty(uint32_t index));
2810  Local<Context> context, uint32_t index);
2811  V8_DEPRECATE_SOON("Use maybe version",
2812  bool HasRealNamedCallbackProperty(Local<String> key));
2814  Local<Context> context, Local<Name> key);
2815 
2816  /**
2817  * If result.IsEmpty() no real property was located in the prototype chain.
2818  * This means interceptors in the prototype chain are not called.
2819  */
2821  "Use maybe version",
2822  Local<Value> GetRealNamedPropertyInPrototypeChain(Local<String> key));
2824  Local<Context> context, Local<Name> key);
2825 
2826  /**
2827  * Gets the property attributes of a real property in the prototype chain,
2828  * which can be None or any combination of ReadOnly, DontEnum and DontDelete.
2829  * Interceptors in the prototype chain are not called.
2830  */
2832  "Use maybe version",
2833  Maybe<PropertyAttribute> GetRealNamedPropertyAttributesInPrototypeChain(
2834  Local<String> key));
2837  Local<Name> key);
2838 
2839  /**
2840  * If result.IsEmpty() no real property was located on the object or
2841  * in the prototype chain.
2842  * This means interceptors in the prototype chain are not called.
2843  */
2844  V8_DEPRECATE_SOON("Use maybe version",
2845  Local<Value> GetRealNamedProperty(Local<String> key));
2847  Local<Context> context, Local<Name> key);
2848 
2849  /**
2850  * Gets the property attributes of a real property which can be
2851  * None or any combination of ReadOnly, DontEnum and DontDelete.
2852  * Interceptors in the prototype chain are not called.
2853  */
2854  V8_DEPRECATE_SOON("Use maybe version",
2855  Maybe<PropertyAttribute> GetRealNamedPropertyAttributes(
2856  Local<String> key));
2858  Local<Context> context, Local<Name> key);
2859 
2860  /** Tests for a named lookup interceptor.*/
2862 
2863  /** Tests for an index lookup interceptor.*/
2865 
2866  /**
2867  * Returns the identity hash for this object. The current implementation
2868  * uses a hidden property on the object to store the identity hash.
2869  *
2870  * The return value will never be 0. Also, it is not guaranteed to be
2871  * unique.
2872  */
2874 
2875  /**
2876  * Access hidden properties on JavaScript objects. These properties are
2877  * hidden from the executing JavaScript and only accessible through the V8
2878  * C++ API. Hidden properties introduced by V8 internally (for example the
2879  * identity hash) are prefixed with "v8::".
2880  */
2881  // TODO(dcarney): convert these to take a isolate and optionally bailout?
2882  bool SetHiddenValue(Local<String> key, Local<Value> value);
2885 
2886  /**
2887  * Clone this object with a fast but shallow copy. Values will point
2888  * to the same values as the original object.
2889  */
2890  // TODO(dcarney): take an isolate and optionally bail out?
2892 
2893  /**
2894  * Returns the context in which the object was created.
2895  */
2897 
2898  /**
2899  * Checks whether a callback is set by the
2900  * ObjectTemplate::SetCallAsFunctionHandler method.
2901  * When an Object is callable this method returns true.
2902  */
2903  bool IsCallable();
2904 
2905  /**
2906  * Call an Object as a function if a callback is set by the
2907  * ObjectTemplate::SetCallAsFunctionHandler method.
2908  */
2909  V8_DEPRECATE_SOON("Use maybe version",
2910  Local<Value> CallAsFunction(Local<Value> recv, int argc,
2911  Local<Value> argv[]));
2913  Local<Value> recv,
2914  int argc,
2915  Local<Value> argv[]);
2916 
2917  /**
2918  * Call an Object as a constructor if a callback is set by the
2919  * ObjectTemplate::SetCallAsFunctionHandler method.
2920  * Note: This method behaves like the Function::NewInstance method.
2921  */
2922  V8_DEPRECATE_SOON("Use maybe version",
2923  Local<Value> CallAsConstructor(int argc,
2924  Local<Value> argv[]));
2926  Local<Context> context, int argc, Local<Value> argv[]);
2927 
2928  /**
2929  * Return the isolate to which the Object belongs to.
2930  */
2931  V8_DEPRECATE_SOON("Keep track of isolate correctly", Isolate* GetIsolate());
2932 
2933  static Local<Object> New(Isolate* isolate);
2934 
2935  V8_INLINE static Object* Cast(Value* obj);
2936 
2937  private:
2938  Object();
2939  static void CheckCast(Value* obj);
2940  Local<Value> SlowGetInternalField(int index);
2941  void* SlowGetAlignedPointerFromInternalField(int index);
2942 };
2943 
2944 
2945 /**
2946  * An instance of the built-in array constructor (ECMA-262, 15.4.2).
2947  */
2948 class V8_EXPORT Array : public Object {
2949  public:
2950  uint32_t Length() const;
2951 
2952  /**
2953  * Clones an element at index |index|. Returns an empty
2954  * handle if cloning fails (for any reason).
2955  */
2956  V8_DEPRECATE_SOON("Use maybe version",
2957  Local<Object> CloneElementAt(uint32_t index));
2959  Local<Context> context, uint32_t index);
2960 
2961  /**
2962  * Creates a JavaScript array with the given length. If the length
2963  * is negative the returned array will have length 0.
2964  */
2965  static Local<Array> New(Isolate* isolate, int length = 0);
2966 
2967  V8_INLINE static Array* Cast(Value* obj);
2968  private:
2969  Array();
2970  static void CheckCast(Value* obj);
2971 };
2972 
2973 
2974 /**
2975  * An instance of the built-in Map constructor (ECMA-262, 6th Edition, 23.1.1).
2976  */
2977 class V8_EXPORT Map : public Object {
2978  public:
2979  size_t Size() const;
2980  void Clear();
2982  Local<Value> key);
2984  Local<Value> key,
2985  Local<Value> value);
2987  Local<Value> key);
2989  Local<Value> key);
2990 
2991  /**
2992  * Returns an array of length Size() * 2, where index N is the Nth key and
2993  * index N + 1 is the Nth value.
2994  */
2995  Local<Array> AsArray() const;
2996 
2997  /**
2998  * Creates a new empty Map.
2999  */
3000  static Local<Map> New(Isolate* isolate);
3001 
3002  /**
3003  * Creates a new Map containing the elements of array, which must be formatted
3004  * in the same manner as the array returned from AsArray().
3005  * Guaranteed to be side-effect free if the array contains no holes.
3006  */
3008  Local<Array> array);
3009 
3010  V8_INLINE static Map* Cast(Value* obj);
3011 
3012  private:
3013  Map();
3014  static void CheckCast(Value* obj);
3015 };
3016 
3017 
3018 /**
3019  * An instance of the built-in Set constructor (ECMA-262, 6th Edition, 23.2.1).
3020  */
3021 class V8_EXPORT Set : public Object {
3022  public:
3023  size_t Size() const;
3024  void Clear();
3026  Local<Value> key);
3028  Local<Value> key);
3030  Local<Value> key);
3031 
3032  /**
3033  * Returns an array of the keys in this Set.
3034  */
3035  Local<Array> AsArray() const;
3036 
3037  /**
3038  * Creates a new empty Set.
3039  */
3040  static Local<Set> New(Isolate* isolate);
3041 
3042  /**
3043  * Creates a new Set containing the items in array.
3044  * Guaranteed to be side-effect free if the array contains no holes.
3045  */
3047  Local<Array> array);
3048 
3049  V8_INLINE static Set* Cast(Value* obj);
3050 
3051  private:
3052  Set();
3053  static void CheckCast(Value* obj);
3054 };
3055 
3056 
3057 template<typename T>
3059  public:
3060  template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
3061  : value_(that.value_) {
3062  TYPE_CHECK(T, S);
3063  }
3064  // Local setters
3065  template <typename S>
3066  V8_INLINE V8_DEPRECATE_SOON("Use Global<> instead",
3067  void Set(const Persistent<S>& handle));
3068  template <typename S>
3069  V8_INLINE void Set(const Global<S>& handle);
3070  template <typename S>
3071  V8_INLINE void Set(const Local<S> handle);
3072  // Fast primitive setters
3073  V8_INLINE void Set(bool value);
3074  V8_INLINE void Set(double i);
3075  V8_INLINE void Set(int32_t i);
3076  V8_INLINE void Set(uint32_t i);
3077  // Fast JS primitive setters
3078  V8_INLINE void SetNull();
3079  V8_INLINE void SetUndefined();
3080  V8_INLINE void SetEmptyString();
3081  // Convenience getter for Isolate
3083 
3084  // Pointer setter: Uncompilable to prevent inadvertent misuse.
3085  template <typename S>
3086  V8_INLINE void Set(S* whatever);
3087 
3088  private:
3089  template<class F> friend class ReturnValue;
3090  template<class F> friend class FunctionCallbackInfo;
3091  template<class F> friend class PropertyCallbackInfo;
3092  template <class F, class G, class H>
3094  V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
3095  V8_INLINE internal::Object* GetDefaultValue();
3096  V8_INLINE explicit ReturnValue(internal::Object** slot);
3097  internal::Object** value_;
3098 };
3099 
3100 
3101 /**
3102  * The argument information given to function call callbacks. This
3103  * class provides access to information about the context of the call,
3104  * including the receiver, the number and values of arguments, and
3105  * the holder of the function.
3106  */
3107 template<typename T>
3109  public:
3110  V8_INLINE int Length() const;
3111  V8_INLINE Local<Value> operator[](int i) const;
3112  V8_INLINE Local<Function> Callee() const;
3113  V8_INLINE Local<Object> This() const;
3114  V8_INLINE Local<Object> Holder() const;
3115  V8_INLINE bool IsConstructCall() const;
3116  V8_INLINE Local<Value> Data() const;
3117  V8_INLINE Isolate* GetIsolate() const;
3119  // This shouldn't be public, but the arm compiler needs it.
3120  static const int kArgsLength = 7;
3121 
3122  protected:
3123  friend class internal::FunctionCallbackArguments;
3125  static const int kHolderIndex = 0;
3126  static const int kIsolateIndex = 1;
3127  static const int kReturnValueDefaultValueIndex = 2;
3128  static const int kReturnValueIndex = 3;
3129  static const int kDataIndex = 4;
3130  static const int kCalleeIndex = 5;
3131  static const int kContextSaveIndex = 6;
3132 
3133  V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
3134  internal::Object** values,
3135  int length,
3136  bool is_construct_call);
3138  internal::Object** values_;
3139  int length_;
3141 };
3142 
3143 
3144 /**
3145  * The information passed to a property callback about the context
3146  * of the property access.
3147  */
3148 template<typename T>
3150  public:
3156  // This shouldn't be public, but the arm compiler needs it.
3157  static const int kArgsLength = 6;
3158 
3159  protected:
3160  friend class MacroAssembler;
3161  friend class internal::PropertyCallbackArguments;
3163  static const int kHolderIndex = 0;
3164  static const int kIsolateIndex = 1;
3165  static const int kReturnValueDefaultValueIndex = 2;
3166  static const int kReturnValueIndex = 3;
3167  static const int kDataIndex = 4;
3168  static const int kThisIndex = 5;
3169 
3170  V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
3171  internal::Object** args_;
3172 };
3173 
3174 
3175 typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
3176 
3177 
3178 /**
3179  * A JavaScript function object (ECMA-262, 15.3).
3180  */
3181 class V8_EXPORT Function : public Object {
3182  public:
3183  /**
3184  * Create a function in the current execution context
3185  * for a given FunctionCallback.
3186  */
3188  FunctionCallback callback,
3189  Local<Value> data = Local<Value>(),
3190  int length = 0);
3192  "Use maybe version",
3193  Local<Function> New(Isolate* isolate, FunctionCallback callback,
3194  Local<Value> data = Local<Value>(), int length = 0));
3195 
3196  V8_DEPRECATE_SOON("Use maybe version",
3197  Local<Object> NewInstance(int argc, Local<Value> argv[])
3198  const);
3200  Local<Context> context, int argc, Local<Value> argv[]) const;
3201 
3202  V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance() const);
3204  Local<Context> context) const {
3205  return NewInstance(context, 0, nullptr);
3206  }
3207 
3208  V8_DEPRECATE_SOON("Use maybe version",
3209  Local<Value> Call(Local<Value> recv, int argc,
3210  Local<Value> argv[]));
3212  Local<Value> recv, int argc,
3213  Local<Value> argv[]);
3214 
3215  void SetName(Local<String> name);
3216  Local<Value> GetName() const;
3217 
3218  /**
3219  * Name inferred from variable or property assignment of this function.
3220  * Used to facilitate debugging and profiling of JavaScript code written
3221  * in an OO style, where many functions are anonymous but are assigned
3222  * to object properties.
3223  */
3225 
3226  /**
3227  * User-defined name assigned to the "displayName" property of this function.
3228  * Used to facilitate debugging and profiling of JavaScript code.
3229  */
3231 
3232  /**
3233  * Returns zero based line number of function body and
3234  * kLineOffsetNotFound if no information available.
3235  */
3236  int GetScriptLineNumber() const;
3237  /**
3238  * Returns zero based column number of function body and
3239  * kLineOffsetNotFound if no information available.
3240  */
3242 
3243  /**
3244  * Tells whether this function is builtin.
3245  */
3246  bool IsBuiltin() const;
3247 
3248  /**
3249  * Returns scriptId.
3250  */
3251  int ScriptId() const;
3252 
3253  /**
3254  * Returns the original function if this function is bound, else returns
3255  * v8::Undefined.
3256  */
3258 
3260  V8_INLINE static Function* Cast(Value* obj);
3261  static const int kLineOffsetNotFound;
3262 
3263  private:
3264  Function();
3265  static void CheckCast(Value* obj);
3266 };
3267 
3268 
3269 /**
3270  * An instance of the built-in Promise constructor (ES6 draft).
3271  * This API is experimental. Only works with --harmony flag.
3272  */
3273 class V8_EXPORT Promise : public Object {
3274  public:
3275  class V8_EXPORT Resolver : public Object {
3276  public:
3277  /**
3278  * Create a new resolver, along with an associated promise in pending state.
3279  */
3280  static V8_DEPRECATE_SOON("Use maybe version",
3281  Local<Resolver> New(Isolate* isolate));
3283  Local<Context> context);
3284 
3285  /**
3286  * Extract the associated promise.
3287  */
3289 
3290  /**
3291  * Resolve/reject the associated promise with a given value.
3292  * Ignored if the promise is no longer pending.
3293  */
3294  V8_DEPRECATE_SOON("Use maybe version", void Resolve(Local<Value> value));
3295  // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3296  Maybe<bool> Resolve(Local<Context> context, Local<Value> value);
3297 
3298  V8_DEPRECATE_SOON("Use maybe version", void Reject(Local<Value> value));
3299  // TODO(dcarney): mark V8_WARN_UNUSED_RESULT
3300  Maybe<bool> Reject(Local<Context> context, Local<Value> value);
3301 
3302  V8_INLINE static Resolver* Cast(Value* obj);
3303 
3304  private:
3305  Resolver();
3306  static void CheckCast(Value* obj);
3307  };
3308 
3309  /**
3310  * Register a resolution/rejection handler with a promise.
3311  * The handler is given the respective resolution/rejection value as
3312  * an argument. If the promise is already resolved/rejected, the handler is
3313  * invoked at the end of turn.
3314  */
3315  V8_DEPRECATE_SOON("Use maybe version",
3316  Local<Promise> Chain(Local<Function> handler));
3318  Local<Function> handler);
3319 
3320  V8_DEPRECATE_SOON("Use maybe version",
3321  Local<Promise> Catch(Local<Function> handler));
3323  Local<Function> handler);
3324 
3325  V8_DEPRECATE_SOON("Use maybe version",
3326  Local<Promise> Then(Local<Function> handler));
3328  Local<Function> handler);
3329 
3330  /**
3331  * Returns true if the promise has at least one derived promise, and
3332  * therefore resolve/reject handlers (including default handler).
3333  */
3334  bool HasHandler();
3335 
3336  V8_INLINE static Promise* Cast(Value* obj);
3337 
3338  private:
3339  Promise();
3340  static void CheckCast(Value* obj);
3341 };
3342 
3343 
3344 #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
3345 // The number of required internal fields can be defined by embedder.
3346 #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
3347 #endif
3348 
3349 
3351 
3352 
3353 /**
3354  * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
3355  * This API is experimental and may change significantly.
3356  */
3357 class V8_EXPORT ArrayBuffer : public Object {
3358  public:
3359  /**
3360  * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
3361  * The allocator is a global V8 setting. It has to be set via
3362  * Isolate::CreateParams.
3363  *
3364  * This API is experimental and may change significantly.
3365  */
3366  class V8_EXPORT Allocator { // NOLINT
3367  public:
3368  virtual ~Allocator() {}
3369 
3370  /**
3371  * Allocate |length| bytes. Return NULL if allocation is not successful.
3372  * Memory should be initialized to zeroes.
3373  */
3374  virtual void* Allocate(size_t length) = 0;
3375 
3376  /**
3377  * Allocate |length| bytes. Return NULL if allocation is not successful.
3378  * Memory does not have to be initialized.
3379  */
3380  virtual void* AllocateUninitialized(size_t length) = 0;
3381  /**
3382  * Free the memory block of size |length|, pointed to by |data|.
3383  * That memory is guaranteed to be previously allocated by |Allocate|.
3384  */
3385  virtual void Free(void* data, size_t length) = 0;
3386  };
3387 
3388  /**
3389  * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
3390  * returns an instance of this class, populated, with a pointer to data
3391  * and byte length.
3392  *
3393  * The Data pointer of ArrayBuffer::Contents is always allocated with
3394  * Allocator::Allocate that is set via Isolate::CreateParams.
3395  *
3396  * This API is experimental and may change significantly.
3397  */
3398  class V8_EXPORT Contents { // NOLINT
3399  public:
3400  Contents() : data_(NULL), byte_length_(0) {}
3401 
3402  void* Data() const { return data_; }
3403  size_t ByteLength() const { return byte_length_; }
3404 
3405  private:
3406  void* data_;
3407  size_t byte_length_;
3408 
3409  friend class ArrayBuffer;
3410  };
3411 
3412 
3413  /**
3414  * Data length in bytes.
3415  */
3416  size_t ByteLength() const;
3417 
3418  /**
3419  * Create a new ArrayBuffer. Allocate |byte_length| bytes.
3420  * Allocated memory will be owned by a created ArrayBuffer and
3421  * will be deallocated when it is garbage-collected,
3422  * unless the object is externalized.
3423  */
3424  static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
3425 
3426  /**
3427  * Create a new ArrayBuffer over an existing memory block.
3428  * The created array buffer is by default immediately in externalized state.
3429  * The memory block will not be reclaimed when a created ArrayBuffer
3430  * is garbage-collected.
3431  */
3433  Isolate* isolate, void* data, size_t byte_length,
3435 
3436  /**
3437  * Returns true if ArrayBuffer is externalized, that is, does not
3438  * own its memory block.
3439  */
3440  bool IsExternal() const;
3441 
3442  /**
3443  * Returns true if this ArrayBuffer may be neutered.
3444  */
3445  bool IsNeuterable() const;
3446 
3447  /**
3448  * Neuters this ArrayBuffer and all its views (typed arrays).
3449  * Neutering sets the byte length of the buffer and all typed arrays to zero,
3450  * preventing JavaScript from ever accessing underlying backing store.
3451  * ArrayBuffer should have been externalized and must be neuterable.
3452  */
3453  void Neuter();
3454 
3455  /**
3456  * Make this ArrayBuffer external. The pointer to underlying memory block
3457  * and byte length are returned as |Contents| structure. After ArrayBuffer
3458  * had been etxrenalized, it does no longer owns the memory block. The caller
3459  * should take steps to free memory when it is no longer needed.
3460  *
3461  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3462  * that has been set via Isolate::CreateParams.
3463  */
3465 
3466  /**
3467  * Get a pointer to the ArrayBuffer's underlying memory block without
3468  * externalizing it. If the ArrayBuffer is not externalized, this pointer
3469  * will become invalid as soon as the ArrayBuffer became garbage collected.
3470  *
3471  * The embedder should make sure to hold a strong reference to the
3472  * ArrayBuffer while accessing this pointer.
3473  *
3474  * The memory block is guaranteed to be allocated with |Allocator::Allocate|.
3475  */
3477 
3478  V8_INLINE static ArrayBuffer* Cast(Value* obj);
3479 
3481 
3482  private:
3483  ArrayBuffer();
3484  static void CheckCast(Value* obj);
3485 };
3486 
3487 
3488 #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
3489 // The number of required internal fields can be defined by embedder.
3490 #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
3491 #endif
3492 
3493 
3494 /**
3495  * A base class for an instance of one of "views" over ArrayBuffer,
3496  * including TypedArrays and DataView (ES6 draft 15.13).
3497  *
3498  * This API is experimental and may change significantly.
3499  */
3501  public:
3502  /**
3503  * Returns underlying ArrayBuffer.
3504  */
3506  /**
3507  * Byte offset in |Buffer|.
3508  */
3509  size_t ByteOffset();
3510  /**
3511  * Size of a view in bytes.
3512  */
3513  size_t ByteLength();
3514 
3515  /**
3516  * Copy the contents of the ArrayBufferView's buffer to an embedder defined
3517  * memory without additional overhead that calling ArrayBufferView::Buffer
3518  * might incur.
3519  *
3520  * Will write at most min(|byte_length|, ByteLength) bytes starting at
3521  * ByteOffset of the underling buffer to the memory starting at |dest|.
3522  * Returns the number of bytes actually written.
3523  */
3524  size_t CopyContents(void* dest, size_t byte_length);
3525 
3526  /**
3527  * Returns true if ArrayBufferView's backing ArrayBuffer has already been
3528  * allocated.
3529  */
3530  bool HasBuffer() const;
3531 
3532  V8_INLINE static ArrayBufferView* Cast(Value* obj);
3533 
3534  static const int kInternalFieldCount =
3536 
3537  private:
3538  ArrayBufferView();
3539  static void CheckCast(Value* obj);
3540 };
3541 
3542 
3543 /**
3544  * A base class for an instance of TypedArray series of constructors
3545  * (ES6 draft 15.13.6).
3546  * This API is experimental and may change significantly.
3547  */
3549  public:
3550  /**
3551  * Number of elements in this typed array
3552  * (e.g. for Int16Array, |ByteLength|/2).
3553  */
3554  size_t Length();
3555 
3556  V8_INLINE static TypedArray* Cast(Value* obj);
3557 
3558  private:
3559  TypedArray();
3560  static void CheckCast(Value* obj);
3561 };
3562 
3563 
3564 /**
3565  * An instance of Uint8Array constructor (ES6 draft 15.13.6).
3566  * This API is experimental and may change significantly.
3567  */
3569  public:
3570  static Local<Uint8Array> New(Local<ArrayBuffer> array_buffer,
3571  size_t byte_offset, size_t length);
3572  static Local<Uint8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3573  size_t byte_offset, size_t length);
3574  V8_INLINE static Uint8Array* Cast(Value* obj);
3575 
3576  private:
3577  Uint8Array();
3578  static void CheckCast(Value* obj);
3579 };
3580 
3581 
3582 /**
3583  * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
3584  * This API is experimental and may change significantly.
3585  */
3587  public:
3589  size_t byte_offset, size_t length);
3591  Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
3592  size_t length);
3593  V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
3594 
3595  private:
3596  Uint8ClampedArray();
3597  static void CheckCast(Value* obj);
3598 };
3599 
3600 /**
3601  * An instance of Int8Array constructor (ES6 draft 15.13.6).
3602  * This API is experimental and may change significantly.
3603  */
3605  public:
3606  static Local<Int8Array> New(Local<ArrayBuffer> array_buffer,
3607  size_t byte_offset, size_t length);
3608  static Local<Int8Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3609  size_t byte_offset, size_t length);
3610  V8_INLINE static Int8Array* Cast(Value* obj);
3611 
3612  private:
3613  Int8Array();
3614  static void CheckCast(Value* obj);
3615 };
3616 
3617 
3618 /**
3619  * An instance of Uint16Array constructor (ES6 draft 15.13.6).
3620  * This API is experimental and may change significantly.
3621  */
3623  public:
3624  static Local<Uint16Array> New(Local<ArrayBuffer> array_buffer,
3625  size_t byte_offset, size_t length);
3626  static Local<Uint16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3627  size_t byte_offset, size_t length);
3628  V8_INLINE static Uint16Array* Cast(Value* obj);
3629 
3630  private:
3631  Uint16Array();
3632  static void CheckCast(Value* obj);
3633 };
3634 
3635 
3636 /**
3637  * An instance of Int16Array constructor (ES6 draft 15.13.6).
3638  * This API is experimental and may change significantly.
3639  */
3641  public:
3642  static Local<Int16Array> New(Local<ArrayBuffer> array_buffer,
3643  size_t byte_offset, size_t length);
3644  static Local<Int16Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3645  size_t byte_offset, size_t length);
3646  V8_INLINE static Int16Array* Cast(Value* obj);
3647 
3648  private:
3649  Int16Array();
3650  static void CheckCast(Value* obj);
3651 };
3652 
3653 
3654 /**
3655  * An instance of Uint32Array constructor (ES6 draft 15.13.6).
3656  * This API is experimental and may change significantly.
3657  */
3659  public:
3660  static Local<Uint32Array> New(Local<ArrayBuffer> array_buffer,
3661  size_t byte_offset, size_t length);
3662  static Local<Uint32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3663  size_t byte_offset, size_t length);
3664  V8_INLINE static Uint32Array* Cast(Value* obj);
3665 
3666  private:
3667  Uint32Array();
3668  static void CheckCast(Value* obj);
3669 };
3670 
3671 
3672 /**
3673  * An instance of Int32Array constructor (ES6 draft 15.13.6).
3674  * This API is experimental and may change significantly.
3675  */
3677  public:
3678  static Local<Int32Array> New(Local<ArrayBuffer> array_buffer,
3679  size_t byte_offset, size_t length);
3680  static Local<Int32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3681  size_t byte_offset, size_t length);
3682  V8_INLINE static Int32Array* Cast(Value* obj);
3683 
3684  private:
3685  Int32Array();
3686  static void CheckCast(Value* obj);
3687 };
3688 
3689 
3690 /**
3691  * An instance of Float32Array constructor (ES6 draft 15.13.6).
3692  * This API is experimental and may change significantly.
3693  */
3695  public:
3696  static Local<Float32Array> New(Local<ArrayBuffer> array_buffer,
3697  size_t byte_offset, size_t length);
3698  static Local<Float32Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3699  size_t byte_offset, size_t length);
3700  V8_INLINE static Float32Array* Cast(Value* obj);
3701 
3702  private:
3703  Float32Array();
3704  static void CheckCast(Value* obj);
3705 };
3706 
3707 
3708 /**
3709  * An instance of Float64Array constructor (ES6 draft 15.13.6).
3710  * This API is experimental and may change significantly.
3711  */
3713  public:
3714  static Local<Float64Array> New(Local<ArrayBuffer> array_buffer,
3715  size_t byte_offset, size_t length);
3716  static Local<Float64Array> New(Local<SharedArrayBuffer> shared_array_buffer,
3717  size_t byte_offset, size_t length);
3718  V8_INLINE static Float64Array* Cast(Value* obj);
3719 
3720  private:
3721  Float64Array();
3722  static void CheckCast(Value* obj);
3723 };
3724 
3725 
3726 /**
3727  * An instance of DataView constructor (ES6 draft 15.13.7).
3728  * This API is experimental and may change significantly.
3729  */
3731  public:
3732  static Local<DataView> New(Local<ArrayBuffer> array_buffer,
3733  size_t byte_offset, size_t length);
3734  static Local<DataView> New(Local<SharedArrayBuffer> shared_array_buffer,
3735  size_t byte_offset, size_t length);
3736  V8_INLINE static DataView* Cast(Value* obj);
3737 
3738  private:
3739  DataView();
3740  static void CheckCast(Value* obj);
3741 };
3742 
3743 
3744 /**
3745  * An instance of the built-in SharedArrayBuffer constructor.
3746  * This API is experimental and may change significantly.
3747  */
3749  public:
3750  /**
3751  * The contents of an |SharedArrayBuffer|. Externalization of
3752  * |SharedArrayBuffer| returns an instance of this class, populated, with a
3753  * pointer to data and byte length.
3754  *
3755  * The Data pointer of SharedArrayBuffer::Contents is always allocated with
3756  * |ArrayBuffer::Allocator::Allocate| by the allocator specified in
3757  * v8::Isolate::CreateParams::array_buffer_allocator.
3758  *
3759  * This API is experimental and may change significantly.
3760  */
3761  class V8_EXPORT Contents { // NOLINT
3762  public:
3763  Contents() : data_(NULL), byte_length_(0) {}
3764 
3765  void* Data() const { return data_; }
3766  size_t ByteLength() const { return byte_length_; }
3767 
3768  private:
3769  void* data_;
3770  size_t byte_length_;
3771 
3772  friend class SharedArrayBuffer;
3773  };
3774 
3775 
3776  /**
3777  * Data length in bytes.
3778  */
3779  size_t ByteLength() const;
3780 
3781  /**
3782  * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
3783  * Allocated memory will be owned by a created SharedArrayBuffer and
3784  * will be deallocated when it is garbage-collected,
3785  * unless the object is externalized.
3786  */
3787  static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
3788 
3789  /**
3790  * Create a new SharedArrayBuffer over an existing memory block. The created
3791  * array buffer is immediately in externalized state unless otherwise
3792  * specified. The memory block will not be reclaimed when a created
3793  * SharedArrayBuffer is garbage-collected.
3794  */
3796  Isolate* isolate, void* data, size_t byte_length,
3798 
3799  /**
3800  * Returns true if SharedArrayBuffer is externalized, that is, does not
3801  * own its memory block.
3802  */
3803  bool IsExternal() const;
3804 
3805  /**
3806  * Make this SharedArrayBuffer external. The pointer to underlying memory
3807  * block and byte length are returned as |Contents| structure. After
3808  * SharedArrayBuffer had been etxrenalized, it does no longer owns the memory
3809  * block. The caller should take steps to free memory when it is no longer
3810  * needed.
3811  *
3812  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3813  * by the allocator specified in
3814  * v8::Isolate::CreateParams::array_buffer_allocator.
3815  *
3816  */
3818 
3819  /**
3820  * Get a pointer to the ArrayBuffer's underlying memory block without
3821  * externalizing it. If the ArrayBuffer is not externalized, this pointer
3822  * will become invalid as soon as the ArrayBuffer became garbage collected.
3823  *
3824  * The embedder should make sure to hold a strong reference to the
3825  * ArrayBuffer while accessing this pointer.
3826  *
3827  * The memory block is guaranteed to be allocated with |Allocator::Allocate|
3828  * by the allocator specified in
3829  * v8::Isolate::CreateParams::array_buffer_allocator.
3830  */
3832 
3833  V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
3834 
3836 
3837  private:
3838  SharedArrayBuffer();
3839  static void CheckCast(Value* obj);
3840 };
3841 
3842 
3843 /**
3844  * An instance of the built-in Date constructor (ECMA-262, 15.9).
3845  */
3846 class V8_EXPORT Date : public Object {
3847  public:
3848  static V8_DEPRECATE_SOON("Use maybe version.",
3849  Local<Value> New(Isolate* isolate, double time));
3851  double time);
3852 
3853  /**
3854  * A specialization of Value::NumberValue that is more efficient
3855  * because we know the structure of this object.
3856  */
3857  double ValueOf() const;
3858 
3859  V8_INLINE static Date* Cast(v8::Value* obj);
3860 
3861  /**
3862  * Notification that the embedder has changed the time zone,
3863  * daylight savings time, or other date / time configuration
3864  * parameters. V8 keeps a cache of various values used for
3865  * date / time computation. This notification will reset
3866  * those cached values for the current context so that date /
3867  * time configuration changes would be reflected in the Date
3868  * object.
3869  *
3870  * This API should not be called more than needed as it will
3871  * negatively impact the performance of date operations.
3872  */
3874 
3875  private:
3876  static void CheckCast(v8::Value* obj);
3877 };
3878 
3879 
3880 /**
3881  * A Number object (ECMA-262, 4.3.21).
3882  */
3884  public:
3885  static Local<Value> New(Isolate* isolate, double value);
3886 
3887  double ValueOf() const;
3888 
3889  V8_INLINE static NumberObject* Cast(v8::Value* obj);
3890 
3891  private:
3892  static void CheckCast(v8::Value* obj);
3893 };
3894 
3895 
3896 /**
3897  * A Boolean object (ECMA-262, 4.3.15).
3898  */
3900  public:
3901  static Local<Value> New(bool value);
3902 
3903  bool ValueOf() const;
3904 
3905  V8_INLINE static BooleanObject* Cast(v8::Value* obj);
3906 
3907  private:
3908  static void CheckCast(v8::Value* obj);
3909 };
3910 
3911 
3912 /**
3913  * A String object (ECMA-262, 4.3.18).
3914  */
3916  public:
3917  static Local<Value> New(Local<String> value);
3918 
3920 
3921  V8_INLINE static StringObject* Cast(v8::Value* obj);
3922 
3923  private:
3924  static void CheckCast(v8::Value* obj);
3925 };
3926 
3927 
3928 /**
3929  * A Symbol object (ECMA-262 edition 6).
3930  *
3931  * This is an experimental feature. Use at your own risk.
3932  */
3934  public:
3935  static Local<Value> New(Isolate* isolate, Local<Symbol> value);
3936 
3938 
3939  V8_INLINE static SymbolObject* Cast(v8::Value* obj);
3940 
3941  private:
3942  static void CheckCast(v8::Value* obj);
3943 };
3944 
3945 
3946 /**
3947  * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
3948  */
3949 class V8_EXPORT RegExp : public Object {
3950  public:
3951  /**
3952  * Regular expression flag bits. They can be or'ed to enable a set
3953  * of flags.
3954  */
3955  enum Flags {
3956  kNone = 0,
3957  kGlobal = 1,
3959  kMultiline = 4
3960  };
3961 
3962  /**
3963  * Creates a regular expression from the given pattern string and
3964  * the flags bit field. May throw a JavaScript exception as
3965  * described in ECMA-262, 15.10.4.1.
3966  *
3967  * For example,
3968  * RegExp::New(v8::String::New("foo"),
3969  * static_cast<RegExp::Flags>(kGlobal | kMultiline))
3970  * is equivalent to evaluating "/foo/gm".
3971  */
3972  static V8_DEPRECATE_SOON("Use maybe version",
3973  Local<RegExp> New(Local<String> pattern,
3974  Flags flags));
3976  Local<String> pattern,
3977  Flags flags);
3978 
3979  /**
3980  * Returns the value of the source property: a string representing
3981  * the regular expression.
3982  */
3984 
3985  /**
3986  * Returns the flags bit field.
3987  */
3988  Flags GetFlags() const;
3989 
3990  V8_INLINE static RegExp* Cast(v8::Value* obj);
3991 
3992  private:
3993  static void CheckCast(v8::Value* obj);
3994 };
3995 
3996 
3997 /**
3998  * A JavaScript value that wraps a C++ void*. This type of value is mainly used
3999  * to associate C++ data structures with JavaScript objects.
4000  */
4001 class V8_EXPORT External : public Value {
4002  public:
4003  static Local<External> New(Isolate* isolate, void* value);
4004  V8_INLINE static External* Cast(Value* obj);
4005  void* Value() const;
4006  private:
4007  static void CheckCast(v8::Value* obj);
4008 };
4009 
4010 
4011 // --- Templates ---
4012 
4013 
4014 /**
4015  * The superclass of object and function templates.
4016  */
4017 class V8_EXPORT Template : public Data {
4018  public:
4019  /** Adds a property to each instance created by this template.*/
4020  void Set(Local<Name> name, Local<Data> value,
4021  PropertyAttribute attributes = None);
4022  V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
4023 
4025  Local<Name> name,
4028  PropertyAttribute attribute = None,
4029  AccessControl settings = DEFAULT);
4030 
4031  /**
4032  * Whenever the property with the given name is accessed on objects
4033  * created from this Template the getter and setter callbacks
4034  * are called instead of getting and setting the property directly
4035  * on the JavaScript object.
4036  *
4037  * \param name The name of the property for which an accessor is added.
4038  * \param getter The callback to invoke when getting the property.
4039  * \param setter The callback to invoke when setting the property.
4040  * \param data A piece of data that will be passed to the getter and setter
4041  * callbacks whenever they are invoked.
4042  * \param settings Access control settings for the accessor. This is a bit
4043  * field consisting of one of more of
4044  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4045  * The default is to not allow cross-context access.
4046  * ALL_CAN_READ means that all cross-context reads are allowed.
4047  * ALL_CAN_WRITE means that all cross-context writes are allowed.
4048  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4049  * cross-context access.
4050  * \param attribute The attributes of the property for which an accessor
4051  * is added.
4052  * \param signature The signature describes valid receivers for the accessor
4053  * and is used to perform implicit instance checks against them. If the
4054  * receiver is incompatible (i.e. is not an instance of the constructor as
4055  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4056  * thrown and no callback is invoked.
4057  */
4059  Local<String> name, AccessorGetterCallback getter,
4060  AccessorSetterCallback setter = 0,
4061  // TODO(dcarney): gcc can't handle Local below
4062  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4064  AccessControl settings = DEFAULT);
4066  Local<Name> name, AccessorNameGetterCallback getter,
4067  AccessorNameSetterCallback setter = 0,
4068  // TODO(dcarney): gcc can't handle Local below
4069  Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
4071  AccessControl settings = DEFAULT);
4072 
4073  private:
4074  Template();
4075 
4076  friend class ObjectTemplate;
4077  friend class FunctionTemplate;
4078 };
4079 
4080 
4081 /**
4082  * NamedProperty[Getter|Setter] are used as interceptors on object.
4083  * See ObjectTemplate::SetNamedPropertyHandler.
4084  */
4086  Local<String> property,
4087  const PropertyCallbackInfo<Value>& info);
4088 
4089 
4090 /**
4091  * Returns the value if the setter intercepts the request.
4092  * Otherwise, returns an empty handle.
4093  */
4095  Local<String> property,
4096  Local<Value> value,
4097  const PropertyCallbackInfo<Value>& info);
4098 
4099 
4100 /**
4101  * Returns a non-empty handle if the interceptor intercepts the request.
4102  * The result is an integer encoding property attributes (like v8::None,
4103  * v8::DontEnum, etc.)
4104  */
4106  Local<String> property,
4107  const PropertyCallbackInfo<Integer>& info);
4108 
4109 
4110 /**
4111  * Returns a non-empty handle if the deleter intercepts the request.
4112  * The return value is true if the property could be deleted and false
4113  * otherwise.
4114  */
4116  Local<String> property,
4117  const PropertyCallbackInfo<Boolean>& info);
4118 
4119 
4120 /**
4121  * Returns an array containing the names of the properties the named
4122  * property getter intercepts.
4123  */
4125  const PropertyCallbackInfo<Array>& info);
4126 
4127 
4128 // TODO(dcarney): Deprecate and remove previous typedefs, and replace
4129 // GenericNamedPropertyFooCallback with just NamedPropertyFooCallback.
4130 /**
4131  * GenericNamedProperty[Getter|Setter] are used as interceptors on object.
4132  * See ObjectTemplate::SetNamedPropertyHandler.
4133  */
4135  Local<Name> property, const PropertyCallbackInfo<Value>& info);
4136 
4137 
4138 /**
4139  * Returns the value if the setter intercepts the request.
4140  * Otherwise, returns an empty handle.
4141  */
4143  Local<Name> property, Local<Value> value,
4144  const PropertyCallbackInfo<Value>& info);
4145 
4146 
4147 /**
4148  * Returns a non-empty handle if the interceptor intercepts the request.
4149  * The result is an integer encoding property attributes (like v8::None,
4150  * v8::DontEnum, etc.)
4151  */
4153  Local<Name> property, const PropertyCallbackInfo<Integer>& info);
4154 
4155 
4156 /**
4157  * Returns a non-empty handle if the deleter intercepts the request.
4158  * The return value is true if the property could be deleted and false
4159  * otherwise.
4160  */
4162  Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
4163 
4164 
4165 /**
4166  * Returns an array containing the names of the properties the named
4167  * property getter intercepts.
4168  */
4170  const PropertyCallbackInfo<Array>& info);
4171 
4172 
4173 /**
4174  * Returns the value of the property if the getter intercepts the
4175  * request. Otherwise, returns an empty handle.
4176  */
4178  uint32_t index,
4179  const PropertyCallbackInfo<Value>& info);
4180 
4181 
4182 /**
4183  * Returns the value if the setter intercepts the request.
4184  * Otherwise, returns an empty handle.
4185  */
4187  uint32_t index,
4188  Local<Value> value,
4189  const PropertyCallbackInfo<Value>& info);
4190 
4191 
4192 /**
4193  * Returns a non-empty handle if the interceptor intercepts the request.
4194  * The result is an integer encoding property attributes.
4195  */
4197  uint32_t index,
4198  const PropertyCallbackInfo<Integer>& info);
4199 
4200 
4201 /**
4202  * Returns a non-empty handle if the deleter intercepts the request.
4203  * The return value is true if the property could be deleted and false
4204  * otherwise.
4205  */
4207  uint32_t index,
4208  const PropertyCallbackInfo<Boolean>& info);
4209 
4210 
4211 /**
4212  * Returns an array containing the indices of the properties the
4213  * indexed property getter intercepts.
4214  */
4216  const PropertyCallbackInfo<Array>& info);
4217 
4218 
4219 /**
4220  * Access type specification.
4221  */
4227  ACCESS_KEYS
4228 };
4229 
4230 
4231 /**
4232  * Returns true if cross-context access should be allowed to the named
4233  * property with the given key on the host object.
4234  */
4235 typedef bool (*NamedSecurityCallback)(Local<Object> host,
4236  Local<Value> key,
4237  AccessType type,
4238  Local<Value> data);
4239 
4240 
4241 /**
4242  * Returns true if cross-context access should be allowed to the indexed
4243  * property with the given index on the host object.
4244  */
4245 typedef bool (*IndexedSecurityCallback)(Local<Object> host,
4246  uint32_t index,
4247  AccessType type,
4248  Local<Value> data);
4249 
4250 
4251 /**
4252  * A FunctionTemplate is used to create functions at runtime. There
4253  * can only be one function created from a FunctionTemplate in a
4254  * context. The lifetime of the created function is equal to the
4255  * lifetime of the context. So in case the embedder needs to create
4256  * temporary functions that can be collected using Scripts is
4257  * preferred.
4258  *
4259  * Any modification of a FunctionTemplate after first instantiation will trigger
4260  *a crash.
4261  *
4262  * A FunctionTemplate can have properties, these properties are added to the
4263  * function object when it is created.
4264  *
4265  * A FunctionTemplate has a corresponding instance template which is
4266  * used to create object instances when the function is used as a
4267  * constructor. Properties added to the instance template are added to
4268  * each object instance.
4269  *
4270  * A FunctionTemplate can have a prototype template. The prototype template
4271  * is used to create the prototype object of the function.
4272  *
4273  * The following example shows how to use a FunctionTemplate:
4274  *
4275  * \code
4276  * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
4277  * t->Set("func_property", v8::Number::New(1));
4278  *
4279  * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
4280  * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
4281  * proto_t->Set("proto_const", v8::Number::New(2));
4282  *
4283  * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
4284  * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
4285  * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
4286  * instance_t->Set("instance_property", Number::New(3));
4287  *
4288  * v8::Local<v8::Function> function = t->GetFunction();
4289  * v8::Local<v8::Object> instance = function->NewInstance();
4290  * \endcode
4291  *
4292  * Let's use "function" as the JS variable name of the function object
4293  * and "instance" for the instance object created above. The function
4294  * and the instance will have the following properties:
4295  *
4296  * \code
4297  * func_property in function == true;
4298  * function.func_property == 1;
4299  *
4300  * function.prototype.proto_method() invokes 'InvokeCallback'
4301  * function.prototype.proto_const == 2;
4302  *
4303  * instance instanceof function == true;
4304  * instance.instance_accessor calls 'InstanceAccessorCallback'
4305  * instance.instance_property == 3;
4306  * \endcode
4307  *
4308  * A FunctionTemplate can inherit from another one by calling the
4309  * FunctionTemplate::Inherit method. The following graph illustrates
4310  * the semantics of inheritance:
4311  *
4312  * \code
4313  * FunctionTemplate Parent -> Parent() . prototype -> { }
4314  * ^ ^
4315  * | Inherit(Parent) | .__proto__
4316  * | |
4317  * FunctionTemplate Child -> Child() . prototype -> { }
4318  * \endcode
4319  *
4320  * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
4321  * object of the Child() function has __proto__ pointing to the
4322  * Parent() function's prototype object. An instance of the Child
4323  * function has all properties on Parent's instance templates.
4324  *
4325  * Let Parent be the FunctionTemplate initialized in the previous
4326  * section and create a Child FunctionTemplate by:
4327  *
4328  * \code
4329  * Local<FunctionTemplate> parent = t;
4330  * Local<FunctionTemplate> child = FunctionTemplate::New();
4331  * child->Inherit(parent);
4332  *
4333  * Local<Function> child_function = child->GetFunction();
4334  * Local<Object> child_instance = child_function->NewInstance();
4335  * \endcode
4336  *
4337  * The Child function and Child instance will have the following
4338  * properties:
4339  *
4340  * \code
4341  * child_func.prototype.__proto__ == function.prototype;
4342  * child_instance.instance_accessor calls 'InstanceAccessorCallback'
4343  * child_instance.instance_property == 3;
4344  * \endcode
4345  */
4347  public:
4348  /** Creates a function template.*/
4350  Isolate* isolate, FunctionCallback callback = 0,
4351  Local<Value> data = Local<Value>(),
4352  Local<Signature> signature = Local<Signature>(), int length = 0);
4353 
4354  /** Returns the unique function instance in the current execution context.*/
4355  V8_DEPRECATE_SOON("Use maybe version", Local<Function> GetFunction());
4357  Local<Context> context);
4358 
4359  /**
4360  * Set the call-handler callback for a FunctionTemplate. This
4361  * callback is called whenever the function created from this
4362  * FunctionTemplate is called.
4363  */
4365  Local<Value> data = Local<Value>());
4366 
4367  /** Set the predefined length property for the FunctionTemplate. */
4368  void SetLength(int length);
4369 
4370  /** Get the InstanceTemplate. */
4372 
4373  /** Causes the function template to inherit from a parent function template.*/
4375 
4376  /**
4377  * A PrototypeTemplate is the template used to create the prototype object
4378  * of the function created by this template.
4379  */
4381 
4382  /**
4383  * Set the class name of the FunctionTemplate. This is used for
4384  * printing objects created with the function created from the
4385  * FunctionTemplate as its constructor.
4386  */
4388 
4389 
4390  /**
4391  * When set to true, no access check will be performed on the receiver of a
4392  * function call. Currently defaults to true, but this is subject to change.
4393  */
4394  void SetAcceptAnyReceiver(bool value);
4395 
4396  /**
4397  * Determines whether the __proto__ accessor ignores instances of
4398  * the function template. If instances of the function template are
4399  * ignored, __proto__ skips all instances and instead returns the
4400  * next object in the prototype chain.
4401  *
4402  * Call with a value of true to make the __proto__ accessor ignore
4403  * instances of the function template. Call with a value of false
4404  * to make the __proto__ accessor not ignore instances of the
4405  * function template. By default, instances of a function template
4406  * are not ignored.
4407  */
4408  void SetHiddenPrototype(bool value);
4409 
4410  /**
4411  * Sets the ReadOnly flag in the attributes of the 'prototype' property
4412  * of functions created from this FunctionTemplate to true.
4413  */
4415 
4416  /**
4417  * Removes the prototype property from functions created from this
4418  * FunctionTemplate.
4419  */
4421 
4422  /**
4423  * Returns true if the given object is an instance of this function
4424  * template.
4425  */
4426  bool HasInstance(Local<Value> object);
4427 
4428  private:
4429  FunctionTemplate();
4430  friend class Context;
4431  friend class ObjectTemplate;
4432 };
4433 
4434 
4436  kNone = 0,
4437  // See ALL_CAN_READ above.
4438  kAllCanRead = 1,
4439  // Will not call into interceptor for properties on the receiver or prototype
4440  // chain. Currently only valid for named interceptors.
4441  kNonMasking = 1 << 1,
4442  // Will not call into interceptor for symbol lookup. Only meaningful for
4443  // named interceptors.
4444  kOnlyInterceptStrings = 1 << 2,
4445 };
4446 
4447 
4450  /** Note: getter is required **/
4456  Local<Value> data = Local<Value>(),
4458  : getter(getter),
4459  setter(setter),
4460  query(query),
4461  deleter(deleter),
4462  enumerator(enumerator),
4463  data(data),
4464  flags(flags) {}
4465 
4473 };
4474 
4475 
4478  /** Note: getter is required **/
4479  IndexedPropertyGetterCallback getter = 0,
4480  IndexedPropertySetterCallback setter = 0,
4481  IndexedPropertyQueryCallback query = 0,
4482  IndexedPropertyDeleterCallback deleter = 0,
4483  IndexedPropertyEnumeratorCallback enumerator = 0,
4484  Local<Value> data = Local<Value>(),
4486  : getter(getter),
4487  setter(setter),
4488  query(query),
4489  deleter(deleter),
4490  enumerator(enumerator),
4491  data(data),
4492  flags(flags) {}
4493 
4501 };
4502 
4503 
4504 /**
4505  * An ObjectTemplate is used to create objects at runtime.
4506  *
4507  * Properties added to an ObjectTemplate are added to each object
4508  * created from the ObjectTemplate.
4509  */
4511  public:
4512  /** Creates an ObjectTemplate. */
4514  Isolate* isolate,
4516  static V8_DEPRECATE_SOON("Use isolate version", Local<ObjectTemplate> New());
4517 
4518  /** Creates a new instance of this template.*/
4519  V8_DEPRECATE_SOON("Use maybe version", Local<Object> NewInstance());
4521 
4522  /**
4523  * Sets an accessor on the object template.
4524  *
4525  * Whenever the property with the given name is accessed on objects
4526  * created from this ObjectTemplate the getter and setter callbacks
4527  * are called instead of getting and setting the property directly
4528  * on the JavaScript object.
4529  *
4530  * \param name The name of the property for which an accessor is added.
4531  * \param getter The callback to invoke when getting the property.
4532  * \param setter The callback to invoke when setting the property.
4533  * \param data A piece of data that will be passed to the getter and setter
4534  * callbacks whenever they are invoked.
4535  * \param settings Access control settings for the accessor. This is a bit
4536  * field consisting of one of more of
4537  * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
4538  * The default is to not allow cross-context access.
4539  * ALL_CAN_READ means that all cross-context reads are allowed.
4540  * ALL_CAN_WRITE means that all cross-context writes are allowed.
4541  * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
4542  * cross-context access.
4543  * \param attribute The attributes of the property for which an accessor
4544  * is added.
4545  * \param signature The signature describes valid receivers for the accessor
4546  * and is used to perform implicit instance checks against them. If the
4547  * receiver is incompatible (i.e. is not an instance of the constructor as
4548  * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
4549  * thrown and no callback is invoked.
4550  */
4552  Local<String> name, AccessorGetterCallback getter,
4553  AccessorSetterCallback setter = 0, Local<Value> data = Local<Value>(),
4554  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4557  Local<Name> name, AccessorNameGetterCallback getter,
4559  AccessControl settings = DEFAULT, PropertyAttribute attribute = None,
4561 
4562  /**
4563  * Sets a named property handler on the object template.
4564  *
4565  * Whenever a property whose name is a string is accessed on objects created
4566  * from this object template, the provided callback is invoked instead of
4567  * accessing the property directly on the JavaScript object.
4568  *
4569  * Note that new code should use the second version that can intercept
4570  * symbol-named properties as well as string-named properties.
4571  *
4572  * \param getter The callback to invoke when getting a property.
4573  * \param setter The callback to invoke when setting a property.
4574  * \param query The callback to invoke to check if a property is present,
4575  * and if present, get its attributes.
4576  * \param deleter The callback to invoke when deleting a property.
4577  * \param enumerator The callback to invoke to enumerate all the named
4578  * properties of an object.
4579  * \param data A piece of data that will be passed to the callbacks
4580  * whenever they are invoked.
4581  */
4582  // TODO(dcarney): deprecate
4584  NamedPropertySetterCallback setter = 0,
4585  NamedPropertyQueryCallback query = 0,
4586  NamedPropertyDeleterCallback deleter = 0,
4587  NamedPropertyEnumeratorCallback enumerator = 0,
4588  Local<Value> data = Local<Value>());
4589  void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
4590 
4591  /**
4592  * Sets an indexed property handler on the object template.
4593  *
4594  * Whenever an indexed property is accessed on objects created from
4595  * this object template, the provided callback is invoked instead of
4596  * accessing the property directly on the JavaScript object.
4597  *
4598  * \param getter The callback to invoke when getting a property.
4599  * \param setter The callback to invoke when setting a property.
4600  * \param query The callback to invoke to check if an object has a property.
4601  * \param deleter The callback to invoke when deleting a property.
4602  * \param enumerator The callback to invoke to enumerate all the indexed
4603  * properties of an object.
4604  * \param data A piece of data that will be passed to the callbacks
4605  * whenever they are invoked.
4606  */
4608  // TODO(dcarney): deprecate
4611  IndexedPropertySetterCallback setter = 0,
4612  IndexedPropertyQueryCallback query = 0,
4613  IndexedPropertyDeleterCallback deleter = 0,
4614  IndexedPropertyEnumeratorCallback enumerator = 0,
4615  Local<Value> data = Local<Value>()) {
4617  deleter, enumerator, data));
4618  }
4619  /**
4620  * Sets the callback to be used when calling instances created from
4621  * this template as a function. If no callback is set, instances
4622  * behave like normal JavaScript objects that cannot be called as a
4623  * function.
4624  */
4626  Local<Value> data = Local<Value>());
4627 
4628  /**
4629  * Mark object instances of the template as undetectable.
4630  *
4631  * In many ways, undetectable objects behave as though they are not
4632  * there. They behave like 'undefined' in conditionals and when
4633  * printed. However, properties can be accessed and called as on
4634  * normal objects.
4635  */
4637 
4638  /**
4639  * Sets access check callbacks on the object template and enables
4640  * access checks.
4641  *
4642  * When accessing properties on instances of this object template,
4643  * the access check callback will be called to determine whether or
4644  * not to allow cross-context access to the properties.
4645  */
4647  IndexedSecurityCallback indexed_handler,
4648  Local<Value> data = Local<Value>());
4649 
4650  /**
4651  * Gets the number of internal fields for objects generated from
4652  * this template.
4653  */
4655 
4656  /**
4657  * Sets the number of internal fields for objects generated from
4658  * this template.
4659  */
4660  void SetInternalFieldCount(int value);
4661 
4662  private:
4663  ObjectTemplate();
4664  static Local<ObjectTemplate> New(internal::Isolate* isolate,
4665  Local<FunctionTemplate> constructor);
4666  friend class FunctionTemplate;
4667 };
4668 
4669 
4670 /**
4671  * A Signature specifies which receiver is valid for a function.
4672  */
4673 class V8_EXPORT Signature : public Data {
4674  public:
4676  Isolate* isolate,
4678 
4679  private:
4680  Signature();
4681 };
4682 
4683 
4684 /**
4685  * An AccessorSignature specifies which receivers are valid parameters
4686  * to an accessor callback.
4687  */
4689  public:
4691  Isolate* isolate,
4693 
4694  private:
4695  AccessorSignature();
4696 };
4697 
4698 
4699 /**
4700  * A utility for determining the type of objects based on the template
4701  * they were constructed from.
4702  */
4703 class V8_EXPORT TypeSwitch : public Data {
4704  public:
4706  static Local<TypeSwitch> New(int argc, Local<FunctionTemplate> types[]);
4707  int match(Local<Value> value);
4708 
4709  private:
4710  TypeSwitch();
4711 };
4712 
4713 
4714 // --- Extensions ---
4715 
4718  public:
4719  ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
4720  ExternalOneByteStringResourceImpl(const char* data, size_t length)
4721  : data_(data), length_(length) {}
4722  const char* data() const { return data_; }
4723  size_t length() const { return length_; }
4724 
4725  private:
4726  const char* data_;
4727  size_t length_;
4728 };
4729 
4730 /**
4731  * Ignore
4732  */
4733 class V8_EXPORT Extension { // NOLINT
4734  public:
4735  // Note that the strings passed into this constructor must live as long
4736  // as the Extension itself.
4737  Extension(const char* name,
4738  const char* source = 0,
4739  int dep_count = 0,
4740  const char** deps = 0,
4741  int source_length = -1);
4742  virtual ~Extension() { }
4744  v8::Isolate* isolate, v8::Local<v8::String> name) {
4746  }
4747 
4748  const char* name() const { return name_; }
4749  size_t source_length() const { return source_length_; }
4751  return &source_; }
4752  int dependency_count() { return dep_count_; }
4753  const char** dependencies() { return deps_; }
4754  void set_auto_enable(bool value) { auto_enable_ = value; }
4755  bool auto_enable() { return auto_enable_; }
4756 
4757  private:
4758  const char* name_;
4759  size_t source_length_; // expected to initialize before source_
4761  int dep_count_;
4762  const char** deps_;
4763  bool auto_enable_;
4764 
4765  // Disallow copying and assigning.
4766  Extension(const Extension&);
4767  void operator=(const Extension&);
4768 };
4769 
4770 
4772 
4773 
4774 // --- Statics ---
4775 
4777 V8_INLINE Local<Primitive> Null(Isolate* isolate);
4778 V8_INLINE Local<Boolean> True(Isolate* isolate);
4779 V8_INLINE Local<Boolean> False(Isolate* isolate);
4780 
4781 
4782 /**
4783  * A set of constraints that specifies the limits of the runtime's memory use.
4784  * You must set the heap size before initializing the VM - the size cannot be
4785  * adjusted after the VM is initialized.
4786  *
4787  * If you are using threads then you should hold the V8::Locker lock while
4788  * setting the stack limit and you must set a non-default stack limit separately
4789  * for each thread.
4790  */
4792  public:
4794 
4795  /**
4796  * Configures the constraints with reasonable default values based on the
4797  * capabilities of the current device the VM is running on.
4798  *
4799  * \param physical_memory The total amount of physical memory on the current
4800  * device, in bytes.
4801  * \param virtual_memory_limit The amount of virtual memory on the current
4802  * device, in bytes, or zero, if there is no limit.
4803  */
4804  void ConfigureDefaults(uint64_t physical_memory,
4805  uint64_t virtual_memory_limit);
4806 
4807  // Deprecated, will be removed soon.
4808  V8_DEPRECATED("Use two-args version instead",
4809  void ConfigureDefaults(uint64_t physical_memory,
4810  uint64_t virtual_memory_limit,
4811  uint32_t number_of_processors));
4812 
4813  int max_semi_space_size() const { return max_semi_space_size_; }
4814  void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
4815  int max_old_space_size() const { return max_old_space_size_; }
4816  void set_max_old_space_size(int value) { max_old_space_size_ = value; }
4817  int max_executable_size() const { return max_executable_size_; }
4818  void set_max_executable_size(int value) { max_executable_size_ = value; }
4819  uint32_t* stack_limit() const { return stack_limit_; }
4820  // Sets an address beyond which the VM's stack may not grow.
4821  void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
4822  V8_DEPRECATED("Unused, will be removed", int max_available_threads() const) {
4823  return max_available_threads_;
4824  }
4825  // Set the number of threads available to V8, assuming at least 1.
4826  V8_DEPRECATED("Unused, will be removed",
4827  void set_max_available_threads(int value)) {
4828  max_available_threads_ = value;
4829  }
4830  size_t code_range_size() const { return code_range_size_; }
4831  void set_code_range_size(size_t value) {
4832  code_range_size_ = value;
4833  }
4834 
4835  private:
4836  int max_semi_space_size_;
4837  int max_old_space_size_;
4838  int max_executable_size_;
4839  uint32_t* stack_limit_;
4840  int max_available_threads_;
4841  size_t code_range_size_;
4842 };
4843 
4844 
4845 // --- Exceptions ---
4846 
4847 
4848 typedef void (*FatalErrorCallback)(const char* location, const char* message);
4849 
4850 
4851 typedef void (*MessageCallback)(Local<Message> message, Local<Value> error);
4852 
4853 // --- Tracing ---
4854 
4855 typedef void (*LogEventCallback)(const char* name, int event);
4856 
4857 /**
4858  * Create new error objects by calling the corresponding error object
4859  * constructor with the message.
4860  */
4862  public:
4863  static Local<Value> RangeError(Local<String> message);
4865  static Local<Value> SyntaxError(Local<String> message);
4866  static Local<Value> TypeError(Local<String> message);
4867  static Local<Value> Error(Local<String> message);
4868 
4869  /**
4870  * Creates an error message for the given exception.
4871  * Will try to reconstruct the original stack trace from the exception value,
4872  * or capture the current stack trace if not available.
4873  */
4874  static Local<Message> CreateMessage(Local<Value> exception);
4875 
4876  /**
4877  * Returns the original stack trace that was captured at the creation time
4878  * of a given exception, or an empty handle if not available.
4879  */
4881 };
4882 
4883 
4884 // --- Counters Callbacks ---
4885 
4886 typedef int* (*CounterLookupCallback)(const char* name);
4887 
4888 typedef void* (*CreateHistogramCallback)(const char* name,
4889  int min,
4890  int max,
4891  size_t buckets);
4892 
4893 typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
4894 
4895 // --- Memory Allocation Callback ---
4905 };
4906 
4911  };
4912 
4914  AllocationAction action,
4915  int size);
4916 
4917 // --- Leave Script Callback ---
4918 typedef void (*CallCompletedCallback)();
4919 
4920 // --- Promise Reject Callback ---
4924 };
4925 
4927  public:
4929  Local<Value> value, Local<StackTrace> stack_trace)
4930  : promise_(promise),
4931  event_(event),
4932  value_(value),
4933  stack_trace_(stack_trace) {}
4934 
4935  V8_INLINE Local<Promise> GetPromise() const { return promise_; }
4936  V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
4937  V8_INLINE Local<Value> GetValue() const { return value_; }
4938 
4939  // DEPRECATED. Use v8::Exception::CreateMessage(GetValue())->GetStackTrace()
4940  V8_INLINE Local<StackTrace> GetStackTrace() const { return stack_trace_; }
4941 
4942  private:
4943  Local<Promise> promise_;
4944  PromiseRejectEvent event_;
4945  Local<Value> value_;
4946  Local<StackTrace> stack_trace_;
4947 };
4948 
4950 
4951 // --- Microtask Callback ---
4952 typedef void (*MicrotaskCallback)(void* data);
4953 
4954 // --- Failed Access Check Callback ---
4955 typedef void (*FailedAccessCheckCallback)(Local<Object> target,
4956  AccessType type,
4957  Local<Value> data);
4958 
4959 // --- AllowCodeGenerationFromStrings callbacks ---
4960 
4961 /**
4962  * Callback to check if code generation from strings is allowed. See
4963  * Context::AllowCodeGenerationFromStrings.
4964  */
4966 
4967 // --- Garbage Collection Callbacks ---
4968 
4969 /**
4970  * Applications can register callback functions which will be called
4971  * before and after a garbage collection. Allocations are not
4972  * allowed in the callback functions, you therefore cannot manipulate
4973  * objects (set or delete properties for example) since it is possible
4974  * such operations will result in the allocation of objects.
4975  */
4976 enum GCType {
4980 };
4981 
4986  kGCCallbackFlagForced = 1 << 2
4987 };
4988 
4989 typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
4990 typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
4991 
4992 typedef void (*InterruptCallback)(Isolate* isolate, void* data);
4993 
4994 
4995 /**
4996  * Collection of V8 heap information.
4997  *
4998  * Instances of this class can be passed to v8::V8::HeapStatistics to
4999  * get heap statistics from V8.
5000  */
5002  public:
5004  size_t total_heap_size() { return total_heap_size_; }
5005  size_t total_heap_size_executable() { return total_heap_size_executable_; }
5006  size_t total_physical_size() { return total_physical_size_; }
5007  size_t total_available_size() { return total_available_size_; }
5008  size_t used_heap_size() { return used_heap_size_; }
5009  size_t heap_size_limit() { return heap_size_limit_; }
5010 
5011  private:
5012  size_t total_heap_size_;
5013  size_t total_heap_size_executable_;
5014  size_t total_physical_size_;
5015  size_t total_available_size_;
5016  size_t used_heap_size_;
5017  size_t heap_size_limit_;
5018 
5019  friend class V8;
5020  friend class Isolate;
5021 };
5022 
5023 
5025  public:
5027  const char* space_name() { return space_name_; }
5028  size_t space_size() { return space_size_; }
5029  size_t space_used_size() { return space_used_size_; }
5030  size_t space_available_size() { return space_available_size_; }
5031  size_t physical_space_size() { return physical_space_size_; }
5032 
5033  private:
5034  const char* space_name_;
5035  size_t space_size_;
5036  size_t space_used_size_;
5037  size_t space_available_size_;
5038  size_t physical_space_size_;
5039 
5040  friend class Isolate;
5041 };
5042 
5043 
5045  public:
5047  const char* object_type() { return object_type_; }
5048  const char* object_sub_type() { return object_sub_type_; }
5049  size_t object_count() { return object_count_; }
5050  size_t object_size() { return object_size_; }
5051 
5052  private:
5053  const char* object_type_;
5054  const char* object_sub_type_;
5055  size_t object_count_;
5056  size_t object_size_;
5057 
5058  friend class Isolate;
5059 };
5060 
5061 
5062 class RetainedObjectInfo;
5063 
5064 
5065 /**
5066  * FunctionEntryHook is the type of the profile entry hook called at entry to
5067  * any generated function when function-level profiling is enabled.
5068  *
5069  * \param function the address of the function that's being entered.
5070  * \param return_addr_location points to a location on stack where the machine
5071  * return address resides. This can be used to identify the caller of
5072  * \p function, and/or modified to divert execution when \p function exits.
5073  *
5074  * \note the entry hook must not cause garbage collection.
5075  */
5076 typedef void (*FunctionEntryHook)(uintptr_t function,
5077  uintptr_t return_addr_location);
5078 
5079 /**
5080  * A JIT code event is issued each time code is added, moved or removed.
5081  *
5082  * \note removal events are not currently issued.
5083  */
5085  enum EventType {
5092  };
5093  // Definition of the code position type. The "POSITION" type means the place
5094  // in the source code which are of interest when making stack traces to
5095  // pin-point the source location of a stack frame as close as possible.
5096  // The "STATEMENT_POSITION" means the place at the beginning of each
5097  // statement, and is used to indicate possible break locations.
5099 
5100  // Type of event.
5102  // Start of the instructions.
5103  void* code_start;
5104  // Size of the instructions.
5105  size_t code_len;
5106  // Script info for CODE_ADDED event.
5108  // User-defined data for *_LINE_INFO_* event. It's used to hold the source
5109  // code line information which is returned from the
5110  // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
5111  // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
5112  void* user_data;
5113 
5114  struct name_t {
5115  // Name of the object associated with the code, note that the string is not
5116  // zero-terminated.
5117  const char* str;
5118  // Number of chars in str.
5119  size_t len;
5120  };
5121 
5122  struct line_info_t {
5123  // PC offset
5124  size_t offset;
5125  // Code postion
5126  size_t pos;
5127  // The position type.
5129  };
5130 
5131  union {
5132  // Only valid for CODE_ADDED.
5133  struct name_t name;
5134 
5135  // Only valid for CODE_ADD_LINE_POS_INFO
5136  struct line_info_t line_info;
5137 
5138  // New location of instructions. Only valid for CODE_MOVED.
5140  };
5141 };
5142 
5143 /**
5144  * Option flags passed to the SetJitCodeEventHandler function.
5145  */
5148  // Generate callbacks for already existent code.
5150 };
5151 
5152 
5153 /**
5154  * Callback function passed to SetJitCodeEventHandler.
5155  *
5156  * \param event code add, move or removal event.
5157  */
5158 typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
5159 
5160 
5161 /**
5162  * Interface for iterating through all external resources in the heap.
5163  */
5165  public:
5167  virtual void VisitExternalString(Local<String> string) {}
5168 };
5169 
5170 
5171 /**
5172  * Interface for iterating through all the persistent handles in the heap.
5173  */
5175  public:
5178  uint16_t class_id) {}
5179 };
5180 
5181 
5182 /**
5183  * Isolate represents an isolated instance of the V8 engine. V8 isolates have
5184  * completely separate states. Objects from one isolate must not be used in
5185  * other isolates. The embedder can create multiple isolates and use them in
5186  * parallel in multiple threads. An isolate can be entered by at most one
5187  * thread at any given time. The Locker/Unlocker API must be used to
5188  * synchronize.
5189  */
5191  public:
5192  /**
5193  * Initial configuration parameters for a new Isolate.
5194  */
5195  struct CreateParams {
5197  : entry_hook(NULL),
5198  code_event_handler(NULL),
5199  snapshot_blob(NULL),
5203  array_buffer_allocator(NULL) {}
5204 
5205  /**
5206  * The optional entry_hook allows the host application to provide the
5207  * address of a function that's invoked on entry to every V8-generated
5208  * function. Note that entry_hook is invoked at the very start of each
5209  * generated function. Furthermore, if an entry_hook is given, V8 will
5210  * always run without a context snapshot.
5211  */
5213 
5214  /**
5215  * Allows the host application to provide the address of a function that is
5216  * notified each time code is added, moved or removed.
5217  */
5219 
5220  /**
5221  * ResourceConstraints to use for the new Isolate.
5222  */
5224 
5225  /**
5226  * Explicitly specify a startup snapshot blob. The embedder owns the blob.
5227  */
5229 
5230 
5231  /**
5232  * Enables the host application to provide a mechanism for recording
5233  * statistics counters.
5234  */
5236 
5237  /**
5238  * Enables the host application to provide a mechanism for recording
5239  * histograms. The CreateHistogram function returns a
5240  * histogram which will later be passed to the AddHistogramSample
5241  * function.
5242  */
5245 
5246  /**
5247  * The ArrayBuffer::Allocator to use for allocating and freeing the backing
5248  * store of ArrayBuffers.
5249  */
5251  };
5252 
5253 
5254  /**
5255  * Stack-allocated class which sets the isolate for all operations
5256  * executed within a local scope.
5257  */
5259  public:
5260  explicit Scope(Isolate* isolate) : isolate_(isolate) {
5261  isolate->Enter();
5262  }
5263 
5264  ~Scope() { isolate_->Exit(); }
5265 
5266  private:
5267  Isolate* const isolate_;
5268 
5269  // Prevent copying of Scope objects.
5270  Scope(const Scope&);
5271  Scope& operator=(const Scope&);
5272  };
5273 
5274 
5275  /**
5276  * Assert that no Javascript code is invoked.
5277  */
5279  public:
5281 
5284 
5285  private:
5286  bool on_failure_;
5287  void* internal_;
5288 
5289  // Prevent copying of Scope objects.
5290  DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
5293  };
5294 
5295 
5296  /**
5297  * Introduce exception to DisallowJavascriptExecutionScope.
5298  */
5300  public:
5303 
5304  private:
5305  void* internal_throws_;
5306  void* internal_assert_;
5307 
5308  // Prevent copying of Scope objects.
5309  AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
5310  AllowJavascriptExecutionScope& operator=(
5312  };
5313 
5314  /**
5315  * Do not run microtasks while this scope is active, even if microtasks are
5316  * automatically executed otherwise.
5317  */
5319  public:
5322 
5323  private:
5324  internal::Isolate* isolate_;
5325 
5326  // Prevent copying of Scope objects.
5327  SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
5330  };
5331 
5332  /**
5333  * Types of garbage collections that can be requested via
5334  * RequestGarbageCollectionForTesting.
5335  */
5339  };
5340 
5341  /**
5342  * Features reported via the SetUseCounterCallback callback. Do not change
5343  * assigned numbers of existing items; add new features to the end of this
5344  * list.
5345  */
5347  kUseAsm = 0,
5355  kUseCounterFeatureCount // This enum value must be last.
5356  };
5357 
5358  typedef void (*UseCounterCallback)(Isolate* isolate,
5359  UseCounterFeature feature);
5360 
5361 
5362  /**
5363  * Creates a new isolate. Does not change the currently entered
5364  * isolate.
5365  *
5366  * When an isolate is no longer used its resources should be freed
5367  * by calling Dispose(). Using the delete operator is not allowed.
5368  *
5369  * V8::Initialize() must have run prior to this.
5370  */
5371  static Isolate* New(const CreateParams& params);
5372 
5373  static V8_DEPRECATED("Always pass CreateParams", Isolate* New());
5374 
5375  /**
5376  * Returns the entered isolate for the current thread or NULL in
5377  * case there is no current isolate.
5378  *
5379  * This method must not be invoked before V8::Initialize() was invoked.
5380  */
5381  static Isolate* GetCurrent();
5382 
5383  /**
5384  * Methods below this point require holding a lock (using Locker) in
5385  * a multi-threaded environment.
5386  */
5387 
5388  /**
5389  * Sets this isolate as the entered one for the current thread.
5390  * Saves the previously entered one (if any), so that it can be
5391  * restored when exiting. Re-entering an isolate is allowed.
5392  */
5393  void Enter();
5394 
5395  /**
5396  * Exits this isolate by restoring the previously entered one in the
5397  * current thread. The isolate may still stay the same, if it was
5398  * entered more than once.
5399  *
5400  * Requires: this == Isolate::GetCurrent().
5401  */
5402  void Exit();
5403 
5404  /**
5405  * Disposes the isolate. The isolate must not be entered by any
5406  * thread to be disposable.
5407  */
5408  void Dispose();
5409 
5410  /**
5411  * Associate embedder-specific data with the isolate. |slot| has to be
5412  * between 0 and GetNumberOfDataSlots() - 1.
5413  */
5414  V8_INLINE void SetData(uint32_t slot, void* data);
5415 
5416  /**
5417  * Retrieve embedder-specific data from the isolate.
5418  * Returns NULL if SetData has never been called for the given |slot|.
5419  */
5420  V8_INLINE void* GetData(uint32_t slot);
5421 
5422  /**
5423  * Returns the maximum number of available embedder data slots. Valid slots
5424  * are in the range of 0 - GetNumberOfDataSlots() - 1.
5425  */
5426  V8_INLINE static uint32_t GetNumberOfDataSlots();
5427 
5428  /**
5429  * Get statistics about the heap memory usage.
5430  */
5431  void GetHeapStatistics(HeapStatistics* heap_statistics);
5432 
5433  /**
5434  * Returns the number of spaces in the heap.
5435  */
5437 
5438  /**
5439  * Get the memory usage of a space in the heap.
5440  *
5441  * \param space_statistics The HeapSpaceStatistics object to fill in
5442  * statistics.
5443  * \param index The index of the space to get statistics from, which ranges
5444  * from 0 to NumberOfHeapSpaces() - 1.
5445  * \returns true on success.
5446  */
5448  size_t index);
5449 
5450  /**
5451  * Returns the number of types of objects tracked in the heap at GC.
5452  */
5454 
5455  /**
5456  * Get statistics about objects in the heap.
5457  *
5458  * \param object_statistics The HeapObjectStatistics object to fill in
5459  * statistics of objects of given type, which were live in the previous GC.
5460  * \param type_index The index of the type of object to fill details about,
5461  * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
5462  * \returns true on success.
5463  */
5465  size_t type_index);
5466 
5467  /**
5468  * Get a call stack sample from the isolate.
5469  * \param state Execution state.
5470  * \param frames Caller allocated buffer to store stack frames.
5471  * \param frames_limit Maximum number of frames to capture. The buffer must
5472  * be large enough to hold the number of frames.
5473  * \param sample_info The sample info is filled up by the function
5474  * provides number of actual captured stack frames and
5475  * the current VM state.
5476  * \note GetStackSample should only be called when the JS thread is paused or
5477  * interrupted. Otherwise the behavior is undefined.
5478  */
5479  void GetStackSample(const RegisterState& state, void** frames,
5480  size_t frames_limit, SampleInfo* sample_info);
5481 
5482  /**
5483  * Adjusts the amount of registered external memory. Used to give V8 an
5484  * indication of the amount of externally allocated memory that is kept alive
5485  * by JavaScript objects. V8 uses this to decide when to perform global
5486  * garbage collections. Registering externally allocated memory will trigger
5487  * global garbage collections more often than it would otherwise in an attempt
5488  * to garbage collect the JavaScript objects that keep the externally
5489  * allocated memory alive.
5490  *
5491  * \param change_in_bytes the change in externally allocated memory that is
5492  * kept alive by JavaScript objects.
5493  * \returns the adjusted value.
5494  */
5495  V8_INLINE int64_t
5496  AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
5497 
5498  /**
5499  * Returns heap profiler for this isolate. Will return NULL until the isolate
5500  * is initialized.
5501  */
5503 
5504  /**
5505  * Returns CPU profiler for this isolate. Will return NULL unless the isolate
5506  * is initialized. It is the embedder's responsibility to stop all CPU
5507  * profiling activities if it has started any.
5508  */
5510 
5511  /** Returns true if this isolate has a current context. */
5512  bool InContext();
5513 
5514  /** Returns the context that is on the top of the stack. */
5516 
5517  /**
5518  * Returns the context of the calling JavaScript code. That is the
5519  * context of the top-most JavaScript frame. If there are no
5520  * JavaScript frames an empty handle is returned.
5521  */
5523 
5524  /** Returns the last entered context. */
5526 
5527  /**
5528  * Schedules an exception to be thrown when returning to JavaScript. When an
5529  * exception has been scheduled it is illegal to invoke any JavaScript
5530  * operation; the caller must return immediately and only after the exception
5531  * has been handled does it become legal to invoke JavaScript operations.
5532  */
5534 
5535  /**
5536  * Allows the host application to group objects together. If one
5537  * object in the group is alive, all objects in the group are alive.
5538  * After each garbage collection, object groups are removed. It is
5539  * intended to be used in the before-garbage-collection callback
5540  * function, for instance to simulate DOM tree connections among JS
5541  * wrapper objects. Object groups for all dependent handles need to
5542  * be provided for kGCTypeMarkSweepCompact collections, for all other
5543  * garbage collection types it is sufficient to provide object groups
5544  * for partially dependent handles only.
5545  */
5546  template<typename T> void SetObjectGroupId(const Persistent<T>& object,
5547  UniqueId id);
5548 
5549  /**
5550  * Allows the host application to declare implicit references from an object
5551  * group to an object. If the objects of the object group are alive, the child
5552  * object is alive too. After each garbage collection, all implicit references
5553  * are removed. It is intended to be used in the before-garbage-collection
5554  * callback function.
5555  */
5556  template<typename T> void SetReferenceFromGroup(UniqueId id,
5557  const Persistent<T>& child);
5558 
5559  /**
5560  * Allows the host application to declare implicit references from an object
5561  * to another object. If the parent object is alive, the child object is alive
5562  * too. After each garbage collection, all implicit references are removed. It
5563  * is intended to be used in the before-garbage-collection callback function.
5564  */
5565  template<typename T, typename S>
5566  void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
5567 
5568  typedef void (*GCPrologueCallback)(Isolate* isolate,
5569  GCType type,
5570  GCCallbackFlags flags);
5571  typedef void (*GCEpilogueCallback)(Isolate* isolate,
5572  GCType type,
5573  GCCallbackFlags flags);
5574 
5575  /**
5576  * Enables the host application to receive a notification before a
5577  * garbage collection. Allocations are allowed in the callback function,
5578  * but the callback is not re-entrant: if the allocation inside it will
5579  * trigger the garbage collection, the callback won't be called again.
5580  * It is possible to specify the GCType filter for your callback. But it is
5581  * not possible to register the same callback function two times with
5582  * different GCType filters.
5583  */
5585  GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
5586 
5587  /**
5588  * This function removes callback which was installed by
5589  * AddGCPrologueCallback function.
5590  */
5592 
5593  /**
5594  * Enables the host application to receive a notification after a
5595  * garbage collection. Allocations are allowed in the callback function,
5596  * but the callback is not re-entrant: if the allocation inside it will
5597  * trigger the garbage collection, the callback won't be called again.
5598  * It is possible to specify the GCType filter for your callback. But it is
5599  * not possible to register the same callback function two times with
5600  * different GCType filters.
5601  */
5603  GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
5604 
5605  /**
5606  * This function removes callback which was installed by
5607  * AddGCEpilogueCallback function.
5608  */
5610 
5611 
5612  /**
5613  * Forcefully terminate the current thread of JavaScript execution
5614  * in the given isolate.
5615  *
5616  * This method can be used by any thread even if that thread has not
5617  * acquired the V8 lock with a Locker object.
5618  */
5620 
5621  /**
5622  * Is V8 terminating JavaScript execution.
5623  *
5624  * Returns true if JavaScript execution is currently terminating
5625  * because of a call to TerminateExecution. In that case there are
5626  * still JavaScript frames on the stack and the termination
5627  * exception is still active.
5628  */
5630 
5631  /**
5632  * Resume execution capability in the given isolate, whose execution
5633  * was previously forcefully terminated using TerminateExecution().
5634  *
5635  * When execution is forcefully terminated using TerminateExecution(),
5636  * the isolate can not resume execution until all JavaScript frames
5637  * have propagated the uncatchable exception which is generated. This
5638  * method allows the program embedding the engine to handle the
5639  * termination event and resume execution capability, even if
5640  * JavaScript frames remain on the stack.
5641  *
5642  * This method can be used by any thread even if that thread has not
5643  * acquired the V8 lock with a Locker object.
5644  */
5646 
5647  /**
5648  * Request V8 to interrupt long running JavaScript code and invoke
5649  * the given |callback| passing the given |data| to it. After |callback|
5650  * returns control will be returned to the JavaScript code.
5651  * There may be a number of interrupt requests in flight.
5652  * Can be called from another thread without acquiring a |Locker|.
5653  * Registered |callback| must not reenter interrupted Isolate.
5654  */
5655  void RequestInterrupt(InterruptCallback callback, void* data);
5656 
5657  /**
5658  * Request garbage collection in this Isolate. It is only valid to call this
5659  * function if --expose_gc was specified.
5660  *
5661  * This should only be used for testing purposes and not to enforce a garbage
5662  * collection schedule. It has strong negative impact on the garbage
5663  * collection performance. Use IdleNotificationDeadline() or
5664  * LowMemoryNotification() instead to influence the garbage collection
5665  * schedule.
5666  */
5668 
5669  /**
5670  * Set the callback to invoke for logging event.
5671  */
5673 
5674  /**
5675  * Adds a callback to notify the host application when a script finished
5676  * running. If a script re-enters the runtime during executing, the
5677  * CallCompletedCallback is only invoked when the outer-most script
5678  * execution ends. Executing scripts inside the callback do not trigger
5679  * further callbacks.
5680  */
5682 
5683  /**
5684  * Removes callback that was installed by AddCallCompletedCallback.
5685  */
5687 
5688 
5689  /**
5690  * Set callback to notify about promise reject with no handler, or
5691  * revocation of such a previous notification once the handler is added.
5692  */
5694 
5695  /**
5696  * Experimental: Runs the Microtask Work Queue until empty
5697  * Any exceptions thrown by microtask callbacks are swallowed.
5698  */
5700 
5701  /**
5702  * Experimental: Enqueues the callback to the Microtask Work Queue
5703  */
5704  void EnqueueMicrotask(Local<Function> microtask);
5705 
5706  /**
5707  * Experimental: Enqueues the callback to the Microtask Work Queue
5708  */
5709  void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
5710 
5711  /**
5712  * Experimental: Controls whether the Microtask Work Queue is automatically
5713  * run when the script call depth decrements to zero.
5714  */
5715  void SetAutorunMicrotasks(bool autorun);
5716 
5717  /**
5718  * Experimental: Returns whether the Microtask Work Queue is automatically
5719  * run when the script call depth decrements to zero.
5720  */
5722 
5723  /**
5724  * Sets a callback for counting the number of times a feature of V8 is used.
5725  */
5727 
5728  /**
5729  * Enables the host application to provide a mechanism for recording
5730  * statistics counters.
5731  */
5733 
5734  /**
5735  * Enables the host application to provide a mechanism for recording
5736  * histograms. The CreateHistogram function returns a
5737  * histogram which will later be passed to the AddHistogramSample
5738  * function.
5739  */
5742 
5743  /**
5744  * Optional notification that the embedder is idle.
5745  * V8 uses the notification to perform garbage collection.
5746  * This call can be used repeatedly if the embedder remains idle.
5747  * Returns true if the embedder should stop calling IdleNotificationDeadline
5748  * until real work has been done. This indicates that V8 has done
5749  * as much cleanup as it will be able to do.
5750  *
5751  * The deadline_in_seconds argument specifies the deadline V8 has to finish
5752  * garbage collection work. deadline_in_seconds is compared with
5753  * MonotonicallyIncreasingTime() and should be based on the same timebase as
5754  * that function. There is no guarantee that the actual work will be done
5755  * within the time limit.
5756  */
5757  bool IdleNotificationDeadline(double deadline_in_seconds);
5758 
5759  V8_DEPRECATE_SOON("use IdleNotificationDeadline()",
5760  bool IdleNotification(int idle_time_in_ms));
5761 
5762  /**
5763  * Optional notification that the system is running low on memory.
5764  * V8 uses these notifications to attempt to free memory.
5765  */
5767 
5768  /**
5769  * Optional notification that a context has been disposed. V8 uses
5770  * these notifications to guide the GC heuristic. Returns the number
5771  * of context disposals - including this one - since the last time
5772  * V8 had a chance to clean up.
5773  *
5774  * The optional parameter |dependant_context| specifies whether the disposed
5775  * context was depending on state from other contexts or not.
5776  */
5777  int ContextDisposedNotification(bool dependant_context = true);
5778 
5779  /**
5780  * Allows the host application to provide the address of a function that is
5781  * notified each time code is added, moved or removed.
5782  *
5783  * \param options options for the JIT code event handler.
5784  * \param event_handler the JIT code event handler, which will be invoked
5785  * each time code is added, moved or removed.
5786  * \note \p event_handler won't get notified of existent code.
5787  * \note since code removal notifications are not currently issued, the
5788  * \p event_handler may get notifications of code that overlaps earlier
5789  * code notifications. This happens when code areas are reused, and the
5790  * earlier overlapping code areas should therefore be discarded.
5791  * \note the events passed to \p event_handler and the strings they point to
5792  * are not guaranteed to live past each call. The \p event_handler must
5793  * copy strings and other parameters it needs to keep around.
5794  * \note the set of events declared in JitCodeEvent::EventType is expected to
5795  * grow over time, and the JitCodeEvent structure is expected to accrue
5796  * new members. The \p event_handler function must ignore event codes
5797  * it does not recognize to maintain future compatibility.
5798  * \note Use Isolate::CreateParams to get events for code executed during
5799  * Isolate setup.
5800  */
5802  JitCodeEventHandler event_handler);
5803 
5804  /**
5805  * Modifies the stack limit for this Isolate.
5806  *
5807  * \param stack_limit An address beyond which the Vm's stack may not grow.
5808  *
5809  * \note If you are using threads then you should hold the V8::Locker lock
5810  * while setting the stack limit and you must set a non-default stack
5811  * limit separately for each thread.
5812  */
5813  void SetStackLimit(uintptr_t stack_limit);
5814 
5815  /**
5816  * Returns a memory range that can potentially contain jitted code.
5817  *
5818  * On Win64, embedders are advised to install function table callbacks for
5819  * these ranges, as default SEH won't be able to unwind through jitted code.
5820  *
5821  * The first page of the code range is reserved for the embedder and is
5822  * committed, writable, and executable.
5823  *
5824  * Might be empty on other platforms.
5825  *
5826  * https://code.google.com/p/v8/issues/detail?id=3598
5827  */
5828  void GetCodeRange(void** start, size_t* length_in_bytes);
5829 
5830  /** Set the callback to invoke in case of fatal errors. */
5832 
5833  /**
5834  * Set the callback to invoke to check if code generation from
5835  * strings should be allowed.
5836  */
5839 
5840  /**
5841  * Check if V8 is dead and therefore unusable. This is the case after
5842  * fatal errors such as out-of-memory situations.
5843  */
5844  bool IsDead();
5845 
5846  /**
5847  * Adds a message listener.
5848  *
5849  * The same message listener can be added more than once and in that
5850  * case it will be called more than once for each message.
5851  *
5852  * If data is specified, it will be passed to the callback when it is called.
5853  * Otherwise, the exception object will be passed to the callback instead.
5854  */
5856  Local<Value> data = Local<Value>());
5857 
5858  /**
5859  * Remove all message listeners from the specified callback function.
5860  */
5862 
5863  /** Callback function for reporting failed access checks.*/
5865 
5866  /**
5867  * Tells V8 to capture current stack trace when uncaught exception occurs
5868  * and report it to the message listeners. The option is off by default.
5869  */
5871  bool capture, int frame_limit = 10,
5873 
5874  /**
5875  * Enables the host application to provide a mechanism to be notified
5876  * and perform custom logging when V8 Allocates Executable Memory.
5877  */
5879  ObjectSpace space, AllocationAction action);
5880 
5881  /**
5882  * Removes callback that was installed by AddMemoryAllocationCallback.
5883  */
5885 
5886  /**
5887  * Iterates through all external resources referenced from current isolate
5888  * heap. GC is not invoked prior to iterating, therefore there is no
5889  * guarantee that visited objects are still alive.
5890  */
5892 
5893  /**
5894  * Iterates through all the persistent handles in the current isolate's heap
5895  * that have class_ids.
5896  */
5898 
5899  /**
5900  * Iterates through all the persistent handles in the current isolate's heap
5901  * that have class_ids and are candidates to be marked as partially dependent
5902  * handles. This will visit handles to young objects created since the last
5903  * garbage collection but is free to visit an arbitrary superset of these
5904  * objects.
5905  */
5907 
5908  private:
5909  template <class K, class V, class Traits>
5911 
5912  Isolate();
5913  Isolate(const Isolate&);
5914  ~Isolate();
5915  Isolate& operator=(const Isolate&);
5916  void* operator new(size_t size);
5917  void operator delete(void*, size_t);
5918 
5919  void SetObjectGroupId(internal::Object** object, UniqueId id);
5920  void SetReferenceFromGroup(UniqueId id, internal::Object** object);
5921  void SetReference(internal::Object** parent, internal::Object** child);
5922  void CollectAllGarbage(const char* gc_reason);
5923 };
5924 
5926  public:
5927  const char* data;
5929 };
5930 
5931 
5932 /**
5933  * EntropySource is used as a callback function when v8 needs a source
5934  * of entropy.
5935  */
5936 typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
5937 
5938 
5939 /**
5940  * ReturnAddressLocationResolver is used as a callback function when v8 is
5941  * resolving the location of a return address on the stack. Profilers that
5942  * change the return address on the stack can use this to resolve the stack
5943  * location to whereever the profiler stashed the original return address.
5944  *
5945  * \param return_addr_location points to a location on stack where a machine
5946  * return address resides.
5947  * \returns either return_addr_location, or else a pointer to the profiler's
5948  * copy of the original return address.
5949  *
5950  * \note the resolver function must not cause garbage collection.
5951  */
5952 typedef uintptr_t (*ReturnAddressLocationResolver)(
5953  uintptr_t return_addr_location);
5954 
5955 
5956 /**
5957  * Container class for static utility functions.
5958  */
5959 class V8_EXPORT V8 {
5960  public:
5961  /** Set the callback to invoke in case of fatal errors. */
5963  "Use isolate version",
5964  void SetFatalErrorHandler(FatalErrorCallback that));
5965 
5966  /**
5967  * Set the callback to invoke to check if code generation from
5968  * strings should be allowed.
5969  */
5971  "Use isolate version", void SetAllowCodeGenerationFromStringsCallback(
5973 
5974  /**
5975  * Set allocator to use for ArrayBuffer memory.
5976  * The allocator should be set only once. The allocator should be set
5977  * before any code tha uses ArrayBuffers is executed.
5978  * This allocator is used in all isolates.
5979  */
5981  "Use isolate version",
5982  void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator));
5983 
5984  /**
5985  * Check if V8 is dead and therefore unusable. This is the case after
5986  * fatal errors such as out-of-memory situations.
5987  */
5988  V8_INLINE static V8_DEPRECATE_SOON("no alternative", bool IsDead());
5989 
5990  /**
5991  * Hand startup data to V8, in case the embedder has chosen to build
5992  * V8 with external startup data.
5993  *
5994  * Note:
5995  * - By default the startup data is linked into the V8 library, in which
5996  * case this function is not meaningful.
5997  * - If this needs to be called, it needs to be called before V8
5998  * tries to make use of its built-ins.
5999  * - To avoid unnecessary copies of data, V8 will point directly into the
6000  * given data blob, so pretty please keep it around until V8 exit.
6001  * - Compression of the startup blob might be useful, but needs to
6002  * handled entirely on the embedders' side.
6003  * - The call will abort if the data is invalid.
6004  */
6005  static void SetNativesDataBlob(StartupData* startup_blob);
6006  static void SetSnapshotDataBlob(StartupData* startup_blob);
6007 
6008  /**
6009  * Create a new isolate and context for the purpose of capturing a snapshot
6010  * Returns { NULL, 0 } on failure.
6011  * The caller owns the data array in the return value.
6012  */
6013  static StartupData CreateSnapshotDataBlob(const char* custom_source = NULL);
6014 
6015  /**
6016  * Adds a message listener.
6017  *
6018  * The same message listener can be added more than once and in that
6019  * case it will be called more than once for each message.
6020  *
6021  * If data is specified, it will be passed to the callback when it is called.
6022  * Otherwise, the exception object will be passed to the callback instead.
6023  */
6025  "Use isolate version",
6026  bool AddMessageListener(MessageCallback that,
6027  Local<Value> data = Local<Value>()));
6028 
6029  /**
6030  * Remove all message listeners from the specified callback function.
6031  */
6033  "Use isolate version", void RemoveMessageListeners(MessageCallback that));
6034 
6035  /**
6036  * Tells V8 to capture current stack trace when uncaught exception occurs
6037  * and report it to the message listeners. The option is off by default.
6038  */
6040  "Use isolate version",
6041  void SetCaptureStackTraceForUncaughtExceptions(
6042  bool capture, int frame_limit = 10,
6044 
6045  /**
6046  * Sets V8 flags from a string.
6047  */
6048  static void SetFlagsFromString(const char* str, int length);
6049 
6050  /**
6051  * Sets V8 flags from the command line.
6052  */
6053  static void SetFlagsFromCommandLine(int* argc,
6054  char** argv,
6055  bool remove_flags);
6056 
6057  /** Get the version string. */
6058  static const char* GetVersion();
6059 
6060  /** Callback function for reporting failed access checks.*/
6062  "Use isolate version",
6063  void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback));
6064 
6065  /**
6066  * Enables the host application to receive a notification before a
6067  * garbage collection. Allocations are not allowed in the
6068  * callback function, you therefore cannot manipulate objects (set
6069  * or delete properties for example) since it is possible such
6070  * operations will result in the allocation of objects. It is possible
6071  * to specify the GCType filter for your callback. But it is not possible to
6072  * register the same callback function two times with different
6073  * GCType filters.
6074  */
6076  "Use isolate version",
6077  void AddGCPrologueCallback(GCPrologueCallback callback,
6078  GCType gc_type_filter = kGCTypeAll));
6079 
6080  /**
6081  * This function removes callback which was installed by
6082  * AddGCPrologueCallback function.
6083  */
6085  "Use isolate version",
6086  void RemoveGCPrologueCallback(GCPrologueCallback callback));
6087 
6088  /**
6089  * Enables the host application to receive a notification after a
6090  * garbage collection. Allocations are not allowed in the
6091  * callback function, you therefore cannot manipulate objects (set
6092  * or delete properties for example) since it is possible such
6093  * operations will result in the allocation of objects. It is possible
6094  * to specify the GCType filter for your callback. But it is not possible to
6095  * register the same callback function two times with different
6096  * GCType filters.
6097  */
6099  "Use isolate version",
6100  void AddGCEpilogueCallback(GCEpilogueCallback callback,
6101  GCType gc_type_filter = kGCTypeAll));
6102 
6103  /**
6104  * This function removes callback which was installed by
6105  * AddGCEpilogueCallback function.
6106  */
6108  "Use isolate version",
6109  void RemoveGCEpilogueCallback(GCEpilogueCallback callback));
6110 
6111  /**
6112  * Enables the host application to provide a mechanism to be notified
6113  * and perform custom logging when V8 Allocates Executable Memory.
6114  */
6116  "Use isolate version",
6117  void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
6118  ObjectSpace space,
6119  AllocationAction action));
6120 
6121  /**
6122  * Removes callback that was installed by AddMemoryAllocationCallback.
6123  */
6125  "Use isolate version",
6126  void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback));
6127 
6128  /**
6129  * Initializes V8. This function needs to be called before the first Isolate
6130  * is created. It always returns true.
6131  */
6132  static bool Initialize();
6133 
6134  /**
6135  * Allows the host application to provide a callback which can be used
6136  * as a source of entropy for random number generators.
6137  */
6138  static void SetEntropySource(EntropySource source);
6139 
6140  /**
6141  * Allows the host application to provide a callback that allows v8 to
6142  * cooperate with a profiler that rewrites return addresses on stack.
6143  */
6145  ReturnAddressLocationResolver return_address_resolver);
6146 
6147  /**
6148  * Forcefully terminate the current thread of JavaScript execution
6149  * in the given isolate.
6150  *
6151  * This method can be used by any thread even if that thread has not
6152  * acquired the V8 lock with a Locker object.
6153  *
6154  * \param isolate The isolate in which to terminate the current JS execution.
6155  */
6156  V8_INLINE static V8_DEPRECATE_SOON("Use isolate version",
6157  void TerminateExecution(Isolate* isolate));
6158 
6159  /**
6160  * Is V8 terminating JavaScript execution.
6161  *
6162  * Returns true if JavaScript execution is currently terminating
6163  * because of a call to TerminateExecution. In that case there are
6164  * still JavaScript frames on the stack and the termination
6165  * exception is still active.
6166  *
6167  * \param isolate The isolate in which to check.
6168  */
6170  "Use isolate version",
6171  bool IsExecutionTerminating(Isolate* isolate = NULL));
6172 
6173  /**
6174  * Resume execution capability in the given isolate, whose execution
6175  * was previously forcefully terminated using TerminateExecution().
6176  *
6177  * When execution is forcefully terminated using TerminateExecution(),
6178  * the isolate can not resume execution until all JavaScript frames
6179  * have propagated the uncatchable exception which is generated. This
6180  * method allows the program embedding the engine to handle the
6181  * termination event and resume execution capability, even if
6182  * JavaScript frames remain on the stack.
6183  *
6184  * This method can be used by any thread even if that thread has not
6185  * acquired the V8 lock with a Locker object.
6186  *
6187  * \param isolate The isolate in which to resume execution capability.
6188  */
6190  "Use isolate version", void CancelTerminateExecution(Isolate* isolate));
6191 
6192  /**
6193  * Releases any resources used by v8 and stops any utility threads
6194  * that may be running. Note that disposing v8 is permanent, it
6195  * cannot be reinitialized.
6196  *
6197  * It should generally not be necessary to dispose v8 before exiting
6198  * a process, this should happen automatically. It is only necessary
6199  * to use if the process needs the resources taken up by v8.
6200  */
6201  static bool Dispose();
6202 
6203  /**
6204  * Iterates through all external resources referenced from current isolate
6205  * heap. GC is not invoked prior to iterating, therefore there is no
6206  * guarantee that visited objects are still alive.
6207  */
6209  "Use isoalte version",
6210  void VisitExternalResources(ExternalResourceVisitor* visitor));
6211 
6212  /**
6213  * Iterates through all the persistent handles in the current isolate's heap
6214  * that have class_ids.
6215  */
6217  "Use isolate version",
6218  void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor));
6219 
6220  /**
6221  * Iterates through all the persistent handles in isolate's heap that have
6222  * class_ids.
6223  */
6225  "Use isolate version",
6226  void VisitHandlesWithClassIds(Isolate* isolate,
6227  PersistentHandleVisitor* visitor));
6228 
6229  /**
6230  * Iterates through all the persistent handles in the current isolate's heap
6231  * that have class_ids and are candidates to be marked as partially dependent
6232  * handles. This will visit handles to young objects created since the last
6233  * garbage collection but is free to visit an arbitrary superset of these
6234  * objects.
6235  */
6237  "Use isolate version",
6238  void VisitHandlesForPartialDependence(Isolate* isolate,
6239  PersistentHandleVisitor* visitor));
6240 
6241  /**
6242  * Initialize the ICU library bundled with V8. The embedder should only
6243  * invoke this method when using the bundled ICU. Returns true on success.
6244  *
6245  * If V8 was compiled with the ICU data in an external file, the location
6246  * of the data file has to be provided.
6247  */
6248  static bool InitializeICU(const char* icu_data_file = NULL);
6249 
6250  /**
6251  * Sets the v8::Platform to use. This should be invoked before V8 is
6252  * initialized.
6253  */
6254  static void InitializePlatform(Platform* platform);
6255 
6256  /**
6257  * Clears all references to the v8::Platform. This should be invoked after
6258  * V8 was disposed.
6259  */
6260  static void ShutdownPlatform();
6261 
6262  private:
6263  V8();
6264 
6265  static internal::Object** GlobalizeReference(internal::Isolate* isolate,
6266  internal::Object** handle);
6267  static internal::Object** CopyPersistent(internal::Object** handle);
6268  static void DisposeGlobal(internal::Object** global_handle);
6269  typedef WeakCallbackData<Value, void>::Callback WeakCallback;
6270  static void MakeWeak(internal::Object** global_handle, void* data,
6271  WeakCallback weak_callback);
6272  static void MakeWeak(internal::Object** global_handle, void* data,
6273  WeakCallbackInfo<void>::Callback weak_callback,
6274  WeakCallbackType type);
6275  static void MakeWeak(internal::Object** global_handle, void* data,
6276  // Must be 0 or -1.
6277  int internal_field_index1,
6278  // Must be 1 or -1.
6279  int internal_field_index2,
6280  WeakCallbackInfo<void>::Callback weak_callback);
6281  static void* ClearWeak(internal::Object** global_handle);
6282  static void Eternalize(Isolate* isolate,
6283  Value* handle,
6284  int* index);
6285  static Local<Value> GetEternal(Isolate* isolate, int index);
6286 
6287  static void FromJustIsNothing();
6288  static void ToLocalEmpty();
6289  static void InternalFieldOutOfBounds(int index);
6290  template <class T> friend class Local;
6291  template <class T>
6292  friend class MaybeLocal;
6293  template <class T>
6294  friend class Maybe;
6295  template <class T>
6296  friend class WeakCallbackInfo;
6297  template <class T> friend class Eternal;
6298  template <class T> friend class PersistentBase;
6299  template <class T, class M> friend class Persistent;
6300  friend class Context;
6301 };
6302 
6303 
6304 /**
6305  * A simple Maybe type, representing an object which may or may not have a
6306  * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
6307  *
6308  * If an API method returns a Maybe<>, the API method can potentially fail
6309  * either because an exception is thrown, or because an exception is pending,
6310  * e.g. because a previous API call threw an exception that hasn't been caught
6311  * yet, or because a TerminateExecution exception was thrown. In that case, a
6312  * "Nothing" value is returned.
6313  */
6314 template <class T>
6315 class Maybe {
6316  public:
6317  V8_INLINE bool IsNothing() const { return !has_value; }
6318  V8_INLINE bool IsJust() const { return has_value; }
6319 
6320  // Will crash if the Maybe<> is nothing.
6321  V8_INLINE T FromJust() const {
6322  if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
6323  return value;
6324  }
6325 
6326  V8_INLINE T FromMaybe(const T& default_value) const {
6327  return has_value ? value : default_value;
6328  }
6329 
6330  V8_INLINE bool operator==(const Maybe& other) const {
6331  return (IsJust() == other.IsJust()) &&
6332  (!IsJust() || FromJust() == other.FromJust());
6333  }
6334 
6335  V8_INLINE bool operator!=(const Maybe& other) const {
6336  return !operator==(other);
6337  }
6338 
6339  private:
6340  Maybe() : has_value(false) {}
6341  explicit Maybe(const T& t) : has_value(true), value(t) {}
6342 
6343  bool has_value;
6344  T value;
6345 
6346  template <class U>
6347  friend Maybe<U> Nothing();
6348  template <class U>
6349  friend Maybe<U> Just(const U& u);
6350 };
6351 
6352 
6353 template <class T>
6354 inline Maybe<T> Nothing() {
6355  return Maybe<T>();
6356 }
6357 
6358 
6359 template <class T>
6360 inline Maybe<T> Just(const T& t) {
6361  return Maybe<T>(t);
6362 }
6363 
6364 
6365 /**
6366  * An external exception handler.
6367  */
6369  public:
6370  /**
6371  * Creates a new try/catch block and registers it with v8. Note that
6372  * all TryCatch blocks should be stack allocated because the memory
6373  * location itself is compared against JavaScript try/catch blocks.
6374  */
6375  V8_DEPRECATE_SOON("Use isolate version", TryCatch());
6376 
6377  /**
6378  * Creates a new try/catch block and registers it with v8. Note that
6379  * all TryCatch blocks should be stack allocated because the memory
6380  * location itself is compared against JavaScript try/catch blocks.
6381  */
6382  TryCatch(Isolate* isolate);
6383 
6384  /**
6385  * Unregisters and deletes this try/catch block.
6386  */
6388 
6389  /**
6390  * Returns true if an exception has been caught by this try/catch block.
6391  */
6392  bool HasCaught() const;
6393 
6394  /**
6395  * For certain types of exceptions, it makes no sense to continue execution.
6396  *
6397  * If CanContinue returns false, the correct action is to perform any C++
6398  * cleanup needed and then return. If CanContinue returns false and
6399  * HasTerminated returns true, it is possible to call
6400  * CancelTerminateExecution in order to continue calling into the engine.
6401  */
6402  bool CanContinue() const;
6403 
6404  /**
6405  * Returns true if an exception has been caught due to script execution
6406  * being terminated.
6407  *
6408  * There is no JavaScript representation of an execution termination
6409  * exception. Such exceptions are thrown when the TerminateExecution
6410  * methods are called to terminate a long-running script.
6411  *
6412  * If such an exception has been thrown, HasTerminated will return true,
6413  * indicating that it is possible to call CancelTerminateExecution in order
6414  * to continue calling into the engine.
6415  */
6416  bool HasTerminated() const;
6417 
6418  /**
6419  * Throws the exception caught by this TryCatch in a way that avoids
6420  * it being caught again by this same TryCatch. As with ThrowException
6421  * it is illegal to execute any JavaScript operations after calling
6422  * ReThrow; the caller must return immediately to where the exception
6423  * is caught.
6424  */
6426 
6427  /**
6428  * Returns the exception caught by this try/catch block. If no exception has
6429  * been caught an empty handle is returned.
6430  *
6431  * The returned handle is valid until this TryCatch block has been destroyed.
6432  */
6434 
6435  /**
6436  * Returns the .stack property of the thrown object. If no .stack
6437  * property is present an empty handle is returned.
6438  */
6439  V8_DEPRECATE_SOON("Use maybe version.", Local<Value> StackTrace() const);
6441  Local<Context> context) const;
6442 
6443  /**
6444  * Returns the message associated with this exception. If there is
6445  * no message associated an empty handle is returned.
6446  *
6447  * The returned handle is valid until this TryCatch block has been
6448  * destroyed.
6449  */
6450  Local<v8::Message> Message() const;
6451 
6452  /**
6453  * Clears any exceptions that may have been caught by this try/catch block.
6454  * After this method has been called, HasCaught() will return false. Cancels
6455  * the scheduled exception if it is caught and ReThrow() is not called before.
6456  *
6457  * It is not necessary to clear a try/catch block before using it again; if
6458  * another exception is thrown the previously caught exception will just be
6459  * overwritten. However, it is often a good idea since it makes it easier
6460  * to determine which operation threw a given exception.
6461  */
6462  void Reset();
6463 
6464  /**
6465  * Set verbosity of the external exception handler.
6466  *
6467  * By default, exceptions that are caught by an external exception
6468  * handler are not reported. Call SetVerbose with true on an
6469  * external exception handler to have exceptions caught by the
6470  * handler reported as if they were not caught.
6471  */
6472  void SetVerbose(bool value);
6473 
6474  /**
6475  * Set whether or not this TryCatch should capture a Message object
6476  * which holds source information about where the exception
6477  * occurred. True by default.
6478  */
6479  void SetCaptureMessage(bool value);
6480 
6481  /**
6482  * There are cases when the raw address of C++ TryCatch object cannot be
6483  * used for comparisons with addresses into the JS stack. The cases are:
6484  * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
6485  * 2) Address sanitizer allocates local C++ object in the heap when
6486  * UseAfterReturn mode is enabled.
6487  * This method returns address that can be used for comparisons with
6488  * addresses into the JS stack. When neither simulator nor ASAN's
6489  * UseAfterReturn is enabled, then the address returned will be the address
6490  * of the C++ try catch handler itself.
6491  */
6492  static void* JSStackComparableAddress(v8::TryCatch* handler) {
6493  if (handler == NULL) return NULL;
6494  return handler->js_stack_comparable_address_;
6495  }
6496 
6497  private:
6498  void ResetInternal();
6499 
6500  // Make it hard to create heap-allocated TryCatch blocks.
6501  TryCatch(const TryCatch&);
6502  void operator=(const TryCatch&);
6503  void* operator new(size_t size);
6504  void operator delete(void*, size_t);
6505 
6506  v8::internal::Isolate* isolate_;
6507  v8::TryCatch* next_;
6508  void* exception_;
6509  void* message_obj_;
6510  void* js_stack_comparable_address_;
6511  bool is_verbose_ : 1;
6512  bool can_continue_ : 1;
6513  bool capture_message_ : 1;
6514  bool rethrow_ : 1;
6515  bool has_terminated_ : 1;
6516 
6517  friend class v8::internal::Isolate;
6518 };
6519 
6520 
6521 // --- Context ---
6522 
6523 
6524 /**
6525  * A container for extension names.
6526  */
6528  public:
6529  ExtensionConfiguration() : name_count_(0), names_(NULL) { }
6530  ExtensionConfiguration(int name_count, const char* names[])
6531  : name_count_(name_count), names_(names) { }
6532 
6533  const char** begin() const { return &names_[0]; }
6534  const char** end() const { return &names_[name_count_]; }
6535 
6536  private:
6537  const int name_count_;
6538  const char** names_;
6539 };
6540 
6541 
6542 /**
6543  * A sandboxed execution context with its own set of built-in objects
6544  * and functions.
6545  */
6547  public:
6548  /**
6549  * Returns the global proxy object.
6550  *
6551  * Global proxy object is a thin wrapper whose prototype points to actual
6552  * context's global object with the properties like Object, etc. This is done
6553  * that way for security reasons (for more details see
6554  * https://wiki.mozilla.org/Gecko:SplitWindow).
6555  *
6556  * Please note that changes to global proxy object prototype most probably
6557  * would break VM---v8 expects only global object as a prototype of global
6558  * proxy object.
6559  */
6561 
6562  /**
6563  * Detaches the global object from its context before
6564  * the global object can be reused to create a new context.
6565  */
6567 
6568  /**
6569  * Creates a new context and returns a handle to the newly allocated
6570  * context.
6571  *
6572  * \param isolate The isolate in which to create the context.
6573  *
6574  * \param extensions An optional extension configuration containing
6575  * the extensions to be installed in the newly created context.
6576  *
6577  * \param global_template An optional object template from which the
6578  * global object for the newly created context will be created.
6579  *
6580  * \param global_object An optional global object to be reused for
6581  * the newly created context. This global object must have been
6582  * created by a previous call to Context::New with the same global
6583  * template. The state of the global object will be completely reset
6584  * and only object identify will remain.
6585  */
6586  static Local<Context> New(
6587  Isolate* isolate, ExtensionConfiguration* extensions = NULL,
6588  Local<ObjectTemplate> global_template = Local<ObjectTemplate>(),
6589  Local<Value> global_object = Local<Value>());
6590 
6591  /**
6592  * Sets the security token for the context. To access an object in
6593  * another context, the security tokens must match.
6594  */
6596 
6597  /** Restores the security token to the default value. */
6599 
6600  /** Returns the security token of this context.*/
6602 
6603  /**
6604  * Enter this context. After entering a context, all code compiled
6605  * and run is compiled and run in this context. If another context
6606  * is already entered, this old context is saved so it can be
6607  * restored when the new context is exited.
6608  */
6609  void Enter();
6610 
6611  /**
6612  * Exit this context. Exiting the current context restores the
6613  * context that was in place when entering the current context.
6614  */
6615  void Exit();
6616 
6617  /** Returns an isolate associated with a current context. */
6619 
6620  /**
6621  * The field at kDebugIdIndex is reserved for V8 debugger implementation.
6622  * The value is propagated to the scripts compiled in given Context and
6623  * can be used for filtering scripts.
6624  */
6626 
6627  /**
6628  * Gets the embedder data with the given index, which must have been set by a
6629  * previous call to SetEmbedderData with the same index. Note that index 0
6630  * currently has a special meaning for Chrome's debugger.
6631  */
6632  V8_INLINE Local<Value> GetEmbedderData(int index);
6633 
6634  /**
6635  * Gets the exports object used by V8 extras. Extra natives get a reference
6636  * to this object and can use it to export functionality.
6637  */
6639 
6640  /**
6641  * Sets the embedder data with the given index, growing the data as
6642  * needed. Note that index 0 currently has a special meaning for Chrome's
6643  * debugger.
6644  */
6645  void SetEmbedderData(int index, Local<Value> value);
6646 
6647  /**
6648  * Gets a 2-byte-aligned native pointer from the embedder data with the given
6649  * index, which must have bees set by a previous call to
6650  * SetAlignedPointerInEmbedderData with the same index. Note that index 0
6651  * currently has a special meaning for Chrome's debugger.
6652  */
6654 
6655  /**
6656  * Sets a 2-byte-aligned native pointer in the embedder data with the given
6657  * index, growing the data as needed. Note that index 0 currently has a
6658  * special meaning for Chrome's debugger.
6659  */
6660  void SetAlignedPointerInEmbedderData(int index, void* value);
6661 
6662  /**
6663  * Control whether code generation from strings is allowed. Calling
6664  * this method with false will disable 'eval' and the 'Function'
6665  * constructor for code running in this context. If 'eval' or the
6666  * 'Function' constructor are used an exception will be thrown.
6667  *
6668  * If code generation from strings is not allowed the
6669  * V8::AllowCodeGenerationFromStrings callback will be invoked if
6670  * set before blocking the call to 'eval' or the 'Function'
6671  * constructor. If that callback returns true, the call will be
6672  * allowed, otherwise an exception will be thrown. If no callback is
6673  * set an exception will be thrown.
6674  */
6676 
6677  /**
6678  * Returns true if code generation from strings is allowed for the context.
6679  * For more details see AllowCodeGenerationFromStrings(bool) documentation.
6680  */
6682 
6683  /**
6684  * Sets the error description for the exception that is thrown when
6685  * code generation from strings is not allowed and 'eval' or the 'Function'
6686  * constructor are called.
6687  */
6689 
6690  /**
6691  * Stack-allocated class which sets the execution context for all
6692  * operations executed within a local scope.
6693  */
6694  class Scope {
6695  public:
6696  explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
6697  context_->Enter();
6698  }
6699  V8_INLINE ~Scope() { context_->Exit(); }
6700 
6701  private:
6702  Local<Context> context_;
6703  };
6704 
6705  private:
6706  friend class Value;
6707  friend class Script;
6708  friend class Object;
6709  friend class Function;
6710 
6711  Local<Value> SlowGetEmbedderData(int index);
6712  void* SlowGetAlignedPointerFromEmbedderData(int index);
6713 };
6714 
6715 
6716 /**
6717  * Multiple threads in V8 are allowed, but only one thread at a time is allowed
6718  * to use any given V8 isolate, see the comments in the Isolate class. The
6719  * definition of 'using a V8 isolate' includes accessing handles or holding onto
6720  * object pointers obtained from V8 handles while in the particular V8 isolate.
6721  * It is up to the user of V8 to ensure, perhaps with locking, that this
6722  * constraint is not violated. In addition to any other synchronization
6723  * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
6724  * used to signal thead switches to V8.
6725  *
6726  * v8::Locker is a scoped lock object. While it's active, i.e. between its
6727  * construction and destruction, the current thread is allowed to use the locked
6728  * isolate. V8 guarantees that an isolate can be locked by at most one thread at
6729  * any time. In other words, the scope of a v8::Locker is a critical section.
6730  *
6731  * Sample usage:
6732 * \code
6733  * ...
6734  * {
6735  * v8::Locker locker(isolate);
6736  * v8::Isolate::Scope isolate_scope(isolate);
6737  * ...
6738  * // Code using V8 and isolate goes here.
6739  * ...
6740  * } // Destructor called here
6741  * \endcode
6742  *
6743  * If you wish to stop using V8 in a thread A you can do this either by
6744  * destroying the v8::Locker object as above or by constructing a v8::Unlocker
6745  * object:
6746  *
6747  * \code
6748  * {
6749  * isolate->Exit();
6750  * v8::Unlocker unlocker(isolate);
6751  * ...
6752  * // Code not using V8 goes here while V8 can run in another thread.
6753  * ...
6754  * } // Destructor called here.
6755  * isolate->Enter();
6756  * \endcode
6757  *
6758  * The Unlocker object is intended for use in a long-running callback from V8,
6759  * where you want to release the V8 lock for other threads to use.
6760  *
6761  * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
6762  * given thread. This can be useful if you have code that can be called either
6763  * from code that holds the lock or from code that does not. The Unlocker is
6764  * not recursive so you can not have several Unlockers on the stack at once, and
6765  * you can not use an Unlocker in a thread that is not inside a Locker's scope.
6766  *
6767  * An unlocker will unlock several lockers if it has to and reinstate the
6768  * correct depth of locking on its destruction, e.g.:
6769  *
6770  * \code
6771  * // V8 not locked.
6772  * {
6773  * v8::Locker locker(isolate);
6774  * Isolate::Scope isolate_scope(isolate);
6775  * // V8 locked.
6776  * {
6777  * v8::Locker another_locker(isolate);
6778  * // V8 still locked (2 levels).
6779  * {
6780  * isolate->Exit();
6781  * v8::Unlocker unlocker(isolate);
6782  * // V8 not locked.
6783  * }
6784  * isolate->Enter();
6785  * // V8 locked again (2 levels).
6786  * }
6787  * // V8 still locked (1 level).
6788  * }
6789  * // V8 Now no longer locked.
6790  * \endcode
6791  */
6793  public:
6794  /**
6795  * Initialize Unlocker for a given Isolate.
6796  */
6797  V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
6798 
6800  private:
6801  void Initialize(Isolate* isolate);
6802 
6803  internal::Isolate* isolate_;
6804 };
6805 
6806 
6808  public:
6809  /**
6810  * Initialize Locker for a given Isolate.
6811  */
6812  V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
6813 
6815 
6816  /**
6817  * Returns whether or not the locker for a given isolate, is locked by the
6818  * current thread.
6819  */
6820  static bool IsLocked(Isolate* isolate);
6821 
6822  /**
6823  * Returns whether v8::Locker is being used by this V8 instance.
6824  */
6825  static bool IsActive();
6826 
6827  private:
6828  void Initialize(Isolate* isolate);
6829 
6830  bool has_lock_;
6831  bool top_level_;
6832  internal::Isolate* isolate_;
6833 
6834  // Disallow copying and assigning.
6835  Locker(const Locker&);
6836  void operator=(const Locker&);
6837 };
6838 
6839 
6840 // --- Implementation ---
6841 
6842 
6843 namespace internal {
6844 
6845 const int kApiPointerSize = sizeof(void*); // NOLINT
6846 const int kApiIntSize = sizeof(int); // NOLINT
6847 const int kApiInt64Size = sizeof(int64_t); // NOLINT
6848 
6849 // Tag information for HeapObject.
6850 const int kHeapObjectTag = 1;
6851 const int kHeapObjectTagSize = 2;
6852 const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
6853 
6854 // Tag information for Smi.
6855 const int kSmiTag = 0;
6856 const int kSmiTagSize = 1;
6857 const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
6858 
6859 template <size_t ptr_size> struct SmiTagging;
6860 
6861 template<int kSmiShiftSize>
6862 V8_INLINE internal::Object* IntToSmi(int value) {
6863  int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
6864  uintptr_t tagged_value =
6865  (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
6866  return reinterpret_cast<internal::Object*>(tagged_value);
6867 }
6868 
6869 // Smi constants for 32-bit systems.
6870 template <> struct SmiTagging<4> {
6871  enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
6872  static int SmiShiftSize() { return kSmiShiftSize; }
6873  static int SmiValueSize() { return kSmiValueSize; }
6874  V8_INLINE static int SmiToInt(const internal::Object* value) {
6875  int shift_bits = kSmiTagSize + kSmiShiftSize;
6876  // Throw away top 32 bits and shift down (requires >> to be sign extending).
6877  return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
6878  }
6879  V8_INLINE static internal::Object* IntToSmi(int value) {
6881  }
6882  V8_INLINE static bool IsValidSmi(intptr_t value) {
6883  // To be representable as an tagged small integer, the two
6884  // most-significant bits of 'value' must be either 00 or 11 due to
6885  // sign-extension. To check this we add 01 to the two
6886  // most-significant bits, and check if the most-significant bit is 0
6887  //
6888  // CAUTION: The original code below:
6889  // bool result = ((value + 0x40000000) & 0x80000000) == 0;
6890  // may lead to incorrect results according to the C language spec, and
6891  // in fact doesn't work correctly with gcc4.1.1 in some cases: The
6892  // compiler may produce undefined results in case of signed integer
6893  // overflow. The computation must be done w/ unsigned ints.
6894  return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
6895  }
6896 };
6897 
6898 // Smi constants for 64-bit systems.
6899 template <> struct SmiTagging<8> {
6900  enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
6901  static int SmiShiftSize() { return kSmiShiftSize; }
6902  static int SmiValueSize() { return kSmiValueSize; }
6903  V8_INLINE static int SmiToInt(const internal::Object* value) {
6904  int shift_bits = kSmiTagSize + kSmiShiftSize;
6905  // Shift down and throw away top 32 bits.
6906  return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
6907  }
6908  V8_INLINE static internal::Object* IntToSmi(int value) {
6910  }
6911  V8_INLINE static bool IsValidSmi(intptr_t value) {
6912  // To be representable as a long smi, the value must be a 32-bit integer.
6913  return (value == static_cast<int32_t>(value));
6914  }
6915 };
6916 
6920 V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
6921 V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
6922 
6923 /**
6924  * This class exports constants and functionality from within v8 that
6925  * is necessary to implement inline functions in the v8 api. Don't
6926  * depend on functions and constants defined here.
6927  */
6928 class Internals {
6929  public:
6930  // These values match non-compiler-dependent values defined within
6931  // the implementation of v8.
6932  static const int kHeapObjectMapOffset = 0;
6935  static const int kStringResourceOffset = 3 * kApiPointerSize;
6936 
6937  static const int kOddballKindOffset = 3 * kApiPointerSize;
6939  static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
6940  static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
6941  static const int kContextHeaderSize = 2 * kApiPointerSize;
6942  static const int kContextEmbedderDataIndex = 81;
6943  static const int kFullStringRepresentationMask = 0x07;
6944  static const int kStringEncodingMask = 0x4;
6945  static const int kExternalTwoByteRepresentationTag = 0x02;
6946  static const int kExternalOneByteRepresentationTag = 0x06;
6947 
6950  4 * kApiPointerSize;
6953  static const int kIsolateRootsOffset =
6956  static const int kUndefinedValueRootIndex = 5;
6957  static const int kNullValueRootIndex = 7;
6958  static const int kTrueValueRootIndex = 8;
6959  static const int kFalseValueRootIndex = 9;
6960  static const int kEmptyStringRootIndex = 10;
6961 
6962  // The external allocation limit should be below 256 MB on all architectures
6963  // to avoid that resource-constrained embedders run low on memory.
6964  static const int kExternalAllocationLimit = 192 * 1024 * 1024;
6965 
6966  static const int kNodeClassIdOffset = 1 * kApiPointerSize;
6967  static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
6968  static const int kNodeStateMask = 0x7;
6969  static const int kNodeStateIsWeakValue = 2;
6970  static const int kNodeStateIsPendingValue = 3;
6971  static const int kNodeStateIsNearDeathValue = 4;
6972  static const int kNodeIsIndependentShift = 3;
6973  static const int kNodeIsPartiallyDependentShift = 4;
6974 
6975  static const int kJSObjectType = 0xbe;
6976  static const int kFirstNonstringType = 0x80;
6977  static const int kOddballType = 0x83;
6978  static const int kForeignType = 0x87;
6979 
6980  static const int kUndefinedOddballKind = 5;
6981  static const int kNullOddballKind = 3;
6982 
6983  static const uint32_t kNumIsolateDataSlots = 4;
6984 
6985  V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
6986  V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
6987 #ifdef V8_ENABLE_CHECKS
6988  CheckInitializedImpl(isolate);
6989 #endif
6990  }
6991 
6992  V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
6993  return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
6994  kHeapObjectTag);
6995  }
6996 
6997  V8_INLINE static int SmiValue(const internal::Object* value) {
6998  return PlatformSmiTagging::SmiToInt(value);
6999  }
7000 
7001  V8_INLINE static internal::Object* IntToSmi(int value) {
7002  return PlatformSmiTagging::IntToSmi(value);
7003  }
7004 
7005  V8_INLINE static bool IsValidSmi(intptr_t value) {
7007  }
7008 
7009  V8_INLINE static int GetInstanceType(const internal::Object* obj) {
7010  typedef internal::Object O;
7012  // Map::InstanceType is defined so that it will always be loaded into
7013  // the LS 8 bits of one 16-bit word, regardless of endianess.
7014  return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
7015  }
7016 
7017  V8_INLINE static int GetOddballKind(const internal::Object* obj) {
7018  typedef internal::Object O;
7020  }
7021 
7022  V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
7023  int representation = (instance_type & kFullStringRepresentationMask);
7024  return representation == kExternalTwoByteRepresentationTag;
7025  }
7026 
7027  V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
7028  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7029  return *addr & static_cast<uint8_t>(1U << shift);
7030  }
7031 
7032  V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
7033  bool value, int shift) {
7034  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7035  uint8_t mask = static_cast<uint8_t>(1U << shift);
7036  *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
7037  }
7038 
7039  V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
7040  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7041  return *addr & kNodeStateMask;
7042  }
7043 
7044  V8_INLINE static void UpdateNodeState(internal::Object** obj,
7045  uint8_t value) {
7046  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
7047  *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
7048  }
7049 
7050  V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
7051  uint32_t slot,
7052  void* data) {
7053  uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
7055  *reinterpret_cast<void**>(addr) = data;
7056  }
7057 
7058  V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
7059  uint32_t slot) {
7060  const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
7062  return *reinterpret_cast<void* const*>(addr);
7063  }
7064 
7065  V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
7066  int index) {
7067  uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
7068  return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
7069  }
7070 
7071  template <typename T>
7072  V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
7073  const uint8_t* addr =
7074  reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
7075  return *reinterpret_cast<const T*>(addr);
7076  }
7077 
7078  template <typename T>
7079  V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
7080  typedef internal::Object O;
7081  typedef internal::Internals I;
7082  O* ctx = *reinterpret_cast<O* const*>(context);
7083  int embedder_data_offset = I::kContextHeaderSize +
7085  O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
7086  int value_offset =
7088  return I::ReadField<T>(embedder_data, value_offset);
7089  }
7090 };
7091 
7092 } // namespace internal
7093 
7094 
7095 template <class T>
7096 Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
7097  return New(isolate, that.val_);
7098 }
7099 
7100 template <class T>
7101 Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
7102  return New(isolate, that.val_);
7103 }
7104 
7105 
7106 template <class T>
7107 Local<T> Local<T>::New(Isolate* isolate, T* that) {
7108  if (that == NULL) return Local<T>();
7109  T* that_ptr = that;
7110  internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
7111  return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
7112  reinterpret_cast<internal::Isolate*>(isolate), *p)));
7113 }
7114 
7115 
7116 template<class T>
7117 template<class S>
7118 void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
7119  TYPE_CHECK(T, S);
7120  V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
7121 }
7122 
7123 
7124 template<class T>
7125 Local<T> Eternal<T>::Get(Isolate* isolate) {
7126  return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
7127 }
7128 
7129 
7130 template <class T>
7132  if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
7133  return Local<T>(val_);
7134 }
7135 
7136 
7137 template <class T>
7138 void* WeakCallbackInfo<T>::GetInternalField(int index) const {
7139 #ifdef V8_ENABLE_CHECKS
7140  if (index < 0 || index >= kInternalFieldsInWeakCallback) {
7141  V8::InternalFieldOutOfBounds(index);
7142  }
7143 #endif
7144  return internal_fields_[index];
7145 }
7146 
7147 
7148 template <class T>
7149 T* PersistentBase<T>::New(Isolate* isolate, T* that) {
7150  if (that == NULL) return NULL;
7151  internal::Object** p = reinterpret_cast<internal::Object**>(that);
7152  return reinterpret_cast<T*>(
7153  V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
7154  p));
7155 }
7156 
7157 
7158 template <class T, class M>
7159 template <class S, class M2>
7160 void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
7161  TYPE_CHECK(T, S);
7162  this->Reset();
7163  if (that.IsEmpty()) return;
7164  internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
7165  this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
7166  M::Copy(that, this);
7167 }
7168 
7169 
7170 template <class T>
7171 bool PersistentBase<T>::IsIndependent() const {
7172  typedef internal::Internals I;
7173  if (this->IsEmpty()) return false;
7174  return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7176 }
7177 
7178 
7179 template <class T>
7180 bool PersistentBase<T>::IsNearDeath() const {
7181  typedef internal::Internals I;
7182  if (this->IsEmpty()) return false;
7183  uint8_t node_state =
7184  I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
7185  return node_state == I::kNodeStateIsNearDeathValue ||
7186  node_state == I::kNodeStateIsPendingValue;
7187 }
7188 
7189 
7190 template <class T>
7191 bool PersistentBase<T>::IsWeak() const {
7192  typedef internal::Internals I;
7193  if (this->IsEmpty()) return false;
7194  return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
7196 }
7197 
7198 
7199 template <class T>
7200 void PersistentBase<T>::Reset() {
7201  if (this->IsEmpty()) return;
7202  V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
7203  val_ = 0;
7204 }
7205 
7206 
7207 template <class T>
7208 template <class S>
7209 void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
7210  TYPE_CHECK(T, S);
7211  Reset();
7212  if (other.IsEmpty()) return;
7213  this->val_ = New(isolate, other.val_);
7214 }
7215 
7216 
7217 template <class T>
7218 template <class S>
7219 void PersistentBase<T>::Reset(Isolate* isolate,
7220  const PersistentBase<S>& other) {
7221  TYPE_CHECK(T, S);
7222  Reset();
7223  if (other.IsEmpty()) return;
7224  this->val_ = New(isolate, other.val_);
7225 }
7226 
7227 
7228 template <class T>
7229 template <typename S, typename P>
7230 void PersistentBase<T>::SetWeak(
7231  P* parameter,
7232  typename WeakCallbackData<S, P>::Callback callback) {
7233  TYPE_CHECK(S, T);
7234  typedef typename WeakCallbackData<Value, void>::Callback Callback;
7235  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7236  reinterpret_cast<Callback>(callback));
7237 }
7238 
7239 
7240 template <class T>
7241 template <typename P>
7243  P* parameter,
7244  typename WeakCallbackData<T, P>::Callback callback) {
7245  SetWeak<T, P>(parameter, callback);
7246 }
7247 
7248 
7249 template <class T>
7250 template <typename P>
7251 void PersistentBase<T>::SetPhantom(
7252  P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7253  int internal_field_index1, int internal_field_index2) {
7254  typedef typename WeakCallbackInfo<void>::Callback Callback;
7255  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7256  internal_field_index1, internal_field_index2,
7257  reinterpret_cast<Callback>(callback));
7258 }
7259 
7260 
7261 template <class T>
7262 template <typename P>
7264  P* parameter, typename WeakCallbackInfo<P>::Callback callback,
7265  WeakCallbackType type) {
7266  typedef typename WeakCallbackInfo<void>::Callback Callback;
7267  V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_), parameter,
7268  reinterpret_cast<Callback>(callback), type);
7269 }
7270 
7271 
7272 template <class T>
7273 template <typename P>
7274 P* PersistentBase<T>::ClearWeak() {
7275  return reinterpret_cast<P*>(
7276  V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
7277 }
7278 
7279 
7280 template <class T>
7282  typedef internal::Internals I;
7283  if (this->IsEmpty()) return;
7284  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7285  true,
7287 }
7288 
7289 
7290 template <class T>
7292  typedef internal::Internals I;
7293  if (this->IsEmpty()) return;
7294  I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
7295  true,
7297 }
7298 
7299 
7300 template <class T>
7301 void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
7302  typedef internal::Internals I;
7303  if (this->IsEmpty()) return;
7304  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7305  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7306  *reinterpret_cast<uint16_t*>(addr) = class_id;
7307 }
7308 
7309 
7310 template <class T>
7311 uint16_t PersistentBase<T>::WrapperClassId() const {
7312  typedef internal::Internals I;
7313  if (this->IsEmpty()) return 0;
7314  internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
7315  uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
7316  return *reinterpret_cast<uint16_t*>(addr);
7317 }
7318 
7319 
7320 template<typename T>
7321 ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
7322 
7323 template<typename T>
7324 template<typename S>
7325 void ReturnValue<T>::Set(const Persistent<S>& handle) {
7326  TYPE_CHECK(T, S);
7327  if (V8_UNLIKELY(handle.IsEmpty())) {
7328  *value_ = GetDefaultValue();
7329  } else {
7330  *value_ = *reinterpret_cast<internal::Object**>(*handle);
7331  }
7332 }
7333 
7334 template <typename T>
7335 template <typename S>
7336 void ReturnValue<T>::Set(const Global<S>& handle) {
7337  TYPE_CHECK(T, S);
7338  if (V8_UNLIKELY(handle.IsEmpty())) {
7339  *value_ = GetDefaultValue();
7340  } else {
7341  *value_ = *reinterpret_cast<internal::Object**>(*handle);
7342  }
7343 }
7344 
7345 template <typename T>
7346 template <typename S>
7347 void ReturnValue<T>::Set(const Local<S> handle) {
7348  TYPE_CHECK(T, S);
7349  if (V8_UNLIKELY(handle.IsEmpty())) {
7350  *value_ = GetDefaultValue();
7351  } else {
7352  *value_ = *reinterpret_cast<internal::Object**>(*handle);
7353  }
7354 }
7355 
7356 template<typename T>
7357 void ReturnValue<T>::Set(double i) {
7358  TYPE_CHECK(T, Number);
7360 }
7361 
7362 template<typename T>
7363 void ReturnValue<T>::Set(int32_t i) {
7364  TYPE_CHECK(T, Integer);
7365  typedef internal::Internals I;
7366  if (V8_LIKELY(I::IsValidSmi(i))) {
7367  *value_ = I::IntToSmi(i);
7368  return;
7369  }
7371 }
7372 
7373 template<typename T>
7374 void ReturnValue<T>::Set(uint32_t i) {
7375  TYPE_CHECK(T, Integer);
7376  // Can't simply use INT32_MAX here for whatever reason.
7377  bool fits_into_int32_t = (i & (1U << 31)) == 0;
7378  if (V8_LIKELY(fits_into_int32_t)) {
7379  Set(static_cast<int32_t>(i));
7380  return;
7381  }
7383 }
7384 
7385 template<typename T>
7386 void ReturnValue<T>::Set(bool value) {
7387  TYPE_CHECK(T, Boolean);
7388  typedef internal::Internals I;
7389  int root_index;
7390  if (value) {
7391  root_index = I::kTrueValueRootIndex;
7392  } else {
7393  root_index = I::kFalseValueRootIndex;
7394  }
7395  *value_ = *I::GetRoot(GetIsolate(), root_index);
7396 }
7397 
7398 template<typename T>
7399 void ReturnValue<T>::SetNull() {
7400  TYPE_CHECK(T, Primitive);
7401  typedef internal::Internals I;
7403 }
7404 
7405 template<typename T>
7407  TYPE_CHECK(T, Primitive);
7408  typedef internal::Internals I;
7410 }
7411 
7412 template<typename T>
7414  TYPE_CHECK(T, String);
7415  typedef internal::Internals I;
7417 }
7418 
7419 template<typename T>
7421  // Isolate is always the pointer below the default value on the stack.
7422  return *reinterpret_cast<Isolate**>(&value_[-2]);
7423 }
7424 
7425 template<typename T>
7426 template<typename S>
7427 void ReturnValue<T>::Set(S* whatever) {
7428  // Uncompilable to prevent inadvertent misuse.
7429  TYPE_CHECK(S*, Primitive);
7430 }
7431 
7432 template<typename T>
7433 internal::Object* ReturnValue<T>::GetDefaultValue() {
7434  // Default value is always the pointer below value_ on the stack.
7435  return value_[-1];
7436 }
7437 
7438 
7439 template<typename T>
7441  internal::Object** values,
7442  int length,
7443  bool is_construct_call)
7444  : implicit_args_(implicit_args),
7445  values_(values),
7446  length_(length),
7447  is_construct_call_(is_construct_call) { }
7448 
7449 
7450 template<typename T>
7452  if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
7453  return Local<Value>(reinterpret_cast<Value*>(values_ - i));
7454 }
7455 
7456 
7457 template<typename T>
7459  return Local<Function>(reinterpret_cast<Function*>(
7461 }
7462 
7463 
7464 template<typename T>
7466  return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
7467 }
7468 
7469 
7470 template<typename T>
7472  return Local<Object>(reinterpret_cast<Object*>(
7474 }
7475 
7476 
7477 template<typename T>
7479  return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
7480 }
7481 
7482 
7483 template<typename T>
7485  return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
7486 }
7487 
7488 
7489 template<typename T>
7492 }
7493 
7494 
7495 template<typename T>
7497  return is_construct_call_ & 0x1;
7498 }
7499 
7500 
7501 template<typename T>
7502 int FunctionCallbackInfo<T>::Length() const {
7503  return length_;
7504 }
7505 
7507  Local<Integer> resource_line_offset,
7508  Local<Integer> resource_column_offset,
7509  Local<Boolean> resource_is_shared_cross_origin,
7510  Local<Integer> script_id,
7511  Local<Boolean> resource_is_embedder_debug_script,
7512  Local<Value> source_map_url,
7513  Local<Boolean> resource_is_opaque)
7514  : resource_name_(resource_name),
7515  resource_line_offset_(resource_line_offset),
7516  resource_column_offset_(resource_column_offset),
7517  options_(!resource_is_embedder_debug_script.IsEmpty() &&
7518  resource_is_embedder_debug_script->IsTrue(),
7519  !resource_is_shared_cross_origin.IsEmpty() &&
7520  resource_is_shared_cross_origin->IsTrue(),
7521  !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue()),
7522  script_id_(script_id),
7523  source_map_url_(source_map_url) {}
7524 
7525 Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
7526 
7527 
7529  return resource_line_offset_;
7530 }
7531 
7532 
7534  return resource_column_offset_;
7535 }
7536 
7537 
7538 Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
7539 
7540 
7541 Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
7542 
7543 
7545  CachedData* data)
7546  : source_string(string),
7547  resource_name(origin.ResourceName()),
7548  resource_line_offset(origin.ResourceLineOffset()),
7549  resource_column_offset(origin.ResourceColumnOffset()),
7550  resource_options(origin.Options()),
7551  source_map_url(origin.SourceMapUrl()),
7552  cached_data(data) {}
7553 
7554 
7556  CachedData* data)
7557  : source_string(string), cached_data(data) {}
7558 
7559 
7561  delete cached_data;
7562 }
7563 
7564 
7566  const {
7567  return cached_data;
7568 }
7569 
7570 
7571 Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
7572  return value ? True(isolate) : False(isolate);
7573 }
7574 
7575 
7576 void Template::Set(Isolate* isolate, const char* name, v8::Local<Data> value) {
7579  value);
7580 }
7581 
7582 
7584 #ifndef V8_ENABLE_CHECKS
7585  typedef internal::Object O;
7586  typedef internal::HeapObject HO;
7587  typedef internal::Internals I;
7588  O* obj = *reinterpret_cast<O**>(this);
7589  // Fast path: If the object is a plain JSObject, which is the common case, we
7590  // know where to find the internal fields and can return the value directly.
7591  if (I::GetInstanceType(obj) == I::kJSObjectType) {
7592  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7593  O* value = I::ReadField<O*>(obj, offset);
7594  O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
7595  return Local<Value>(reinterpret_cast<Value*>(result));
7596  }
7597 #endif
7598  return SlowGetInternalField(index);
7599 }
7600 
7601 
7603 #ifndef V8_ENABLE_CHECKS
7604  typedef internal::Object O;
7605  typedef internal::Internals I;
7606  O* obj = *reinterpret_cast<O**>(this);
7607  // Fast path: If the object is a plain JSObject, which is the common case, we
7608  // know where to find the internal fields and can return the value directly.
7610  int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
7611  return I::ReadField<void*>(obj, offset);
7612  }
7613 #endif
7614  return SlowGetAlignedPointerFromInternalField(index);
7615 }
7616 
7617 
7618 String* String::Cast(v8::Value* value) {
7619 #ifdef V8_ENABLE_CHECKS
7620  CheckCast(value);
7621 #endif
7622  return static_cast<String*>(value);
7623 }
7624 
7625 
7627  typedef internal::Object* S;
7628  typedef internal::Internals I;
7629  I::CheckInitialized(isolate);
7630  S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
7631  return Local<String>(reinterpret_cast<String*>(slot));
7632 }
7633 
7634 
7636  typedef internal::Object O;
7637  typedef internal::Internals I;
7638  O* obj = *reinterpret_cast<O* const*>(this);
7639  String::ExternalStringResource* result;
7641  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7642  result = reinterpret_cast<String::ExternalStringResource*>(value);
7643  } else {
7644  result = NULL;
7645  }
7646 #ifdef V8_ENABLE_CHECKS
7647  VerifyExternalStringResource(result);
7648 #endif
7649  return result;
7650 }
7651 
7652 
7654  String::Encoding* encoding_out) const {
7655  typedef internal::Object O;
7656  typedef internal::Internals I;
7657  O* obj = *reinterpret_cast<O* const*>(this);
7659  *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
7660  ExternalStringResourceBase* resource = NULL;
7661  if (type == I::kExternalOneByteRepresentationTag ||
7663  void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
7664  resource = static_cast<ExternalStringResourceBase*>(value);
7665  }
7666 #ifdef V8_ENABLE_CHECKS
7667  VerifyExternalStringResourceBase(resource, *encoding_out);
7668 #endif
7669  return resource;
7670 }
7671 
7672 
7673 bool Value::IsUndefined() const {
7674 #ifdef V8_ENABLE_CHECKS
7675  return FullIsUndefined();
7676 #else
7677  return QuickIsUndefined();
7678 #endif
7679 }
7680 
7681 bool Value::QuickIsUndefined() const {
7682  typedef internal::Object O;
7683  typedef internal::Internals I;
7684  O* obj = *reinterpret_cast<O* const*>(this);
7685  if (!I::HasHeapObjectTag(obj)) return false;
7686  if (I::GetInstanceType(obj) != I::kOddballType) return false;
7688 }
7689 
7690 
7691 bool Value::IsNull() const {
7692 #ifdef V8_ENABLE_CHECKS
7693  return FullIsNull();
7694 #else
7695  return QuickIsNull();
7696 #endif
7697 }
7698 
7699 bool Value::QuickIsNull() const {
7700  typedef internal::Object O;
7701  typedef internal::Internals I;
7702  O* obj = *reinterpret_cast<O* const*>(this);
7703  if (!I::HasHeapObjectTag(obj)) return false;
7704  if (I::GetInstanceType(obj) != I::kOddballType) return false;
7705  return (I::GetOddballKind(obj) == I::kNullOddballKind);
7706 }
7707 
7708 
7709 bool Value::IsString() const {
7710 #ifdef V8_ENABLE_CHECKS
7711  return FullIsString();
7712 #else
7713  return QuickIsString();
7714 #endif
7715 }
7716 
7717 bool Value::QuickIsString() const {
7718  typedef internal::Object O;
7719  typedef internal::Internals I;
7720  O* obj = *reinterpret_cast<O* const*>(this);
7721  if (!I::HasHeapObjectTag(obj)) return false;
7723 }
7724 
7725 
7726 template <class T> Value* Value::Cast(T* value) {
7727  return static_cast<Value*>(value);
7728 }
7729 
7730 
7731 Local<Boolean> Value::ToBoolean() const {
7733  .FromMaybe(Local<Boolean>());
7734 }
7735 
7736 
7737 Local<Number> Value::ToNumber() const {
7739  .FromMaybe(Local<Number>());
7740 }
7741 
7742 
7743 Local<String> Value::ToString() const {
7745  .FromMaybe(Local<String>());
7746 }
7747 
7748 
7749 Local<String> Value::ToDetailString() const {
7751  .FromMaybe(Local<String>());
7752 }
7753 
7754 
7755 Local<Object> Value::ToObject() const {
7757  .FromMaybe(Local<Object>());
7758 }
7759 
7760 
7761 Local<Integer> Value::ToInteger() const {
7763  .FromMaybe(Local<Integer>());
7764 }
7765 
7766 
7767 Local<Uint32> Value::ToUint32() const {
7769  .FromMaybe(Local<Uint32>());
7770 }
7771 
7772 
7773 Local<Int32> Value::ToInt32() const {
7775  .FromMaybe(Local<Int32>());
7776 }
7777 
7778 
7780 #ifdef V8_ENABLE_CHECKS
7781  CheckCast(value);
7782 #endif
7783  return static_cast<Boolean*>(value);
7784 }
7785 
7786 
7787 Name* Name::Cast(v8::Value* value) {
7788 #ifdef V8_ENABLE_CHECKS
7789  CheckCast(value);
7790 #endif
7791  return static_cast<Name*>(value);
7792 }
7793 
7794 
7795 Symbol* Symbol::Cast(v8::Value* value) {
7796 #ifdef V8_ENABLE_CHECKS
7797  CheckCast(value);
7798 #endif
7799  return static_cast<Symbol*>(value);
7800 }
7801 
7802 
7803 Number* Number::Cast(v8::Value* value) {
7804 #ifdef V8_ENABLE_CHECKS
7805  CheckCast(value);
7806 #endif
7807  return static_cast<Number*>(value);
7808 }
7809 
7810 
7812 #ifdef V8_ENABLE_CHECKS
7813  CheckCast(value);
7814 #endif
7815  return static_cast<Integer*>(value);
7816 }
7817 
7818 
7819 Int32* Int32::Cast(v8::Value* value) {
7820 #ifdef V8_ENABLE_CHECKS
7821  CheckCast(value);
7822 #endif
7823  return static_cast<Int32*>(value);
7824 }
7825 
7826 
7827 Uint32* Uint32::Cast(v8::Value* value) {
7828 #ifdef V8_ENABLE_CHECKS
7829  CheckCast(value);
7830 #endif
7831  return static_cast<Uint32*>(value);
7832 }
7833 
7834 
7835 Date* Date::Cast(v8::Value* value) {
7836 #ifdef V8_ENABLE_CHECKS
7837  CheckCast(value);
7838 #endif
7839  return static_cast<Date*>(value);
7840 }
7841 
7842 
7844 #ifdef V8_ENABLE_CHECKS
7845  CheckCast(value);
7846 #endif
7847  return static_cast<StringObject*>(value);
7848 }
7849 
7850 
7852 #ifdef V8_ENABLE_CHECKS
7853  CheckCast(value);
7854 #endif
7855  return static_cast<SymbolObject*>(value);
7856 }
7857 
7858 
7860 #ifdef V8_ENABLE_CHECKS
7861  CheckCast(value);
7862 #endif
7863  return static_cast<NumberObject*>(value);
7864 }
7865 
7866 
7868 #ifdef V8_ENABLE_CHECKS
7869  CheckCast(value);
7870 #endif
7871  return static_cast<BooleanObject*>(value);
7872 }
7873 
7874 
7875 RegExp* RegExp::Cast(v8::Value* value) {
7876 #ifdef V8_ENABLE_CHECKS
7877  CheckCast(value);
7878 #endif
7879  return static_cast<RegExp*>(value);
7880 }
7881 
7882 
7883 Object* Object::Cast(v8::Value* value) {
7884 #ifdef V8_ENABLE_CHECKS
7885  CheckCast(value);
7886 #endif
7887  return static_cast<Object*>(value);
7888 }
7889 
7890 
7891 Array* Array::Cast(v8::Value* value) {
7892 #ifdef V8_ENABLE_CHECKS
7893  CheckCast(value);
7894 #endif
7895  return static_cast<Array*>(value);
7896 }
7897 
7898 
7899 Map* Map::Cast(v8::Value* value) {
7900 #ifdef V8_ENABLE_CHECKS
7901  CheckCast(value);
7902 #endif
7903  return static_cast<Map*>(value);
7904 }
7905 
7906 
7907 Set* Set::Cast(v8::Value* value) {
7908 #ifdef V8_ENABLE_CHECKS
7909  CheckCast(value);
7910 #endif
7911  return static_cast<Set*>(value);
7912 }
7913 
7914 
7916 #ifdef V8_ENABLE_CHECKS
7917  CheckCast(value);
7918 #endif
7919  return static_cast<Promise*>(value);
7920 }
7921 
7922 
7924 #ifdef V8_ENABLE_CHECKS
7925  CheckCast(value);
7926 #endif
7927  return static_cast<Promise::Resolver*>(value);
7928 }
7929 
7930 
7932 #ifdef V8_ENABLE_CHECKS
7933  CheckCast(value);
7934 #endif
7935  return static_cast<ArrayBuffer*>(value);
7936 }
7937 
7938 
7940 #ifdef V8_ENABLE_CHECKS
7941  CheckCast(value);
7942 #endif
7943  return static_cast<ArrayBufferView*>(value);
7944 }
7945 
7946 
7948 #ifdef V8_ENABLE_CHECKS
7949  CheckCast(value);
7950 #endif
7951  return static_cast<TypedArray*>(value);
7952 }
7953 
7954 
7956 #ifdef V8_ENABLE_CHECKS
7957  CheckCast(value);
7958 #endif
7959  return static_cast<Uint8Array*>(value);
7960 }
7961 
7962 
7964 #ifdef V8_ENABLE_CHECKS
7965  CheckCast(value);
7966 #endif
7967  return static_cast<Int8Array*>(value);
7968 }
7969 
7970 
7972 #ifdef V8_ENABLE_CHECKS
7973  CheckCast(value);
7974 #endif
7975  return static_cast<Uint16Array*>(value);
7976 }
7977 
7978 
7980 #ifdef V8_ENABLE_CHECKS
7981  CheckCast(value);
7982 #endif
7983  return static_cast<Int16Array*>(value);
7984 }
7985 
7986 
7988 #ifdef V8_ENABLE_CHECKS
7989  CheckCast(value);
7990 #endif
7991  return static_cast<Uint32Array*>(value);
7992 }
7993 
7994 
7996 #ifdef V8_ENABLE_CHECKS
7997  CheckCast(value);
7998 #endif
7999  return static_cast<Int32Array*>(value);
8000 }
8001 
8002 
8004 #ifdef V8_ENABLE_CHECKS
8005  CheckCast(value);
8006 #endif
8007  return static_cast<Float32Array*>(value);
8008 }
8009 
8010 
8012 #ifdef V8_ENABLE_CHECKS
8013  CheckCast(value);
8014 #endif
8015  return static_cast<Float64Array*>(value);
8016 }
8017 
8018 
8020 #ifdef V8_ENABLE_CHECKS
8021  CheckCast(value);
8022 #endif
8023  return static_cast<Uint8ClampedArray*>(value);
8024 }
8025 
8026 
8028 #ifdef V8_ENABLE_CHECKS
8029  CheckCast(value);
8030 #endif
8031  return static_cast<DataView*>(value);
8032 }
8033 
8034 
8036 #ifdef V8_ENABLE_CHECKS
8037  CheckCast(value);
8038 #endif
8039  return static_cast<SharedArrayBuffer*>(value);
8040 }
8041 
8042 
8044 #ifdef V8_ENABLE_CHECKS
8045  CheckCast(value);
8046 #endif
8047  return static_cast<Function*>(value);
8048 }
8049 
8050 
8052 #ifdef V8_ENABLE_CHECKS
8053  CheckCast(value);
8054 #endif
8055  return static_cast<External*>(value);
8056 }
8057 
8058 
8059 template<typename T>
8061  return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
8062 }
8063 
8064 
8065 template<typename T>
8067  return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
8068 }
8069 
8070 
8071 template<typename T>
8073  return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
8074 }
8075 
8076 
8077 template<typename T>
8079  return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
8080 }
8081 
8082 
8083 template<typename T>
8085  return ReturnValue<T>(&args_[kReturnValueIndex]);
8086 }
8087 
8088 
8090  typedef internal::Object* S;
8091  typedef internal::Internals I;
8092  I::CheckInitialized(isolate);
8093  S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
8094  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8095 }
8096 
8097 
8099  typedef internal::Object* S;
8100  typedef internal::Internals I;
8101  I::CheckInitialized(isolate);
8102  S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
8103  return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
8104 }
8105 
8106 
8108  typedef internal::Object* S;
8109  typedef internal::Internals I;
8110  I::CheckInitialized(isolate);
8111  S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
8112  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8113 }
8114 
8115 
8117  typedef internal::Object* S;
8118  typedef internal::Internals I;
8119  I::CheckInitialized(isolate);
8120  S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
8121  return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
8122 }
8123 
8124 
8125 void Isolate::SetData(uint32_t slot, void* data) {
8126  typedef internal::Internals I;
8127  I::SetEmbedderData(this, slot, data);
8128 }
8129 
8130 
8131 void* Isolate::GetData(uint32_t slot) {
8132  typedef internal::Internals I;
8133  return I::GetEmbedderData(this, slot);
8134 }
8135 
8136 
8138  typedef internal::Internals I;
8139  return I::kNumIsolateDataSlots;
8140 }
8141 
8142 
8144  int64_t change_in_bytes) {
8145  typedef internal::Internals I;
8146  int64_t* amount_of_external_allocated_memory =
8147  reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
8149  int64_t* amount_of_external_allocated_memory_at_last_global_gc =
8150  reinterpret_cast<int64_t*>(
8151  reinterpret_cast<uint8_t*>(this) +
8153  int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
8154  if (change_in_bytes > 0 &&
8155  amount - *amount_of_external_allocated_memory_at_last_global_gc >
8157  CollectAllGarbage("external memory allocation limit reached.");
8158  }
8159  *amount_of_external_allocated_memory = amount;
8160  return *amount_of_external_allocated_memory;
8161 }
8162 
8163 
8164 template<typename T>
8165 void Isolate::SetObjectGroupId(const Persistent<T>& object,
8166  UniqueId id) {
8167  TYPE_CHECK(Value, T);
8168  SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
8169 }
8170 
8171 
8172 template<typename T>
8174  const Persistent<T>& object) {
8175  TYPE_CHECK(Value, T);
8176  SetReferenceFromGroup(id,
8177  reinterpret_cast<v8::internal::Object**>(object.val_));
8178 }
8179 
8180 
8181 template<typename T, typename S>
8182 void Isolate::SetReference(const Persistent<T>& parent,
8183  const Persistent<S>& child) {
8184  TYPE_CHECK(Object, T);
8185  TYPE_CHECK(Value, S);
8186  SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
8187  reinterpret_cast<v8::internal::Object**>(child.val_));
8188 }
8189 
8190 
8192 #ifndef V8_ENABLE_CHECKS
8193  typedef internal::Object O;
8194  typedef internal::HeapObject HO;
8195  typedef internal::Internals I;
8196  HO* context = *reinterpret_cast<HO**>(this);
8197  O** result =
8198  HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
8199  return Local<Value>(reinterpret_cast<Value*>(result));
8200 #else
8201  return SlowGetEmbedderData(index);
8202 #endif
8203 }
8204 
8205 
8207 #ifndef V8_ENABLE_CHECKS
8208  typedef internal::Internals I;
8209  return I::ReadEmbedderData<void*>(this, index);
8210 #else
8211  return SlowGetAlignedPointerFromEmbedderData(index);
8212 #endif
8213 }
8214 
8215 
8216 void V8::SetAllowCodeGenerationFromStringsCallback(
8218  Isolate* isolate = Isolate::GetCurrent();
8220 }
8221 
8222 
8223 bool V8::IsDead() {
8224  Isolate* isolate = Isolate::GetCurrent();
8225  return isolate->IsDead();
8226 }
8227 
8228 
8229 bool V8::AddMessageListener(MessageCallback that, Local<Value> data) {
8230  Isolate* isolate = Isolate::GetCurrent();
8231  return isolate->AddMessageListener(that, data);
8232 }
8233 
8234 
8235 void V8::RemoveMessageListeners(MessageCallback that) {
8236  Isolate* isolate = Isolate::GetCurrent();
8237  isolate->RemoveMessageListeners(that);
8238 }
8239 
8240 
8241 void V8::SetFailedAccessCheckCallbackFunction(
8242  FailedAccessCheckCallback callback) {
8243  Isolate* isolate = Isolate::GetCurrent();
8245 }
8246 
8247 
8248 void V8::SetCaptureStackTraceForUncaughtExceptions(
8249  bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
8250  Isolate* isolate = Isolate::GetCurrent();
8251  isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
8252  options);
8253 }
8254 
8255 
8256 void V8::SetFatalErrorHandler(FatalErrorCallback callback) {
8257  Isolate* isolate = Isolate::GetCurrent();
8258  isolate->SetFatalErrorHandler(callback);
8259 }
8260 
8261 
8262 void V8::RemoveGCPrologueCallback(GCPrologueCallback callback) {
8263  Isolate* isolate = Isolate::GetCurrent();
8265  reinterpret_cast<v8::Isolate::GCPrologueCallback>(callback));
8266 }
8267 
8268 
8269 void V8::RemoveGCEpilogueCallback(GCEpilogueCallback callback) {
8270  Isolate* isolate = Isolate::GetCurrent();
8272  reinterpret_cast<v8::Isolate::GCEpilogueCallback>(callback));
8273 }
8274 
8275 
8276 void V8::AddMemoryAllocationCallback(MemoryAllocationCallback callback,
8277  ObjectSpace space,
8278  AllocationAction action) {
8279  Isolate* isolate = Isolate::GetCurrent();
8280  isolate->AddMemoryAllocationCallback(callback, space, action);
8281 }
8282 
8283 
8284 void V8::RemoveMemoryAllocationCallback(MemoryAllocationCallback callback) {
8285  Isolate* isolate = Isolate::GetCurrent();
8286  isolate->RemoveMemoryAllocationCallback(callback);
8287 }
8288 
8289 
8290 void V8::TerminateExecution(Isolate* isolate) { isolate->TerminateExecution(); }
8291 
8292 
8293 bool V8::IsExecutionTerminating(Isolate* isolate) {
8294  if (isolate == NULL) {
8295  isolate = Isolate::GetCurrent();
8296  }
8297  return isolate->IsExecutionTerminating();
8298 }
8299 
8300 
8301 void V8::CancelTerminateExecution(Isolate* isolate) {
8303 }
8304 
8305 
8306 void V8::VisitExternalResources(ExternalResourceVisitor* visitor) {
8307  Isolate* isolate = Isolate::GetCurrent();
8308  isolate->VisitExternalResources(visitor);
8309 }
8310 
8311 
8312 void V8::VisitHandlesWithClassIds(PersistentHandleVisitor* visitor) {
8313  Isolate* isolate = Isolate::GetCurrent();
8314  isolate->VisitHandlesWithClassIds(visitor);
8315 }
8316 
8317 
8318 void V8::VisitHandlesWithClassIds(Isolate* isolate,
8319  PersistentHandleVisitor* visitor) {
8320  isolate->VisitHandlesWithClassIds(visitor);
8321 }
8322 
8323 
8324 void V8::VisitHandlesForPartialDependence(Isolate* isolate,
8325  PersistentHandleVisitor* visitor) {
8327 }
8328 
8329 /**
8330  * \example shell.cc
8331  * A simple shell that takes a list of expressions on the
8332  * command-line and executes them.
8333  */
8334 
8335 
8336 /**
8337  * \example process.cc
8338  */
8339 
8340 
8341 } // namespace v8
8342 
8343 
8344 #undef TYPE_CHECK
8345 
8346 
8347 #endif // V8_H_