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