Team Fortress 2 Source Code as on 22/4/2020
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

7052 lines
216 KiB

  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. /** \mainpage V8 API Reference Guide
  5. *
  6. * V8 is Google's open source JavaScript engine.
  7. *
  8. * This set of documents provides reference material generated from the
  9. * V8 header file, include/v8.h.
  10. *
  11. * For other documentation see http://code.google.com/apis/v8/
  12. */
  13. #ifndef V8_H_
  14. #define V8_H_
  15. #include "v8stdint.h"
  16. // We reserve the V8_* prefix for macros defined in V8 public API and
  17. // assume there are no name conflicts with the embedder's code.
  18. #ifdef V8_OS_WIN
  19. // Setup for Windows DLL export/import. When building the V8 DLL the
  20. // BUILDING_V8_SHARED needs to be defined. When building a program which uses
  21. // the V8 DLL USING_V8_SHARED needs to be defined. When either building the V8
  22. // static library or building a program which uses the V8 static library neither
  23. // BUILDING_V8_SHARED nor USING_V8_SHARED should be defined.
  24. #if defined(BUILDING_V8_SHARED) && defined(USING_V8_SHARED)
  25. #error both BUILDING_V8_SHARED and USING_V8_SHARED are set - please check the\
  26. build configuration to ensure that at most one of these is set
  27. #endif
  28. #ifdef BUILDING_V8_SHARED
  29. # define V8_EXPORT __declspec(dllexport)
  30. #elif USING_V8_SHARED
  31. # define V8_EXPORT __declspec(dllimport)
  32. #else
  33. # define V8_EXPORT
  34. #endif // BUILDING_V8_SHARED
  35. #else // V8_OS_WIN
  36. // Setup for Linux shared library export.
  37. # ifdef V8_SHARED
  38. # define V8_EXPORT __attribute__ ((visibility("default")))
  39. # else
  40. # define V8_EXPORT
  41. # endif
  42. #endif // V8_OS_WIN
  43. /**
  44. * The v8 JavaScript engine.
  45. */
  46. namespace v8 {
  47. class AccessorSignature;
  48. class Array;
  49. class Boolean;
  50. class BooleanObject;
  51. class Context;
  52. class CpuProfiler;
  53. class Data;
  54. class Date;
  55. class DeclaredAccessorDescriptor;
  56. class External;
  57. class Function;
  58. class FunctionTemplate;
  59. class HeapProfiler;
  60. class ImplementationUtilities;
  61. class Int32;
  62. class Integer;
  63. class Isolate;
  64. class Name;
  65. class Number;
  66. class NumberObject;
  67. class Object;
  68. class ObjectOperationDescriptor;
  69. class ObjectTemplate;
  70. class Platform;
  71. class Primitive;
  72. class Promise;
  73. class RawOperationDescriptor;
  74. class Script;
  75. class Signature;
  76. class StackFrame;
  77. class StackTrace;
  78. class String;
  79. class StringObject;
  80. class Symbol;
  81. class SymbolObject;
  82. class Private;
  83. class Uint32;
  84. class Utils;
  85. class Value;
  86. template <class T> class Handle;
  87. template <class T> class Local;
  88. template <class T> class Eternal;
  89. template<class T> class NonCopyablePersistentTraits;
  90. template<class T> class PersistentBase;
  91. template<class T,
  92. class M = NonCopyablePersistentTraits<T> > class Persistent;
  93. template<class T> class UniquePersistent;
  94. template<class K, class V, class T> class PersistentValueMap;
  95. template<class V, class T> class PersistentValueVector;
  96. template<class T, class P> class WeakCallbackObject;
  97. class FunctionTemplate;
  98. class ObjectTemplate;
  99. class Data;
  100. template<typename T> class FunctionCallbackInfo;
  101. template<typename T> class PropertyCallbackInfo;
  102. class StackTrace;
  103. class StackFrame;
  104. class Isolate;
  105. class DeclaredAccessorDescriptor;
  106. class ObjectOperationDescriptor;
  107. class RawOperationDescriptor;
  108. class CallHandlerHelper;
  109. class EscapableHandleScope;
  110. template<typename T> class ReturnValue;
  111. namespace internal {
  112. class Arguments;
  113. class Heap;
  114. class HeapObject;
  115. class Isolate;
  116. class Object;
  117. struct StreamedSource;
  118. template<typename T> class CustomArguments;
  119. class PropertyCallbackArguments;
  120. class FunctionCallbackArguments;
  121. class GlobalHandles;
  122. }
  123. /**
  124. * General purpose unique identifier.
  125. */
  126. class UniqueId {
  127. public:
  128. explicit UniqueId(intptr_t data)
  129. : data_(data) {}
  130. bool operator==(const UniqueId& other) const {
  131. return data_ == other.data_;
  132. }
  133. bool operator!=(const UniqueId& other) const {
  134. return data_ != other.data_;
  135. }
  136. bool operator<(const UniqueId& other) const {
  137. return data_ < other.data_;
  138. }
  139. private:
  140. intptr_t data_;
  141. };
  142. // --- Handles ---
  143. #define TYPE_CHECK(T, S) \
  144. while (false) { \
  145. *(static_cast<T* volatile*>(0)) = static_cast<S*>(0); \
  146. }
  147. /**
  148. * An object reference managed by the v8 garbage collector.
  149. *
  150. * All objects returned from v8 have to be tracked by the garbage
  151. * collector so that it knows that the objects are still alive. Also,
  152. * because the garbage collector may move objects, it is unsafe to
  153. * point directly to an object. Instead, all objects are stored in
  154. * handles which are known by the garbage collector and updated
  155. * whenever an object moves. Handles should always be passed by value
  156. * (except in cases like out-parameters) and they should never be
  157. * allocated on the heap.
  158. *
  159. * There are two types of handles: local and persistent handles.
  160. * Local handles are light-weight and transient and typically used in
  161. * local operations. They are managed by HandleScopes. Persistent
  162. * handles can be used when storing objects across several independent
  163. * operations and have to be explicitly deallocated when they're no
  164. * longer used.
  165. *
  166. * It is safe to extract the object stored in the handle by
  167. * dereferencing the handle (for instance, to extract the Object* from
  168. * a Handle<Object>); the value will still be governed by a handle
  169. * behind the scenes and the same rules apply to these values as to
  170. * their handles.
  171. */
  172. template <class T> class Handle {
  173. public:
  174. /**
  175. * Creates an empty handle.
  176. */
  177. V8_INLINE Handle() : val_(0) {}
  178. /**
  179. * Creates a handle for the contents of the specified handle. This
  180. * constructor allows you to pass handles as arguments by value and
  181. * to assign between handles. However, if you try to assign between
  182. * incompatible handles, for instance from a Handle<String> to a
  183. * Handle<Number> it will cause a compile-time error. Assigning
  184. * between compatible handles, for instance assigning a
  185. * Handle<String> to a variable declared as Handle<Value>, is legal
  186. * because String is a subclass of Value.
  187. */
  188. template <class S> V8_INLINE Handle(Handle<S> that)
  189. : val_(reinterpret_cast<T*>(*that)) {
  190. /**
  191. * This check fails when trying to convert between incompatible
  192. * handles. For example, converting from a Handle<String> to a
  193. * Handle<Number>.
  194. */
  195. TYPE_CHECK(T, S);
  196. }
  197. /**
  198. * Returns true if the handle is empty.
  199. */
  200. V8_INLINE bool IsEmpty() const { return val_ == 0; }
  201. /**
  202. * Sets the handle to be empty. IsEmpty() will then return true.
  203. */
  204. V8_INLINE void Clear() { val_ = 0; }
  205. V8_INLINE T* operator->() const { return val_; }
  206. V8_INLINE T* operator*() const { return val_; }
  207. /**
  208. * Checks whether two handles are the same.
  209. * Returns true if both are empty, or if the objects
  210. * to which they refer are identical.
  211. * The handles' references are not checked.
  212. */
  213. template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
  214. internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
  215. internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
  216. if (a == 0) return b == 0;
  217. if (b == 0) return false;
  218. return *a == *b;
  219. }
  220. template <class S> V8_INLINE bool operator==(
  221. const PersistentBase<S>& that) const {
  222. internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
  223. internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
  224. if (a == 0) return b == 0;
  225. if (b == 0) return false;
  226. return *a == *b;
  227. }
  228. /**
  229. * Checks whether two handles are different.
  230. * Returns true if only one of the handles is empty, or if
  231. * the objects to which they refer are different.
  232. * The handles' references are not checked.
  233. */
  234. template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
  235. return !operator==(that);
  236. }
  237. template <class S> V8_INLINE bool operator!=(
  238. const Persistent<S>& that) const {
  239. return !operator==(that);
  240. }
  241. template <class S> V8_INLINE static Handle<T> Cast(Handle<S> that) {
  242. #ifdef V8_ENABLE_CHECKS
  243. // If we're going to perform the type check then we have to check
  244. // that the handle isn't empty before doing the checked cast.
  245. if (that.IsEmpty()) return Handle<T>();
  246. #endif
  247. return Handle<T>(T::Cast(*that));
  248. }
  249. template <class S> V8_INLINE Handle<S> As() {
  250. return Handle<S>::Cast(*this);
  251. }
  252. V8_INLINE static Handle<T> New(Isolate* isolate, Handle<T> that) {
  253. return New(isolate, that.val_);
  254. }
  255. V8_INLINE static Handle<T> New(Isolate* isolate,
  256. const PersistentBase<T>& that) {
  257. return New(isolate, that.val_);
  258. }
  259. private:
  260. friend class Utils;
  261. template<class F, class M> friend class Persistent;
  262. template<class F> friend class PersistentBase;
  263. template<class F> friend class Handle;
  264. template<class F> friend class Local;
  265. template<class F> friend class FunctionCallbackInfo;
  266. template<class F> friend class PropertyCallbackInfo;
  267. template<class F> friend class internal::CustomArguments;
  268. friend Handle<Primitive> Undefined(Isolate* isolate);
  269. friend Handle<Primitive> Null(Isolate* isolate);
  270. friend Handle<Boolean> True(Isolate* isolate);
  271. friend Handle<Boolean> False(Isolate* isolate);
  272. friend class Context;
  273. friend class HandleScope;
  274. friend class Object;
  275. friend class Private;
  276. /**
  277. * Creates a new handle for the specified value.
  278. */
  279. V8_INLINE explicit Handle(T* val) : val_(val) {}
  280. V8_INLINE static Handle<T> New(Isolate* isolate, T* that);
  281. T* val_;
  282. };
  283. /**
  284. * A light-weight stack-allocated object handle. All operations
  285. * that return objects from within v8 return them in local handles. They
  286. * are created within HandleScopes, and all local handles allocated within a
  287. * handle scope are destroyed when the handle scope is destroyed. Hence it
  288. * is not necessary to explicitly deallocate local handles.
  289. */
  290. template <class T> class Local : public Handle<T> {
  291. public:
  292. V8_INLINE Local();
  293. template <class S> V8_INLINE Local(Local<S> that)
  294. : Handle<T>(reinterpret_cast<T*>(*that)) {
  295. /**
  296. * This check fails when trying to convert between incompatible
  297. * handles. For example, converting from a Handle<String> to a
  298. * Handle<Number>.
  299. */
  300. TYPE_CHECK(T, S);
  301. }
  302. template <class S> V8_INLINE static Local<T> Cast(Local<S> that) {
  303. #ifdef V8_ENABLE_CHECKS
  304. // If we're going to perform the type check then we have to check
  305. // that the handle isn't empty before doing the checked cast.
  306. if (that.IsEmpty()) return Local<T>();
  307. #endif
  308. return Local<T>(T::Cast(*that));
  309. }
  310. template <class S> V8_INLINE Local(Handle<S> that)
  311. : Handle<T>(reinterpret_cast<T*>(*that)) {
  312. TYPE_CHECK(T, S);
  313. }
  314. template <class S> V8_INLINE Local<S> As() {
  315. return Local<S>::Cast(*this);
  316. }
  317. /**
  318. * Create a local handle for the content of another handle.
  319. * The referee is kept alive by the local handle even when
  320. * the original handle is destroyed/disposed.
  321. */
  322. V8_INLINE static Local<T> New(Isolate* isolate, Handle<T> that);
  323. V8_INLINE static Local<T> New(Isolate* isolate,
  324. const PersistentBase<T>& that);
  325. private:
  326. friend class Utils;
  327. template<class F> friend class Eternal;
  328. template<class F> friend class PersistentBase;
  329. template<class F, class M> friend class Persistent;
  330. template<class F> friend class Handle;
  331. template<class F> friend class Local;
  332. template<class F> friend class FunctionCallbackInfo;
  333. template<class F> friend class PropertyCallbackInfo;
  334. friend class String;
  335. friend class Object;
  336. friend class Context;
  337. template<class F> friend class internal::CustomArguments;
  338. friend class HandleScope;
  339. friend class EscapableHandleScope;
  340. template<class F1, class F2, class F3> friend class PersistentValueMap;
  341. template<class F1, class F2> friend class PersistentValueVector;
  342. template <class S> V8_INLINE Local(S* that) : Handle<T>(that) { }
  343. V8_INLINE static Local<T> New(Isolate* isolate, T* that);
  344. };
  345. // Eternal handles are set-once handles that live for the life of the isolate.
  346. template <class T> class Eternal {
  347. public:
  348. V8_INLINE Eternal() : index_(kInitialValue) { }
  349. template<class S>
  350. V8_INLINE Eternal(Isolate* isolate, Local<S> handle) : index_(kInitialValue) {
  351. Set(isolate, handle);
  352. }
  353. // Can only be safely called if already set.
  354. V8_INLINE Local<T> Get(Isolate* isolate);
  355. V8_INLINE bool IsEmpty() { return index_ == kInitialValue; }
  356. template<class S> V8_INLINE void Set(Isolate* isolate, Local<S> handle);
  357. private:
  358. static const int kInitialValue = -1;
  359. int index_;
  360. };
  361. template<class T, class P>
  362. class WeakCallbackData {
  363. public:
  364. typedef void (*Callback)(const WeakCallbackData<T, P>& data);
  365. V8_INLINE Isolate* GetIsolate() const { return isolate_; }
  366. V8_INLINE Local<T> GetValue() const { return handle_; }
  367. V8_INLINE P* GetParameter() const { return parameter_; }
  368. private:
  369. friend class internal::GlobalHandles;
  370. WeakCallbackData(Isolate* isolate, Local<T> handle, P* parameter)
  371. : isolate_(isolate), handle_(handle), parameter_(parameter) { }
  372. Isolate* isolate_;
  373. Local<T> handle_;
  374. P* parameter_;
  375. };
  376. /**
  377. * An object reference that is independent of any handle scope. Where
  378. * a Local handle only lives as long as the HandleScope in which it was
  379. * allocated, a PersistentBase handle remains valid until it is explicitly
  380. * disposed.
  381. *
  382. * A persistent handle contains a reference to a storage cell within
  383. * the v8 engine which holds an object value and which is updated by
  384. * the garbage collector whenever the object is moved. A new storage
  385. * cell can be created using the constructor or PersistentBase::Reset and
  386. * existing handles can be disposed using PersistentBase::Reset.
  387. *
  388. */
  389. template <class T> class PersistentBase {
  390. public:
  391. /**
  392. * If non-empty, destroy the underlying storage cell
  393. * IsEmpty() will return true after this call.
  394. */
  395. V8_INLINE void Reset();
  396. /**
  397. * If non-empty, destroy the underlying storage cell
  398. * and create a new one with the contents of other if other is non empty
  399. */
  400. template <class S>
  401. V8_INLINE void Reset(Isolate* isolate, const Handle<S>& other);
  402. /**
  403. * If non-empty, destroy the underlying storage cell
  404. * and create a new one with the contents of other if other is non empty
  405. */
  406. template <class S>
  407. V8_INLINE void Reset(Isolate* isolate, const PersistentBase<S>& other);
  408. V8_INLINE bool IsEmpty() const { return val_ == 0; }
  409. template <class S>
  410. V8_INLINE bool operator==(const PersistentBase<S>& that) const {
  411. internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
  412. internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
  413. if (a == 0) return b == 0;
  414. if (b == 0) return false;
  415. return *a == *b;
  416. }
  417. template <class S> V8_INLINE bool operator==(const Handle<S>& that) const {
  418. internal::Object** a = reinterpret_cast<internal::Object**>(this->val_);
  419. internal::Object** b = reinterpret_cast<internal::Object**>(that.val_);
  420. if (a == 0) return b == 0;
  421. if (b == 0) return false;
  422. return *a == *b;
  423. }
  424. template <class S>
  425. V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
  426. return !operator==(that);
  427. }
  428. template <class S> V8_INLINE bool operator!=(const Handle<S>& that) const {
  429. return !operator==(that);
  430. }
  431. /**
  432. * Install a finalization callback on this object.
  433. * NOTE: There is no guarantee as to *when* or even *if* the callback is
  434. * invoked. The invocation is performed solely on a best effort basis.
  435. * As always, GC-based finalization should *not* be relied upon for any
  436. * critical form of resource management!
  437. */
  438. template<typename P>
  439. V8_INLINE void SetWeak(
  440. P* parameter,
  441. typename WeakCallbackData<T, P>::Callback callback);
  442. template<typename S, typename P>
  443. V8_INLINE void SetWeak(
  444. P* parameter,
  445. typename WeakCallbackData<S, P>::Callback callback);
  446. template<typename P>
  447. V8_INLINE P* ClearWeak();
  448. // TODO(dcarney): remove this.
  449. V8_INLINE void ClearWeak() { ClearWeak<void>(); }
  450. /**
  451. * Marks the reference to this object independent. Garbage collector is free
  452. * to ignore any object groups containing this object. Weak callback for an
  453. * independent handle should not assume that it will be preceded by a global
  454. * GC prologue callback or followed by a global GC epilogue callback.
  455. */
  456. V8_INLINE void MarkIndependent();
  457. /**
  458. * Marks the reference to this object partially dependent. Partially dependent
  459. * handles only depend on other partially dependent handles and these
  460. * dependencies are provided through object groups. It provides a way to build
  461. * smaller object groups for young objects that represent only a subset of all
  462. * external dependencies. This mark is automatically cleared after each
  463. * garbage collection.
  464. */
  465. V8_INLINE void MarkPartiallyDependent();
  466. V8_INLINE bool IsIndependent() const;
  467. /** Checks if the handle holds the only reference to an object. */
  468. V8_INLINE bool IsNearDeath() const;
  469. /** Returns true if the handle's reference is weak. */
  470. V8_INLINE bool IsWeak() const;
  471. /**
  472. * Assigns a wrapper class ID to the handle. See RetainedObjectInfo interface
  473. * description in v8-profiler.h for details.
  474. */
  475. V8_INLINE void SetWrapperClassId(uint16_t class_id);
  476. /**
  477. * Returns the class ID previously assigned to this handle or 0 if no class ID
  478. * was previously assigned.
  479. */
  480. V8_INLINE uint16_t WrapperClassId() const;
  481. private:
  482. friend class Isolate;
  483. friend class Utils;
  484. template<class F> friend class Handle;
  485. template<class F> friend class Local;
  486. template<class F1, class F2> friend class Persistent;
  487. template<class F> friend class UniquePersistent;
  488. template<class F> friend class PersistentBase;
  489. template<class F> friend class ReturnValue;
  490. template<class F1, class F2, class F3> friend class PersistentValueMap;
  491. template<class F1, class F2> friend class PersistentValueVector;
  492. friend class Object;
  493. explicit V8_INLINE PersistentBase(T* val) : val_(val) {}
  494. PersistentBase(PersistentBase& other); // NOLINT
  495. void operator=(PersistentBase&);
  496. V8_INLINE static T* New(Isolate* isolate, T* that);
  497. T* val_;
  498. };
  499. /**
  500. * Default traits for Persistent. This class does not allow
  501. * use of the copy constructor or assignment operator.
  502. * At present kResetInDestructor is not set, but that will change in a future
  503. * version.
  504. */
  505. template<class T>
  506. class NonCopyablePersistentTraits {
  507. public:
  508. typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent;
  509. static const bool kResetInDestructor = false;
  510. template<class S, class M>
  511. V8_INLINE static void Copy(const Persistent<S, M>& source,
  512. NonCopyablePersistent* dest) {
  513. Uncompilable<Object>();
  514. }
  515. // TODO(dcarney): come up with a good compile error here.
  516. template<class O> V8_INLINE static void Uncompilable() {
  517. TYPE_CHECK(O, Primitive);
  518. }
  519. };
  520. /**
  521. * Helper class traits to allow copying and assignment of Persistent.
  522. * This will clone the contents of storage cell, but not any of the flags, etc.
  523. */
  524. template<class T>
  525. struct CopyablePersistentTraits {
  526. typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent;
  527. static const bool kResetInDestructor = true;
  528. template<class S, class M>
  529. static V8_INLINE void Copy(const Persistent<S, M>& source,
  530. CopyablePersistent* dest) {
  531. // do nothing, just allow copy
  532. }
  533. };
  534. /**
  535. * A PersistentBase which allows copy and assignment.
  536. *
  537. * Copy, assignment and destructor bevavior is controlled by the traits
  538. * class M.
  539. *
  540. * Note: Persistent class hierarchy is subject to future changes.
  541. */
  542. template <class T, class M> class Persistent : public PersistentBase<T> {
  543. public:
  544. /**
  545. * A Persistent with no storage cell.
  546. */
  547. V8_INLINE Persistent() : PersistentBase<T>(0) { }
  548. /**
  549. * Construct a Persistent from a Handle.
  550. * When the Handle is non-empty, a new storage cell is created
  551. * pointing to the same object, and no flags are set.
  552. */
  553. template <class S> V8_INLINE Persistent(Isolate* isolate, Handle<S> that)
  554. : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
  555. TYPE_CHECK(T, S);
  556. }
  557. /**
  558. * Construct a Persistent from a Persistent.
  559. * When the Persistent is non-empty, a new storage cell is created
  560. * pointing to the same object, and no flags are set.
  561. */
  562. template <class S, class M2>
  563. V8_INLINE Persistent(Isolate* isolate, const Persistent<S, M2>& that)
  564. : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
  565. TYPE_CHECK(T, S);
  566. }
  567. /**
  568. * The copy constructors and assignment operator create a Persistent
  569. * exactly as the Persistent constructor, but the Copy function from the
  570. * traits class is called, allowing the setting of flags based on the
  571. * copied Persistent.
  572. */
  573. V8_INLINE Persistent(const Persistent& that) : PersistentBase<T>(0) {
  574. Copy(that);
  575. }
  576. template <class S, class M2>
  577. V8_INLINE Persistent(const Persistent<S, M2>& that) : PersistentBase<T>(0) {
  578. Copy(that);
  579. }
  580. V8_INLINE Persistent& operator=(const Persistent& that) { // NOLINT
  581. Copy(that);
  582. return *this;
  583. }
  584. template <class S, class M2>
  585. V8_INLINE Persistent& operator=(const Persistent<S, M2>& that) { // NOLINT
  586. Copy(that);
  587. return *this;
  588. }
  589. /**
  590. * The destructor will dispose the Persistent based on the
  591. * kResetInDestructor flags in the traits class. Since not calling dispose
  592. * can result in a memory leak, it is recommended to always set this flag.
  593. */
  594. V8_INLINE ~Persistent() {
  595. if (M::kResetInDestructor) this->Reset();
  596. }
  597. // TODO(dcarney): this is pretty useless, fix or remove
  598. template <class S>
  599. V8_INLINE static Persistent<T>& Cast(Persistent<S>& that) { // NOLINT
  600. #ifdef V8_ENABLE_CHECKS
  601. // If we're going to perform the type check then we have to check
  602. // that the handle isn't empty before doing the checked cast.
  603. if (!that.IsEmpty()) T::Cast(*that);
  604. #endif
  605. return reinterpret_cast<Persistent<T>&>(that);
  606. }
  607. // TODO(dcarney): this is pretty useless, fix or remove
  608. template <class S> V8_INLINE Persistent<S>& As() { // NOLINT
  609. return Persistent<S>::Cast(*this);
  610. }
  611. private:
  612. friend class Isolate;
  613. friend class Utils;
  614. template<class F> friend class Handle;
  615. template<class F> friend class Local;
  616. template<class F1, class F2> friend class Persistent;
  617. template<class F> friend class ReturnValue;
  618. template <class S> V8_INLINE Persistent(S* that) : PersistentBase<T>(that) { }
  619. V8_INLINE T* operator*() const { return this->val_; }
  620. template<class S, class M2>
  621. V8_INLINE void Copy(const Persistent<S, M2>& that);
  622. };
  623. /**
  624. * A PersistentBase which has move semantics.
  625. *
  626. * Note: Persistent class hierarchy is subject to future changes.
  627. */
  628. template<class T>
  629. class UniquePersistent : public PersistentBase<T> {
  630. struct RValue {
  631. V8_INLINE explicit RValue(UniquePersistent* obj) : object(obj) {}
  632. UniquePersistent* object;
  633. };
  634. public:
  635. /**
  636. * A UniquePersistent with no storage cell.
  637. */
  638. V8_INLINE UniquePersistent() : PersistentBase<T>(0) { }
  639. /**
  640. * Construct a UniquePersistent from a Handle.
  641. * When the Handle is non-empty, a new storage cell is created
  642. * pointing to the same object, and no flags are set.
  643. */
  644. template <class S>
  645. V8_INLINE UniquePersistent(Isolate* isolate, Handle<S> that)
  646. : PersistentBase<T>(PersistentBase<T>::New(isolate, *that)) {
  647. TYPE_CHECK(T, S);
  648. }
  649. /**
  650. * Construct a UniquePersistent from a PersistentBase.
  651. * When the Persistent is non-empty, a new storage cell is created
  652. * pointing to the same object, and no flags are set.
  653. */
  654. template <class S>
  655. V8_INLINE UniquePersistent(Isolate* isolate, const PersistentBase<S>& that)
  656. : PersistentBase<T>(PersistentBase<T>::New(isolate, that.val_)) {
  657. TYPE_CHECK(T, S);
  658. }
  659. /**
  660. * Move constructor.
  661. */
  662. V8_INLINE UniquePersistent(RValue rvalue)
  663. : PersistentBase<T>(rvalue.object->val_) {
  664. rvalue.object->val_ = 0;
  665. }
  666. V8_INLINE ~UniquePersistent() { this->Reset(); }
  667. /**
  668. * Move via assignment.
  669. */
  670. template<class S>
  671. V8_INLINE UniquePersistent& operator=(UniquePersistent<S> rhs) {
  672. TYPE_CHECK(T, S);
  673. this->Reset();
  674. this->val_ = rhs.val_;
  675. rhs.val_ = 0;
  676. return *this;
  677. }
  678. /**
  679. * Cast operator for moves.
  680. */
  681. V8_INLINE operator RValue() { return RValue(this); }
  682. /**
  683. * Pass allows returning uniques from functions, etc.
  684. */
  685. UniquePersistent Pass() { return UniquePersistent(RValue(this)); }
  686. private:
  687. UniquePersistent(UniquePersistent&);
  688. void operator=(UniquePersistent&);
  689. };
  690. /**
  691. * A stack-allocated class that governs a number of local handles.
  692. * After a handle scope has been created, all local handles will be
  693. * allocated within that handle scope until either the handle scope is
  694. * deleted or another handle scope is created. If there is already a
  695. * handle scope and a new one is created, all allocations will take
  696. * place in the new handle scope until it is deleted. After that,
  697. * new handles will again be allocated in the original handle scope.
  698. *
  699. * After the handle scope of a local handle has been deleted the
  700. * garbage collector will no longer track the object stored in the
  701. * handle and may deallocate it. The behavior of accessing a handle
  702. * for which the handle scope has been deleted is undefined.
  703. */
  704. class V8_EXPORT HandleScope {
  705. public:
  706. HandleScope(Isolate* isolate);
  707. ~HandleScope();
  708. /**
  709. * Counts the number of allocated handles.
  710. */
  711. static int NumberOfHandles(Isolate* isolate);
  712. V8_INLINE Isolate* GetIsolate() const {
  713. return reinterpret_cast<Isolate*>(isolate_);
  714. }
  715. protected:
  716. V8_INLINE HandleScope() {}
  717. void Initialize(Isolate* isolate);
  718. static internal::Object** CreateHandle(internal::Isolate* isolate,
  719. internal::Object* value);
  720. private:
  721. // Uses heap_object to obtain the current Isolate.
  722. static internal::Object** CreateHandle(internal::HeapObject* heap_object,
  723. internal::Object* value);
  724. // Make it hard to create heap-allocated or illegal handle scopes by
  725. // disallowing certain operations.
  726. HandleScope(const HandleScope&);
  727. void operator=(const HandleScope&);
  728. void* operator new(size_t size);
  729. void operator delete(void*, size_t);
  730. internal::Isolate* isolate_;
  731. internal::Object** prev_next_;
  732. internal::Object** prev_limit_;
  733. // Local::New uses CreateHandle with an Isolate* parameter.
  734. template<class F> friend class Local;
  735. // Object::GetInternalField and Context::GetEmbedderData use CreateHandle with
  736. // a HeapObject* in their shortcuts.
  737. friend class Object;
  738. friend class Context;
  739. };
  740. /**
  741. * A HandleScope which first allocates a handle in the current scope
  742. * which will be later filled with the escape value.
  743. */
  744. class V8_EXPORT EscapableHandleScope : public HandleScope {
  745. public:
  746. EscapableHandleScope(Isolate* isolate);
  747. V8_INLINE ~EscapableHandleScope() {}
  748. /**
  749. * Pushes the value into the previous scope and returns a handle to it.
  750. * Cannot be called twice.
  751. */
  752. template <class T>
  753. V8_INLINE Local<T> Escape(Local<T> value) {
  754. internal::Object** slot =
  755. Escape(reinterpret_cast<internal::Object**>(*value));
  756. return Local<T>(reinterpret_cast<T*>(slot));
  757. }
  758. private:
  759. internal::Object** Escape(internal::Object** escape_value);
  760. // Make it hard to create heap-allocated or illegal handle scopes by
  761. // disallowing certain operations.
  762. EscapableHandleScope(const EscapableHandleScope&);
  763. void operator=(const EscapableHandleScope&);
  764. void* operator new(size_t size);
  765. void operator delete(void*, size_t);
  766. internal::Object** escape_slot_;
  767. };
  768. /**
  769. * A simple Maybe type, representing an object which may or may not have a
  770. * value.
  771. */
  772. template<class T>
  773. struct Maybe {
  774. Maybe() : has_value(false) {}
  775. explicit Maybe(T t) : has_value(true), value(t) {}
  776. Maybe(bool has, T t) : has_value(has), value(t) {}
  777. bool has_value;
  778. T value;
  779. };
  780. // Convenience wrapper.
  781. template <class T>
  782. inline Maybe<T> maybe(T t) {
  783. return Maybe<T>(t);
  784. }
  785. // --- Special objects ---
  786. /**
  787. * The superclass of values and API object templates.
  788. */
  789. class V8_EXPORT Data {
  790. private:
  791. Data();
  792. };
  793. /**
  794. * The origin, within a file, of a script.
  795. */
  796. class ScriptOrigin {
  797. public:
  798. V8_INLINE ScriptOrigin(
  799. Handle<Value> resource_name,
  800. Handle<Integer> resource_line_offset = Handle<Integer>(),
  801. Handle<Integer> resource_column_offset = Handle<Integer>(),
  802. Handle<Boolean> resource_is_shared_cross_origin = Handle<Boolean>(),
  803. Handle<Integer> script_id = Handle<Integer>())
  804. : resource_name_(resource_name),
  805. resource_line_offset_(resource_line_offset),
  806. resource_column_offset_(resource_column_offset),
  807. resource_is_shared_cross_origin_(resource_is_shared_cross_origin),
  808. script_id_(script_id) { }
  809. V8_INLINE Handle<Value> ResourceName() const;
  810. V8_INLINE Handle<Integer> ResourceLineOffset() const;
  811. V8_INLINE Handle<Integer> ResourceColumnOffset() const;
  812. V8_INLINE Handle<Boolean> ResourceIsSharedCrossOrigin() const;
  813. V8_INLINE Handle<Integer> ScriptID() const;
  814. private:
  815. Handle<Value> resource_name_;
  816. Handle<Integer> resource_line_offset_;
  817. Handle<Integer> resource_column_offset_;
  818. Handle<Boolean> resource_is_shared_cross_origin_;
  819. Handle<Integer> script_id_;
  820. };
  821. /**
  822. * A compiled JavaScript script, not yet tied to a Context.
  823. */
  824. class V8_EXPORT UnboundScript {
  825. public:
  826. /**
  827. * Binds the script to the currently entered context.
  828. */
  829. Local<Script> BindToCurrentContext();
  830. int GetId();
  831. Handle<Value> GetScriptName();
  832. /**
  833. * Data read from magic sourceURL comments.
  834. */
  835. Handle<Value> GetSourceURL();
  836. /**
  837. * Data read from magic sourceMappingURL comments.
  838. */
  839. Handle<Value> GetSourceMappingURL();
  840. /**
  841. * Returns zero based line number of the code_pos location in the script.
  842. * -1 will be returned if no information available.
  843. */
  844. int GetLineNumber(int code_pos);
  845. static const int kNoScriptId = 0;
  846. };
  847. /**
  848. * A compiled JavaScript script, tied to a Context which was active when the
  849. * script was compiled.
  850. */
  851. class V8_EXPORT Script {
  852. public:
  853. /**
  854. * A shorthand for ScriptCompiler::Compile().
  855. */
  856. static Local<Script> Compile(Handle<String> source,
  857. ScriptOrigin* origin = NULL);
  858. // To be decprecated, use the Compile above.
  859. static Local<Script> Compile(Handle<String> source,
  860. Handle<String> file_name);
  861. /**
  862. * Runs the script returning the resulting value. It will be run in the
  863. * context in which it was created (ScriptCompiler::CompileBound or
  864. * UnboundScript::BindToGlobalContext()).
  865. */
  866. Local<Value> Run();
  867. /**
  868. * Returns the corresponding context-unbound script.
  869. */
  870. Local<UnboundScript> GetUnboundScript();
  871. V8_DEPRECATED("Use GetUnboundScript()->GetId()",
  872. int GetId()) {
  873. return GetUnboundScript()->GetId();
  874. }
  875. };
  876. /**
  877. * For compiling scripts.
  878. */
  879. class V8_EXPORT ScriptCompiler {
  880. public:
  881. /**
  882. * Compilation data that the embedder can cache and pass back to speed up
  883. * future compilations. The data is produced if the CompilerOptions passed to
  884. * the compilation functions in ScriptCompiler contains produce_data_to_cache
  885. * = true. The data to cache can then can be retrieved from
  886. * UnboundScript.
  887. */
  888. struct V8_EXPORT CachedData {
  889. enum BufferPolicy {
  890. BufferNotOwned,
  891. BufferOwned
  892. };
  893. CachedData() : data(NULL), length(0), buffer_policy(BufferNotOwned) {}
  894. // If buffer_policy is BufferNotOwned, the caller keeps the ownership of
  895. // data and guarantees that it stays alive until the CachedData object is
  896. // destroyed. If the policy is BufferOwned, the given data will be deleted
  897. // (with delete[]) when the CachedData object is destroyed.
  898. CachedData(const uint8_t* data, int length,
  899. BufferPolicy buffer_policy = BufferNotOwned);
  900. ~CachedData();
  901. // TODO(marja): Async compilation; add constructors which take a callback
  902. // which will be called when V8 no longer needs the data.
  903. const uint8_t* data;
  904. int length;
  905. BufferPolicy buffer_policy;
  906. private:
  907. // Prevent copying. Not implemented.
  908. CachedData(const CachedData&);
  909. CachedData& operator=(const CachedData&);
  910. };
  911. /**
  912. * Source code which can be then compiled to a UnboundScript or Script.
  913. */
  914. class Source {
  915. public:
  916. // Source takes ownership of CachedData.
  917. V8_INLINE Source(Local<String> source_string, const ScriptOrigin& origin,
  918. CachedData* cached_data = NULL);
  919. V8_INLINE Source(Local<String> source_string,
  920. CachedData* cached_data = NULL);
  921. V8_INLINE ~Source();
  922. // Ownership of the CachedData or its buffers is *not* transferred to the
  923. // caller. The CachedData object is alive as long as the Source object is
  924. // alive.
  925. V8_INLINE const CachedData* GetCachedData() const;
  926. private:
  927. friend class ScriptCompiler;
  928. // Prevent copying. Not implemented.
  929. Source(const Source&);
  930. Source& operator=(const Source&);
  931. Local<String> source_string;
  932. // Origin information
  933. Handle<Value> resource_name;
  934. Handle<Integer> resource_line_offset;
  935. Handle<Integer> resource_column_offset;
  936. Handle<Boolean> resource_is_shared_cross_origin;
  937. // Cached data from previous compilation (if a kConsume*Cache flag is
  938. // set), or hold newly generated cache data (kProduce*Cache flags) are
  939. // set when calling a compile method.
  940. CachedData* cached_data;
  941. };
  942. /**
  943. * For streaming incomplete script data to V8. The embedder should implement a
  944. * subclass of this class.
  945. */
  946. class ExternalSourceStream {
  947. public:
  948. virtual ~ExternalSourceStream() {}
  949. /**
  950. * V8 calls this to request the next chunk of data from the embedder. This
  951. * function will be called on a background thread, so it's OK to block and
  952. * wait for the data, if the embedder doesn't have data yet. Returns the
  953. * length of the data returned. When the data ends, GetMoreData should
  954. * return 0. Caller takes ownership of the data.
  955. *
  956. * When streaming UTF-8 data, V8 handles multi-byte characters split between
  957. * two data chunks, but doesn't handle multi-byte characters split between
  958. * more than two data chunks. The embedder can avoid this problem by always
  959. * returning at least 2 bytes of data.
  960. *
  961. * If the embedder wants to cancel the streaming, they should make the next
  962. * GetMoreData call return 0. V8 will interpret it as end of data (and most
  963. * probably, parsing will fail). The streaming task will return as soon as
  964. * V8 has parsed the data it received so far.
  965. */
  966. virtual size_t GetMoreData(const uint8_t** src) = 0;
  967. };
  968. /**
  969. * Source code which can be streamed into V8 in pieces. It will be parsed
  970. * while streaming. It can be compiled after the streaming is complete.
  971. * StreamedSource must be kept alive while the streaming task is ran (see
  972. * ScriptStreamingTask below).
  973. */
  974. class V8_EXPORT StreamedSource {
  975. public:
  976. enum Encoding { ONE_BYTE, TWO_BYTE, UTF8 };
  977. StreamedSource(ExternalSourceStream* source_stream, Encoding encoding);
  978. ~StreamedSource();
  979. // Ownership of the CachedData or its buffers is *not* transferred to the
  980. // caller. The CachedData object is alive as long as the StreamedSource
  981. // object is alive.
  982. const CachedData* GetCachedData() const;
  983. internal::StreamedSource* impl() const { return impl_; }
  984. private:
  985. // Prevent copying. Not implemented.
  986. StreamedSource(const StreamedSource&);
  987. StreamedSource& operator=(const StreamedSource&);
  988. internal::StreamedSource* impl_;
  989. };
  990. /**
  991. * A streaming task which the embedder must run on a background thread to
  992. * stream scripts into V8. Returned by ScriptCompiler::StartStreamingScript.
  993. */
  994. class ScriptStreamingTask {
  995. public:
  996. virtual ~ScriptStreamingTask() {}
  997. virtual void Run() = 0;
  998. };
  999. enum CompileOptions {
  1000. kNoCompileOptions = 0,
  1001. kProduceParserCache,
  1002. kConsumeParserCache,
  1003. kProduceCodeCache,
  1004. kConsumeCodeCache,
  1005. // Support the previous API for a transition period.
  1006. kProduceDataToCache
  1007. };
  1008. /**
  1009. * Compiles the specified script (context-independent).
  1010. * Cached data as part of the source object can be optionally produced to be
  1011. * consumed later to speed up compilation of identical source scripts.
  1012. *
  1013. * Note that when producing cached data, the source must point to NULL for
  1014. * cached data. When consuming cached data, the cached data must have been
  1015. * produced by the same version of V8.
  1016. *
  1017. * \param source Script source code.
  1018. * \return Compiled script object (context independent; for running it must be
  1019. * bound to a context).
  1020. */
  1021. static Local<UnboundScript> CompileUnbound(
  1022. Isolate* isolate, Source* source,
  1023. CompileOptions options = kNoCompileOptions);
  1024. /**
  1025. * Compiles the specified script (bound to current context).
  1026. *
  1027. * \param source Script source code.
  1028. * \param pre_data Pre-parsing data, as obtained by ScriptData::PreCompile()
  1029. * using pre_data speeds compilation if it's done multiple times.
  1030. * Owned by caller, no references are kept when this function returns.
  1031. * \return Compiled script object, bound to the context that was active
  1032. * when this function was called. When run it will always use this
  1033. * context.
  1034. */
  1035. static Local<Script> Compile(
  1036. Isolate* isolate, Source* source,
  1037. CompileOptions options = kNoCompileOptions);
  1038. /**
  1039. * Returns a task which streams script data into V8, or NULL if the script
  1040. * cannot be streamed. The user is responsible for running the task on a
  1041. * background thread and deleting it. When ran, the task starts parsing the
  1042. * script, and it will request data from the StreamedSource as needed. When
  1043. * ScriptStreamingTask::Run exits, all data has been streamed and the script
  1044. * can be compiled (see Compile below).
  1045. *
  1046. * This API allows to start the streaming with as little data as possible, and
  1047. * the remaining data (for example, the ScriptOrigin) is passed to Compile.
  1048. */
  1049. static ScriptStreamingTask* StartStreamingScript(
  1050. Isolate* isolate, StreamedSource* source,
  1051. CompileOptions options = kNoCompileOptions);
  1052. /**
  1053. * Compiles a streamed script (bound to current context).
  1054. *
  1055. * This can only be called after the streaming has finished
  1056. * (ScriptStreamingTask has been run). V8 doesn't construct the source string
  1057. * during streaming, so the embedder needs to pass the full source here.
  1058. */
  1059. static Local<Script> Compile(Isolate* isolate, StreamedSource* source,
  1060. Handle<String> full_source_string,
  1061. const ScriptOrigin& origin);
  1062. };
  1063. /**
  1064. * An error message.
  1065. */
  1066. class V8_EXPORT Message {
  1067. public:
  1068. Local<String> Get() const;
  1069. Local<String> GetSourceLine() const;
  1070. /**
  1071. * Returns the origin for the script from where the function causing the
  1072. * error originates.
  1073. */
  1074. ScriptOrigin GetScriptOrigin() const;
  1075. /**
  1076. * Returns the resource name for the script from where the function causing
  1077. * the error originates.
  1078. */
  1079. Handle<Value> GetScriptResourceName() const;
  1080. /**
  1081. * Exception stack trace. By default stack traces are not captured for
  1082. * uncaught exceptions. SetCaptureStackTraceForUncaughtExceptions allows
  1083. * to change this option.
  1084. */
  1085. Handle<StackTrace> GetStackTrace() const;
  1086. /**
  1087. * Returns the number, 1-based, of the line where the error occurred.
  1088. */
  1089. int GetLineNumber() const;
  1090. /**
  1091. * Returns the index within the script of the first character where
  1092. * the error occurred.
  1093. */
  1094. int GetStartPosition() const;
  1095. /**
  1096. * Returns the index within the script of the last character where
  1097. * the error occurred.
  1098. */
  1099. int GetEndPosition() const;
  1100. /**
  1101. * Returns the index within the line of the first character where
  1102. * the error occurred.
  1103. */
  1104. int GetStartColumn() const;
  1105. /**
  1106. * Returns the index within the line of the last character where
  1107. * the error occurred.
  1108. */
  1109. int GetEndColumn() const;
  1110. /**
  1111. * Passes on the value set by the embedder when it fed the script from which
  1112. * this Message was generated to V8.
  1113. */
  1114. bool IsSharedCrossOrigin() const;
  1115. // TODO(1245381): Print to a string instead of on a FILE.
  1116. static void PrintCurrentStackTrace(Isolate* isolate, FILE* out);
  1117. static const int kNoLineNumberInfo = 0;
  1118. static const int kNoColumnInfo = 0;
  1119. static const int kNoScriptIdInfo = 0;
  1120. };
  1121. /**
  1122. * Representation of a JavaScript stack trace. The information collected is a
  1123. * snapshot of the execution stack and the information remains valid after
  1124. * execution continues.
  1125. */
  1126. class V8_EXPORT StackTrace {
  1127. public:
  1128. /**
  1129. * Flags that determine what information is placed captured for each
  1130. * StackFrame when grabbing the current stack trace.
  1131. */
  1132. enum StackTraceOptions {
  1133. kLineNumber = 1,
  1134. kColumnOffset = 1 << 1 | kLineNumber,
  1135. kScriptName = 1 << 2,
  1136. kFunctionName = 1 << 3,
  1137. kIsEval = 1 << 4,
  1138. kIsConstructor = 1 << 5,
  1139. kScriptNameOrSourceURL = 1 << 6,
  1140. kScriptId = 1 << 7,
  1141. kExposeFramesAcrossSecurityOrigins = 1 << 8,
  1142. kOverview = kLineNumber | kColumnOffset | kScriptName | kFunctionName,
  1143. kDetailed = kOverview | kIsEval | kIsConstructor | kScriptNameOrSourceURL
  1144. };
  1145. /**
  1146. * Returns a StackFrame at a particular index.
  1147. */
  1148. Local<StackFrame> GetFrame(uint32_t index) const;
  1149. /**
  1150. * Returns the number of StackFrames.
  1151. */
  1152. int GetFrameCount() const;
  1153. /**
  1154. * Returns StackTrace as a v8::Array that contains StackFrame objects.
  1155. */
  1156. Local<Array> AsArray();
  1157. /**
  1158. * Grab a snapshot of the current JavaScript execution stack.
  1159. *
  1160. * \param frame_limit The maximum number of stack frames we want to capture.
  1161. * \param options Enumerates the set of things we will capture for each
  1162. * StackFrame.
  1163. */
  1164. static Local<StackTrace> CurrentStackTrace(
  1165. Isolate* isolate,
  1166. int frame_limit,
  1167. StackTraceOptions options = kOverview);
  1168. };
  1169. /**
  1170. * A single JavaScript stack frame.
  1171. */
  1172. class V8_EXPORT StackFrame {
  1173. public:
  1174. /**
  1175. * Returns the number, 1-based, of the line for the associate function call.
  1176. * This method will return Message::kNoLineNumberInfo if it is unable to
  1177. * retrieve the line number, or if kLineNumber was not passed as an option
  1178. * when capturing the StackTrace.
  1179. */
  1180. int GetLineNumber() const;
  1181. /**
  1182. * Returns the 1-based column offset on the line for the associated function
  1183. * call.
  1184. * This method will return Message::kNoColumnInfo if it is unable to retrieve
  1185. * the column number, or if kColumnOffset was not passed as an option when
  1186. * capturing the StackTrace.
  1187. */
  1188. int GetColumn() const;
  1189. /**
  1190. * Returns the id of the script for the function for this StackFrame.
  1191. * This method will return Message::kNoScriptIdInfo if it is unable to
  1192. * retrieve the script id, or if kScriptId was not passed as an option when
  1193. * capturing the StackTrace.
  1194. */
  1195. int GetScriptId() const;
  1196. /**
  1197. * Returns the name of the resource that contains the script for the
  1198. * function for this StackFrame.
  1199. */
  1200. Local<String> GetScriptName() const;
  1201. /**
  1202. * Returns the name of the resource that contains the script for the
  1203. * function for this StackFrame or sourceURL value if the script name
  1204. * is undefined and its source ends with //# sourceURL=... string or
  1205. * deprecated //@ sourceURL=... string.
  1206. */
  1207. Local<String> GetScriptNameOrSourceURL() const;
  1208. /**
  1209. * Returns the name of the function associated with this stack frame.
  1210. */
  1211. Local<String> GetFunctionName() const;
  1212. /**
  1213. * Returns whether or not the associated function is compiled via a call to
  1214. * eval().
  1215. */
  1216. bool IsEval() const;
  1217. /**
  1218. * Returns whether or not the associated function is called as a
  1219. * constructor via "new".
  1220. */
  1221. bool IsConstructor() const;
  1222. };
  1223. // A StateTag represents a possible state of the VM.
  1224. enum StateTag { JS, GC, COMPILER, OTHER, EXTERNAL, IDLE };
  1225. // A RegisterState represents the current state of registers used
  1226. // by the sampling profiler API.
  1227. struct RegisterState {
  1228. RegisterState() : pc(NULL), sp(NULL), fp(NULL) {}
  1229. void* pc; // Instruction pointer.
  1230. void* sp; // Stack pointer.
  1231. void* fp; // Frame pointer.
  1232. };
  1233. // The output structure filled up by GetStackSample API function.
  1234. struct SampleInfo {
  1235. size_t frames_count;
  1236. StateTag vm_state;
  1237. };
  1238. /**
  1239. * A JSON Parser.
  1240. */
  1241. class V8_EXPORT JSON {
  1242. public:
  1243. /**
  1244. * Tries to parse the string |json_string| and returns it as value if
  1245. * successful.
  1246. *
  1247. * \param json_string The string to parse.
  1248. * \return The corresponding value if successfully parsed.
  1249. */
  1250. static Local<Value> Parse(Local<String> json_string);
  1251. };
  1252. // --- Value ---
  1253. /**
  1254. * The superclass of all JavaScript values and objects.
  1255. */
  1256. class V8_EXPORT Value : public Data {
  1257. public:
  1258. /**
  1259. * Returns true if this value is the undefined value. See ECMA-262
  1260. * 4.3.10.
  1261. */
  1262. V8_INLINE bool IsUndefined() const;
  1263. /**
  1264. * Returns true if this value is the null value. See ECMA-262
  1265. * 4.3.11.
  1266. */
  1267. V8_INLINE bool IsNull() const;
  1268. /**
  1269. * Returns true if this value is true.
  1270. */
  1271. bool IsTrue() const;
  1272. /**
  1273. * Returns true if this value is false.
  1274. */
  1275. bool IsFalse() const;
  1276. /**
  1277. * Returns true if this value is a symbol or a string.
  1278. * This is an experimental feature.
  1279. */
  1280. bool IsName() const;
  1281. /**
  1282. * Returns true if this value is an instance of the String type.
  1283. * See ECMA-262 8.4.
  1284. */
  1285. V8_INLINE bool IsString() const;
  1286. /**
  1287. * Returns true if this value is a symbol.
  1288. * This is an experimental feature.
  1289. */
  1290. bool IsSymbol() const;
  1291. /**
  1292. * Returns true if this value is a function.
  1293. */
  1294. bool IsFunction() const;
  1295. /**
  1296. * Returns true if this value is an array.
  1297. */
  1298. bool IsArray() const;
  1299. /**
  1300. * Returns true if this value is an object.
  1301. */
  1302. bool IsObject() const;
  1303. /**
  1304. * Returns true if this value is boolean.
  1305. */
  1306. bool IsBoolean() const;
  1307. /**
  1308. * Returns true if this value is a number.
  1309. */
  1310. bool IsNumber() const;
  1311. /**
  1312. * Returns true if this value is external.
  1313. */
  1314. bool IsExternal() const;
  1315. /**
  1316. * Returns true if this value is a 32-bit signed integer.
  1317. */
  1318. bool IsInt32() const;
  1319. /**
  1320. * Returns true if this value is a 32-bit unsigned integer.
  1321. */
  1322. bool IsUint32() const;
  1323. /**
  1324. * Returns true if this value is a Date.
  1325. */
  1326. bool IsDate() const;
  1327. /**
  1328. * Returns true if this value is an Arguments object.
  1329. */
  1330. bool IsArgumentsObject() const;
  1331. /**
  1332. * Returns true if this value is a Boolean object.
  1333. */
  1334. bool IsBooleanObject() const;
  1335. /**
  1336. * Returns true if this value is a Number object.
  1337. */
  1338. bool IsNumberObject() const;
  1339. /**
  1340. * Returns true if this value is a String object.
  1341. */
  1342. bool IsStringObject() const;
  1343. /**
  1344. * Returns true if this value is a Symbol object.
  1345. * This is an experimental feature.
  1346. */
  1347. bool IsSymbolObject() const;
  1348. /**
  1349. * Returns true if this value is a NativeError.
  1350. */
  1351. bool IsNativeError() const;
  1352. /**
  1353. * Returns true if this value is a RegExp.
  1354. */
  1355. bool IsRegExp() const;
  1356. /**
  1357. * Returns true if this value is a Generator function.
  1358. * This is an experimental feature.
  1359. */
  1360. bool IsGeneratorFunction() const;
  1361. /**
  1362. * Returns true if this value is a Generator object (iterator).
  1363. * This is an experimental feature.
  1364. */
  1365. bool IsGeneratorObject() const;
  1366. /**
  1367. * Returns true if this value is a Promise.
  1368. * This is an experimental feature.
  1369. */
  1370. bool IsPromise() const;
  1371. /**
  1372. * Returns true if this value is a Map.
  1373. * This is an experimental feature.
  1374. */
  1375. bool IsMap() const;
  1376. /**
  1377. * Returns true if this value is a Set.
  1378. * This is an experimental feature.
  1379. */
  1380. bool IsSet() const;
  1381. /**
  1382. * Returns true if this value is a WeakMap.
  1383. * This is an experimental feature.
  1384. */
  1385. bool IsWeakMap() const;
  1386. /**
  1387. * Returns true if this value is a WeakSet.
  1388. * This is an experimental feature.
  1389. */
  1390. bool IsWeakSet() const;
  1391. /**
  1392. * Returns true if this value is an ArrayBuffer.
  1393. * This is an experimental feature.
  1394. */
  1395. bool IsArrayBuffer() const;
  1396. /**
  1397. * Returns true if this value is an ArrayBufferView.
  1398. * This is an experimental feature.
  1399. */
  1400. bool IsArrayBufferView() const;
  1401. /**
  1402. * Returns true if this value is one of TypedArrays.
  1403. * This is an experimental feature.
  1404. */
  1405. bool IsTypedArray() const;
  1406. /**
  1407. * Returns true if this value is an Uint8Array.
  1408. * This is an experimental feature.
  1409. */
  1410. bool IsUint8Array() const;
  1411. /**
  1412. * Returns true if this value is an Uint8ClampedArray.
  1413. * This is an experimental feature.
  1414. */
  1415. bool IsUint8ClampedArray() const;
  1416. /**
  1417. * Returns true if this value is an Int8Array.
  1418. * This is an experimental feature.
  1419. */
  1420. bool IsInt8Array() const;
  1421. /**
  1422. * Returns true if this value is an Uint16Array.
  1423. * This is an experimental feature.
  1424. */
  1425. bool IsUint16Array() const;
  1426. /**
  1427. * Returns true if this value is an Int16Array.
  1428. * This is an experimental feature.
  1429. */
  1430. bool IsInt16Array() const;
  1431. /**
  1432. * Returns true if this value is an Uint32Array.
  1433. * This is an experimental feature.
  1434. */
  1435. bool IsUint32Array() const;
  1436. /**
  1437. * Returns true if this value is an Int32Array.
  1438. * This is an experimental feature.
  1439. */
  1440. bool IsInt32Array() const;
  1441. /**
  1442. * Returns true if this value is a Float32Array.
  1443. * This is an experimental feature.
  1444. */
  1445. bool IsFloat32Array() const;
  1446. /**
  1447. * Returns true if this value is a Float64Array.
  1448. * This is an experimental feature.
  1449. */
  1450. bool IsFloat64Array() const;
  1451. /**
  1452. * Returns true if this value is a DataView.
  1453. * This is an experimental feature.
  1454. */
  1455. bool IsDataView() const;
  1456. Local<Boolean> ToBoolean() const;
  1457. Local<Number> ToNumber() const;
  1458. Local<String> ToString() const;
  1459. Local<String> ToDetailString() const;
  1460. Local<Object> ToObject() const;
  1461. Local<Integer> ToInteger() const;
  1462. Local<Uint32> ToUint32() const;
  1463. Local<Int32> ToInt32() const;
  1464. /**
  1465. * Attempts to convert a string to an array index.
  1466. * Returns an empty handle if the conversion fails.
  1467. */
  1468. Local<Uint32> ToArrayIndex() const;
  1469. bool BooleanValue() const;
  1470. double NumberValue() const;
  1471. int64_t IntegerValue() const;
  1472. uint32_t Uint32Value() const;
  1473. int32_t Int32Value() const;
  1474. /** JS == */
  1475. bool Equals(Handle<Value> that) const;
  1476. bool StrictEquals(Handle<Value> that) const;
  1477. bool SameValue(Handle<Value> that) const;
  1478. template <class T> V8_INLINE static Value* Cast(T* value);
  1479. private:
  1480. V8_INLINE bool QuickIsUndefined() const;
  1481. V8_INLINE bool QuickIsNull() const;
  1482. V8_INLINE bool QuickIsString() const;
  1483. bool FullIsUndefined() const;
  1484. bool FullIsNull() const;
  1485. bool FullIsString() const;
  1486. };
  1487. /**
  1488. * The superclass of primitive values. See ECMA-262 4.3.2.
  1489. */
  1490. class V8_EXPORT Primitive : public Value { };
  1491. /**
  1492. * A primitive boolean value (ECMA-262, 4.3.14). Either the true
  1493. * or false value.
  1494. */
  1495. class V8_EXPORT Boolean : public Primitive {
  1496. public:
  1497. bool Value() const;
  1498. V8_INLINE static Handle<Boolean> New(Isolate* isolate, bool value);
  1499. };
  1500. /**
  1501. * A superclass for symbols and strings.
  1502. */
  1503. class V8_EXPORT Name : public Primitive {
  1504. public:
  1505. V8_INLINE static Name* Cast(v8::Value* obj);
  1506. private:
  1507. static void CheckCast(v8::Value* obj);
  1508. };
  1509. /**
  1510. * A JavaScript string value (ECMA-262, 4.3.17).
  1511. */
  1512. class V8_EXPORT String : public Name {
  1513. public:
  1514. enum Encoding {
  1515. UNKNOWN_ENCODING = 0x1,
  1516. TWO_BYTE_ENCODING = 0x0,
  1517. ASCII_ENCODING = 0x4, // TODO(yangguo): deprecate this.
  1518. ONE_BYTE_ENCODING = 0x4
  1519. };
  1520. /**
  1521. * Returns the number of characters in this string.
  1522. */
  1523. int Length() const;
  1524. /**
  1525. * Returns the number of bytes in the UTF-8 encoded
  1526. * representation of this string.
  1527. */
  1528. int Utf8Length() const;
  1529. /**
  1530. * Returns whether this string is known to contain only one byte data.
  1531. * Does not read the string.
  1532. * False negatives are possible.
  1533. */
  1534. bool IsOneByte() const;
  1535. /**
  1536. * Returns whether this string contain only one byte data.
  1537. * Will read the entire string in some cases.
  1538. */
  1539. bool ContainsOnlyOneByte() const;
  1540. /**
  1541. * Write the contents of the string to an external buffer.
  1542. * If no arguments are given, expects the buffer to be large
  1543. * enough to hold the entire string and NULL terminator. Copies
  1544. * the contents of the string and the NULL terminator into the
  1545. * buffer.
  1546. *
  1547. * WriteUtf8 will not write partial UTF-8 sequences, preferring to stop
  1548. * before the end of the buffer.
  1549. *
  1550. * Copies up to length characters into the output buffer.
  1551. * Only null-terminates if there is enough space in the buffer.
  1552. *
  1553. * \param buffer The buffer into which the string will be copied.
  1554. * \param start The starting position within the string at which
  1555. * copying begins.
  1556. * \param length The number of characters to copy from the string. For
  1557. * WriteUtf8 the number of bytes in the buffer.
  1558. * \param nchars_ref The number of characters written, can be NULL.
  1559. * \param options Various options that might affect performance of this or
  1560. * subsequent operations.
  1561. * \return The number of characters copied to the buffer excluding the null
  1562. * terminator. For WriteUtf8: The number of bytes copied to the buffer
  1563. * including the null terminator (if written).
  1564. */
  1565. enum WriteOptions {
  1566. NO_OPTIONS = 0,
  1567. HINT_MANY_WRITES_EXPECTED = 1,
  1568. NO_NULL_TERMINATION = 2,
  1569. PRESERVE_ASCII_NULL = 4, // TODO(yangguo): deprecate this.
  1570. PRESERVE_ONE_BYTE_NULL = 4,
  1571. // Used by WriteUtf8 to replace orphan surrogate code units with the
  1572. // unicode replacement character. Needs to be set to guarantee valid UTF-8
  1573. // output.
  1574. REPLACE_INVALID_UTF8 = 8
  1575. };
  1576. // 16-bit character codes.
  1577. int Write(uint16_t* buffer,
  1578. int start = 0,
  1579. int length = -1,
  1580. int options = NO_OPTIONS) const;
  1581. // One byte characters.
  1582. int WriteOneByte(uint8_t* buffer,
  1583. int start = 0,
  1584. int length = -1,
  1585. int options = NO_OPTIONS) const;
  1586. // UTF-8 encoded characters.
  1587. int WriteUtf8(char* buffer,
  1588. int length = -1,
  1589. int* nchars_ref = NULL,
  1590. int options = NO_OPTIONS) const;
  1591. /**
  1592. * A zero length string.
  1593. */
  1594. V8_INLINE static v8::Local<v8::String> Empty(Isolate* isolate);
  1595. /**
  1596. * Returns true if the string is external
  1597. */
  1598. bool IsExternal() const;
  1599. /**
  1600. * Returns true if the string is both external and one-byte.
  1601. */
  1602. bool IsExternalOneByte() const;
  1603. // TODO(yangguo): deprecate this.
  1604. bool IsExternalAscii() const { return IsExternalOneByte(); }
  1605. class V8_EXPORT ExternalStringResourceBase { // NOLINT
  1606. public:
  1607. virtual ~ExternalStringResourceBase() {}
  1608. protected:
  1609. ExternalStringResourceBase() {}
  1610. /**
  1611. * Internally V8 will call this Dispose method when the external string
  1612. * resource is no longer needed. The default implementation will use the
  1613. * delete operator. This method can be overridden in subclasses to
  1614. * control how allocated external string resources are disposed.
  1615. */
  1616. virtual void Dispose() { delete this; }
  1617. private:
  1618. // Disallow copying and assigning.
  1619. ExternalStringResourceBase(const ExternalStringResourceBase&);
  1620. void operator=(const ExternalStringResourceBase&);
  1621. friend class v8::internal::Heap;
  1622. };
  1623. /**
  1624. * An ExternalStringResource is a wrapper around a two-byte string
  1625. * buffer that resides outside V8's heap. Implement an
  1626. * ExternalStringResource to manage the life cycle of the underlying
  1627. * buffer. Note that the string data must be immutable.
  1628. */
  1629. class V8_EXPORT ExternalStringResource
  1630. : public ExternalStringResourceBase {
  1631. public:
  1632. /**
  1633. * Override the destructor to manage the life cycle of the underlying
  1634. * buffer.
  1635. */
  1636. virtual ~ExternalStringResource() {}
  1637. /**
  1638. * The string data from the underlying buffer.
  1639. */
  1640. virtual const uint16_t* data() const = 0;
  1641. /**
  1642. * The length of the string. That is, the number of two-byte characters.
  1643. */
  1644. virtual size_t length() const = 0;
  1645. protected:
  1646. ExternalStringResource() {}
  1647. };
  1648. /**
  1649. * An ExternalOneByteStringResource is a wrapper around an one-byte
  1650. * string buffer that resides outside V8's heap. Implement an
  1651. * ExternalOneByteStringResource to manage the life cycle of the
  1652. * underlying buffer. Note that the string data must be immutable
  1653. * and that the data must be Latin-1 and not UTF-8, which would require
  1654. * special treatment internally in the engine and do not allow efficient
  1655. * indexing. Use String::New or convert to 16 bit data for non-Latin1.
  1656. */
  1657. class V8_EXPORT ExternalOneByteStringResource
  1658. : public ExternalStringResourceBase {
  1659. public:
  1660. /**
  1661. * Override the destructor to manage the life cycle of the underlying
  1662. * buffer.
  1663. */
  1664. virtual ~ExternalOneByteStringResource() {}
  1665. /** The string data from the underlying buffer.*/
  1666. virtual const char* data() const = 0;
  1667. /** The number of Latin-1 characters in the string.*/
  1668. virtual size_t length() const = 0;
  1669. protected:
  1670. ExternalOneByteStringResource() {}
  1671. };
  1672. typedef ExternalOneByteStringResource ExternalAsciiStringResource;
  1673. /**
  1674. * If the string is an external string, return the ExternalStringResourceBase
  1675. * regardless of the encoding, otherwise return NULL. The encoding of the
  1676. * string is returned in encoding_out.
  1677. */
  1678. V8_INLINE ExternalStringResourceBase* GetExternalStringResourceBase(
  1679. Encoding* encoding_out) const;
  1680. /**
  1681. * Get the ExternalStringResource for an external string. Returns
  1682. * NULL if IsExternal() doesn't return true.
  1683. */
  1684. V8_INLINE ExternalStringResource* GetExternalStringResource() const;
  1685. /**
  1686. * Get the ExternalOneByteStringResource for an external one-byte string.
  1687. * Returns NULL if IsExternalOneByte() doesn't return true.
  1688. */
  1689. const ExternalOneByteStringResource* GetExternalOneByteStringResource() const;
  1690. // TODO(yangguo): deprecate this.
  1691. const ExternalAsciiStringResource* GetExternalAsciiStringResource() const {
  1692. return GetExternalOneByteStringResource();
  1693. }
  1694. V8_INLINE static String* Cast(v8::Value* obj);
  1695. enum NewStringType {
  1696. kNormalString, kInternalizedString, kUndetectableString
  1697. };
  1698. /** Allocates a new string from UTF-8 data.*/
  1699. static Local<String> NewFromUtf8(Isolate* isolate,
  1700. const char* data,
  1701. NewStringType type = kNormalString,
  1702. int length = -1);
  1703. /** Allocates a new string from Latin-1 data.*/
  1704. static Local<String> NewFromOneByte(
  1705. Isolate* isolate,
  1706. const uint8_t* data,
  1707. NewStringType type = kNormalString,
  1708. int length = -1);
  1709. /** Allocates a new string from UTF-16 data.*/
  1710. static Local<String> NewFromTwoByte(
  1711. Isolate* isolate,
  1712. const uint16_t* data,
  1713. NewStringType type = kNormalString,
  1714. int length = -1);
  1715. /**
  1716. * Creates a new string by concatenating the left and the right strings
  1717. * passed in as parameters.
  1718. */
  1719. static Local<String> Concat(Handle<String> left, Handle<String> right);
  1720. /**
  1721. * Creates a new external string using the data defined in the given
  1722. * resource. When the external string is no longer live on V8's heap the
  1723. * resource will be disposed by calling its Dispose method. The caller of
  1724. * this function should not otherwise delete or modify the resource. Neither
  1725. * should the underlying buffer be deallocated or modified except through the
  1726. * destructor of the external string resource.
  1727. */
  1728. static Local<String> NewExternal(Isolate* isolate,
  1729. ExternalStringResource* resource);
  1730. /**
  1731. * Associate an external string resource with this string by transforming it
  1732. * in place so that existing references to this string in the JavaScript heap
  1733. * will use the external string resource. The external string resource's
  1734. * character contents need to be equivalent to this string.
  1735. * Returns true if the string has been changed to be an external string.
  1736. * The string is not modified if the operation fails. See NewExternal for
  1737. * information on the lifetime of the resource.
  1738. */
  1739. bool MakeExternal(ExternalStringResource* resource);
  1740. /**
  1741. * Creates a new external string using the one-byte data defined in the given
  1742. * resource. When the external string is no longer live on V8's heap the
  1743. * resource will be disposed by calling its Dispose method. The caller of
  1744. * this function should not otherwise delete or modify the resource. Neither
  1745. * should the underlying buffer be deallocated or modified except through the
  1746. * destructor of the external string resource.
  1747. */
  1748. static Local<String> NewExternal(Isolate* isolate,
  1749. ExternalOneByteStringResource* resource);
  1750. /**
  1751. * Associate an external string resource with this string by transforming it
  1752. * in place so that existing references to this string in the JavaScript heap
  1753. * will use the external string resource. The external string resource's
  1754. * character contents need to be equivalent to this string.
  1755. * Returns true if the string has been changed to be an external string.
  1756. * The string is not modified if the operation fails. See NewExternal for
  1757. * information on the lifetime of the resource.
  1758. */
  1759. bool MakeExternal(ExternalOneByteStringResource* resource);
  1760. /**
  1761. * Returns true if this string can be made external.
  1762. */
  1763. bool CanMakeExternal();
  1764. /**
  1765. * Converts an object to a UTF-8-encoded character array. Useful if
  1766. * you want to print the object. If conversion to a string fails
  1767. * (e.g. due to an exception in the toString() method of the object)
  1768. * then the length() method returns 0 and the * operator returns
  1769. * NULL.
  1770. */
  1771. class V8_EXPORT Utf8Value {
  1772. public:
  1773. explicit Utf8Value(Handle<v8::Value> obj);
  1774. ~Utf8Value();
  1775. char* operator*() { return str_; }
  1776. const char* operator*() const { return str_; }
  1777. int length() const { return length_; }
  1778. private:
  1779. char* str_;
  1780. int length_;
  1781. // Disallow copying and assigning.
  1782. Utf8Value(const Utf8Value&);
  1783. void operator=(const Utf8Value&);
  1784. };
  1785. /**
  1786. * Converts an object to a two-byte string.
  1787. * If conversion to a string fails (eg. due to an exception in the toString()
  1788. * method of the object) then the length() method returns 0 and the * operator
  1789. * returns NULL.
  1790. */
  1791. class V8_EXPORT Value {
  1792. public:
  1793. explicit Value(Handle<v8::Value> obj);
  1794. ~Value();
  1795. uint16_t* operator*() { return str_; }
  1796. const uint16_t* operator*() const { return str_; }
  1797. int length() const { return length_; }
  1798. private:
  1799. uint16_t* str_;
  1800. int length_;
  1801. // Disallow copying and assigning.
  1802. Value(const Value&);
  1803. void operator=(const Value&);
  1804. };
  1805. private:
  1806. void VerifyExternalStringResourceBase(ExternalStringResourceBase* v,
  1807. Encoding encoding) const;
  1808. void VerifyExternalStringResource(ExternalStringResource* val) const;
  1809. static void CheckCast(v8::Value* obj);
  1810. };
  1811. /**
  1812. * A JavaScript symbol (ECMA-262 edition 6)
  1813. *
  1814. * This is an experimental feature. Use at your own risk.
  1815. */
  1816. class V8_EXPORT Symbol : public Name {
  1817. public:
  1818. // Returns the print name string of the symbol, or undefined if none.
  1819. Local<Value> Name() const;
  1820. // Create a symbol. If name is not empty, it will be used as the description.
  1821. static Local<Symbol> New(
  1822. Isolate *isolate, Local<String> name = Local<String>());
  1823. // Access global symbol registry.
  1824. // Note that symbols created this way are never collected, so
  1825. // they should only be used for statically fixed properties.
  1826. // Also, there is only one global name space for the names used as keys.
  1827. // To minimize the potential for clashes, use qualified names as keys.
  1828. static Local<Symbol> For(Isolate *isolate, Local<String> name);
  1829. // Retrieve a global symbol. Similar to |For|, but using a separate
  1830. // registry that is not accessible by (and cannot clash with) JavaScript code.
  1831. static Local<Symbol> ForApi(Isolate *isolate, Local<String> name);
  1832. // Well-known symbols
  1833. static Local<Symbol> GetIterator(Isolate* isolate);
  1834. static Local<Symbol> GetUnscopables(Isolate* isolate);
  1835. V8_INLINE static Symbol* Cast(v8::Value* obj);
  1836. private:
  1837. Symbol();
  1838. static void CheckCast(v8::Value* obj);
  1839. };
  1840. /**
  1841. * A private symbol
  1842. *
  1843. * This is an experimental feature. Use at your own risk.
  1844. */
  1845. class V8_EXPORT Private : public Data {
  1846. public:
  1847. // Returns the print name string of the private symbol, or undefined if none.
  1848. Local<Value> Name() const;
  1849. // Create a private symbol. If name is not empty, it will be the description.
  1850. static Local<Private> New(
  1851. Isolate *isolate, Local<String> name = Local<String>());
  1852. // Retrieve a global private symbol. If a symbol with this name has not
  1853. // been retrieved in the same isolate before, it is created.
  1854. // Note that private symbols created this way are never collected, so
  1855. // they should only be used for statically fixed properties.
  1856. // Also, there is only one global name space for the names used as keys.
  1857. // To minimize the potential for clashes, use qualified names as keys,
  1858. // e.g., "Class#property".
  1859. static Local<Private> ForApi(Isolate *isolate, Local<String> name);
  1860. private:
  1861. Private();
  1862. };
  1863. /**
  1864. * A JavaScript number value (ECMA-262, 4.3.20)
  1865. */
  1866. class V8_EXPORT Number : public Primitive {
  1867. public:
  1868. double Value() const;
  1869. static Local<Number> New(Isolate* isolate, double value);
  1870. V8_INLINE static Number* Cast(v8::Value* obj);
  1871. private:
  1872. Number();
  1873. static void CheckCast(v8::Value* obj);
  1874. };
  1875. /**
  1876. * A JavaScript value representing a signed integer.
  1877. */
  1878. class V8_EXPORT Integer : public Number {
  1879. public:
  1880. static Local<Integer> New(Isolate* isolate, int32_t value);
  1881. static Local<Integer> NewFromUnsigned(Isolate* isolate, uint32_t value);
  1882. int64_t Value() const;
  1883. V8_INLINE static Integer* Cast(v8::Value* obj);
  1884. private:
  1885. Integer();
  1886. static void CheckCast(v8::Value* obj);
  1887. };
  1888. /**
  1889. * A JavaScript value representing a 32-bit signed integer.
  1890. */
  1891. class V8_EXPORT Int32 : public Integer {
  1892. public:
  1893. int32_t Value() const;
  1894. private:
  1895. Int32();
  1896. };
  1897. /**
  1898. * A JavaScript value representing a 32-bit unsigned integer.
  1899. */
  1900. class V8_EXPORT Uint32 : public Integer {
  1901. public:
  1902. uint32_t Value() const;
  1903. private:
  1904. Uint32();
  1905. };
  1906. enum PropertyAttribute {
  1907. None = 0,
  1908. ReadOnly = 1 << 0,
  1909. DontEnum = 1 << 1,
  1910. DontDelete = 1 << 2
  1911. };
  1912. enum ExternalArrayType {
  1913. kExternalInt8Array = 1,
  1914. kExternalUint8Array,
  1915. kExternalInt16Array,
  1916. kExternalUint16Array,
  1917. kExternalInt32Array,
  1918. kExternalUint32Array,
  1919. kExternalFloat32Array,
  1920. kExternalFloat64Array,
  1921. kExternalUint8ClampedArray,
  1922. // Legacy constant names
  1923. kExternalByteArray = kExternalInt8Array,
  1924. kExternalUnsignedByteArray = kExternalUint8Array,
  1925. kExternalShortArray = kExternalInt16Array,
  1926. kExternalUnsignedShortArray = kExternalUint16Array,
  1927. kExternalIntArray = kExternalInt32Array,
  1928. kExternalUnsignedIntArray = kExternalUint32Array,
  1929. kExternalFloatArray = kExternalFloat32Array,
  1930. kExternalDoubleArray = kExternalFloat64Array,
  1931. kExternalPixelArray = kExternalUint8ClampedArray
  1932. };
  1933. /**
  1934. * Accessor[Getter|Setter] are used as callback functions when
  1935. * setting|getting a particular property. See Object and ObjectTemplate's
  1936. * method SetAccessor.
  1937. */
  1938. typedef void (*AccessorGetterCallback)(
  1939. Local<String> property,
  1940. const PropertyCallbackInfo<Value>& info);
  1941. typedef void (*AccessorNameGetterCallback)(
  1942. Local<Name> property,
  1943. const PropertyCallbackInfo<Value>& info);
  1944. typedef void (*AccessorSetterCallback)(
  1945. Local<String> property,
  1946. Local<Value> value,
  1947. const PropertyCallbackInfo<void>& info);
  1948. typedef void (*AccessorNameSetterCallback)(
  1949. Local<Name> property,
  1950. Local<Value> value,
  1951. const PropertyCallbackInfo<void>& info);
  1952. /**
  1953. * Access control specifications.
  1954. *
  1955. * Some accessors should be accessible across contexts. These
  1956. * accessors have an explicit access control parameter which specifies
  1957. * the kind of cross-context access that should be allowed.
  1958. *
  1959. * TODO(dcarney): Remove PROHIBITS_OVERWRITING as it is now unused.
  1960. */
  1961. enum AccessControl {
  1962. DEFAULT = 0,
  1963. ALL_CAN_READ = 1,
  1964. ALL_CAN_WRITE = 1 << 1,
  1965. PROHIBITS_OVERWRITING = 1 << 2
  1966. };
  1967. /**
  1968. * A JavaScript object (ECMA-262, 4.3.3)
  1969. */
  1970. class V8_EXPORT Object : public Value {
  1971. public:
  1972. bool Set(Handle<Value> key, Handle<Value> value);
  1973. bool Set(uint32_t index, Handle<Value> value);
  1974. // Sets an own property on this object bypassing interceptors and
  1975. // overriding accessors or read-only properties.
  1976. //
  1977. // Note that if the object has an interceptor the property will be set
  1978. // locally, but since the interceptor takes precedence the local property
  1979. // will only be returned if the interceptor doesn't return a value.
  1980. //
  1981. // Note also that this only works for named properties.
  1982. bool ForceSet(Handle<Value> key,
  1983. Handle<Value> value,
  1984. PropertyAttribute attribs = None);
  1985. Local<Value> Get(Handle<Value> key);
  1986. Local<Value> Get(uint32_t index);
  1987. /**
  1988. * Gets the property attributes of a property which can be None or
  1989. * any combination of ReadOnly, DontEnum and DontDelete. Returns
  1990. * None when the property doesn't exist.
  1991. */
  1992. PropertyAttribute GetPropertyAttributes(Handle<Value> key);
  1993. /**
  1994. * Returns Object.getOwnPropertyDescriptor as per ES5 section 15.2.3.3.
  1995. */
  1996. Local<Value> GetOwnPropertyDescriptor(Local<String> key);
  1997. bool Has(Handle<Value> key);
  1998. bool Delete(Handle<Value> key);
  1999. // Delete a property on this object bypassing interceptors and
  2000. // ignoring dont-delete attributes.
  2001. bool ForceDelete(Handle<Value> key);
  2002. bool Has(uint32_t index);
  2003. bool Delete(uint32_t index);
  2004. bool SetAccessor(Handle<String> name,
  2005. AccessorGetterCallback getter,
  2006. AccessorSetterCallback setter = 0,
  2007. Handle<Value> data = Handle<Value>(),
  2008. AccessControl settings = DEFAULT,
  2009. PropertyAttribute attribute = None);
  2010. bool SetAccessor(Handle<Name> name,
  2011. AccessorNameGetterCallback getter,
  2012. AccessorNameSetterCallback setter = 0,
  2013. Handle<Value> data = Handle<Value>(),
  2014. AccessControl settings = DEFAULT,
  2015. PropertyAttribute attribute = None);
  2016. // This function is not yet stable and should not be used at this time.
  2017. bool SetDeclaredAccessor(Local<Name> name,
  2018. Local<DeclaredAccessorDescriptor> descriptor,
  2019. PropertyAttribute attribute = None,
  2020. AccessControl settings = DEFAULT);
  2021. void SetAccessorProperty(Local<Name> name,
  2022. Local<Function> getter,
  2023. Handle<Function> setter = Handle<Function>(),
  2024. PropertyAttribute attribute = None,
  2025. AccessControl settings = DEFAULT);
  2026. /**
  2027. * Functionality for private properties.
  2028. * This is an experimental feature, use at your own risk.
  2029. * Note: Private properties are inherited. Do not rely on this, since it may
  2030. * change.
  2031. */
  2032. bool HasPrivate(Handle<Private> key);
  2033. bool SetPrivate(Handle<Private> key, Handle<Value> value);
  2034. bool DeletePrivate(Handle<Private> key);
  2035. Local<Value> GetPrivate(Handle<Private> key);
  2036. /**
  2037. * Returns an array containing the names of the enumerable properties
  2038. * of this object, including properties from prototype objects. The
  2039. * array returned by this method contains the same values as would
  2040. * be enumerated by a for-in statement over this object.
  2041. */
  2042. Local<Array> GetPropertyNames();
  2043. /**
  2044. * This function has the same functionality as GetPropertyNames but
  2045. * the returned array doesn't contain the names of properties from
  2046. * prototype objects.
  2047. */
  2048. Local<Array> GetOwnPropertyNames();
  2049. /**
  2050. * Get the prototype object. This does not skip objects marked to
  2051. * be skipped by __proto__ and it does not consult the security
  2052. * handler.
  2053. */
  2054. Local<Value> GetPrototype();
  2055. /**
  2056. * Set the prototype object. This does not skip objects marked to
  2057. * be skipped by __proto__ and it does not consult the security
  2058. * handler.
  2059. */
  2060. bool SetPrototype(Handle<Value> prototype);
  2061. /**
  2062. * Finds an instance of the given function template in the prototype
  2063. * chain.
  2064. */
  2065. Local<Object> FindInstanceInPrototypeChain(Handle<FunctionTemplate> tmpl);
  2066. /**
  2067. * Call builtin Object.prototype.toString on this object.
  2068. * This is different from Value::ToString() that may call
  2069. * user-defined toString function. This one does not.
  2070. */
  2071. Local<String> ObjectProtoToString();
  2072. /**
  2073. * Returns the name of the function invoked as a constructor for this object.
  2074. */
  2075. Local<String> GetConstructorName();
  2076. /** Gets the number of internal fields for this Object. */
  2077. int InternalFieldCount();
  2078. /** Same as above, but works for Persistents */
  2079. V8_INLINE static int InternalFieldCount(
  2080. const PersistentBase<Object>& object) {
  2081. return object.val_->InternalFieldCount();
  2082. }
  2083. /** Gets the value from an internal field. */
  2084. V8_INLINE Local<Value> GetInternalField(int index);
  2085. /** Sets the value in an internal field. */
  2086. void SetInternalField(int index, Handle<Value> value);
  2087. /**
  2088. * Gets a 2-byte-aligned native pointer from an internal field. This field
  2089. * must have been set by SetAlignedPointerInInternalField, everything else
  2090. * leads to undefined behavior.
  2091. */
  2092. V8_INLINE void* GetAlignedPointerFromInternalField(int index);
  2093. /** Same as above, but works for Persistents */
  2094. V8_INLINE static void* GetAlignedPointerFromInternalField(
  2095. const PersistentBase<Object>& object, int index) {
  2096. return object.val_->GetAlignedPointerFromInternalField(index);
  2097. }
  2098. /**
  2099. * Sets a 2-byte-aligned native pointer in an internal field. To retrieve such
  2100. * a field, GetAlignedPointerFromInternalField must be used, everything else
  2101. * leads to undefined behavior.
  2102. */
  2103. void SetAlignedPointerInInternalField(int index, void* value);
  2104. // Testers for local properties.
  2105. bool HasOwnProperty(Handle<String> key);
  2106. bool HasRealNamedProperty(Handle<String> key);
  2107. bool HasRealIndexedProperty(uint32_t index);
  2108. bool HasRealNamedCallbackProperty(Handle<String> key);
  2109. /**
  2110. * If result.IsEmpty() no real property was located in the prototype chain.
  2111. * This means interceptors in the prototype chain are not called.
  2112. */
  2113. Local<Value> GetRealNamedPropertyInPrototypeChain(Handle<String> key);
  2114. /**
  2115. * If result.IsEmpty() no real property was located on the object or
  2116. * in the prototype chain.
  2117. * This means interceptors in the prototype chain are not called.
  2118. */
  2119. Local<Value> GetRealNamedProperty(Handle<String> key);
  2120. /** Tests for a named lookup interceptor.*/
  2121. bool HasNamedLookupInterceptor();
  2122. /** Tests for an index lookup interceptor.*/
  2123. bool HasIndexedLookupInterceptor();
  2124. /**
  2125. * Turns on access check on the object if the object is an instance of
  2126. * a template that has access check callbacks. If an object has no
  2127. * access check info, the object cannot be accessed by anyone.
  2128. */
  2129. void TurnOnAccessCheck();
  2130. /**
  2131. * Returns the identity hash for this object. The current implementation
  2132. * uses a hidden property on the object to store the identity hash.
  2133. *
  2134. * The return value will never be 0. Also, it is not guaranteed to be
  2135. * unique.
  2136. */
  2137. int GetIdentityHash();
  2138. /**
  2139. * Access hidden properties on JavaScript objects. These properties are
  2140. * hidden from the executing JavaScript and only accessible through the V8
  2141. * C++ API. Hidden properties introduced by V8 internally (for example the
  2142. * identity hash) are prefixed with "v8::".
  2143. */
  2144. bool SetHiddenValue(Handle<String> key, Handle<Value> value);
  2145. Local<Value> GetHiddenValue(Handle<String> key);
  2146. bool DeleteHiddenValue(Handle<String> key);
  2147. /**
  2148. * Returns true if this is an instance of an api function (one
  2149. * created from a function created from a function template) and has
  2150. * been modified since it was created. Note that this method is
  2151. * conservative and may return true for objects that haven't actually
  2152. * been modified.
  2153. */
  2154. bool IsDirty();
  2155. /**
  2156. * Clone this object with a fast but shallow copy. Values will point
  2157. * to the same values as the original object.
  2158. */
  2159. Local<Object> Clone();
  2160. /**
  2161. * Returns the context in which the object was created.
  2162. */
  2163. Local<Context> CreationContext();
  2164. /**
  2165. * Set the backing store of the indexed properties to be managed by the
  2166. * embedding layer. Access to the indexed properties will follow the rules
  2167. * spelled out in CanvasPixelArray.
  2168. * Note: The embedding program still owns the data and needs to ensure that
  2169. * the backing store is preserved while V8 has a reference.
  2170. */
  2171. void SetIndexedPropertiesToPixelData(uint8_t* data, int length);
  2172. bool HasIndexedPropertiesInPixelData();
  2173. uint8_t* GetIndexedPropertiesPixelData();
  2174. int GetIndexedPropertiesPixelDataLength();
  2175. /**
  2176. * Set the backing store of the indexed properties to be managed by the
  2177. * embedding layer. Access to the indexed properties will follow the rules
  2178. * spelled out for the CanvasArray subtypes in the WebGL specification.
  2179. * Note: The embedding program still owns the data and needs to ensure that
  2180. * the backing store is preserved while V8 has a reference.
  2181. */
  2182. void SetIndexedPropertiesToExternalArrayData(void* data,
  2183. ExternalArrayType array_type,
  2184. int number_of_elements);
  2185. bool HasIndexedPropertiesInExternalArrayData();
  2186. void* GetIndexedPropertiesExternalArrayData();
  2187. ExternalArrayType GetIndexedPropertiesExternalArrayDataType();
  2188. int GetIndexedPropertiesExternalArrayDataLength();
  2189. /**
  2190. * Checks whether a callback is set by the
  2191. * ObjectTemplate::SetCallAsFunctionHandler method.
  2192. * When an Object is callable this method returns true.
  2193. */
  2194. bool IsCallable();
  2195. /**
  2196. * Call an Object as a function if a callback is set by the
  2197. * ObjectTemplate::SetCallAsFunctionHandler method.
  2198. */
  2199. Local<Value> CallAsFunction(Handle<Value> recv,
  2200. int argc,
  2201. Handle<Value> argv[]);
  2202. /**
  2203. * Call an Object as a constructor if a callback is set by the
  2204. * ObjectTemplate::SetCallAsFunctionHandler method.
  2205. * Note: This method behaves like the Function::NewInstance method.
  2206. */
  2207. Local<Value> CallAsConstructor(int argc, Handle<Value> argv[]);
  2208. /**
  2209. * Return the isolate to which the Object belongs to.
  2210. */
  2211. Isolate* GetIsolate();
  2212. static Local<Object> New(Isolate* isolate);
  2213. V8_INLINE static Object* Cast(Value* obj);
  2214. private:
  2215. Object();
  2216. static void CheckCast(Value* obj);
  2217. Local<Value> SlowGetInternalField(int index);
  2218. void* SlowGetAlignedPointerFromInternalField(int index);
  2219. };
  2220. /**
  2221. * An instance of the built-in array constructor (ECMA-262, 15.4.2).
  2222. */
  2223. class V8_EXPORT Array : public Object {
  2224. public:
  2225. uint32_t Length() const;
  2226. /**
  2227. * Clones an element at index |index|. Returns an empty
  2228. * handle if cloning fails (for any reason).
  2229. */
  2230. Local<Object> CloneElementAt(uint32_t index);
  2231. /**
  2232. * Creates a JavaScript array with the given length. If the length
  2233. * is negative the returned array will have length 0.
  2234. */
  2235. static Local<Array> New(Isolate* isolate, int length = 0);
  2236. V8_INLINE static Array* Cast(Value* obj);
  2237. private:
  2238. Array();
  2239. static void CheckCast(Value* obj);
  2240. };
  2241. template<typename T>
  2242. class ReturnValue {
  2243. public:
  2244. template <class S> V8_INLINE ReturnValue(const ReturnValue<S>& that)
  2245. : value_(that.value_) {
  2246. TYPE_CHECK(T, S);
  2247. }
  2248. // Handle setters
  2249. template <typename S> V8_INLINE void Set(const Persistent<S>& handle);
  2250. template <typename S> V8_INLINE void Set(const Handle<S> handle);
  2251. // Fast primitive setters
  2252. V8_INLINE void Set(bool value);
  2253. V8_INLINE void Set(double i);
  2254. V8_INLINE void Set(int32_t i);
  2255. V8_INLINE void Set(uint32_t i);
  2256. // Fast JS primitive setters
  2257. V8_INLINE void SetNull();
  2258. V8_INLINE void SetUndefined();
  2259. V8_INLINE void SetEmptyString();
  2260. // Convenience getter for Isolate
  2261. V8_INLINE Isolate* GetIsolate();
  2262. // Pointer setter: Uncompilable to prevent inadvertent misuse.
  2263. template <typename S>
  2264. V8_INLINE void Set(S* whatever);
  2265. private:
  2266. template<class F> friend class ReturnValue;
  2267. template<class F> friend class FunctionCallbackInfo;
  2268. template<class F> friend class PropertyCallbackInfo;
  2269. template<class F, class G, class H> friend class PersistentValueMap;
  2270. V8_INLINE void SetInternal(internal::Object* value) { *value_ = value; }
  2271. V8_INLINE internal::Object* GetDefaultValue();
  2272. V8_INLINE explicit ReturnValue(internal::Object** slot);
  2273. internal::Object** value_;
  2274. };
  2275. /**
  2276. * The argument information given to function call callbacks. This
  2277. * class provides access to information about the context of the call,
  2278. * including the receiver, the number and values of arguments, and
  2279. * the holder of the function.
  2280. */
  2281. template<typename T>
  2282. class FunctionCallbackInfo {
  2283. public:
  2284. V8_INLINE int Length() const;
  2285. V8_INLINE Local<Value> operator[](int i) const;
  2286. V8_INLINE Local<Function> Callee() const;
  2287. V8_INLINE Local<Object> This() const;
  2288. V8_INLINE Local<Object> Holder() const;
  2289. V8_INLINE bool IsConstructCall() const;
  2290. V8_INLINE Local<Value> Data() const;
  2291. V8_INLINE Isolate* GetIsolate() const;
  2292. V8_INLINE ReturnValue<T> GetReturnValue() const;
  2293. // This shouldn't be public, but the arm compiler needs it.
  2294. static const int kArgsLength = 7;
  2295. protected:
  2296. friend class internal::FunctionCallbackArguments;
  2297. friend class internal::CustomArguments<FunctionCallbackInfo>;
  2298. static const int kHolderIndex = 0;
  2299. static const int kIsolateIndex = 1;
  2300. static const int kReturnValueDefaultValueIndex = 2;
  2301. static const int kReturnValueIndex = 3;
  2302. static const int kDataIndex = 4;
  2303. static const int kCalleeIndex = 5;
  2304. static const int kContextSaveIndex = 6;
  2305. V8_INLINE FunctionCallbackInfo(internal::Object** implicit_args,
  2306. internal::Object** values,
  2307. int length,
  2308. bool is_construct_call);
  2309. internal::Object** implicit_args_;
  2310. internal::Object** values_;
  2311. int length_;
  2312. bool is_construct_call_;
  2313. };
  2314. /**
  2315. * The information passed to a property callback about the context
  2316. * of the property access.
  2317. */
  2318. template<typename T>
  2319. class PropertyCallbackInfo {
  2320. public:
  2321. V8_INLINE Isolate* GetIsolate() const;
  2322. V8_INLINE Local<Value> Data() const;
  2323. V8_INLINE Local<Object> This() const;
  2324. V8_INLINE Local<Object> Holder() const;
  2325. V8_INLINE ReturnValue<T> GetReturnValue() const;
  2326. // This shouldn't be public, but the arm compiler needs it.
  2327. static const int kArgsLength = 6;
  2328. protected:
  2329. friend class MacroAssembler;
  2330. friend class internal::PropertyCallbackArguments;
  2331. friend class internal::CustomArguments<PropertyCallbackInfo>;
  2332. static const int kHolderIndex = 0;
  2333. static const int kIsolateIndex = 1;
  2334. static const int kReturnValueDefaultValueIndex = 2;
  2335. static const int kReturnValueIndex = 3;
  2336. static const int kDataIndex = 4;
  2337. static const int kThisIndex = 5;
  2338. V8_INLINE PropertyCallbackInfo(internal::Object** args) : args_(args) {}
  2339. internal::Object** args_;
  2340. };
  2341. typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
  2342. /**
  2343. * A JavaScript function object (ECMA-262, 15.3).
  2344. */
  2345. class V8_EXPORT Function : public Object {
  2346. public:
  2347. /**
  2348. * Create a function in the current execution context
  2349. * for a given FunctionCallback.
  2350. */
  2351. static Local<Function> New(Isolate* isolate,
  2352. FunctionCallback callback,
  2353. Local<Value> data = Local<Value>(),
  2354. int length = 0);
  2355. Local<Object> NewInstance() const;
  2356. Local<Object> NewInstance(int argc, Handle<Value> argv[]) const;
  2357. Local<Value> Call(Handle<Value> recv, int argc, Handle<Value> argv[]);
  2358. void SetName(Handle<String> name);
  2359. Handle<Value> GetName() const;
  2360. /**
  2361. * Name inferred from variable or property assignment of this function.
  2362. * Used to facilitate debugging and profiling of JavaScript code written
  2363. * in an OO style, where many functions are anonymous but are assigned
  2364. * to object properties.
  2365. */
  2366. Handle<Value> GetInferredName() const;
  2367. /**
  2368. * User-defined name assigned to the "displayName" property of this function.
  2369. * Used to facilitate debugging and profiling of JavaScript code.
  2370. */
  2371. Handle<Value> GetDisplayName() const;
  2372. /**
  2373. * Returns zero based line number of function body and
  2374. * kLineOffsetNotFound if no information available.
  2375. */
  2376. int GetScriptLineNumber() const;
  2377. /**
  2378. * Returns zero based column number of function body and
  2379. * kLineOffsetNotFound if no information available.
  2380. */
  2381. int GetScriptColumnNumber() const;
  2382. /**
  2383. * Tells whether this function is builtin.
  2384. */
  2385. bool IsBuiltin() const;
  2386. /**
  2387. * Returns scriptId.
  2388. */
  2389. int ScriptId() const;
  2390. /**
  2391. * Returns the original function if this function is bound, else returns
  2392. * v8::Undefined.
  2393. */
  2394. Local<Value> GetBoundFunction() const;
  2395. ScriptOrigin GetScriptOrigin() const;
  2396. V8_INLINE static Function* Cast(Value* obj);
  2397. static const int kLineOffsetNotFound;
  2398. private:
  2399. Function();
  2400. static void CheckCast(Value* obj);
  2401. };
  2402. /**
  2403. * An instance of the built-in Promise constructor (ES6 draft).
  2404. * This API is experimental. Only works with --harmony flag.
  2405. */
  2406. class V8_EXPORT Promise : public Object {
  2407. public:
  2408. class V8_EXPORT Resolver : public Object {
  2409. public:
  2410. /**
  2411. * Create a new resolver, along with an associated promise in pending state.
  2412. */
  2413. static Local<Resolver> New(Isolate* isolate);
  2414. /**
  2415. * Extract the associated promise.
  2416. */
  2417. Local<Promise> GetPromise();
  2418. /**
  2419. * Resolve/reject the associated promise with a given value.
  2420. * Ignored if the promise is no longer pending.
  2421. */
  2422. void Resolve(Handle<Value> value);
  2423. void Reject(Handle<Value> value);
  2424. V8_INLINE static Resolver* Cast(Value* obj);
  2425. private:
  2426. Resolver();
  2427. static void CheckCast(Value* obj);
  2428. };
  2429. /**
  2430. * Register a resolution/rejection handler with a promise.
  2431. * The handler is given the respective resolution/rejection value as
  2432. * an argument. If the promise is already resolved/rejected, the handler is
  2433. * invoked at the end of turn.
  2434. */
  2435. Local<Promise> Chain(Handle<Function> handler);
  2436. Local<Promise> Catch(Handle<Function> handler);
  2437. Local<Promise> Then(Handle<Function> handler);
  2438. /**
  2439. * Returns true if the promise has at least one derived promise, and
  2440. * therefore resolve/reject handlers (including default handler).
  2441. */
  2442. bool HasHandler();
  2443. V8_INLINE static Promise* Cast(Value* obj);
  2444. private:
  2445. Promise();
  2446. static void CheckCast(Value* obj);
  2447. };
  2448. #ifndef V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT
  2449. // The number of required internal fields can be defined by embedder.
  2450. #define V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT 2
  2451. #endif
  2452. /**
  2453. * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
  2454. * This API is experimental and may change significantly.
  2455. */
  2456. class V8_EXPORT ArrayBuffer : public Object {
  2457. public:
  2458. /**
  2459. * Allocator that V8 uses to allocate |ArrayBuffer|'s memory.
  2460. * The allocator is a global V8 setting. It should be set with
  2461. * V8::SetArrayBufferAllocator prior to creation of a first ArrayBuffer.
  2462. *
  2463. * This API is experimental and may change significantly.
  2464. */
  2465. class V8_EXPORT Allocator { // NOLINT
  2466. public:
  2467. virtual ~Allocator() {}
  2468. /**
  2469. * Allocate |length| bytes. Return NULL if allocation is not successful.
  2470. * Memory should be initialized to zeroes.
  2471. */
  2472. virtual void* Allocate(size_t length) = 0;
  2473. /**
  2474. * Allocate |length| bytes. Return NULL if allocation is not successful.
  2475. * Memory does not have to be initialized.
  2476. */
  2477. virtual void* AllocateUninitialized(size_t length) = 0;
  2478. /**
  2479. * Free the memory block of size |length|, pointed to by |data|.
  2480. * That memory is guaranteed to be previously allocated by |Allocate|.
  2481. */
  2482. virtual void Free(void* data, size_t length) = 0;
  2483. };
  2484. /**
  2485. * The contents of an |ArrayBuffer|. Externalization of |ArrayBuffer|
  2486. * returns an instance of this class, populated, with a pointer to data
  2487. * and byte length.
  2488. *
  2489. * The Data pointer of ArrayBuffer::Contents is always allocated with
  2490. * Allocator::Allocate that is set with V8::SetArrayBufferAllocator.
  2491. *
  2492. * This API is experimental and may change significantly.
  2493. */
  2494. class V8_EXPORT Contents { // NOLINT
  2495. public:
  2496. Contents() : data_(NULL), byte_length_(0) {}
  2497. void* Data() const { return data_; }
  2498. size_t ByteLength() const { return byte_length_; }
  2499. private:
  2500. void* data_;
  2501. size_t byte_length_;
  2502. friend class ArrayBuffer;
  2503. };
  2504. /**
  2505. * Data length in bytes.
  2506. */
  2507. size_t ByteLength() const;
  2508. /**
  2509. * Create a new ArrayBuffer. Allocate |byte_length| bytes.
  2510. * Allocated memory will be owned by a created ArrayBuffer and
  2511. * will be deallocated when it is garbage-collected,
  2512. * unless the object is externalized.
  2513. */
  2514. static Local<ArrayBuffer> New(Isolate* isolate, size_t byte_length);
  2515. /**
  2516. * Create a new ArrayBuffer over an existing memory block.
  2517. * The created array buffer is immediately in externalized state.
  2518. * The memory block will not be reclaimed when a created ArrayBuffer
  2519. * is garbage-collected.
  2520. */
  2521. static Local<ArrayBuffer> New(Isolate* isolate, void* data,
  2522. size_t byte_length);
  2523. /**
  2524. * Returns true if ArrayBuffer is extrenalized, that is, does not
  2525. * own its memory block.
  2526. */
  2527. bool IsExternal() const;
  2528. /**
  2529. * Neuters this ArrayBuffer and all its views (typed arrays).
  2530. * Neutering sets the byte length of the buffer and all typed arrays to zero,
  2531. * preventing JavaScript from ever accessing underlying backing store.
  2532. * ArrayBuffer should have been externalized.
  2533. */
  2534. void Neuter();
  2535. /**
  2536. * Make this ArrayBuffer external. The pointer to underlying memory block
  2537. * and byte length are returned as |Contents| structure. After ArrayBuffer
  2538. * had been etxrenalized, it does no longer owns the memory block. The caller
  2539. * should take steps to free memory when it is no longer needed.
  2540. *
  2541. * The memory block is guaranteed to be allocated with |Allocator::Allocate|
  2542. * that has been set with V8::SetArrayBufferAllocator.
  2543. */
  2544. Contents Externalize();
  2545. V8_INLINE static ArrayBuffer* Cast(Value* obj);
  2546. static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
  2547. private:
  2548. ArrayBuffer();
  2549. static void CheckCast(Value* obj);
  2550. };
  2551. #ifndef V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT
  2552. // The number of required internal fields can be defined by embedder.
  2553. #define V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT 2
  2554. #endif
  2555. /**
  2556. * A base class for an instance of one of "views" over ArrayBuffer,
  2557. * including TypedArrays and DataView (ES6 draft 15.13).
  2558. *
  2559. * This API is experimental and may change significantly.
  2560. */
  2561. class V8_EXPORT ArrayBufferView : public Object {
  2562. public:
  2563. /**
  2564. * Returns underlying ArrayBuffer.
  2565. */
  2566. Local<ArrayBuffer> Buffer();
  2567. /**
  2568. * Byte offset in |Buffer|.
  2569. */
  2570. size_t ByteOffset();
  2571. /**
  2572. * Size of a view in bytes.
  2573. */
  2574. size_t ByteLength();
  2575. V8_INLINE static ArrayBufferView* Cast(Value* obj);
  2576. static const int kInternalFieldCount =
  2577. V8_ARRAY_BUFFER_VIEW_INTERNAL_FIELD_COUNT;
  2578. private:
  2579. ArrayBufferView();
  2580. static void CheckCast(Value* obj);
  2581. };
  2582. /**
  2583. * A base class for an instance of TypedArray series of constructors
  2584. * (ES6 draft 15.13.6).
  2585. * This API is experimental and may change significantly.
  2586. */
  2587. class V8_EXPORT TypedArray : public ArrayBufferView {
  2588. public:
  2589. /**
  2590. * Number of elements in this typed array
  2591. * (e.g. for Int16Array, |ByteLength|/2).
  2592. */
  2593. size_t Length();
  2594. V8_INLINE static TypedArray* Cast(Value* obj);
  2595. private:
  2596. TypedArray();
  2597. static void CheckCast(Value* obj);
  2598. };
  2599. /**
  2600. * An instance of Uint8Array constructor (ES6 draft 15.13.6).
  2601. * This API is experimental and may change significantly.
  2602. */
  2603. class V8_EXPORT Uint8Array : public TypedArray {
  2604. public:
  2605. static Local<Uint8Array> New(Handle<ArrayBuffer> array_buffer,
  2606. size_t byte_offset, size_t length);
  2607. V8_INLINE static Uint8Array* Cast(Value* obj);
  2608. private:
  2609. Uint8Array();
  2610. static void CheckCast(Value* obj);
  2611. };
  2612. /**
  2613. * An instance of Uint8ClampedArray constructor (ES6 draft 15.13.6).
  2614. * This API is experimental and may change significantly.
  2615. */
  2616. class V8_EXPORT Uint8ClampedArray : public TypedArray {
  2617. public:
  2618. static Local<Uint8ClampedArray> New(Handle<ArrayBuffer> array_buffer,
  2619. size_t byte_offset, size_t length);
  2620. V8_INLINE static Uint8ClampedArray* Cast(Value* obj);
  2621. private:
  2622. Uint8ClampedArray();
  2623. static void CheckCast(Value* obj);
  2624. };
  2625. /**
  2626. * An instance of Int8Array constructor (ES6 draft 15.13.6).
  2627. * This API is experimental and may change significantly.
  2628. */
  2629. class V8_EXPORT Int8Array : public TypedArray {
  2630. public:
  2631. static Local<Int8Array> New(Handle<ArrayBuffer> array_buffer,
  2632. size_t byte_offset, size_t length);
  2633. V8_INLINE static Int8Array* Cast(Value* obj);
  2634. private:
  2635. Int8Array();
  2636. static void CheckCast(Value* obj);
  2637. };
  2638. /**
  2639. * An instance of Uint16Array constructor (ES6 draft 15.13.6).
  2640. * This API is experimental and may change significantly.
  2641. */
  2642. class V8_EXPORT Uint16Array : public TypedArray {
  2643. public:
  2644. static Local<Uint16Array> New(Handle<ArrayBuffer> array_buffer,
  2645. size_t byte_offset, size_t length);
  2646. V8_INLINE static Uint16Array* Cast(Value* obj);
  2647. private:
  2648. Uint16Array();
  2649. static void CheckCast(Value* obj);
  2650. };
  2651. /**
  2652. * An instance of Int16Array constructor (ES6 draft 15.13.6).
  2653. * This API is experimental and may change significantly.
  2654. */
  2655. class V8_EXPORT Int16Array : public TypedArray {
  2656. public:
  2657. static Local<Int16Array> New(Handle<ArrayBuffer> array_buffer,
  2658. size_t byte_offset, size_t length);
  2659. V8_INLINE static Int16Array* Cast(Value* obj);
  2660. private:
  2661. Int16Array();
  2662. static void CheckCast(Value* obj);
  2663. };
  2664. /**
  2665. * An instance of Uint32Array constructor (ES6 draft 15.13.6).
  2666. * This API is experimental and may change significantly.
  2667. */
  2668. class V8_EXPORT Uint32Array : public TypedArray {
  2669. public:
  2670. static Local<Uint32Array> New(Handle<ArrayBuffer> array_buffer,
  2671. size_t byte_offset, size_t length);
  2672. V8_INLINE static Uint32Array* Cast(Value* obj);
  2673. private:
  2674. Uint32Array();
  2675. static void CheckCast(Value* obj);
  2676. };
  2677. /**
  2678. * An instance of Int32Array constructor (ES6 draft 15.13.6).
  2679. * This API is experimental and may change significantly.
  2680. */
  2681. class V8_EXPORT Int32Array : public TypedArray {
  2682. public:
  2683. static Local<Int32Array> New(Handle<ArrayBuffer> array_buffer,
  2684. size_t byte_offset, size_t length);
  2685. V8_INLINE static Int32Array* Cast(Value* obj);
  2686. private:
  2687. Int32Array();
  2688. static void CheckCast(Value* obj);
  2689. };
  2690. /**
  2691. * An instance of Float32Array constructor (ES6 draft 15.13.6).
  2692. * This API is experimental and may change significantly.
  2693. */
  2694. class V8_EXPORT Float32Array : public TypedArray {
  2695. public:
  2696. static Local<Float32Array> New(Handle<ArrayBuffer> array_buffer,
  2697. size_t byte_offset, size_t length);
  2698. V8_INLINE static Float32Array* Cast(Value* obj);
  2699. private:
  2700. Float32Array();
  2701. static void CheckCast(Value* obj);
  2702. };
  2703. /**
  2704. * An instance of Float64Array constructor (ES6 draft 15.13.6).
  2705. * This API is experimental and may change significantly.
  2706. */
  2707. class V8_EXPORT Float64Array : public TypedArray {
  2708. public:
  2709. static Local<Float64Array> New(Handle<ArrayBuffer> array_buffer,
  2710. size_t byte_offset, size_t length);
  2711. V8_INLINE static Float64Array* Cast(Value* obj);
  2712. private:
  2713. Float64Array();
  2714. static void CheckCast(Value* obj);
  2715. };
  2716. /**
  2717. * An instance of DataView constructor (ES6 draft 15.13.7).
  2718. * This API is experimental and may change significantly.
  2719. */
  2720. class V8_EXPORT DataView : public ArrayBufferView {
  2721. public:
  2722. static Local<DataView> New(Handle<ArrayBuffer> array_buffer,
  2723. size_t byte_offset, size_t length);
  2724. V8_INLINE static DataView* Cast(Value* obj);
  2725. private:
  2726. DataView();
  2727. static void CheckCast(Value* obj);
  2728. };
  2729. /**
  2730. * An instance of the built-in Date constructor (ECMA-262, 15.9).
  2731. */
  2732. class V8_EXPORT Date : public Object {
  2733. public:
  2734. static Local<Value> New(Isolate* isolate, double time);
  2735. /**
  2736. * A specialization of Value::NumberValue that is more efficient
  2737. * because we know the structure of this object.
  2738. */
  2739. double ValueOf() const;
  2740. V8_INLINE static Date* Cast(v8::Value* obj);
  2741. /**
  2742. * Notification that the embedder has changed the time zone,
  2743. * daylight savings time, or other date / time configuration
  2744. * parameters. V8 keeps a cache of various values used for
  2745. * date / time computation. This notification will reset
  2746. * those cached values for the current context so that date /
  2747. * time configuration changes would be reflected in the Date
  2748. * object.
  2749. *
  2750. * This API should not be called more than needed as it will
  2751. * negatively impact the performance of date operations.
  2752. */
  2753. static void DateTimeConfigurationChangeNotification(Isolate* isolate);
  2754. private:
  2755. static void CheckCast(v8::Value* obj);
  2756. };
  2757. /**
  2758. * A Number object (ECMA-262, 4.3.21).
  2759. */
  2760. class V8_EXPORT NumberObject : public Object {
  2761. public:
  2762. static Local<Value> New(Isolate* isolate, double value);
  2763. double ValueOf() const;
  2764. V8_INLINE static NumberObject* Cast(v8::Value* obj);
  2765. private:
  2766. static void CheckCast(v8::Value* obj);
  2767. };
  2768. /**
  2769. * A Boolean object (ECMA-262, 4.3.15).
  2770. */
  2771. class V8_EXPORT BooleanObject : public Object {
  2772. public:
  2773. static Local<Value> New(bool value);
  2774. bool ValueOf() const;
  2775. V8_INLINE static BooleanObject* Cast(v8::Value* obj);
  2776. private:
  2777. static void CheckCast(v8::Value* obj);
  2778. };
  2779. /**
  2780. * A String object (ECMA-262, 4.3.18).
  2781. */
  2782. class V8_EXPORT StringObject : public Object {
  2783. public:
  2784. static Local<Value> New(Handle<String> value);
  2785. Local<String> ValueOf() const;
  2786. V8_INLINE static StringObject* Cast(v8::Value* obj);
  2787. private:
  2788. static void CheckCast(v8::Value* obj);
  2789. };
  2790. /**
  2791. * A Symbol object (ECMA-262 edition 6).
  2792. *
  2793. * This is an experimental feature. Use at your own risk.
  2794. */
  2795. class V8_EXPORT SymbolObject : public Object {
  2796. public:
  2797. static Local<Value> New(Isolate* isolate, Handle<Symbol> value);
  2798. Local<Symbol> ValueOf() const;
  2799. V8_INLINE static SymbolObject* Cast(v8::Value* obj);
  2800. private:
  2801. static void CheckCast(v8::Value* obj);
  2802. };
  2803. /**
  2804. * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
  2805. */
  2806. class V8_EXPORT RegExp : public Object {
  2807. public:
  2808. /**
  2809. * Regular expression flag bits. They can be or'ed to enable a set
  2810. * of flags.
  2811. */
  2812. enum Flags {
  2813. kNone = 0,
  2814. kGlobal = 1,
  2815. kIgnoreCase = 2,
  2816. kMultiline = 4
  2817. };
  2818. /**
  2819. * Creates a regular expression from the given pattern string and
  2820. * the flags bit field. May throw a JavaScript exception as
  2821. * described in ECMA-262, 15.10.4.1.
  2822. *
  2823. * For example,
  2824. * RegExp::New(v8::String::New("foo"),
  2825. * static_cast<RegExp::Flags>(kGlobal | kMultiline))
  2826. * is equivalent to evaluating "/foo/gm".
  2827. */
  2828. static Local<RegExp> New(Handle<String> pattern, Flags flags);
  2829. /**
  2830. * Returns the value of the source property: a string representing
  2831. * the regular expression.
  2832. */
  2833. Local<String> GetSource() const;
  2834. /**
  2835. * Returns the flags bit field.
  2836. */
  2837. Flags GetFlags() const;
  2838. V8_INLINE static RegExp* Cast(v8::Value* obj);
  2839. private:
  2840. static void CheckCast(v8::Value* obj);
  2841. };
  2842. /**
  2843. * A JavaScript value that wraps a C++ void*. This type of value is mainly used
  2844. * to associate C++ data structures with JavaScript objects.
  2845. */
  2846. class V8_EXPORT External : public Value {
  2847. public:
  2848. static Local<External> New(Isolate* isolate, void* value);
  2849. V8_INLINE static External* Cast(Value* obj);
  2850. void* Value() const;
  2851. private:
  2852. static void CheckCast(v8::Value* obj);
  2853. };
  2854. // --- Templates ---
  2855. /**
  2856. * The superclass of object and function templates.
  2857. */
  2858. class V8_EXPORT Template : public Data {
  2859. public:
  2860. /** Adds a property to each instance created by this template.*/
  2861. void Set(Handle<Name> name, Handle<Data> value,
  2862. PropertyAttribute attributes = None);
  2863. V8_INLINE void Set(Isolate* isolate, const char* name, Handle<Data> value);
  2864. void SetAccessorProperty(
  2865. Local<Name> name,
  2866. Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
  2867. Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
  2868. PropertyAttribute attribute = None,
  2869. AccessControl settings = DEFAULT);
  2870. /**
  2871. * Whenever the property with the given name is accessed on objects
  2872. * created from this Template the getter and setter callbacks
  2873. * are called instead of getting and setting the property directly
  2874. * on the JavaScript object.
  2875. *
  2876. * \param name The name of the property for which an accessor is added.
  2877. * \param getter The callback to invoke when getting the property.
  2878. * \param setter The callback to invoke when setting the property.
  2879. * \param data A piece of data that will be passed to the getter and setter
  2880. * callbacks whenever they are invoked.
  2881. * \param settings Access control settings for the accessor. This is a bit
  2882. * field consisting of one of more of
  2883. * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
  2884. * The default is to not allow cross-context access.
  2885. * ALL_CAN_READ means that all cross-context reads are allowed.
  2886. * ALL_CAN_WRITE means that all cross-context writes are allowed.
  2887. * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
  2888. * cross-context access.
  2889. * \param attribute The attributes of the property for which an accessor
  2890. * is added.
  2891. * \param signature The signature describes valid receivers for the accessor
  2892. * and is used to perform implicit instance checks against them. If the
  2893. * receiver is incompatible (i.e. is not an instance of the constructor as
  2894. * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
  2895. * thrown and no callback is invoked.
  2896. */
  2897. void SetNativeDataProperty(Local<String> name,
  2898. AccessorGetterCallback getter,
  2899. AccessorSetterCallback setter = 0,
  2900. // TODO(dcarney): gcc can't handle Local below
  2901. Handle<Value> data = Handle<Value>(),
  2902. PropertyAttribute attribute = None,
  2903. Local<AccessorSignature> signature =
  2904. Local<AccessorSignature>(),
  2905. AccessControl settings = DEFAULT);
  2906. void SetNativeDataProperty(Local<Name> name,
  2907. AccessorNameGetterCallback getter,
  2908. AccessorNameSetterCallback setter = 0,
  2909. // TODO(dcarney): gcc can't handle Local below
  2910. Handle<Value> data = Handle<Value>(),
  2911. PropertyAttribute attribute = None,
  2912. Local<AccessorSignature> signature =
  2913. Local<AccessorSignature>(),
  2914. AccessControl settings = DEFAULT);
  2915. // This function is not yet stable and should not be used at this time.
  2916. bool SetDeclaredAccessor(Local<Name> name,
  2917. Local<DeclaredAccessorDescriptor> descriptor,
  2918. PropertyAttribute attribute = None,
  2919. Local<AccessorSignature> signature =
  2920. Local<AccessorSignature>(),
  2921. AccessControl settings = DEFAULT);
  2922. private:
  2923. Template();
  2924. friend class ObjectTemplate;
  2925. friend class FunctionTemplate;
  2926. };
  2927. /**
  2928. * NamedProperty[Getter|Setter] are used as interceptors on object.
  2929. * See ObjectTemplate::SetNamedPropertyHandler.
  2930. */
  2931. typedef void (*NamedPropertyGetterCallback)(
  2932. Local<String> property,
  2933. const PropertyCallbackInfo<Value>& info);
  2934. /**
  2935. * Returns the value if the setter intercepts the request.
  2936. * Otherwise, returns an empty handle.
  2937. */
  2938. typedef void (*NamedPropertySetterCallback)(
  2939. Local<String> property,
  2940. Local<Value> value,
  2941. const PropertyCallbackInfo<Value>& info);
  2942. /**
  2943. * Returns a non-empty handle if the interceptor intercepts the request.
  2944. * The result is an integer encoding property attributes (like v8::None,
  2945. * v8::DontEnum, etc.)
  2946. */
  2947. typedef void (*NamedPropertyQueryCallback)(
  2948. Local<String> property,
  2949. const PropertyCallbackInfo<Integer>& info);
  2950. /**
  2951. * Returns a non-empty handle if the deleter intercepts the request.
  2952. * The return value is true if the property could be deleted and false
  2953. * otherwise.
  2954. */
  2955. typedef void (*NamedPropertyDeleterCallback)(
  2956. Local<String> property,
  2957. const PropertyCallbackInfo<Boolean>& info);
  2958. /**
  2959. * Returns an array containing the names of the properties the named
  2960. * property getter intercepts.
  2961. */
  2962. typedef void (*NamedPropertyEnumeratorCallback)(
  2963. const PropertyCallbackInfo<Array>& info);
  2964. /**
  2965. * Returns the value of the property if the getter intercepts the
  2966. * request. Otherwise, returns an empty handle.
  2967. */
  2968. typedef void (*IndexedPropertyGetterCallback)(
  2969. uint32_t index,
  2970. const PropertyCallbackInfo<Value>& info);
  2971. /**
  2972. * Returns the value if the setter intercepts the request.
  2973. * Otherwise, returns an empty handle.
  2974. */
  2975. typedef void (*IndexedPropertySetterCallback)(
  2976. uint32_t index,
  2977. Local<Value> value,
  2978. const PropertyCallbackInfo<Value>& info);
  2979. /**
  2980. * Returns a non-empty handle if the interceptor intercepts the request.
  2981. * The result is an integer encoding property attributes.
  2982. */
  2983. typedef void (*IndexedPropertyQueryCallback)(
  2984. uint32_t index,
  2985. const PropertyCallbackInfo<Integer>& info);
  2986. /**
  2987. * Returns a non-empty handle if the deleter intercepts the request.
  2988. * The return value is true if the property could be deleted and false
  2989. * otherwise.
  2990. */
  2991. typedef void (*IndexedPropertyDeleterCallback)(
  2992. uint32_t index,
  2993. const PropertyCallbackInfo<Boolean>& info);
  2994. /**
  2995. * Returns an array containing the indices of the properties the
  2996. * indexed property getter intercepts.
  2997. */
  2998. typedef void (*IndexedPropertyEnumeratorCallback)(
  2999. const PropertyCallbackInfo<Array>& info);
  3000. /**
  3001. * Access type specification.
  3002. */
  3003. enum AccessType {
  3004. ACCESS_GET,
  3005. ACCESS_SET,
  3006. ACCESS_HAS,
  3007. ACCESS_DELETE,
  3008. ACCESS_KEYS
  3009. };
  3010. /**
  3011. * Returns true if cross-context access should be allowed to the named
  3012. * property with the given key on the host object.
  3013. */
  3014. typedef bool (*NamedSecurityCallback)(Local<Object> host,
  3015. Local<Value> key,
  3016. AccessType type,
  3017. Local<Value> data);
  3018. /**
  3019. * Returns true if cross-context access should be allowed to the indexed
  3020. * property with the given index on the host object.
  3021. */
  3022. typedef bool (*IndexedSecurityCallback)(Local<Object> host,
  3023. uint32_t index,
  3024. AccessType type,
  3025. Local<Value> data);
  3026. /**
  3027. * A FunctionTemplate is used to create functions at runtime. There
  3028. * can only be one function created from a FunctionTemplate in a
  3029. * context. The lifetime of the created function is equal to the
  3030. * lifetime of the context. So in case the embedder needs to create
  3031. * temporary functions that can be collected using Scripts is
  3032. * preferred.
  3033. *
  3034. * A FunctionTemplate can have properties, these properties are added to the
  3035. * function object when it is created.
  3036. *
  3037. * A FunctionTemplate has a corresponding instance template which is
  3038. * used to create object instances when the function is used as a
  3039. * constructor. Properties added to the instance template are added to
  3040. * each object instance.
  3041. *
  3042. * A FunctionTemplate can have a prototype template. The prototype template
  3043. * is used to create the prototype object of the function.
  3044. *
  3045. * The following example shows how to use a FunctionTemplate:
  3046. *
  3047. * \code
  3048. * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New();
  3049. * t->Set("func_property", v8::Number::New(1));
  3050. *
  3051. * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
  3052. * proto_t->Set("proto_method", v8::FunctionTemplate::New(InvokeCallback));
  3053. * proto_t->Set("proto_const", v8::Number::New(2));
  3054. *
  3055. * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
  3056. * instance_t->SetAccessor("instance_accessor", InstanceAccessorCallback);
  3057. * instance_t->SetNamedPropertyHandler(PropertyHandlerCallback, ...);
  3058. * instance_t->Set("instance_property", Number::New(3));
  3059. *
  3060. * v8::Local<v8::Function> function = t->GetFunction();
  3061. * v8::Local<v8::Object> instance = function->NewInstance();
  3062. * \endcode
  3063. *
  3064. * Let's use "function" as the JS variable name of the function object
  3065. * and "instance" for the instance object created above. The function
  3066. * and the instance will have the following properties:
  3067. *
  3068. * \code
  3069. * func_property in function == true;
  3070. * function.func_property == 1;
  3071. *
  3072. * function.prototype.proto_method() invokes 'InvokeCallback'
  3073. * function.prototype.proto_const == 2;
  3074. *
  3075. * instance instanceof function == true;
  3076. * instance.instance_accessor calls 'InstanceAccessorCallback'
  3077. * instance.instance_property == 3;
  3078. * \endcode
  3079. *
  3080. * A FunctionTemplate can inherit from another one by calling the
  3081. * FunctionTemplate::Inherit method. The following graph illustrates
  3082. * the semantics of inheritance:
  3083. *
  3084. * \code
  3085. * FunctionTemplate Parent -> Parent() . prototype -> { }
  3086. * ^ ^
  3087. * | Inherit(Parent) | .__proto__
  3088. * | |
  3089. * FunctionTemplate Child -> Child() . prototype -> { }
  3090. * \endcode
  3091. *
  3092. * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
  3093. * object of the Child() function has __proto__ pointing to the
  3094. * Parent() function's prototype object. An instance of the Child
  3095. * function has all properties on Parent's instance templates.
  3096. *
  3097. * Let Parent be the FunctionTemplate initialized in the previous
  3098. * section and create a Child FunctionTemplate by:
  3099. *
  3100. * \code
  3101. * Local<FunctionTemplate> parent = t;
  3102. * Local<FunctionTemplate> child = FunctionTemplate::New();
  3103. * child->Inherit(parent);
  3104. *
  3105. * Local<Function> child_function = child->GetFunction();
  3106. * Local<Object> child_instance = child_function->NewInstance();
  3107. * \endcode
  3108. *
  3109. * The Child function and Child instance will have the following
  3110. * properties:
  3111. *
  3112. * \code
  3113. * child_func.prototype.__proto__ == function.prototype;
  3114. * child_instance.instance_accessor calls 'InstanceAccessorCallback'
  3115. * child_instance.instance_property == 3;
  3116. * \endcode
  3117. */
  3118. class V8_EXPORT FunctionTemplate : public Template {
  3119. public:
  3120. /** Creates a function template.*/
  3121. static Local<FunctionTemplate> New(
  3122. Isolate* isolate,
  3123. FunctionCallback callback = 0,
  3124. Handle<Value> data = Handle<Value>(),
  3125. Handle<Signature> signature = Handle<Signature>(),
  3126. int length = 0);
  3127. /** Returns the unique function instance in the current execution context.*/
  3128. Local<Function> GetFunction();
  3129. /**
  3130. * Set the call-handler callback for a FunctionTemplate. This
  3131. * callback is called whenever the function created from this
  3132. * FunctionTemplate is called.
  3133. */
  3134. void SetCallHandler(FunctionCallback callback,
  3135. Handle<Value> data = Handle<Value>());
  3136. /** Set the predefined length property for the FunctionTemplate. */
  3137. void SetLength(int length);
  3138. /** Get the InstanceTemplate. */
  3139. Local<ObjectTemplate> InstanceTemplate();
  3140. /** Causes the function template to inherit from a parent function template.*/
  3141. void Inherit(Handle<FunctionTemplate> parent);
  3142. /**
  3143. * A PrototypeTemplate is the template used to create the prototype object
  3144. * of the function created by this template.
  3145. */
  3146. Local<ObjectTemplate> PrototypeTemplate();
  3147. /**
  3148. * Set the class name of the FunctionTemplate. This is used for
  3149. * printing objects created with the function created from the
  3150. * FunctionTemplate as its constructor.
  3151. */
  3152. void SetClassName(Handle<String> name);
  3153. /**
  3154. * Determines whether the __proto__ accessor ignores instances of
  3155. * the function template. If instances of the function template are
  3156. * ignored, __proto__ skips all instances and instead returns the
  3157. * next object in the prototype chain.
  3158. *
  3159. * Call with a value of true to make the __proto__ accessor ignore
  3160. * instances of the function template. Call with a value of false
  3161. * to make the __proto__ accessor not ignore instances of the
  3162. * function template. By default, instances of a function template
  3163. * are not ignored.
  3164. */
  3165. void SetHiddenPrototype(bool value);
  3166. /**
  3167. * Sets the ReadOnly flag in the attributes of the 'prototype' property
  3168. * of functions created from this FunctionTemplate to true.
  3169. */
  3170. void ReadOnlyPrototype();
  3171. /**
  3172. * Removes the prototype property from functions created from this
  3173. * FunctionTemplate.
  3174. */
  3175. void RemovePrototype();
  3176. /**
  3177. * Returns true if the given object is an instance of this function
  3178. * template.
  3179. */
  3180. bool HasInstance(Handle<Value> object);
  3181. private:
  3182. FunctionTemplate();
  3183. friend class Context;
  3184. friend class ObjectTemplate;
  3185. };
  3186. /**
  3187. * An ObjectTemplate is used to create objects at runtime.
  3188. *
  3189. * Properties added to an ObjectTemplate are added to each object
  3190. * created from the ObjectTemplate.
  3191. */
  3192. class V8_EXPORT ObjectTemplate : public Template {
  3193. public:
  3194. /** Creates an ObjectTemplate. */
  3195. static Local<ObjectTemplate> New(Isolate* isolate);
  3196. // Will be deprecated soon.
  3197. static Local<ObjectTemplate> New();
  3198. /** Creates a new instance of this template.*/
  3199. Local<Object> NewInstance();
  3200. /**
  3201. * Sets an accessor on the object template.
  3202. *
  3203. * Whenever the property with the given name is accessed on objects
  3204. * created from this ObjectTemplate the getter and setter callbacks
  3205. * are called instead of getting and setting the property directly
  3206. * on the JavaScript object.
  3207. *
  3208. * \param name The name of the property for which an accessor is added.
  3209. * \param getter The callback to invoke when getting the property.
  3210. * \param setter The callback to invoke when setting the property.
  3211. * \param data A piece of data that will be passed to the getter and setter
  3212. * callbacks whenever they are invoked.
  3213. * \param settings Access control settings for the accessor. This is a bit
  3214. * field consisting of one of more of
  3215. * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
  3216. * The default is to not allow cross-context access.
  3217. * ALL_CAN_READ means that all cross-context reads are allowed.
  3218. * ALL_CAN_WRITE means that all cross-context writes are allowed.
  3219. * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
  3220. * cross-context access.
  3221. * \param attribute The attributes of the property for which an accessor
  3222. * is added.
  3223. * \param signature The signature describes valid receivers for the accessor
  3224. * and is used to perform implicit instance checks against them. If the
  3225. * receiver is incompatible (i.e. is not an instance of the constructor as
  3226. * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
  3227. * thrown and no callback is invoked.
  3228. */
  3229. void SetAccessor(Handle<String> name,
  3230. AccessorGetterCallback getter,
  3231. AccessorSetterCallback setter = 0,
  3232. Handle<Value> data = Handle<Value>(),
  3233. AccessControl settings = DEFAULT,
  3234. PropertyAttribute attribute = None,
  3235. Handle<AccessorSignature> signature =
  3236. Handle<AccessorSignature>());
  3237. void SetAccessor(Handle<Name> name,
  3238. AccessorNameGetterCallback getter,
  3239. AccessorNameSetterCallback setter = 0,
  3240. Handle<Value> data = Handle<Value>(),
  3241. AccessControl settings = DEFAULT,
  3242. PropertyAttribute attribute = None,
  3243. Handle<AccessorSignature> signature =
  3244. Handle<AccessorSignature>());
  3245. /**
  3246. * Sets a named property handler on the object template.
  3247. *
  3248. * Whenever a property whose name is a string is accessed on objects created
  3249. * from this object template, the provided callback is invoked instead of
  3250. * accessing the property directly on the JavaScript object.
  3251. *
  3252. * \param getter The callback to invoke when getting a property.
  3253. * \param setter The callback to invoke when setting a property.
  3254. * \param query The callback to invoke to check if a property is present,
  3255. * and if present, get its attributes.
  3256. * \param deleter The callback to invoke when deleting a property.
  3257. * \param enumerator The callback to invoke to enumerate all the named
  3258. * properties of an object.
  3259. * \param data A piece of data that will be passed to the callbacks
  3260. * whenever they are invoked.
  3261. */
  3262. void SetNamedPropertyHandler(
  3263. NamedPropertyGetterCallback getter,
  3264. NamedPropertySetterCallback setter = 0,
  3265. NamedPropertyQueryCallback query = 0,
  3266. NamedPropertyDeleterCallback deleter = 0,
  3267. NamedPropertyEnumeratorCallback enumerator = 0,
  3268. Handle<Value> data = Handle<Value>());
  3269. /**
  3270. * Sets an indexed property handler on the object template.
  3271. *
  3272. * Whenever an indexed property is accessed on objects created from
  3273. * this object template, the provided callback is invoked instead of
  3274. * accessing the property directly on the JavaScript object.
  3275. *
  3276. * \param getter The callback to invoke when getting a property.
  3277. * \param setter The callback to invoke when setting a property.
  3278. * \param query The callback to invoke to check if an object has a property.
  3279. * \param deleter The callback to invoke when deleting a property.
  3280. * \param enumerator The callback to invoke to enumerate all the indexed
  3281. * properties of an object.
  3282. * \param data A piece of data that will be passed to the callbacks
  3283. * whenever they are invoked.
  3284. */
  3285. void SetIndexedPropertyHandler(
  3286. IndexedPropertyGetterCallback getter,
  3287. IndexedPropertySetterCallback setter = 0,
  3288. IndexedPropertyQueryCallback query = 0,
  3289. IndexedPropertyDeleterCallback deleter = 0,
  3290. IndexedPropertyEnumeratorCallback enumerator = 0,
  3291. Handle<Value> data = Handle<Value>());
  3292. /**
  3293. * Sets the callback to be used when calling instances created from
  3294. * this template as a function. If no callback is set, instances
  3295. * behave like normal JavaScript objects that cannot be called as a
  3296. * function.
  3297. */
  3298. void SetCallAsFunctionHandler(FunctionCallback callback,
  3299. Handle<Value> data = Handle<Value>());
  3300. /**
  3301. * Mark object instances of the template as undetectable.
  3302. *
  3303. * In many ways, undetectable objects behave as though they are not
  3304. * there. They behave like 'undefined' in conditionals and when
  3305. * printed. However, properties can be accessed and called as on
  3306. * normal objects.
  3307. */
  3308. void MarkAsUndetectable();
  3309. /**
  3310. * Sets access check callbacks on the object template.
  3311. *
  3312. * When accessing properties on instances of this object template,
  3313. * the access check callback will be called to determine whether or
  3314. * not to allow cross-context access to the properties.
  3315. * The last parameter specifies whether access checks are turned
  3316. * on by default on instances. If access checks are off by default,
  3317. * they can be turned on on individual instances by calling
  3318. * Object::TurnOnAccessCheck().
  3319. */
  3320. void SetAccessCheckCallbacks(NamedSecurityCallback named_handler,
  3321. IndexedSecurityCallback indexed_handler,
  3322. Handle<Value> data = Handle<Value>(),
  3323. bool turned_on_by_default = true);
  3324. /**
  3325. * Gets the number of internal fields for objects generated from
  3326. * this template.
  3327. */
  3328. int InternalFieldCount();
  3329. /**
  3330. * Sets the number of internal fields for objects generated from
  3331. * this template.
  3332. */
  3333. void SetInternalFieldCount(int value);
  3334. private:
  3335. ObjectTemplate();
  3336. static Local<ObjectTemplate> New(internal::Isolate* isolate,
  3337. Handle<FunctionTemplate> constructor);
  3338. friend class FunctionTemplate;
  3339. };
  3340. /**
  3341. * A Signature specifies which receivers and arguments are valid
  3342. * parameters to a function.
  3343. */
  3344. class V8_EXPORT Signature : public Data {
  3345. public:
  3346. static Local<Signature> New(Isolate* isolate,
  3347. Handle<FunctionTemplate> receiver =
  3348. Handle<FunctionTemplate>(),
  3349. int argc = 0,
  3350. Handle<FunctionTemplate> argv[] = 0);
  3351. private:
  3352. Signature();
  3353. };
  3354. /**
  3355. * An AccessorSignature specifies which receivers are valid parameters
  3356. * to an accessor callback.
  3357. */
  3358. class V8_EXPORT AccessorSignature : public Data {
  3359. public:
  3360. static Local<AccessorSignature> New(Isolate* isolate,
  3361. Handle<FunctionTemplate> receiver =
  3362. Handle<FunctionTemplate>());
  3363. private:
  3364. AccessorSignature();
  3365. };
  3366. class V8_EXPORT DeclaredAccessorDescriptor : public Data {
  3367. private:
  3368. DeclaredAccessorDescriptor();
  3369. };
  3370. class V8_EXPORT ObjectOperationDescriptor : public Data {
  3371. public:
  3372. // This function is not yet stable and should not be used at this time.
  3373. static Local<RawOperationDescriptor> NewInternalFieldDereference(
  3374. Isolate* isolate,
  3375. int internal_field);
  3376. private:
  3377. ObjectOperationDescriptor();
  3378. };
  3379. enum DeclaredAccessorDescriptorDataType {
  3380. kDescriptorBoolType,
  3381. kDescriptorInt8Type, kDescriptorUint8Type,
  3382. kDescriptorInt16Type, kDescriptorUint16Type,
  3383. kDescriptorInt32Type, kDescriptorUint32Type,
  3384. kDescriptorFloatType, kDescriptorDoubleType
  3385. };
  3386. class V8_EXPORT RawOperationDescriptor : public Data {
  3387. public:
  3388. Local<DeclaredAccessorDescriptor> NewHandleDereference(Isolate* isolate);
  3389. Local<RawOperationDescriptor> NewRawDereference(Isolate* isolate);
  3390. Local<RawOperationDescriptor> NewRawShift(Isolate* isolate,
  3391. int16_t byte_offset);
  3392. Local<DeclaredAccessorDescriptor> NewPointerCompare(Isolate* isolate,
  3393. void* compare_value);
  3394. Local<DeclaredAccessorDescriptor> NewPrimitiveValue(
  3395. Isolate* isolate,
  3396. DeclaredAccessorDescriptorDataType data_type,
  3397. uint8_t bool_offset = 0);
  3398. Local<DeclaredAccessorDescriptor> NewBitmaskCompare8(Isolate* isolate,
  3399. uint8_t bitmask,
  3400. uint8_t compare_value);
  3401. Local<DeclaredAccessorDescriptor> NewBitmaskCompare16(
  3402. Isolate* isolate,
  3403. uint16_t bitmask,
  3404. uint16_t compare_value);
  3405. Local<DeclaredAccessorDescriptor> NewBitmaskCompare32(
  3406. Isolate* isolate,
  3407. uint32_t bitmask,
  3408. uint32_t compare_value);
  3409. private:
  3410. RawOperationDescriptor();
  3411. };
  3412. /**
  3413. * A utility for determining the type of objects based on the template
  3414. * they were constructed from.
  3415. */
  3416. class V8_EXPORT TypeSwitch : public Data {
  3417. public:
  3418. static Local<TypeSwitch> New(Handle<FunctionTemplate> type);
  3419. static Local<TypeSwitch> New(int argc, Handle<FunctionTemplate> types[]);
  3420. int match(Handle<Value> value);
  3421. private:
  3422. TypeSwitch();
  3423. };
  3424. // --- Extensions ---
  3425. class V8_EXPORT ExternalOneByteStringResourceImpl
  3426. : public String::ExternalOneByteStringResource {
  3427. public:
  3428. ExternalOneByteStringResourceImpl() : data_(0), length_(0) {}
  3429. ExternalOneByteStringResourceImpl(const char* data, size_t length)
  3430. : data_(data), length_(length) {}
  3431. const char* data() const { return data_; }
  3432. size_t length() const { return length_; }
  3433. private:
  3434. const char* data_;
  3435. size_t length_;
  3436. };
  3437. /**
  3438. * Ignore
  3439. */
  3440. class V8_EXPORT Extension { // NOLINT
  3441. public:
  3442. // Note that the strings passed into this constructor must live as long
  3443. // as the Extension itself.
  3444. Extension(const char* name,
  3445. const char* source = 0,
  3446. int dep_count = 0,
  3447. const char** deps = 0,
  3448. int source_length = -1);
  3449. virtual ~Extension() { }
  3450. virtual v8::Handle<v8::FunctionTemplate> GetNativeFunctionTemplate(
  3451. v8::Isolate* isolate, v8::Handle<v8::String> name) {
  3452. return v8::Handle<v8::FunctionTemplate>();
  3453. }
  3454. const char* name() const { return name_; }
  3455. size_t source_length() const { return source_length_; }
  3456. const String::ExternalOneByteStringResource* source() const {
  3457. return &source_; }
  3458. int dependency_count() { return dep_count_; }
  3459. const char** dependencies() { return deps_; }
  3460. void set_auto_enable(bool value) { auto_enable_ = value; }
  3461. bool auto_enable() { return auto_enable_; }
  3462. private:
  3463. const char* name_;
  3464. size_t source_length_; // expected to initialize before source_
  3465. ExternalOneByteStringResourceImpl source_;
  3466. int dep_count_;
  3467. const char** deps_;
  3468. bool auto_enable_;
  3469. // Disallow copying and assigning.
  3470. Extension(const Extension&);
  3471. void operator=(const Extension&);
  3472. };
  3473. void V8_EXPORT RegisterExtension(Extension* extension);
  3474. // --- Statics ---
  3475. V8_INLINE Handle<Primitive> Undefined(Isolate* isolate);
  3476. V8_INLINE Handle<Primitive> Null(Isolate* isolate);
  3477. V8_INLINE Handle<Boolean> True(Isolate* isolate);
  3478. V8_INLINE Handle<Boolean> False(Isolate* isolate);
  3479. /**
  3480. * A set of constraints that specifies the limits of the runtime's memory use.
  3481. * You must set the heap size before initializing the VM - the size cannot be
  3482. * adjusted after the VM is initialized.
  3483. *
  3484. * If you are using threads then you should hold the V8::Locker lock while
  3485. * setting the stack limit and you must set a non-default stack limit separately
  3486. * for each thread.
  3487. */
  3488. class V8_EXPORT ResourceConstraints {
  3489. public:
  3490. ResourceConstraints();
  3491. /**
  3492. * Configures the constraints with reasonable default values based on the
  3493. * capabilities of the current device the VM is running on.
  3494. *
  3495. * \param physical_memory The total amount of physical memory on the current
  3496. * device, in bytes.
  3497. * \param virtual_memory_limit The amount of virtual memory on the current
  3498. * device, in bytes, or zero, if there is no limit.
  3499. * \param number_of_processors The number of CPUs available on the current
  3500. * device.
  3501. */
  3502. void ConfigureDefaults(uint64_t physical_memory,
  3503. uint64_t virtual_memory_limit,
  3504. uint32_t number_of_processors);
  3505. int max_semi_space_size() const { return max_semi_space_size_; }
  3506. void set_max_semi_space_size(int value) { max_semi_space_size_ = value; }
  3507. int max_old_space_size() const { return max_old_space_size_; }
  3508. void set_max_old_space_size(int value) { max_old_space_size_ = value; }
  3509. int max_executable_size() const { return max_executable_size_; }
  3510. void set_max_executable_size(int value) { max_executable_size_ = value; }
  3511. uint32_t* stack_limit() const { return stack_limit_; }
  3512. // Sets an address beyond which the VM's stack may not grow.
  3513. void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
  3514. int max_available_threads() const { return max_available_threads_; }
  3515. // Set the number of threads available to V8, assuming at least 1.
  3516. void set_max_available_threads(int value) {
  3517. max_available_threads_ = value;
  3518. }
  3519. size_t code_range_size() const { return code_range_size_; }
  3520. void set_code_range_size(size_t value) {
  3521. code_range_size_ = value;
  3522. }
  3523. private:
  3524. int max_semi_space_size_;
  3525. int max_old_space_size_;
  3526. int max_executable_size_;
  3527. uint32_t* stack_limit_;
  3528. int max_available_threads_;
  3529. size_t code_range_size_;
  3530. };
  3531. // --- Exceptions ---
  3532. typedef void (*FatalErrorCallback)(const char* location, const char* message);
  3533. typedef void (*MessageCallback)(Handle<Message> message, Handle<Value> error);
  3534. // --- Tracing ---
  3535. typedef void (*LogEventCallback)(const char* name, int event);
  3536. /**
  3537. * Create new error objects by calling the corresponding error object
  3538. * constructor with the message.
  3539. */
  3540. class V8_EXPORT Exception {
  3541. public:
  3542. static Local<Value> RangeError(Handle<String> message);
  3543. static Local<Value> ReferenceError(Handle<String> message);
  3544. static Local<Value> SyntaxError(Handle<String> message);
  3545. static Local<Value> TypeError(Handle<String> message);
  3546. static Local<Value> Error(Handle<String> message);
  3547. };
  3548. // --- Counters Callbacks ---
  3549. typedef int* (*CounterLookupCallback)(const char* name);
  3550. typedef void* (*CreateHistogramCallback)(const char* name,
  3551. int min,
  3552. int max,
  3553. size_t buckets);
  3554. typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
  3555. // --- Memory Allocation Callback ---
  3556. enum ObjectSpace {
  3557. kObjectSpaceNewSpace = 1 << 0,
  3558. kObjectSpaceOldPointerSpace = 1 << 1,
  3559. kObjectSpaceOldDataSpace = 1 << 2,
  3560. kObjectSpaceCodeSpace = 1 << 3,
  3561. kObjectSpaceMapSpace = 1 << 4,
  3562. kObjectSpaceLoSpace = 1 << 5,
  3563. kObjectSpaceAll = kObjectSpaceNewSpace | kObjectSpaceOldPointerSpace |
  3564. kObjectSpaceOldDataSpace | kObjectSpaceCodeSpace | kObjectSpaceMapSpace |
  3565. kObjectSpaceLoSpace
  3566. };
  3567. enum AllocationAction {
  3568. kAllocationActionAllocate = 1 << 0,
  3569. kAllocationActionFree = 1 << 1,
  3570. kAllocationActionAll = kAllocationActionAllocate | kAllocationActionFree
  3571. };
  3572. typedef void (*MemoryAllocationCallback)(ObjectSpace space,
  3573. AllocationAction action,
  3574. int size);
  3575. // --- Leave Script Callback ---
  3576. typedef void (*CallCompletedCallback)();
  3577. // --- Promise Reject Callback ---
  3578. enum PromiseRejectEvent {
  3579. kPromiseRejectWithNoHandler = 0,
  3580. kPromiseHandlerAddedAfterReject = 1
  3581. };
  3582. class PromiseRejectMessage {
  3583. public:
  3584. PromiseRejectMessage(Handle<Promise> promise, PromiseRejectEvent event,
  3585. Handle<Value> value, Handle<StackTrace> stack_trace)
  3586. : promise_(promise),
  3587. event_(event),
  3588. value_(value),
  3589. stack_trace_(stack_trace) {}
  3590. V8_INLINE Handle<Promise> GetPromise() const { return promise_; }
  3591. V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
  3592. V8_INLINE Handle<Value> GetValue() const { return value_; }
  3593. V8_INLINE Handle<StackTrace> GetStackTrace() const { return stack_trace_; }
  3594. private:
  3595. Handle<Promise> promise_;
  3596. PromiseRejectEvent event_;
  3597. Handle<Value> value_;
  3598. Handle<StackTrace> stack_trace_;
  3599. };
  3600. typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
  3601. // --- Microtask Callback ---
  3602. typedef void (*MicrotaskCallback)(void* data);
  3603. // --- Failed Access Check Callback ---
  3604. typedef void (*FailedAccessCheckCallback)(Local<Object> target,
  3605. AccessType type,
  3606. Local<Value> data);
  3607. // --- AllowCodeGenerationFromStrings callbacks ---
  3608. /**
  3609. * Callback to check if code generation from strings is allowed. See
  3610. * Context::AllowCodeGenerationFromStrings.
  3611. */
  3612. typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context);
  3613. // --- Garbage Collection Callbacks ---
  3614. /**
  3615. * Applications can register callback functions which will be called
  3616. * before and after a garbage collection. Allocations are not
  3617. * allowed in the callback functions, you therefore cannot manipulate
  3618. * objects (set or delete properties for example) since it is possible
  3619. * such operations will result in the allocation of objects.
  3620. */
  3621. enum GCType {
  3622. kGCTypeScavenge = 1 << 0,
  3623. kGCTypeMarkSweepCompact = 1 << 1,
  3624. kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact
  3625. };
  3626. enum GCCallbackFlags {
  3627. kNoGCCallbackFlags = 0,
  3628. kGCCallbackFlagCompacted = 1 << 0,
  3629. kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
  3630. kGCCallbackFlagForced = 1 << 2
  3631. };
  3632. typedef void (*GCPrologueCallback)(GCType type, GCCallbackFlags flags);
  3633. typedef void (*GCEpilogueCallback)(GCType type, GCCallbackFlags flags);
  3634. typedef void (*InterruptCallback)(Isolate* isolate, void* data);
  3635. /**
  3636. * Collection of V8 heap information.
  3637. *
  3638. * Instances of this class can be passed to v8::V8::HeapStatistics to
  3639. * get heap statistics from V8.
  3640. */
  3641. class V8_EXPORT HeapStatistics {
  3642. public:
  3643. HeapStatistics();
  3644. size_t total_heap_size() { return total_heap_size_; }
  3645. size_t total_heap_size_executable() { return total_heap_size_executable_; }
  3646. size_t total_physical_size() { return total_physical_size_; }
  3647. size_t used_heap_size() { return used_heap_size_; }
  3648. size_t heap_size_limit() { return heap_size_limit_; }
  3649. private:
  3650. size_t total_heap_size_;
  3651. size_t total_heap_size_executable_;
  3652. size_t total_physical_size_;
  3653. size_t used_heap_size_;
  3654. size_t heap_size_limit_;
  3655. friend class V8;
  3656. friend class Isolate;
  3657. };
  3658. class RetainedObjectInfo;
  3659. /**
  3660. * FunctionEntryHook is the type of the profile entry hook called at entry to
  3661. * any generated function when function-level profiling is enabled.
  3662. *
  3663. * \param function the address of the function that's being entered.
  3664. * \param return_addr_location points to a location on stack where the machine
  3665. * return address resides. This can be used to identify the caller of
  3666. * \p function, and/or modified to divert execution when \p function exits.
  3667. *
  3668. * \note the entry hook must not cause garbage collection.
  3669. */
  3670. typedef void (*FunctionEntryHook)(uintptr_t function,
  3671. uintptr_t return_addr_location);
  3672. /**
  3673. * A JIT code event is issued each time code is added, moved or removed.
  3674. *
  3675. * \note removal events are not currently issued.
  3676. */
  3677. struct JitCodeEvent {
  3678. enum EventType {
  3679. CODE_ADDED,
  3680. CODE_MOVED,
  3681. CODE_REMOVED,
  3682. CODE_ADD_LINE_POS_INFO,
  3683. CODE_START_LINE_INFO_RECORDING,
  3684. CODE_END_LINE_INFO_RECORDING
  3685. };
  3686. // Definition of the code position type. The "POSITION" type means the place
  3687. // in the source code which are of interest when making stack traces to
  3688. // pin-point the source location of a stack frame as close as possible.
  3689. // The "STATEMENT_POSITION" means the place at the beginning of each
  3690. // statement, and is used to indicate possible break locations.
  3691. enum PositionType { POSITION, STATEMENT_POSITION };
  3692. // Type of event.
  3693. EventType type;
  3694. // Start of the instructions.
  3695. void* code_start;
  3696. // Size of the instructions.
  3697. size_t code_len;
  3698. // Script info for CODE_ADDED event.
  3699. Handle<UnboundScript> script;
  3700. // User-defined data for *_LINE_INFO_* event. It's used to hold the source
  3701. // code line information which is returned from the
  3702. // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
  3703. // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
  3704. void* user_data;
  3705. struct name_t {
  3706. // Name of the object associated with the code, note that the string is not
  3707. // zero-terminated.
  3708. const char* str;
  3709. // Number of chars in str.
  3710. size_t len;
  3711. };
  3712. struct line_info_t {
  3713. // PC offset
  3714. size_t offset;
  3715. // Code postion
  3716. size_t pos;
  3717. // The position type.
  3718. PositionType position_type;
  3719. };
  3720. union {
  3721. // Only valid for CODE_ADDED.
  3722. struct name_t name;
  3723. // Only valid for CODE_ADD_LINE_POS_INFO
  3724. struct line_info_t line_info;
  3725. // New location of instructions. Only valid for CODE_MOVED.
  3726. void* new_code_start;
  3727. };
  3728. };
  3729. /**
  3730. * Option flags passed to the SetJitCodeEventHandler function.
  3731. */
  3732. enum JitCodeEventOptions {
  3733. kJitCodeEventDefault = 0,
  3734. // Generate callbacks for already existent code.
  3735. kJitCodeEventEnumExisting = 1
  3736. };
  3737. /**
  3738. * Callback function passed to SetJitCodeEventHandler.
  3739. *
  3740. * \param event code add, move or removal event.
  3741. */
  3742. typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
  3743. /**
  3744. * Isolate represents an isolated instance of the V8 engine. V8 isolates have
  3745. * completely separate states. Objects from one isolate must not be used in
  3746. * other isolates. The embedder can create multiple isolates and use them in
  3747. * parallel in multiple threads. An isolate can be entered by at most one
  3748. * thread at any given time. The Locker/Unlocker API must be used to
  3749. * synchronize.
  3750. */
  3751. class V8_EXPORT Isolate {
  3752. public:
  3753. /**
  3754. * Initial configuration parameters for a new Isolate.
  3755. */
  3756. struct CreateParams {
  3757. CreateParams()
  3758. : entry_hook(NULL),
  3759. code_event_handler(NULL),
  3760. enable_serializer(false) {}
  3761. /**
  3762. * The optional entry_hook allows the host application to provide the
  3763. * address of a function that's invoked on entry to every V8-generated
  3764. * function. Note that entry_hook is invoked at the very start of each
  3765. * generated function. Furthermore, if an entry_hook is given, V8 will
  3766. * always run without a context snapshot.
  3767. */
  3768. FunctionEntryHook entry_hook;
  3769. /**
  3770. * Allows the host application to provide the address of a function that is
  3771. * notified each time code is added, moved or removed.
  3772. */
  3773. JitCodeEventHandler code_event_handler;
  3774. /**
  3775. * ResourceConstraints to use for the new Isolate.
  3776. */
  3777. ResourceConstraints constraints;
  3778. /**
  3779. * This flag currently renders the Isolate unusable.
  3780. */
  3781. bool enable_serializer;
  3782. };
  3783. /**
  3784. * Stack-allocated class which sets the isolate for all operations
  3785. * executed within a local scope.
  3786. */
  3787. class V8_EXPORT Scope {
  3788. public:
  3789. explicit Scope(Isolate* isolate) : isolate_(isolate) {
  3790. isolate->Enter();
  3791. }
  3792. ~Scope() { isolate_->Exit(); }
  3793. private:
  3794. Isolate* const isolate_;
  3795. // Prevent copying of Scope objects.
  3796. Scope(const Scope&);
  3797. Scope& operator=(const Scope&);
  3798. };
  3799. /**
  3800. * Assert that no Javascript code is invoked.
  3801. */
  3802. class V8_EXPORT DisallowJavascriptExecutionScope {
  3803. public:
  3804. enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE };
  3805. DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
  3806. ~DisallowJavascriptExecutionScope();
  3807. private:
  3808. bool on_failure_;
  3809. void* internal_;
  3810. // Prevent copying of Scope objects.
  3811. DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&);
  3812. DisallowJavascriptExecutionScope& operator=(
  3813. const DisallowJavascriptExecutionScope&);
  3814. };
  3815. /**
  3816. * Introduce exception to DisallowJavascriptExecutionScope.
  3817. */
  3818. class V8_EXPORT AllowJavascriptExecutionScope {
  3819. public:
  3820. explicit AllowJavascriptExecutionScope(Isolate* isolate);
  3821. ~AllowJavascriptExecutionScope();
  3822. private:
  3823. void* internal_throws_;
  3824. void* internal_assert_;
  3825. // Prevent copying of Scope objects.
  3826. AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&);
  3827. AllowJavascriptExecutionScope& operator=(
  3828. const AllowJavascriptExecutionScope&);
  3829. };
  3830. /**
  3831. * Do not run microtasks while this scope is active, even if microtasks are
  3832. * automatically executed otherwise.
  3833. */
  3834. class V8_EXPORT SuppressMicrotaskExecutionScope {
  3835. public:
  3836. explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
  3837. ~SuppressMicrotaskExecutionScope();
  3838. private:
  3839. internal::Isolate* isolate_;
  3840. // Prevent copying of Scope objects.
  3841. SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&);
  3842. SuppressMicrotaskExecutionScope& operator=(
  3843. const SuppressMicrotaskExecutionScope&);
  3844. };
  3845. /**
  3846. * Types of garbage collections that can be requested via
  3847. * RequestGarbageCollectionForTesting.
  3848. */
  3849. enum GarbageCollectionType {
  3850. kFullGarbageCollection,
  3851. kMinorGarbageCollection
  3852. };
  3853. /**
  3854. * Features reported via the SetUseCounterCallback callback. Do not chang
  3855. * assigned numbers of existing items; add new features to the end of this
  3856. * list.
  3857. */
  3858. enum UseCounterFeature {
  3859. kUseAsm = 0,
  3860. kBreakIterator = 1,
  3861. kUseCounterFeatureCount // This enum value must be last.
  3862. };
  3863. typedef void (*UseCounterCallback)(Isolate* isolate,
  3864. UseCounterFeature feature);
  3865. /**
  3866. * Creates a new isolate. Does not change the currently entered
  3867. * isolate.
  3868. *
  3869. * When an isolate is no longer used its resources should be freed
  3870. * by calling Dispose(). Using the delete operator is not allowed.
  3871. *
  3872. * V8::Initialize() must have run prior to this.
  3873. */
  3874. static Isolate* New(const CreateParams& params = CreateParams());
  3875. /**
  3876. * Returns the entered isolate for the current thread or NULL in
  3877. * case there is no current isolate.
  3878. */
  3879. static Isolate* GetCurrent();
  3880. /**
  3881. * Methods below this point require holding a lock (using Locker) in
  3882. * a multi-threaded environment.
  3883. */
  3884. /**
  3885. * Sets this isolate as the entered one for the current thread.
  3886. * Saves the previously entered one (if any), so that it can be
  3887. * restored when exiting. Re-entering an isolate is allowed.
  3888. */
  3889. void Enter();
  3890. /**
  3891. * Exits this isolate by restoring the previously entered one in the
  3892. * current thread. The isolate may still stay the same, if it was
  3893. * entered more than once.
  3894. *
  3895. * Requires: this == Isolate::GetCurrent().
  3896. */
  3897. void Exit();
  3898. /**
  3899. * Disposes the isolate. The isolate must not be entered by any
  3900. * thread to be disposable.
  3901. */
  3902. void Dispose();
  3903. /**
  3904. * Associate embedder-specific data with the isolate. |slot| has to be
  3905. * between 0 and GetNumberOfDataSlots() - 1.
  3906. */
  3907. V8_INLINE void SetData(uint32_t slot, void* data);
  3908. /**
  3909. * Retrieve embedder-specific data from the isolate.
  3910. * Returns NULL if SetData has never been called for the given |slot|.
  3911. */
  3912. V8_INLINE void* GetData(uint32_t slot);
  3913. /**
  3914. * Returns the maximum number of available embedder data slots. Valid slots
  3915. * are in the range of 0 - GetNumberOfDataSlots() - 1.
  3916. */
  3917. V8_INLINE static uint32_t GetNumberOfDataSlots();
  3918. /**
  3919. * Get statistics about the heap memory usage.
  3920. */
  3921. void GetHeapStatistics(HeapStatistics* heap_statistics);
  3922. /**
  3923. * Get a call stack sample from the isolate.
  3924. * \param state Execution state.
  3925. * \param frames Caller allocated buffer to store stack frames.
  3926. * \param frames_limit Maximum number of frames to capture. The buffer must
  3927. * be large enough to hold the number of frames.
  3928. * \param sample_info The sample info is filled up by the function
  3929. * provides number of actual captured stack frames and
  3930. * the current VM state.
  3931. * \note GetStackSample should only be called when the JS thread is paused or
  3932. * interrupted. Otherwise the behavior is undefined.
  3933. */
  3934. void GetStackSample(const RegisterState& state, void** frames,
  3935. size_t frames_limit, SampleInfo* sample_info);
  3936. /**
  3937. * Adjusts the amount of registered external memory. Used to give V8 an
  3938. * indication of the amount of externally allocated memory that is kept alive
  3939. * by JavaScript objects. V8 uses this to decide when to perform global
  3940. * garbage collections. Registering externally allocated memory will trigger
  3941. * global garbage collections more often than it would otherwise in an attempt
  3942. * to garbage collect the JavaScript objects that keep the externally
  3943. * allocated memory alive.
  3944. *
  3945. * \param change_in_bytes the change in externally allocated memory that is
  3946. * kept alive by JavaScript objects.
  3947. * \returns the adjusted value.
  3948. */
  3949. V8_INLINE int64_t
  3950. AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
  3951. /**
  3952. * Returns heap profiler for this isolate. Will return NULL until the isolate
  3953. * is initialized.
  3954. */
  3955. HeapProfiler* GetHeapProfiler();
  3956. /**
  3957. * Returns CPU profiler for this isolate. Will return NULL unless the isolate
  3958. * is initialized. It is the embedder's responsibility to stop all CPU
  3959. * profiling activities if it has started any.
  3960. */
  3961. CpuProfiler* GetCpuProfiler();
  3962. /** Returns true if this isolate has a current context. */
  3963. bool InContext();
  3964. /** Returns the context that is on the top of the stack. */
  3965. Local<Context> GetCurrentContext();
  3966. /**
  3967. * Returns the context of the calling JavaScript code. That is the
  3968. * context of the top-most JavaScript frame. If there are no
  3969. * JavaScript frames an empty handle is returned.
  3970. */
  3971. Local<Context> GetCallingContext();
  3972. /** Returns the last entered context. */
  3973. Local<Context> GetEnteredContext();
  3974. /**
  3975. * Schedules an exception to be thrown when returning to JavaScript. When an
  3976. * exception has been scheduled it is illegal to invoke any JavaScript
  3977. * operation; the caller must return immediately and only after the exception
  3978. * has been handled does it become legal to invoke JavaScript operations.
  3979. */
  3980. Local<Value> ThrowException(Local<Value> exception);
  3981. /**
  3982. * Allows the host application to group objects together. If one
  3983. * object in the group is alive, all objects in the group are alive.
  3984. * After each garbage collection, object groups are removed. It is
  3985. * intended to be used in the before-garbage-collection callback
  3986. * function, for instance to simulate DOM tree connections among JS
  3987. * wrapper objects. Object groups for all dependent handles need to
  3988. * be provided for kGCTypeMarkSweepCompact collections, for all other
  3989. * garbage collection types it is sufficient to provide object groups
  3990. * for partially dependent handles only.
  3991. */
  3992. template<typename T> void SetObjectGroupId(const Persistent<T>& object,
  3993. UniqueId id);
  3994. /**
  3995. * Allows the host application to declare implicit references from an object
  3996. * group to an object. If the objects of the object group are alive, the child
  3997. * object is alive too. After each garbage collection, all implicit references
  3998. * are removed. It is intended to be used in the before-garbage-collection
  3999. * callback function.
  4000. */
  4001. template<typename T> void SetReferenceFromGroup(UniqueId id,
  4002. const Persistent<T>& child);
  4003. /**
  4004. * Allows the host application to declare implicit references from an object
  4005. * to another object. If the parent object is alive, the child object is alive
  4006. * too. After each garbage collection, all implicit references are removed. It
  4007. * is intended to be used in the before-garbage-collection callback function.
  4008. */
  4009. template<typename T, typename S>
  4010. void SetReference(const Persistent<T>& parent, const Persistent<S>& child);
  4011. typedef void (*GCPrologueCallback)(Isolate* isolate,
  4012. GCType type,
  4013. GCCallbackFlags flags);
  4014. typedef void (*GCEpilogueCallback)(Isolate* isolate,
  4015. GCType type,
  4016. GCCallbackFlags flags);
  4017. /**
  4018. * Enables the host application to receive a notification before a
  4019. * garbage collection. Allocations are allowed in the callback function,
  4020. * but the callback is not re-entrant: if the allocation inside it will
  4021. * trigger the garbage collection, the callback won't be called again.
  4022. * It is possible to specify the GCType filter for your callback. But it is
  4023. * not possible to register the same callback function two times with
  4024. * different GCType filters.
  4025. */
  4026. void AddGCPrologueCallback(
  4027. GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
  4028. /**
  4029. * This function removes callback which was installed by
  4030. * AddGCPrologueCallback function.
  4031. */
  4032. void RemoveGCPrologueCallback(GCPrologueCallback callback);
  4033. /**
  4034. * Enables the host application to receive a notification after a
  4035. * garbage collection. Allocations are allowed in the callback function,
  4036. * but the callback is not re-entrant: if the allocation inside it will
  4037. * trigger the garbage collection, the callback won't be called again.
  4038. * It is possible to specify the GCType filter for your callback. But it is
  4039. * not possible to register the same callback function two times with
  4040. * different GCType filters.
  4041. */
  4042. void AddGCEpilogueCallback(
  4043. GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
  4044. /**
  4045. * This function removes callback which was installed by
  4046. * AddGCEpilogueCallback function.
  4047. */
  4048. void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
  4049. /**
  4050. * Request V8 to interrupt long running JavaScript code and invoke
  4051. * the given |callback| passing the given |data| to it. After |callback|
  4052. * returns control will be returned to the JavaScript code.
  4053. * At any given moment V8 can remember only a single callback for the very
  4054. * last interrupt request.
  4055. * Can be called from another thread without acquiring a |Locker|.
  4056. * Registered |callback| must not reenter interrupted Isolate.
  4057. */
  4058. void RequestInterrupt(InterruptCallback callback, void* data);
  4059. /**
  4060. * Clear interrupt request created by |RequestInterrupt|.
  4061. * Can be called from another thread without acquiring a |Locker|.
  4062. */
  4063. void ClearInterrupt();
  4064. /**
  4065. * Request garbage collection in this Isolate. It is only valid to call this
  4066. * function if --expose_gc was specified.
  4067. *
  4068. * This should only be used for testing purposes and not to enforce a garbage
  4069. * collection schedule. It has strong negative impact on the garbage
  4070. * collection performance. Use IdleNotification() or LowMemoryNotification()
  4071. * instead to influence the garbage collection schedule.
  4072. */
  4073. void RequestGarbageCollectionForTesting(GarbageCollectionType type);
  4074. /**
  4075. * Set the callback to invoke for logging event.
  4076. */
  4077. void SetEventLogger(LogEventCallback that);
  4078. /**
  4079. * Adds a callback to notify the host application when a script finished
  4080. * running. If a script re-enters the runtime during executing, the
  4081. * CallCompletedCallback is only invoked when the outer-most script
  4082. * execution ends. Executing scripts inside the callback do not trigger
  4083. * further callbacks.
  4084. */
  4085. void AddCallCompletedCallback(CallCompletedCallback callback);
  4086. /**
  4087. * Removes callback that was installed by AddCallCompletedCallback.
  4088. */
  4089. void RemoveCallCompletedCallback(CallCompletedCallback callback);
  4090. /**
  4091. * Set callback to notify about promise reject with no handler, or
  4092. * revocation of such a previous notification once the handler is added.
  4093. */
  4094. void SetPromiseRejectCallback(PromiseRejectCallback callback);
  4095. /**
  4096. * Experimental: Runs the Microtask Work Queue until empty
  4097. * Any exceptions thrown by microtask callbacks are swallowed.
  4098. */
  4099. void RunMicrotasks();
  4100. /**
  4101. * Experimental: Enqueues the callback to the Microtask Work Queue
  4102. */
  4103. void EnqueueMicrotask(Handle<Function> microtask);
  4104. /**
  4105. * Experimental: Enqueues the callback to the Microtask Work Queue
  4106. */
  4107. void EnqueueMicrotask(MicrotaskCallback microtask, void* data = NULL);
  4108. /**
  4109. * Experimental: Controls whether the Microtask Work Queue is automatically
  4110. * run when the script call depth decrements to zero.
  4111. */
  4112. void SetAutorunMicrotasks(bool autorun);
  4113. /**
  4114. * Experimental: Returns whether the Microtask Work Queue is automatically
  4115. * run when the script call depth decrements to zero.
  4116. */
  4117. bool WillAutorunMicrotasks() const;
  4118. /**
  4119. * Sets a callback for counting the number of times a feature of V8 is used.
  4120. */
  4121. void SetUseCounterCallback(UseCounterCallback callback);
  4122. /**
  4123. * Enables the host application to provide a mechanism for recording
  4124. * statistics counters.
  4125. */
  4126. void SetCounterFunction(CounterLookupCallback);
  4127. /**
  4128. * Enables the host application to provide a mechanism for recording
  4129. * histograms. The CreateHistogram function returns a
  4130. * histogram which will later be passed to the AddHistogramSample
  4131. * function.
  4132. */
  4133. void SetCreateHistogramFunction(CreateHistogramCallback);
  4134. void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
  4135. /**
  4136. * Optional notification that the embedder is idle.
  4137. * V8 uses the notification to reduce memory footprint.
  4138. * This call can be used repeatedly if the embedder remains idle.
  4139. * Returns true if the embedder should stop calling IdleNotification
  4140. * until real work has been done. This indicates that V8 has done
  4141. * as much cleanup as it will be able to do.
  4142. *
  4143. * The idle_time_in_ms argument specifies the time V8 has to do reduce
  4144. * the memory footprint. There is no guarantee that the actual work will be
  4145. * done within the time limit.
  4146. */
  4147. bool IdleNotification(int idle_time_in_ms);
  4148. /**
  4149. * Optional notification that the system is running low on memory.
  4150. * V8 uses these notifications to attempt to free memory.
  4151. */
  4152. void LowMemoryNotification();
  4153. /**
  4154. * Optional notification that a context has been disposed. V8 uses
  4155. * these notifications to guide the GC heuristic. Returns the number
  4156. * of context disposals - including this one - since the last time
  4157. * V8 had a chance to clean up.
  4158. */
  4159. int ContextDisposedNotification();
  4160. /**
  4161. * Allows the host application to provide the address of a function that is
  4162. * notified each time code is added, moved or removed.
  4163. *
  4164. * \param options options for the JIT code event handler.
  4165. * \param event_handler the JIT code event handler, which will be invoked
  4166. * each time code is added, moved or removed.
  4167. * \note \p event_handler won't get notified of existent code.
  4168. * \note since code removal notifications are not currently issued, the
  4169. * \p event_handler may get notifications of code that overlaps earlier
  4170. * code notifications. This happens when code areas are reused, and the
  4171. * earlier overlapping code areas should therefore be discarded.
  4172. * \note the events passed to \p event_handler and the strings they point to
  4173. * are not guaranteed to live past each call. The \p event_handler must
  4174. * copy strings and other parameters it needs to keep around.
  4175. * \note the set of events declared in JitCodeEvent::EventType is expected to
  4176. * grow over time, and the JitCodeEvent structure is expected to accrue
  4177. * new members. The \p event_handler function must ignore event codes
  4178. * it does not recognize to maintain future compatibility.
  4179. * \note Use Isolate::CreateParams to get events for code executed during
  4180. * Isolate setup.
  4181. */
  4182. void SetJitCodeEventHandler(JitCodeEventOptions options,
  4183. JitCodeEventHandler event_handler);
  4184. /**
  4185. * Modifies the stack limit for this Isolate.
  4186. *
  4187. * \param stack_limit An address beyond which the Vm's stack may not grow.
  4188. *
  4189. * \note If you are using threads then you should hold the V8::Locker lock
  4190. * while setting the stack limit and you must set a non-default stack
  4191. * limit separately for each thread.
  4192. */
  4193. void SetStackLimit(uintptr_t stack_limit);
  4194. /**
  4195. * Returns a memory range that can potentially contain jitted code.
  4196. *
  4197. * On Win64, embedders are advised to install function table callbacks for
  4198. * these ranges, as default SEH won't be able to unwind through jitted code.
  4199. *
  4200. * The first page of the code range is reserved for the embedder and is
  4201. * committed, writable, and executable.
  4202. *
  4203. * Might be empty on other platforms.
  4204. *
  4205. * https://code.google.com/p/v8/issues/detail?id=3598
  4206. */
  4207. void GetCodeRange(void** start, size_t* length_in_bytes);
  4208. private:
  4209. template<class K, class V, class Traits> friend class PersistentValueMap;
  4210. Isolate();
  4211. Isolate(const Isolate&);
  4212. ~Isolate();
  4213. Isolate& operator=(const Isolate&);
  4214. void* operator new(size_t size);
  4215. void operator delete(void*, size_t);
  4216. void SetObjectGroupId(internal::Object** object, UniqueId id);
  4217. void SetReferenceFromGroup(UniqueId id, internal::Object** object);
  4218. void SetReference(internal::Object** parent, internal::Object** child);
  4219. void CollectAllGarbage(const char* gc_reason);
  4220. };
  4221. class V8_EXPORT StartupData {
  4222. public:
  4223. enum CompressionAlgorithm {
  4224. kUncompressed,
  4225. kBZip2
  4226. };
  4227. const char* data;
  4228. int compressed_size;
  4229. int raw_size;
  4230. };
  4231. /**
  4232. * A helper class for driving V8 startup data decompression. It is based on
  4233. * "CompressedStartupData" API functions from the V8 class. It isn't mandatory
  4234. * for an embedder to use this class, instead, API functions can be used
  4235. * directly.
  4236. *
  4237. * For an example of the class usage, see the "shell.cc" sample application.
  4238. */
  4239. class V8_EXPORT StartupDataDecompressor { // NOLINT
  4240. public:
  4241. StartupDataDecompressor();
  4242. virtual ~StartupDataDecompressor();
  4243. int Decompress();
  4244. protected:
  4245. virtual int DecompressData(char* raw_data,
  4246. int* raw_data_size,
  4247. const char* compressed_data,
  4248. int compressed_data_size) = 0;
  4249. private:
  4250. char** raw_data;
  4251. };
  4252. /**
  4253. * EntropySource is used as a callback function when v8 needs a source
  4254. * of entropy.
  4255. */
  4256. typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
  4257. /**
  4258. * ReturnAddressLocationResolver is used as a callback function when v8 is
  4259. * resolving the location of a return address on the stack. Profilers that
  4260. * change the return address on the stack can use this to resolve the stack
  4261. * location to whereever the profiler stashed the original return address.
  4262. *
  4263. * \param return_addr_location points to a location on stack where a machine
  4264. * return address resides.
  4265. * \returns either return_addr_location, or else a pointer to the profiler's
  4266. * copy of the original return address.
  4267. *
  4268. * \note the resolver function must not cause garbage collection.
  4269. */
  4270. typedef uintptr_t (*ReturnAddressLocationResolver)(
  4271. uintptr_t return_addr_location);
  4272. /**
  4273. * Interface for iterating through all external resources in the heap.
  4274. */
  4275. class V8_EXPORT ExternalResourceVisitor { // NOLINT
  4276. public:
  4277. virtual ~ExternalResourceVisitor() {}
  4278. virtual void VisitExternalString(Handle<String> string) {}
  4279. };
  4280. /**
  4281. * Interface for iterating through all the persistent handles in the heap.
  4282. */
  4283. class V8_EXPORT PersistentHandleVisitor { // NOLINT
  4284. public:
  4285. virtual ~PersistentHandleVisitor() {}
  4286. virtual void VisitPersistentHandle(Persistent<Value>* value,
  4287. uint16_t class_id) {}
  4288. };
  4289. /**
  4290. * Container class for static utility functions.
  4291. */
  4292. class V8_EXPORT V8 {
  4293. public:
  4294. /** Set the callback to invoke in case of fatal errors. */
  4295. static void SetFatalErrorHandler(FatalErrorCallback that);
  4296. /**
  4297. * Set the callback to invoke to check if code generation from
  4298. * strings should be allowed.
  4299. */
  4300. static void SetAllowCodeGenerationFromStringsCallback(
  4301. AllowCodeGenerationFromStringsCallback that);
  4302. /**
  4303. * Set allocator to use for ArrayBuffer memory.
  4304. * The allocator should be set only once. The allocator should be set
  4305. * before any code tha uses ArrayBuffers is executed.
  4306. * This allocator is used in all isolates.
  4307. */
  4308. static void SetArrayBufferAllocator(ArrayBuffer::Allocator* allocator);
  4309. /**
  4310. * Check if V8 is dead and therefore unusable. This is the case after
  4311. * fatal errors such as out-of-memory situations.
  4312. */
  4313. static bool IsDead();
  4314. /**
  4315. * The following 4 functions are to be used when V8 is built with
  4316. * the 'compress_startup_data' flag enabled. In this case, the
  4317. * embedder must decompress startup data prior to initializing V8.
  4318. *
  4319. * This is how interaction with V8 should look like:
  4320. * int compressed_data_count = v8::V8::GetCompressedStartupDataCount();
  4321. * v8::StartupData* compressed_data =
  4322. * new v8::StartupData[compressed_data_count];
  4323. * v8::V8::GetCompressedStartupData(compressed_data);
  4324. * ... decompress data (compressed_data can be updated in-place) ...
  4325. * v8::V8::SetDecompressedStartupData(compressed_data);
  4326. * ... now V8 can be initialized
  4327. * ... make sure the decompressed data stays valid until V8 shutdown
  4328. *
  4329. * A helper class StartupDataDecompressor is provided. It implements
  4330. * the protocol of the interaction described above, and can be used in
  4331. * most cases instead of calling these API functions directly.
  4332. */
  4333. static StartupData::CompressionAlgorithm GetCompressedStartupDataAlgorithm();
  4334. static int GetCompressedStartupDataCount();
  4335. static void GetCompressedStartupData(StartupData* compressed_data);
  4336. static void SetDecompressedStartupData(StartupData* decompressed_data);
  4337. /**
  4338. * Hand startup data to V8, in case the embedder has chosen to build
  4339. * V8 with external startup data.
  4340. *
  4341. * Note:
  4342. * - By default the startup data is linked into the V8 library, in which
  4343. * case this function is not meaningful.
  4344. * - If this needs to be called, it needs to be called before V8
  4345. * tries to make use of its built-ins.
  4346. * - To avoid unnecessary copies of data, V8 will point directly into the
  4347. * given data blob, so pretty please keep it around until V8 exit.
  4348. * - Compression of the startup blob might be useful, but needs to
  4349. * handled entirely on the embedders' side.
  4350. * - The call will abort if the data is invalid.
  4351. */
  4352. static void SetNativesDataBlob(StartupData* startup_blob);
  4353. static void SetSnapshotDataBlob(StartupData* startup_blob);
  4354. /**
  4355. * Adds a message listener.
  4356. *
  4357. * The same message listener can be added more than once and in that
  4358. * case it will be called more than once for each message.
  4359. *
  4360. * If data is specified, it will be passed to the callback when it is called.
  4361. * Otherwise, the exception object will be passed to the callback instead.
  4362. */
  4363. static bool AddMessageListener(MessageCallback that,
  4364. Handle<Value> data = Handle<Value>());
  4365. /**
  4366. * Remove all message listeners from the specified callback function.
  4367. */
  4368. static void RemoveMessageListeners(MessageCallback that);
  4369. /**
  4370. * Tells V8 to capture current stack trace when uncaught exception occurs
  4371. * and report it to the message listeners. The option is off by default.
  4372. */
  4373. static void SetCaptureStackTraceForUncaughtExceptions(
  4374. bool capture,
  4375. int frame_limit = 10,
  4376. StackTrace::StackTraceOptions options = StackTrace::kOverview);
  4377. /**
  4378. * Sets V8 flags from a string.
  4379. */
  4380. static void SetFlagsFromString(const char* str, int length);
  4381. /**
  4382. * Sets V8 flags from the command line.
  4383. */
  4384. static void SetFlagsFromCommandLine(int* argc,
  4385. char** argv,
  4386. bool remove_flags);
  4387. /** Get the version string. */
  4388. static const char* GetVersion();
  4389. /** Callback function for reporting failed access checks.*/
  4390. static void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
  4391. /**
  4392. * Enables the host application to receive a notification before a
  4393. * garbage collection. Allocations are not allowed in the
  4394. * callback function, you therefore cannot manipulate objects (set
  4395. * or delete properties for example) since it is possible such
  4396. * operations will result in the allocation of objects. It is possible
  4397. * to specify the GCType filter for your callback. But it is not possible to
  4398. * register the same callback function two times with different
  4399. * GCType filters.
  4400. */
  4401. static void AddGCPrologueCallback(
  4402. GCPrologueCallback callback, GCType gc_type_filter = kGCTypeAll);
  4403. /**
  4404. * This function removes callback which was installed by
  4405. * AddGCPrologueCallback function.
  4406. */
  4407. static void RemoveGCPrologueCallback(GCPrologueCallback callback);
  4408. /**
  4409. * Enables the host application to receive a notification after a
  4410. * garbage collection. Allocations are not allowed in the
  4411. * callback function, you therefore cannot manipulate objects (set
  4412. * or delete properties for example) since it is possible such
  4413. * operations will result in the allocation of objects. It is possible
  4414. * to specify the GCType filter for your callback. But it is not possible to
  4415. * register the same callback function two times with different
  4416. * GCType filters.
  4417. */
  4418. static void AddGCEpilogueCallback(
  4419. GCEpilogueCallback callback, GCType gc_type_filter = kGCTypeAll);
  4420. /**
  4421. * This function removes callback which was installed by
  4422. * AddGCEpilogueCallback function.
  4423. */
  4424. static void RemoveGCEpilogueCallback(GCEpilogueCallback callback);
  4425. /**
  4426. * Enables the host application to provide a mechanism to be notified
  4427. * and perform custom logging when V8 Allocates Executable Memory.
  4428. */
  4429. static void AddMemoryAllocationCallback(MemoryAllocationCallback callback,
  4430. ObjectSpace space,
  4431. AllocationAction action);
  4432. /**
  4433. * Removes callback that was installed by AddMemoryAllocationCallback.
  4434. */
  4435. static void RemoveMemoryAllocationCallback(MemoryAllocationCallback callback);
  4436. /**
  4437. * Initializes V8. This function needs to be called before the first Isolate
  4438. * is created. It always returns true.
  4439. */
  4440. static bool Initialize();
  4441. /**
  4442. * Allows the host application to provide a callback which can be used
  4443. * as a source of entropy for random number generators.
  4444. */
  4445. static void SetEntropySource(EntropySource source);
  4446. /**
  4447. * Allows the host application to provide a callback that allows v8 to
  4448. * cooperate with a profiler that rewrites return addresses on stack.
  4449. */
  4450. static void SetReturnAddressLocationResolver(
  4451. ReturnAddressLocationResolver return_address_resolver);
  4452. /**
  4453. * Forcefully terminate the current thread of JavaScript execution
  4454. * in the given isolate.
  4455. *
  4456. * This method can be used by any thread even if that thread has not
  4457. * acquired the V8 lock with a Locker object.
  4458. *
  4459. * \param isolate The isolate in which to terminate the current JS execution.
  4460. */
  4461. static void TerminateExecution(Isolate* isolate);
  4462. /**
  4463. * Is V8 terminating JavaScript execution.
  4464. *
  4465. * Returns true if JavaScript execution is currently terminating
  4466. * because of a call to TerminateExecution. In that case there are
  4467. * still JavaScript frames on the stack and the termination
  4468. * exception is still active.
  4469. *
  4470. * \param isolate The isolate in which to check.
  4471. */
  4472. static bool IsExecutionTerminating(Isolate* isolate = NULL);
  4473. /**
  4474. * Resume execution capability in the given isolate, whose execution
  4475. * was previously forcefully terminated using TerminateExecution().
  4476. *
  4477. * When execution is forcefully terminated using TerminateExecution(),
  4478. * the isolate can not resume execution until all JavaScript frames
  4479. * have propagated the uncatchable exception which is generated. This
  4480. * method allows the program embedding the engine to handle the
  4481. * termination event and resume execution capability, even if
  4482. * JavaScript frames remain on the stack.
  4483. *
  4484. * This method can be used by any thread even if that thread has not
  4485. * acquired the V8 lock with a Locker object.
  4486. *
  4487. * \param isolate The isolate in which to resume execution capability.
  4488. */
  4489. static void CancelTerminateExecution(Isolate* isolate);
  4490. /**
  4491. * Releases any resources used by v8 and stops any utility threads
  4492. * that may be running. Note that disposing v8 is permanent, it
  4493. * cannot be reinitialized.
  4494. *
  4495. * It should generally not be necessary to dispose v8 before exiting
  4496. * a process, this should happen automatically. It is only necessary
  4497. * to use if the process needs the resources taken up by v8.
  4498. */
  4499. static bool Dispose();
  4500. /**
  4501. * Iterates through all external resources referenced from current isolate
  4502. * heap. GC is not invoked prior to iterating, therefore there is no
  4503. * guarantee that visited objects are still alive.
  4504. */
  4505. static void VisitExternalResources(ExternalResourceVisitor* visitor);
  4506. /**
  4507. * Iterates through all the persistent handles in the current isolate's heap
  4508. * that have class_ids.
  4509. */
  4510. static void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
  4511. /**
  4512. * Iterates through all the persistent handles in the current isolate's heap
  4513. * that have class_ids and are candidates to be marked as partially dependent
  4514. * handles. This will visit handles to young objects created since the last
  4515. * garbage collection but is free to visit an arbitrary superset of these
  4516. * objects.
  4517. */
  4518. static void VisitHandlesForPartialDependence(
  4519. Isolate* isolate, PersistentHandleVisitor* visitor);
  4520. /**
  4521. * Initialize the ICU library bundled with V8. The embedder should only
  4522. * invoke this method when using the bundled ICU. Returns true on success.
  4523. *
  4524. * If V8 was compiled with the ICU data in an external file, the location
  4525. * of the data file has to be provided.
  4526. */
  4527. static bool InitializeICU(const char* icu_data_file = NULL);
  4528. /**
  4529. * Sets the v8::Platform to use. This should be invoked before V8 is
  4530. * initialized.
  4531. */
  4532. static void InitializePlatform(Platform* platform);
  4533. /**
  4534. * Clears all references to the v8::Platform. This should be invoked after
  4535. * V8 was disposed.
  4536. */
  4537. static void ShutdownPlatform();
  4538. private:
  4539. V8();
  4540. static internal::Object** GlobalizeReference(internal::Isolate* isolate,
  4541. internal::Object** handle);
  4542. static internal::Object** CopyPersistent(internal::Object** handle);
  4543. static void DisposeGlobal(internal::Object** global_handle);
  4544. typedef WeakCallbackData<Value, void>::Callback WeakCallback;
  4545. static void MakeWeak(internal::Object** global_handle,
  4546. void* data,
  4547. WeakCallback weak_callback);
  4548. static void* ClearWeak(internal::Object** global_handle);
  4549. static void Eternalize(Isolate* isolate,
  4550. Value* handle,
  4551. int* index);
  4552. static Local<Value> GetEternal(Isolate* isolate, int index);
  4553. template <class T> friend class Handle;
  4554. template <class T> friend class Local;
  4555. template <class T> friend class Eternal;
  4556. template <class T> friend class PersistentBase;
  4557. template <class T, class M> friend class Persistent;
  4558. friend class Context;
  4559. };
  4560. /**
  4561. * An external exception handler.
  4562. */
  4563. class V8_EXPORT TryCatch {
  4564. public:
  4565. /**
  4566. * Creates a new try/catch block and registers it with v8. Note that
  4567. * all TryCatch blocks should be stack allocated because the memory
  4568. * location itself is compared against JavaScript try/catch blocks.
  4569. */
  4570. TryCatch();
  4571. /**
  4572. * Unregisters and deletes this try/catch block.
  4573. */
  4574. ~TryCatch();
  4575. /**
  4576. * Returns true if an exception has been caught by this try/catch block.
  4577. */
  4578. bool HasCaught() const;
  4579. /**
  4580. * For certain types of exceptions, it makes no sense to continue execution.
  4581. *
  4582. * If CanContinue returns false, the correct action is to perform any C++
  4583. * cleanup needed and then return. If CanContinue returns false and
  4584. * HasTerminated returns true, it is possible to call
  4585. * CancelTerminateExecution in order to continue calling into the engine.
  4586. */
  4587. bool CanContinue() const;
  4588. /**
  4589. * Returns true if an exception has been caught due to script execution
  4590. * being terminated.
  4591. *
  4592. * There is no JavaScript representation of an execution termination
  4593. * exception. Such exceptions are thrown when the TerminateExecution
  4594. * methods are called to terminate a long-running script.
  4595. *
  4596. * If such an exception has been thrown, HasTerminated will return true,
  4597. * indicating that it is possible to call CancelTerminateExecution in order
  4598. * to continue calling into the engine.
  4599. */
  4600. bool HasTerminated() const;
  4601. /**
  4602. * Throws the exception caught by this TryCatch in a way that avoids
  4603. * it being caught again by this same TryCatch. As with ThrowException
  4604. * it is illegal to execute any JavaScript operations after calling
  4605. * ReThrow; the caller must return immediately to where the exception
  4606. * is caught.
  4607. */
  4608. Handle<Value> ReThrow();
  4609. /**
  4610. * Returns the exception caught by this try/catch block. If no exception has
  4611. * been caught an empty handle is returned.
  4612. *
  4613. * The returned handle is valid until this TryCatch block has been destroyed.
  4614. */
  4615. Local<Value> Exception() const;
  4616. /**
  4617. * Returns the .stack property of the thrown object. If no .stack
  4618. * property is present an empty handle is returned.
  4619. */
  4620. Local<Value> StackTrace() const;
  4621. /**
  4622. * Returns the message associated with this exception. If there is
  4623. * no message associated an empty handle is returned.
  4624. *
  4625. * The returned handle is valid until this TryCatch block has been
  4626. * destroyed.
  4627. */
  4628. Local<v8::Message> Message() const;
  4629. /**
  4630. * Clears any exceptions that may have been caught by this try/catch block.
  4631. * After this method has been called, HasCaught() will return false. Cancels
  4632. * the scheduled exception if it is caught and ReThrow() is not called before.
  4633. *
  4634. * It is not necessary to clear a try/catch block before using it again; if
  4635. * another exception is thrown the previously caught exception will just be
  4636. * overwritten. However, it is often a good idea since it makes it easier
  4637. * to determine which operation threw a given exception.
  4638. */
  4639. void Reset();
  4640. /**
  4641. * Set verbosity of the external exception handler.
  4642. *
  4643. * By default, exceptions that are caught by an external exception
  4644. * handler are not reported. Call SetVerbose with true on an
  4645. * external exception handler to have exceptions caught by the
  4646. * handler reported as if they were not caught.
  4647. */
  4648. void SetVerbose(bool value);
  4649. /**
  4650. * Set whether or not this TryCatch should capture a Message object
  4651. * which holds source information about where the exception
  4652. * occurred. True by default.
  4653. */
  4654. void SetCaptureMessage(bool value);
  4655. /**
  4656. * There are cases when the raw address of C++ TryCatch object cannot be
  4657. * used for comparisons with addresses into the JS stack. The cases are:
  4658. * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
  4659. * 2) Address sanitizer allocates local C++ object in the heap when
  4660. * UseAfterReturn mode is enabled.
  4661. * This method returns address that can be used for comparisons with
  4662. * addresses into the JS stack. When neither simulator nor ASAN's
  4663. * UseAfterReturn is enabled, then the address returned will be the address
  4664. * of the C++ try catch handler itself.
  4665. */
  4666. static void* JSStackComparableAddress(v8::TryCatch* handler) {
  4667. if (handler == NULL) return NULL;
  4668. return handler->js_stack_comparable_address_;
  4669. }
  4670. private:
  4671. void ResetInternal();
  4672. // Make it hard to create heap-allocated TryCatch blocks.
  4673. TryCatch(const TryCatch&);
  4674. void operator=(const TryCatch&);
  4675. void* operator new(size_t size);
  4676. void operator delete(void*, size_t);
  4677. v8::internal::Isolate* isolate_;
  4678. v8::TryCatch* next_;
  4679. void* exception_;
  4680. void* message_obj_;
  4681. void* message_script_;
  4682. void* js_stack_comparable_address_;
  4683. int message_start_pos_;
  4684. int message_end_pos_;
  4685. bool is_verbose_ : 1;
  4686. bool can_continue_ : 1;
  4687. bool capture_message_ : 1;
  4688. bool rethrow_ : 1;
  4689. bool has_terminated_ : 1;
  4690. friend class v8::internal::Isolate;
  4691. };
  4692. // --- Context ---
  4693. /**
  4694. * A container for extension names.
  4695. */
  4696. class V8_EXPORT ExtensionConfiguration {
  4697. public:
  4698. ExtensionConfiguration() : name_count_(0), names_(NULL) { }
  4699. ExtensionConfiguration(int name_count, const char* names[])
  4700. : name_count_(name_count), names_(names) { }
  4701. const char** begin() const { return &names_[0]; }
  4702. const char** end() const { return &names_[name_count_]; }
  4703. private:
  4704. const int name_count_;
  4705. const char** names_;
  4706. };
  4707. /**
  4708. * A sandboxed execution context with its own set of built-in objects
  4709. * and functions.
  4710. */
  4711. class V8_EXPORT Context {
  4712. public:
  4713. /**
  4714. * Returns the global proxy object.
  4715. *
  4716. * Global proxy object is a thin wrapper whose prototype points to actual
  4717. * context's global object with the properties like Object, etc. This is done
  4718. * that way for security reasons (for more details see
  4719. * https://wiki.mozilla.org/Gecko:SplitWindow).
  4720. *
  4721. * Please note that changes to global proxy object prototype most probably
  4722. * would break VM---v8 expects only global object as a prototype of global
  4723. * proxy object.
  4724. */
  4725. Local<Object> Global();
  4726. /**
  4727. * Detaches the global object from its context before
  4728. * the global object can be reused to create a new context.
  4729. */
  4730. void DetachGlobal();
  4731. /**
  4732. * Creates a new context and returns a handle to the newly allocated
  4733. * context.
  4734. *
  4735. * \param isolate The isolate in which to create the context.
  4736. *
  4737. * \param extensions An optional extension configuration containing
  4738. * the extensions to be installed in the newly created context.
  4739. *
  4740. * \param global_template An optional object template from which the
  4741. * global object for the newly created context will be created.
  4742. *
  4743. * \param global_object An optional global object to be reused for
  4744. * the newly created context. This global object must have been
  4745. * created by a previous call to Context::New with the same global
  4746. * template. The state of the global object will be completely reset
  4747. * and only object identify will remain.
  4748. */
  4749. static Local<Context> New(
  4750. Isolate* isolate,
  4751. ExtensionConfiguration* extensions = NULL,
  4752. Handle<ObjectTemplate> global_template = Handle<ObjectTemplate>(),
  4753. Handle<Value> global_object = Handle<Value>());
  4754. /**
  4755. * Sets the security token for the context. To access an object in
  4756. * another context, the security tokens must match.
  4757. */
  4758. void SetSecurityToken(Handle<Value> token);
  4759. /** Restores the security token to the default value. */
  4760. void UseDefaultSecurityToken();
  4761. /** Returns the security token of this context.*/
  4762. Handle<Value> GetSecurityToken();
  4763. /**
  4764. * Enter this context. After entering a context, all code compiled
  4765. * and run is compiled and run in this context. If another context
  4766. * is already entered, this old context is saved so it can be
  4767. * restored when the new context is exited.
  4768. */
  4769. void Enter();
  4770. /**
  4771. * Exit this context. Exiting the current context restores the
  4772. * context that was in place when entering the current context.
  4773. */
  4774. void Exit();
  4775. /** Returns an isolate associated with a current context. */
  4776. v8::Isolate* GetIsolate();
  4777. /**
  4778. * Gets the embedder data with the given index, which must have been set by a
  4779. * previous call to SetEmbedderData with the same index. Note that index 0
  4780. * currently has a special meaning for Chrome's debugger.
  4781. */
  4782. V8_INLINE Local<Value> GetEmbedderData(int index);
  4783. /**
  4784. * Sets the embedder data with the given index, growing the data as
  4785. * needed. Note that index 0 currently has a special meaning for Chrome's
  4786. * debugger.
  4787. */
  4788. void SetEmbedderData(int index, Handle<Value> value);
  4789. /**
  4790. * Gets a 2-byte-aligned native pointer from the embedder data with the given
  4791. * index, which must have bees set by a previous call to
  4792. * SetAlignedPointerInEmbedderData with the same index. Note that index 0
  4793. * currently has a special meaning for Chrome's debugger.
  4794. */
  4795. V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
  4796. /**
  4797. * Sets a 2-byte-aligned native pointer in the embedder data with the given
  4798. * index, growing the data as needed. Note that index 0 currently has a
  4799. * special meaning for Chrome's debugger.
  4800. */
  4801. void SetAlignedPointerInEmbedderData(int index, void* value);
  4802. /**
  4803. * Control whether code generation from strings is allowed. Calling
  4804. * this method with false will disable 'eval' and the 'Function'
  4805. * constructor for code running in this context. If 'eval' or the
  4806. * 'Function' constructor are used an exception will be thrown.
  4807. *
  4808. * If code generation from strings is not allowed the
  4809. * V8::AllowCodeGenerationFromStrings callback will be invoked if
  4810. * set before blocking the call to 'eval' or the 'Function'
  4811. * constructor. If that callback returns true, the call will be
  4812. * allowed, otherwise an exception will be thrown. If no callback is
  4813. * set an exception will be thrown.
  4814. */
  4815. void AllowCodeGenerationFromStrings(bool allow);
  4816. /**
  4817. * Returns true if code generation from strings is allowed for the context.
  4818. * For more details see AllowCodeGenerationFromStrings(bool) documentation.
  4819. */
  4820. bool IsCodeGenerationFromStringsAllowed();
  4821. /**
  4822. * Sets the error description for the exception that is thrown when
  4823. * code generation from strings is not allowed and 'eval' or the 'Function'
  4824. * constructor are called.
  4825. */
  4826. void SetErrorMessageForCodeGenerationFromStrings(Handle<String> message);
  4827. /**
  4828. * Stack-allocated class which sets the execution context for all
  4829. * operations executed within a local scope.
  4830. */
  4831. class Scope {
  4832. public:
  4833. explicit V8_INLINE Scope(Handle<Context> context) : context_(context) {
  4834. context_->Enter();
  4835. }
  4836. V8_INLINE ~Scope() { context_->Exit(); }
  4837. private:
  4838. Handle<Context> context_;
  4839. };
  4840. private:
  4841. friend class Value;
  4842. friend class Script;
  4843. friend class Object;
  4844. friend class Function;
  4845. Local<Value> SlowGetEmbedderData(int index);
  4846. void* SlowGetAlignedPointerFromEmbedderData(int index);
  4847. };
  4848. /**
  4849. * Multiple threads in V8 are allowed, but only one thread at a time is allowed
  4850. * to use any given V8 isolate, see the comments in the Isolate class. The
  4851. * definition of 'using a V8 isolate' includes accessing handles or holding onto
  4852. * object pointers obtained from V8 handles while in the particular V8 isolate.
  4853. * It is up to the user of V8 to ensure, perhaps with locking, that this
  4854. * constraint is not violated. In addition to any other synchronization
  4855. * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
  4856. * used to signal thead switches to V8.
  4857. *
  4858. * v8::Locker is a scoped lock object. While it's active, i.e. between its
  4859. * construction and destruction, the current thread is allowed to use the locked
  4860. * isolate. V8 guarantees that an isolate can be locked by at most one thread at
  4861. * any time. In other words, the scope of a v8::Locker is a critical section.
  4862. *
  4863. * Sample usage:
  4864. * \code
  4865. * ...
  4866. * {
  4867. * v8::Locker locker(isolate);
  4868. * v8::Isolate::Scope isolate_scope(isolate);
  4869. * ...
  4870. * // Code using V8 and isolate goes here.
  4871. * ...
  4872. * } // Destructor called here
  4873. * \endcode
  4874. *
  4875. * If you wish to stop using V8 in a thread A you can do this either by
  4876. * destroying the v8::Locker object as above or by constructing a v8::Unlocker
  4877. * object:
  4878. *
  4879. * \code
  4880. * {
  4881. * isolate->Exit();
  4882. * v8::Unlocker unlocker(isolate);
  4883. * ...
  4884. * // Code not using V8 goes here while V8 can run in another thread.
  4885. * ...
  4886. * } // Destructor called here.
  4887. * isolate->Enter();
  4888. * \endcode
  4889. *
  4890. * The Unlocker object is intended for use in a long-running callback from V8,
  4891. * where you want to release the V8 lock for other threads to use.
  4892. *
  4893. * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
  4894. * given thread. This can be useful if you have code that can be called either
  4895. * from code that holds the lock or from code that does not. The Unlocker is
  4896. * not recursive so you can not have several Unlockers on the stack at once, and
  4897. * you can not use an Unlocker in a thread that is not inside a Locker's scope.
  4898. *
  4899. * An unlocker will unlock several lockers if it has to and reinstate the
  4900. * correct depth of locking on its destruction, e.g.:
  4901. *
  4902. * \code
  4903. * // V8 not locked.
  4904. * {
  4905. * v8::Locker locker(isolate);
  4906. * Isolate::Scope isolate_scope(isolate);
  4907. * // V8 locked.
  4908. * {
  4909. * v8::Locker another_locker(isolate);
  4910. * // V8 still locked (2 levels).
  4911. * {
  4912. * isolate->Exit();
  4913. * v8::Unlocker unlocker(isolate);
  4914. * // V8 not locked.
  4915. * }
  4916. * isolate->Enter();
  4917. * // V8 locked again (2 levels).
  4918. * }
  4919. * // V8 still locked (1 level).
  4920. * }
  4921. * // V8 Now no longer locked.
  4922. * \endcode
  4923. */
  4924. class V8_EXPORT Unlocker {
  4925. public:
  4926. /**
  4927. * Initialize Unlocker for a given Isolate.
  4928. */
  4929. V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
  4930. ~Unlocker();
  4931. private:
  4932. void Initialize(Isolate* isolate);
  4933. internal::Isolate* isolate_;
  4934. };
  4935. class V8_EXPORT Locker {
  4936. public:
  4937. /**
  4938. * Initialize Locker for a given Isolate.
  4939. */
  4940. V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
  4941. ~Locker();
  4942. /**
  4943. * Returns whether or not the locker for a given isolate, is locked by the
  4944. * current thread.
  4945. */
  4946. static bool IsLocked(Isolate* isolate);
  4947. /**
  4948. * Returns whether v8::Locker is being used by this V8 instance.
  4949. */
  4950. static bool IsActive();
  4951. private:
  4952. void Initialize(Isolate* isolate);
  4953. bool has_lock_;
  4954. bool top_level_;
  4955. internal::Isolate* isolate_;
  4956. // Disallow copying and assigning.
  4957. Locker(const Locker&);
  4958. void operator=(const Locker&);
  4959. };
  4960. // --- Implementation ---
  4961. namespace internal {
  4962. const int kApiPointerSize = sizeof(void*); // NOLINT
  4963. const int kApiIntSize = sizeof(int); // NOLINT
  4964. const int kApiInt64Size = sizeof(int64_t); // NOLINT
  4965. // Tag information for HeapObject.
  4966. const int kHeapObjectTag = 1;
  4967. const int kHeapObjectTagSize = 2;
  4968. const intptr_t kHeapObjectTagMask = (1 << kHeapObjectTagSize) - 1;
  4969. // Tag information for Smi.
  4970. const int kSmiTag = 0;
  4971. const int kSmiTagSize = 1;
  4972. const intptr_t kSmiTagMask = (1 << kSmiTagSize) - 1;
  4973. template <size_t ptr_size> struct SmiTagging;
  4974. template<int kSmiShiftSize>
  4975. V8_INLINE internal::Object* IntToSmi(int value) {
  4976. int smi_shift_bits = kSmiTagSize + kSmiShiftSize;
  4977. uintptr_t tagged_value =
  4978. (static_cast<uintptr_t>(value) << smi_shift_bits) | kSmiTag;
  4979. return reinterpret_cast<internal::Object*>(tagged_value);
  4980. }
  4981. // Smi constants for 32-bit systems.
  4982. template <> struct SmiTagging<4> {
  4983. enum { kSmiShiftSize = 0, kSmiValueSize = 31 };
  4984. static int SmiShiftSize() { return kSmiShiftSize; }
  4985. static int SmiValueSize() { return kSmiValueSize; }
  4986. V8_INLINE static int SmiToInt(const internal::Object* value) {
  4987. int shift_bits = kSmiTagSize + kSmiShiftSize;
  4988. // Throw away top 32 bits and shift down (requires >> to be sign extending).
  4989. return static_cast<int>(reinterpret_cast<intptr_t>(value)) >> shift_bits;
  4990. }
  4991. V8_INLINE static internal::Object* IntToSmi(int value) {
  4992. return internal::IntToSmi<kSmiShiftSize>(value);
  4993. }
  4994. V8_INLINE static bool IsValidSmi(intptr_t value) {
  4995. // To be representable as an tagged small integer, the two
  4996. // most-significant bits of 'value' must be either 00 or 11 due to
  4997. // sign-extension. To check this we add 01 to the two
  4998. // most-significant bits, and check if the most-significant bit is 0
  4999. //
  5000. // CAUTION: The original code below:
  5001. // bool result = ((value + 0x40000000) & 0x80000000) == 0;
  5002. // may lead to incorrect results according to the C language spec, and
  5003. // in fact doesn't work correctly with gcc4.1.1 in some cases: The
  5004. // compiler may produce undefined results in case of signed integer
  5005. // overflow. The computation must be done w/ unsigned ints.
  5006. return static_cast<uintptr_t>(value + 0x40000000U) < 0x80000000U;
  5007. }
  5008. };
  5009. // Smi constants for 64-bit systems.
  5010. template <> struct SmiTagging<8> {
  5011. enum { kSmiShiftSize = 31, kSmiValueSize = 32 };
  5012. static int SmiShiftSize() { return kSmiShiftSize; }
  5013. static int SmiValueSize() { return kSmiValueSize; }
  5014. V8_INLINE static int SmiToInt(const internal::Object* value) {
  5015. int shift_bits = kSmiTagSize + kSmiShiftSize;
  5016. // Shift down and throw away top 32 bits.
  5017. return static_cast<int>(reinterpret_cast<intptr_t>(value) >> shift_bits);
  5018. }
  5019. V8_INLINE static internal::Object* IntToSmi(int value) {
  5020. return internal::IntToSmi<kSmiShiftSize>(value);
  5021. }
  5022. V8_INLINE static bool IsValidSmi(intptr_t value) {
  5023. // To be representable as a long smi, the value must be a 32-bit integer.
  5024. return (value == static_cast<int32_t>(value));
  5025. }
  5026. };
  5027. typedef SmiTagging<kApiPointerSize> PlatformSmiTagging;
  5028. const int kSmiShiftSize = PlatformSmiTagging::kSmiShiftSize;
  5029. const int kSmiValueSize = PlatformSmiTagging::kSmiValueSize;
  5030. V8_INLINE static bool SmiValuesAre31Bits() { return kSmiValueSize == 31; }
  5031. V8_INLINE static bool SmiValuesAre32Bits() { return kSmiValueSize == 32; }
  5032. /**
  5033. * This class exports constants and functionality from within v8 that
  5034. * is necessary to implement inline functions in the v8 api. Don't
  5035. * depend on functions and constants defined here.
  5036. */
  5037. class Internals {
  5038. public:
  5039. // These values match non-compiler-dependent values defined within
  5040. // the implementation of v8.
  5041. static const int kHeapObjectMapOffset = 0;
  5042. static const int kMapInstanceTypeAndBitFieldOffset =
  5043. 1 * kApiPointerSize + kApiIntSize;
  5044. static const int kStringResourceOffset = 3 * kApiPointerSize;
  5045. static const int kOddballKindOffset = 3 * kApiPointerSize;
  5046. static const int kForeignAddressOffset = kApiPointerSize;
  5047. static const int kJSObjectHeaderSize = 3 * kApiPointerSize;
  5048. static const int kFixedArrayHeaderSize = 2 * kApiPointerSize;
  5049. static const int kContextHeaderSize = 2 * kApiPointerSize;
  5050. static const int kContextEmbedderDataIndex = 76;
  5051. static const int kFullStringRepresentationMask = 0x07;
  5052. static const int kStringEncodingMask = 0x4;
  5053. static const int kExternalTwoByteRepresentationTag = 0x02;
  5054. static const int kExternalOneByteRepresentationTag = 0x06;
  5055. static const int kIsolateEmbedderDataOffset = 0 * kApiPointerSize;
  5056. static const int kAmountOfExternalAllocatedMemoryOffset =
  5057. 4 * kApiPointerSize;
  5058. static const int kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset =
  5059. kAmountOfExternalAllocatedMemoryOffset + kApiInt64Size;
  5060. static const int kIsolateRootsOffset =
  5061. kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset + kApiInt64Size +
  5062. kApiPointerSize;
  5063. static const int kUndefinedValueRootIndex = 5;
  5064. static const int kNullValueRootIndex = 7;
  5065. static const int kTrueValueRootIndex = 8;
  5066. static const int kFalseValueRootIndex = 9;
  5067. static const int kEmptyStringRootIndex = 154;
  5068. // The external allocation limit should be below 256 MB on all architectures
  5069. // to avoid that resource-constrained embedders run low on memory.
  5070. static const int kExternalAllocationLimit = 192 * 1024 * 1024;
  5071. static const int kNodeClassIdOffset = 1 * kApiPointerSize;
  5072. static const int kNodeFlagsOffset = 1 * kApiPointerSize + 3;
  5073. static const int kNodeStateMask = 0xf;
  5074. static const int kNodeStateIsWeakValue = 2;
  5075. static const int kNodeStateIsPendingValue = 3;
  5076. static const int kNodeStateIsNearDeathValue = 4;
  5077. static const int kNodeIsIndependentShift = 4;
  5078. static const int kNodeIsPartiallyDependentShift = 5;
  5079. static const int kJSObjectType = 0xbd;
  5080. static const int kFirstNonstringType = 0x80;
  5081. static const int kOddballType = 0x83;
  5082. static const int kForeignType = 0x88;
  5083. static const int kUndefinedOddballKind = 5;
  5084. static const int kNullOddballKind = 3;
  5085. static const uint32_t kNumIsolateDataSlots = 4;
  5086. V8_EXPORT static void CheckInitializedImpl(v8::Isolate* isolate);
  5087. V8_INLINE static void CheckInitialized(v8::Isolate* isolate) {
  5088. #ifdef V8_ENABLE_CHECKS
  5089. CheckInitializedImpl(isolate);
  5090. #endif
  5091. }
  5092. V8_INLINE static bool HasHeapObjectTag(const internal::Object* value) {
  5093. return ((reinterpret_cast<intptr_t>(value) & kHeapObjectTagMask) ==
  5094. kHeapObjectTag);
  5095. }
  5096. V8_INLINE static int SmiValue(const internal::Object* value) {
  5097. return PlatformSmiTagging::SmiToInt(value);
  5098. }
  5099. V8_INLINE static internal::Object* IntToSmi(int value) {
  5100. return PlatformSmiTagging::IntToSmi(value);
  5101. }
  5102. V8_INLINE static bool IsValidSmi(intptr_t value) {
  5103. return PlatformSmiTagging::IsValidSmi(value);
  5104. }
  5105. V8_INLINE static int GetInstanceType(const internal::Object* obj) {
  5106. typedef internal::Object O;
  5107. O* map = ReadField<O*>(obj, kHeapObjectMapOffset);
  5108. // Map::InstanceType is defined so that it will always be loaded into
  5109. // the LS 8 bits of one 16-bit word, regardless of endianess.
  5110. return ReadField<uint16_t>(map, kMapInstanceTypeAndBitFieldOffset) & 0xff;
  5111. }
  5112. V8_INLINE static int GetOddballKind(const internal::Object* obj) {
  5113. typedef internal::Object O;
  5114. return SmiValue(ReadField<O*>(obj, kOddballKindOffset));
  5115. }
  5116. V8_INLINE static bool IsExternalTwoByteString(int instance_type) {
  5117. int representation = (instance_type & kFullStringRepresentationMask);
  5118. return representation == kExternalTwoByteRepresentationTag;
  5119. }
  5120. V8_INLINE static uint8_t GetNodeFlag(internal::Object** obj, int shift) {
  5121. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
  5122. return *addr & static_cast<uint8_t>(1U << shift);
  5123. }
  5124. V8_INLINE static void UpdateNodeFlag(internal::Object** obj,
  5125. bool value, int shift) {
  5126. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
  5127. uint8_t mask = static_cast<uint8_t>(1U << shift);
  5128. *addr = static_cast<uint8_t>((*addr & ~mask) | (value << shift));
  5129. }
  5130. V8_INLINE static uint8_t GetNodeState(internal::Object** obj) {
  5131. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
  5132. return *addr & kNodeStateMask;
  5133. }
  5134. V8_INLINE static void UpdateNodeState(internal::Object** obj,
  5135. uint8_t value) {
  5136. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + kNodeFlagsOffset;
  5137. *addr = static_cast<uint8_t>((*addr & ~kNodeStateMask) | value);
  5138. }
  5139. V8_INLINE static void SetEmbedderData(v8::Isolate* isolate,
  5140. uint32_t slot,
  5141. void* data) {
  5142. uint8_t *addr = reinterpret_cast<uint8_t *>(isolate) +
  5143. kIsolateEmbedderDataOffset + slot * kApiPointerSize;
  5144. *reinterpret_cast<void**>(addr) = data;
  5145. }
  5146. V8_INLINE static void* GetEmbedderData(const v8::Isolate* isolate,
  5147. uint32_t slot) {
  5148. const uint8_t* addr = reinterpret_cast<const uint8_t*>(isolate) +
  5149. kIsolateEmbedderDataOffset + slot * kApiPointerSize;
  5150. return *reinterpret_cast<void* const*>(addr);
  5151. }
  5152. V8_INLINE static internal::Object** GetRoot(v8::Isolate* isolate,
  5153. int index) {
  5154. uint8_t* addr = reinterpret_cast<uint8_t*>(isolate) + kIsolateRootsOffset;
  5155. return reinterpret_cast<internal::Object**>(addr + index * kApiPointerSize);
  5156. }
  5157. template <typename T>
  5158. V8_INLINE static T ReadField(const internal::Object* ptr, int offset) {
  5159. const uint8_t* addr =
  5160. reinterpret_cast<const uint8_t*>(ptr) + offset - kHeapObjectTag;
  5161. return *reinterpret_cast<const T*>(addr);
  5162. }
  5163. template <typename T>
  5164. V8_INLINE static T ReadEmbedderData(const v8::Context* context, int index) {
  5165. typedef internal::Object O;
  5166. typedef internal::Internals I;
  5167. O* ctx = *reinterpret_cast<O* const*>(context);
  5168. int embedder_data_offset = I::kContextHeaderSize +
  5169. (internal::kApiPointerSize * I::kContextEmbedderDataIndex);
  5170. O* embedder_data = I::ReadField<O*>(ctx, embedder_data_offset);
  5171. int value_offset =
  5172. I::kFixedArrayHeaderSize + (internal::kApiPointerSize * index);
  5173. return I::ReadField<T>(embedder_data, value_offset);
  5174. }
  5175. };
  5176. } // namespace internal
  5177. template <class T>
  5178. Local<T>::Local() : Handle<T>() { }
  5179. template <class T>
  5180. Local<T> Local<T>::New(Isolate* isolate, Handle<T> that) {
  5181. return New(isolate, that.val_);
  5182. }
  5183. template <class T>
  5184. Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
  5185. return New(isolate, that.val_);
  5186. }
  5187. template <class T>
  5188. Handle<T> Handle<T>::New(Isolate* isolate, T* that) {
  5189. if (that == NULL) return Handle<T>();
  5190. T* that_ptr = that;
  5191. internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
  5192. return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
  5193. reinterpret_cast<internal::Isolate*>(isolate), *p)));
  5194. }
  5195. template <class T>
  5196. Local<T> Local<T>::New(Isolate* isolate, T* that) {
  5197. if (that == NULL) return Local<T>();
  5198. T* that_ptr = that;
  5199. internal::Object** p = reinterpret_cast<internal::Object**>(that_ptr);
  5200. return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
  5201. reinterpret_cast<internal::Isolate*>(isolate), *p)));
  5202. }
  5203. template<class T>
  5204. template<class S>
  5205. void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
  5206. TYPE_CHECK(T, S);
  5207. V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle), &this->index_);
  5208. }
  5209. template<class T>
  5210. Local<T> Eternal<T>::Get(Isolate* isolate) {
  5211. return Local<T>(reinterpret_cast<T*>(*V8::GetEternal(isolate, index_)));
  5212. }
  5213. template <class T>
  5214. T* PersistentBase<T>::New(Isolate* isolate, T* that) {
  5215. if (that == NULL) return NULL;
  5216. internal::Object** p = reinterpret_cast<internal::Object**>(that);
  5217. return reinterpret_cast<T*>(
  5218. V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
  5219. p));
  5220. }
  5221. template <class T, class M>
  5222. template <class S, class M2>
  5223. void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
  5224. TYPE_CHECK(T, S);
  5225. this->Reset();
  5226. if (that.IsEmpty()) return;
  5227. internal::Object** p = reinterpret_cast<internal::Object**>(that.val_);
  5228. this->val_ = reinterpret_cast<T*>(V8::CopyPersistent(p));
  5229. M::Copy(that, this);
  5230. }
  5231. template <class T>
  5232. bool PersistentBase<T>::IsIndependent() const {
  5233. typedef internal::Internals I;
  5234. if (this->IsEmpty()) return false;
  5235. return I::GetNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
  5236. I::kNodeIsIndependentShift);
  5237. }
  5238. template <class T>
  5239. bool PersistentBase<T>::IsNearDeath() const {
  5240. typedef internal::Internals I;
  5241. if (this->IsEmpty()) return false;
  5242. uint8_t node_state =
  5243. I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_));
  5244. return node_state == I::kNodeStateIsNearDeathValue ||
  5245. node_state == I::kNodeStateIsPendingValue;
  5246. }
  5247. template <class T>
  5248. bool PersistentBase<T>::IsWeak() const {
  5249. typedef internal::Internals I;
  5250. if (this->IsEmpty()) return false;
  5251. return I::GetNodeState(reinterpret_cast<internal::Object**>(this->val_)) ==
  5252. I::kNodeStateIsWeakValue;
  5253. }
  5254. template <class T>
  5255. void PersistentBase<T>::Reset() {
  5256. if (this->IsEmpty()) return;
  5257. V8::DisposeGlobal(reinterpret_cast<internal::Object**>(this->val_));
  5258. val_ = 0;
  5259. }
  5260. template <class T>
  5261. template <class S>
  5262. void PersistentBase<T>::Reset(Isolate* isolate, const Handle<S>& other) {
  5263. TYPE_CHECK(T, S);
  5264. Reset();
  5265. if (other.IsEmpty()) return;
  5266. this->val_ = New(isolate, other.val_);
  5267. }
  5268. template <class T>
  5269. template <class S>
  5270. void PersistentBase<T>::Reset(Isolate* isolate,
  5271. const PersistentBase<S>& other) {
  5272. TYPE_CHECK(T, S);
  5273. Reset();
  5274. if (other.IsEmpty()) return;
  5275. this->val_ = New(isolate, other.val_);
  5276. }
  5277. template <class T>
  5278. template <typename S, typename P>
  5279. void PersistentBase<T>::SetWeak(
  5280. P* parameter,
  5281. typename WeakCallbackData<S, P>::Callback callback) {
  5282. TYPE_CHECK(S, T);
  5283. typedef typename WeakCallbackData<Value, void>::Callback Callback;
  5284. V8::MakeWeak(reinterpret_cast<internal::Object**>(this->val_),
  5285. parameter,
  5286. reinterpret_cast<Callback>(callback));
  5287. }
  5288. template <class T>
  5289. template <typename P>
  5290. void PersistentBase<T>::SetWeak(
  5291. P* parameter,
  5292. typename WeakCallbackData<T, P>::Callback callback) {
  5293. SetWeak<T, P>(parameter, callback);
  5294. }
  5295. template <class T>
  5296. template<typename P>
  5297. P* PersistentBase<T>::ClearWeak() {
  5298. return reinterpret_cast<P*>(
  5299. V8::ClearWeak(reinterpret_cast<internal::Object**>(this->val_)));
  5300. }
  5301. template <class T>
  5302. void PersistentBase<T>::MarkIndependent() {
  5303. typedef internal::Internals I;
  5304. if (this->IsEmpty()) return;
  5305. I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
  5306. true,
  5307. I::kNodeIsIndependentShift);
  5308. }
  5309. template <class T>
  5310. void PersistentBase<T>::MarkPartiallyDependent() {
  5311. typedef internal::Internals I;
  5312. if (this->IsEmpty()) return;
  5313. I::UpdateNodeFlag(reinterpret_cast<internal::Object**>(this->val_),
  5314. true,
  5315. I::kNodeIsPartiallyDependentShift);
  5316. }
  5317. template <class T>
  5318. void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
  5319. typedef internal::Internals I;
  5320. if (this->IsEmpty()) return;
  5321. internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
  5322. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
  5323. *reinterpret_cast<uint16_t*>(addr) = class_id;
  5324. }
  5325. template <class T>
  5326. uint16_t PersistentBase<T>::WrapperClassId() const {
  5327. typedef internal::Internals I;
  5328. if (this->IsEmpty()) return 0;
  5329. internal::Object** obj = reinterpret_cast<internal::Object**>(this->val_);
  5330. uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
  5331. return *reinterpret_cast<uint16_t*>(addr);
  5332. }
  5333. template<typename T>
  5334. ReturnValue<T>::ReturnValue(internal::Object** slot) : value_(slot) {}
  5335. template<typename T>
  5336. template<typename S>
  5337. void ReturnValue<T>::Set(const Persistent<S>& handle) {
  5338. TYPE_CHECK(T, S);
  5339. if (V8_UNLIKELY(handle.IsEmpty())) {
  5340. *value_ = GetDefaultValue();
  5341. } else {
  5342. *value_ = *reinterpret_cast<internal::Object**>(*handle);
  5343. }
  5344. }
  5345. template<typename T>
  5346. template<typename S>
  5347. void ReturnValue<T>::Set(const Handle<S> handle) {
  5348. TYPE_CHECK(T, S);
  5349. if (V8_UNLIKELY(handle.IsEmpty())) {
  5350. *value_ = GetDefaultValue();
  5351. } else {
  5352. *value_ = *reinterpret_cast<internal::Object**>(*handle);
  5353. }
  5354. }
  5355. template<typename T>
  5356. void ReturnValue<T>::Set(double i) {
  5357. TYPE_CHECK(T, Number);
  5358. Set(Number::New(GetIsolate(), i));
  5359. }
  5360. template<typename T>
  5361. void ReturnValue<T>::Set(int32_t i) {
  5362. TYPE_CHECK(T, Integer);
  5363. typedef internal::Internals I;
  5364. if (V8_LIKELY(I::IsValidSmi(i))) {
  5365. *value_ = I::IntToSmi(i);
  5366. return;
  5367. }
  5368. Set(Integer::New(GetIsolate(), i));
  5369. }
  5370. template<typename T>
  5371. void ReturnValue<T>::Set(uint32_t i) {
  5372. TYPE_CHECK(T, Integer);
  5373. // Can't simply use INT32_MAX here for whatever reason.
  5374. bool fits_into_int32_t = (i & (1U << 31)) == 0;
  5375. if (V8_LIKELY(fits_into_int32_t)) {
  5376. Set(static_cast<int32_t>(i));
  5377. return;
  5378. }
  5379. Set(Integer::NewFromUnsigned(GetIsolate(), i));
  5380. }
  5381. template<typename T>
  5382. void ReturnValue<T>::Set(bool value) {
  5383. TYPE_CHECK(T, Boolean);
  5384. typedef internal::Internals I;
  5385. int root_index;
  5386. if (value) {
  5387. root_index = I::kTrueValueRootIndex;
  5388. } else {
  5389. root_index = I::kFalseValueRootIndex;
  5390. }
  5391. *value_ = *I::GetRoot(GetIsolate(), root_index);
  5392. }
  5393. template<typename T>
  5394. void ReturnValue<T>::SetNull() {
  5395. TYPE_CHECK(T, Primitive);
  5396. typedef internal::Internals I;
  5397. *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
  5398. }
  5399. template<typename T>
  5400. void ReturnValue<T>::SetUndefined() {
  5401. TYPE_CHECK(T, Primitive);
  5402. typedef internal::Internals I;
  5403. *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
  5404. }
  5405. template<typename T>
  5406. void ReturnValue<T>::SetEmptyString() {
  5407. TYPE_CHECK(T, String);
  5408. typedef internal::Internals I;
  5409. *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
  5410. }
  5411. template<typename T>
  5412. Isolate* ReturnValue<T>::GetIsolate() {
  5413. // Isolate is always the pointer below the default value on the stack.
  5414. return *reinterpret_cast<Isolate**>(&value_[-2]);
  5415. }
  5416. template<typename T>
  5417. template<typename S>
  5418. void ReturnValue<T>::Set(S* whatever) {
  5419. // Uncompilable to prevent inadvertent misuse.
  5420. TYPE_CHECK(S*, Primitive);
  5421. }
  5422. template<typename T>
  5423. internal::Object* ReturnValue<T>::GetDefaultValue() {
  5424. // Default value is always the pointer below value_ on the stack.
  5425. return value_[-1];
  5426. }
  5427. template<typename T>
  5428. FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Object** implicit_args,
  5429. internal::Object** values,
  5430. int length,
  5431. bool is_construct_call)
  5432. : implicit_args_(implicit_args),
  5433. values_(values),
  5434. length_(length),
  5435. is_construct_call_(is_construct_call) { }
  5436. template<typename T>
  5437. Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
  5438. if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
  5439. return Local<Value>(reinterpret_cast<Value*>(values_ - i));
  5440. }
  5441. template<typename T>
  5442. Local<Function> FunctionCallbackInfo<T>::Callee() const {
  5443. return Local<Function>(reinterpret_cast<Function*>(
  5444. &implicit_args_[kCalleeIndex]));
  5445. }
  5446. template<typename T>
  5447. Local<Object> FunctionCallbackInfo<T>::This() const {
  5448. return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
  5449. }
  5450. template<typename T>
  5451. Local<Object> FunctionCallbackInfo<T>::Holder() const {
  5452. return Local<Object>(reinterpret_cast<Object*>(
  5453. &implicit_args_[kHolderIndex]));
  5454. }
  5455. template<typename T>
  5456. Local<Value> FunctionCallbackInfo<T>::Data() const {
  5457. return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
  5458. }
  5459. template<typename T>
  5460. Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
  5461. return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
  5462. }
  5463. template<typename T>
  5464. ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
  5465. return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
  5466. }
  5467. template<typename T>
  5468. bool FunctionCallbackInfo<T>::IsConstructCall() const {
  5469. return is_construct_call_;
  5470. }
  5471. template<typename T>
  5472. int FunctionCallbackInfo<T>::Length() const {
  5473. return length_;
  5474. }
  5475. Handle<Value> ScriptOrigin::ResourceName() const {
  5476. return resource_name_;
  5477. }
  5478. Handle<Integer> ScriptOrigin::ResourceLineOffset() const {
  5479. return resource_line_offset_;
  5480. }
  5481. Handle<Integer> ScriptOrigin::ResourceColumnOffset() const {
  5482. return resource_column_offset_;
  5483. }
  5484. Handle<Boolean> ScriptOrigin::ResourceIsSharedCrossOrigin() const {
  5485. return resource_is_shared_cross_origin_;
  5486. }
  5487. Handle<Integer> ScriptOrigin::ScriptID() const {
  5488. return script_id_;
  5489. }
  5490. ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
  5491. CachedData* data)
  5492. : source_string(string),
  5493. resource_name(origin.ResourceName()),
  5494. resource_line_offset(origin.ResourceLineOffset()),
  5495. resource_column_offset(origin.ResourceColumnOffset()),
  5496. resource_is_shared_cross_origin(origin.ResourceIsSharedCrossOrigin()),
  5497. cached_data(data) {}
  5498. ScriptCompiler::Source::Source(Local<String> string,
  5499. CachedData* data)
  5500. : source_string(string), cached_data(data) {}
  5501. ScriptCompiler::Source::~Source() {
  5502. delete cached_data;
  5503. }
  5504. const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
  5505. const {
  5506. return cached_data;
  5507. }
  5508. Handle<Boolean> Boolean::New(Isolate* isolate, bool value) {
  5509. return value ? True(isolate) : False(isolate);
  5510. }
  5511. void Template::Set(Isolate* isolate, const char* name, v8::Handle<Data> value) {
  5512. Set(v8::String::NewFromUtf8(isolate, name), value);
  5513. }
  5514. Local<Value> Object::GetInternalField(int index) {
  5515. #ifndef V8_ENABLE_CHECKS
  5516. typedef internal::Object O;
  5517. typedef internal::HeapObject HO;
  5518. typedef internal::Internals I;
  5519. O* obj = *reinterpret_cast<O**>(this);
  5520. // Fast path: If the object is a plain JSObject, which is the common case, we
  5521. // know where to find the internal fields and can return the value directly.
  5522. if (I::GetInstanceType(obj) == I::kJSObjectType) {
  5523. int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
  5524. O* value = I::ReadField<O*>(obj, offset);
  5525. O** result = HandleScope::CreateHandle(reinterpret_cast<HO*>(obj), value);
  5526. return Local<Value>(reinterpret_cast<Value*>(result));
  5527. }
  5528. #endif
  5529. return SlowGetInternalField(index);
  5530. }
  5531. void* Object::GetAlignedPointerFromInternalField(int index) {
  5532. #ifndef V8_ENABLE_CHECKS
  5533. typedef internal::Object O;
  5534. typedef internal::Internals I;
  5535. O* obj = *reinterpret_cast<O**>(this);
  5536. // Fast path: If the object is a plain JSObject, which is the common case, we
  5537. // know where to find the internal fields and can return the value directly.
  5538. if (V8_LIKELY(I::GetInstanceType(obj) == I::kJSObjectType)) {
  5539. int offset = I::kJSObjectHeaderSize + (internal::kApiPointerSize * index);
  5540. return I::ReadField<void*>(obj, offset);
  5541. }
  5542. #endif
  5543. return SlowGetAlignedPointerFromInternalField(index);
  5544. }
  5545. String* String::Cast(v8::Value* value) {
  5546. #ifdef V8_ENABLE_CHECKS
  5547. CheckCast(value);
  5548. #endif
  5549. return static_cast<String*>(value);
  5550. }
  5551. Local<String> String::Empty(Isolate* isolate) {
  5552. typedef internal::Object* S;
  5553. typedef internal::Internals I;
  5554. I::CheckInitialized(isolate);
  5555. S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
  5556. return Local<String>(reinterpret_cast<String*>(slot));
  5557. }
  5558. String::ExternalStringResource* String::GetExternalStringResource() const {
  5559. typedef internal::Object O;
  5560. typedef internal::Internals I;
  5561. O* obj = *reinterpret_cast<O* const*>(this);
  5562. String::ExternalStringResource* result;
  5563. if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
  5564. void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
  5565. result = reinterpret_cast<String::ExternalStringResource*>(value);
  5566. } else {
  5567. result = NULL;
  5568. }
  5569. #ifdef V8_ENABLE_CHECKS
  5570. VerifyExternalStringResource(result);
  5571. #endif
  5572. return result;
  5573. }
  5574. String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
  5575. String::Encoding* encoding_out) const {
  5576. typedef internal::Object O;
  5577. typedef internal::Internals I;
  5578. O* obj = *reinterpret_cast<O* const*>(this);
  5579. int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
  5580. *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
  5581. ExternalStringResourceBase* resource = NULL;
  5582. if (type == I::kExternalOneByteRepresentationTag ||
  5583. type == I::kExternalTwoByteRepresentationTag) {
  5584. void* value = I::ReadField<void*>(obj, I::kStringResourceOffset);
  5585. resource = static_cast<ExternalStringResourceBase*>(value);
  5586. }
  5587. #ifdef V8_ENABLE_CHECKS
  5588. VerifyExternalStringResourceBase(resource, *encoding_out);
  5589. #endif
  5590. return resource;
  5591. }
  5592. bool Value::IsUndefined() const {
  5593. #ifdef V8_ENABLE_CHECKS
  5594. return FullIsUndefined();
  5595. #else
  5596. return QuickIsUndefined();
  5597. #endif
  5598. }
  5599. bool Value::QuickIsUndefined() const {
  5600. typedef internal::Object O;
  5601. typedef internal::Internals I;
  5602. O* obj = *reinterpret_cast<O* const*>(this);
  5603. if (!I::HasHeapObjectTag(obj)) return false;
  5604. if (I::GetInstanceType(obj) != I::kOddballType) return false;
  5605. return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
  5606. }
  5607. bool Value::IsNull() const {
  5608. #ifdef V8_ENABLE_CHECKS
  5609. return FullIsNull();
  5610. #else
  5611. return QuickIsNull();
  5612. #endif
  5613. }
  5614. bool Value::QuickIsNull() const {
  5615. typedef internal::Object O;
  5616. typedef internal::Internals I;
  5617. O* obj = *reinterpret_cast<O* const*>(this);
  5618. if (!I::HasHeapObjectTag(obj)) return false;
  5619. if (I::GetInstanceType(obj) != I::kOddballType) return false;
  5620. return (I::GetOddballKind(obj) == I::kNullOddballKind);
  5621. }
  5622. bool Value::IsString() const {
  5623. #ifdef V8_ENABLE_CHECKS
  5624. return FullIsString();
  5625. #else
  5626. return QuickIsString();
  5627. #endif
  5628. }
  5629. bool Value::QuickIsString() const {
  5630. typedef internal::Object O;
  5631. typedef internal::Internals I;
  5632. O* obj = *reinterpret_cast<O* const*>(this);
  5633. if (!I::HasHeapObjectTag(obj)) return false;
  5634. return (I::GetInstanceType(obj) < I::kFirstNonstringType);
  5635. }
  5636. template <class T> Value* Value::Cast(T* value) {
  5637. return static_cast<Value*>(value);
  5638. }
  5639. Name* Name::Cast(v8::Value* value) {
  5640. #ifdef V8_ENABLE_CHECKS
  5641. CheckCast(value);
  5642. #endif
  5643. return static_cast<Name*>(value);
  5644. }
  5645. Symbol* Symbol::Cast(v8::Value* value) {
  5646. #ifdef V8_ENABLE_CHECKS
  5647. CheckCast(value);
  5648. #endif
  5649. return static_cast<Symbol*>(value);
  5650. }
  5651. Number* Number::Cast(v8::Value* value) {
  5652. #ifdef V8_ENABLE_CHECKS
  5653. CheckCast(value);
  5654. #endif
  5655. return static_cast<Number*>(value);
  5656. }
  5657. Integer* Integer::Cast(v8::Value* value) {
  5658. #ifdef V8_ENABLE_CHECKS
  5659. CheckCast(value);
  5660. #endif
  5661. return static_cast<Integer*>(value);
  5662. }
  5663. Date* Date::Cast(v8::Value* value) {
  5664. #ifdef V8_ENABLE_CHECKS
  5665. CheckCast(value);
  5666. #endif
  5667. return static_cast<Date*>(value);
  5668. }
  5669. StringObject* StringObject::Cast(v8::Value* value) {
  5670. #ifdef V8_ENABLE_CHECKS
  5671. CheckCast(value);
  5672. #endif
  5673. return static_cast<StringObject*>(value);
  5674. }
  5675. SymbolObject* SymbolObject::Cast(v8::Value* value) {
  5676. #ifdef V8_ENABLE_CHECKS
  5677. CheckCast(value);
  5678. #endif
  5679. return static_cast<SymbolObject*>(value);
  5680. }
  5681. NumberObject* NumberObject::Cast(v8::Value* value) {
  5682. #ifdef V8_ENABLE_CHECKS
  5683. CheckCast(value);
  5684. #endif
  5685. return static_cast<NumberObject*>(value);
  5686. }
  5687. BooleanObject* BooleanObject::Cast(v8::Value* value) {
  5688. #ifdef V8_ENABLE_CHECKS
  5689. CheckCast(value);
  5690. #endif
  5691. return static_cast<BooleanObject*>(value);
  5692. }
  5693. RegExp* RegExp::Cast(v8::Value* value) {
  5694. #ifdef V8_ENABLE_CHECKS
  5695. CheckCast(value);
  5696. #endif
  5697. return static_cast<RegExp*>(value);
  5698. }
  5699. Object* Object::Cast(v8::Value* value) {
  5700. #ifdef V8_ENABLE_CHECKS
  5701. CheckCast(value);
  5702. #endif
  5703. return static_cast<Object*>(value);
  5704. }
  5705. Array* Array::Cast(v8::Value* value) {
  5706. #ifdef V8_ENABLE_CHECKS
  5707. CheckCast(value);
  5708. #endif
  5709. return static_cast<Array*>(value);
  5710. }
  5711. Promise* Promise::Cast(v8::Value* value) {
  5712. #ifdef V8_ENABLE_CHECKS
  5713. CheckCast(value);
  5714. #endif
  5715. return static_cast<Promise*>(value);
  5716. }
  5717. Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
  5718. #ifdef V8_ENABLE_CHECKS
  5719. CheckCast(value);
  5720. #endif
  5721. return static_cast<Promise::Resolver*>(value);
  5722. }
  5723. ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
  5724. #ifdef V8_ENABLE_CHECKS
  5725. CheckCast(value);
  5726. #endif
  5727. return static_cast<ArrayBuffer*>(value);
  5728. }
  5729. ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
  5730. #ifdef V8_ENABLE_CHECKS
  5731. CheckCast(value);
  5732. #endif
  5733. return static_cast<ArrayBufferView*>(value);
  5734. }
  5735. TypedArray* TypedArray::Cast(v8::Value* value) {
  5736. #ifdef V8_ENABLE_CHECKS
  5737. CheckCast(value);
  5738. #endif
  5739. return static_cast<TypedArray*>(value);
  5740. }
  5741. Uint8Array* Uint8Array::Cast(v8::Value* value) {
  5742. #ifdef V8_ENABLE_CHECKS
  5743. CheckCast(value);
  5744. #endif
  5745. return static_cast<Uint8Array*>(value);
  5746. }
  5747. Int8Array* Int8Array::Cast(v8::Value* value) {
  5748. #ifdef V8_ENABLE_CHECKS
  5749. CheckCast(value);
  5750. #endif
  5751. return static_cast<Int8Array*>(value);
  5752. }
  5753. Uint16Array* Uint16Array::Cast(v8::Value* value) {
  5754. #ifdef V8_ENABLE_CHECKS
  5755. CheckCast(value);
  5756. #endif
  5757. return static_cast<Uint16Array*>(value);
  5758. }
  5759. Int16Array* Int16Array::Cast(v8::Value* value) {
  5760. #ifdef V8_ENABLE_CHECKS
  5761. CheckCast(value);
  5762. #endif
  5763. return static_cast<Int16Array*>(value);
  5764. }
  5765. Uint32Array* Uint32Array::Cast(v8::Value* value) {
  5766. #ifdef V8_ENABLE_CHECKS
  5767. CheckCast(value);
  5768. #endif
  5769. return static_cast<Uint32Array*>(value);
  5770. }
  5771. Int32Array* Int32Array::Cast(v8::Value* value) {
  5772. #ifdef V8_ENABLE_CHECKS
  5773. CheckCast(value);
  5774. #endif
  5775. return static_cast<Int32Array*>(value);
  5776. }
  5777. Float32Array* Float32Array::Cast(v8::Value* value) {
  5778. #ifdef V8_ENABLE_CHECKS
  5779. CheckCast(value);
  5780. #endif
  5781. return static_cast<Float32Array*>(value);
  5782. }
  5783. Float64Array* Float64Array::Cast(v8::Value* value) {
  5784. #ifdef V8_ENABLE_CHECKS
  5785. CheckCast(value);
  5786. #endif
  5787. return static_cast<Float64Array*>(value);
  5788. }
  5789. Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
  5790. #ifdef V8_ENABLE_CHECKS
  5791. CheckCast(value);
  5792. #endif
  5793. return static_cast<Uint8ClampedArray*>(value);
  5794. }
  5795. DataView* DataView::Cast(v8::Value* value) {
  5796. #ifdef V8_ENABLE_CHECKS
  5797. CheckCast(value);
  5798. #endif
  5799. return static_cast<DataView*>(value);
  5800. }
  5801. Function* Function::Cast(v8::Value* value) {
  5802. #ifdef V8_ENABLE_CHECKS
  5803. CheckCast(value);
  5804. #endif
  5805. return static_cast<Function*>(value);
  5806. }
  5807. External* External::Cast(v8::Value* value) {
  5808. #ifdef V8_ENABLE_CHECKS
  5809. CheckCast(value);
  5810. #endif
  5811. return static_cast<External*>(value);
  5812. }
  5813. template<typename T>
  5814. Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
  5815. return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
  5816. }
  5817. template<typename T>
  5818. Local<Value> PropertyCallbackInfo<T>::Data() const {
  5819. return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
  5820. }
  5821. template<typename T>
  5822. Local<Object> PropertyCallbackInfo<T>::This() const {
  5823. return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
  5824. }
  5825. template<typename T>
  5826. Local<Object> PropertyCallbackInfo<T>::Holder() const {
  5827. return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
  5828. }
  5829. template<typename T>
  5830. ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
  5831. return ReturnValue<T>(&args_[kReturnValueIndex]);
  5832. }
  5833. Handle<Primitive> Undefined(Isolate* isolate) {
  5834. typedef internal::Object* S;
  5835. typedef internal::Internals I;
  5836. I::CheckInitialized(isolate);
  5837. S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
  5838. return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
  5839. }
  5840. Handle<Primitive> Null(Isolate* isolate) {
  5841. typedef internal::Object* S;
  5842. typedef internal::Internals I;
  5843. I::CheckInitialized(isolate);
  5844. S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
  5845. return Handle<Primitive>(reinterpret_cast<Primitive*>(slot));
  5846. }
  5847. Handle<Boolean> True(Isolate* isolate) {
  5848. typedef internal::Object* S;
  5849. typedef internal::Internals I;
  5850. I::CheckInitialized(isolate);
  5851. S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
  5852. return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
  5853. }
  5854. Handle<Boolean> False(Isolate* isolate) {
  5855. typedef internal::Object* S;
  5856. typedef internal::Internals I;
  5857. I::CheckInitialized(isolate);
  5858. S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
  5859. return Handle<Boolean>(reinterpret_cast<Boolean*>(slot));
  5860. }
  5861. void Isolate::SetData(uint32_t slot, void* data) {
  5862. typedef internal::Internals I;
  5863. I::SetEmbedderData(this, slot, data);
  5864. }
  5865. void* Isolate::GetData(uint32_t slot) {
  5866. typedef internal::Internals I;
  5867. return I::GetEmbedderData(this, slot);
  5868. }
  5869. uint32_t Isolate::GetNumberOfDataSlots() {
  5870. typedef internal::Internals I;
  5871. return I::kNumIsolateDataSlots;
  5872. }
  5873. int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
  5874. int64_t change_in_bytes) {
  5875. typedef internal::Internals I;
  5876. int64_t* amount_of_external_allocated_memory =
  5877. reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
  5878. I::kAmountOfExternalAllocatedMemoryOffset);
  5879. int64_t* amount_of_external_allocated_memory_at_last_global_gc =
  5880. reinterpret_cast<int64_t*>(
  5881. reinterpret_cast<uint8_t*>(this) +
  5882. I::kAmountOfExternalAllocatedMemoryAtLastGlobalGCOffset);
  5883. int64_t amount = *amount_of_external_allocated_memory + change_in_bytes;
  5884. if (change_in_bytes > 0 &&
  5885. amount - *amount_of_external_allocated_memory_at_last_global_gc >
  5886. I::kExternalAllocationLimit) {
  5887. CollectAllGarbage("external memory allocation limit reached.");
  5888. } else {
  5889. *amount_of_external_allocated_memory = amount;
  5890. }
  5891. return *amount_of_external_allocated_memory;
  5892. }
  5893. template<typename T>
  5894. void Isolate::SetObjectGroupId(const Persistent<T>& object,
  5895. UniqueId id) {
  5896. TYPE_CHECK(Value, T);
  5897. SetObjectGroupId(reinterpret_cast<v8::internal::Object**>(object.val_), id);
  5898. }
  5899. template<typename T>
  5900. void Isolate::SetReferenceFromGroup(UniqueId id,
  5901. const Persistent<T>& object) {
  5902. TYPE_CHECK(Value, T);
  5903. SetReferenceFromGroup(id,
  5904. reinterpret_cast<v8::internal::Object**>(object.val_));
  5905. }
  5906. template<typename T, typename S>
  5907. void Isolate::SetReference(const Persistent<T>& parent,
  5908. const Persistent<S>& child) {
  5909. TYPE_CHECK(Object, T);
  5910. TYPE_CHECK(Value, S);
  5911. SetReference(reinterpret_cast<v8::internal::Object**>(parent.val_),
  5912. reinterpret_cast<v8::internal::Object**>(child.val_));
  5913. }
  5914. Local<Value> Context::GetEmbedderData(int index) {
  5915. #ifndef V8_ENABLE_CHECKS
  5916. typedef internal::Object O;
  5917. typedef internal::HeapObject HO;
  5918. typedef internal::Internals I;
  5919. HO* context = *reinterpret_cast<HO**>(this);
  5920. O** result =
  5921. HandleScope::CreateHandle(context, I::ReadEmbedderData<O*>(this, index));
  5922. return Local<Value>(reinterpret_cast<Value*>(result));
  5923. #else
  5924. return SlowGetEmbedderData(index);
  5925. #endif
  5926. }
  5927. void* Context::GetAlignedPointerFromEmbedderData(int index) {
  5928. #ifndef V8_ENABLE_CHECKS
  5929. typedef internal::Internals I;
  5930. return I::ReadEmbedderData<void*>(this, index);
  5931. #else
  5932. return SlowGetAlignedPointerFromEmbedderData(index);
  5933. #endif
  5934. }
  5935. /**
  5936. * \example shell.cc
  5937. * A simple shell that takes a list of expressions on the
  5938. * command-line and executes them.
  5939. */
  5940. /**
  5941. * \example process.cc
  5942. */
  5943. } // namespace v8
  5944. #undef TYPE_CHECK
  5945. #endif // V8_H_