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