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