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