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