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