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 9542695 : V8_INLINE Local() : val_(nullptr) {}
186 : template <class S>
187 : V8_INLINE Local(Local<S> that)
188 20870390 : : 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 77941133 : V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
201 :
202 : /**
203 : * Sets the handle to be empty. IsEmpty() will then return true.
204 : */
205 112856 : V8_INLINE void Clear() { val_ = nullptr; }
206 :
207 68427370 : V8_INLINE T* operator->() const { return val_; }
208 :
209 22400200 : 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 504724 : internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
220 375145 : internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
221 507420 : if (a == nullptr) return b == nullptr;
222 506736 : if (b == nullptr) return false;
223 506736 : 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 364894 : 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 60 : 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 3139313 : V8_INLINE MaybeLocal() : val_(nullptr) {}
342 : template <class S>
343 : V8_INLINE MaybeLocal(Local<S> that)
344 73812 : : val_(reinterpret_cast<T*>(*that)) {
345 : TYPE_CHECK(T, S);
346 : }
347 :
348 211242 : 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 19131426 : 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 5775264 : : isolate_(isolate), parameter_(parameter), callback_(callback) {
412 28876320 : for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
413 11550528 : embedder_fields_[i] = embedder_fields[i];
414 : }
415 : }
416 :
417 5395993 : V8_INLINE Isolate* GetIsolate() const { return isolate_; }
418 5754297 : 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 2698271 : 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 7337233 : 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 3378536 : 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 213254 : V8_INLINE ~Persistent() {
719 : if (M::kResetInDestructor) this->Reset();
720 227764 : }
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 3215193 : 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 6851279 : 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 7725167 : 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 6851290 : 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 1336207 : : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1157 1338052 : (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1158 279609 : (is_module ? kIsModule : 0)) {}
1159 : V8_INLINE ScriptOriginOptions(int flags)
1160 4515407 : : flags_(flags &
1161 0 : (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1162 :
1163 : bool IsSharedCrossOrigin() const {
1164 1939300 : return (flags_ & kIsSharedCrossOrigin) != 0;
1165 : }
1166 1335195 : bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1167 6421 : bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1168 2947580 : bool IsModule() const { return (flags_ & kIsModule) != 0; }
1169 :
1170 1540494 : 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 38334 : 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 13897 : class V8_EXPORT ExternalSourceStream {
1481 : public:
1482 13897 : 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 13402 : 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 13402 : : 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 65571 : 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 1926 : 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_DEPRECATED("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_DEPRECATED("Use maybe version",
2542 : Local<Number> ToNumber(Isolate* isolate) const);
2543 : V8_DEPRECATED("Use maybe version",
2544 : Local<String> ToString(Isolate* isolate) const);
2545 : V8_DEPRECATED("Use maybe version",
2546 : Local<Object> ToObject(Isolate* isolate) const);
2547 : V8_DEPRECATED("Use maybe version",
2548 : Local<Integer> ToInteger(Isolate* isolate) const);
2549 : V8_DEPRECATED("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 629217 : 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 24848 : virtual bool IsCacheable() const { return true; }
2766 :
2767 : protected:
2768 636212 : 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 83196 : 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 3790 : virtual void Lock() const {}
2790 :
2791 : /**
2792 : * Unlocks the string.
2793 : */
2794 3786 : 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 145138 : ~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 72564 : 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 1113296 : ~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 563648 : 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_DEPRECATED(
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_DEPRECATED(
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 2686945 : 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 738 : 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 104 : 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 211059 : class V8_EXPORT Allocator { // NOLINT
4682 : public:
4683 182136 : 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 :
5169 : void* AllocationBase() const { return allocation_base_; }
5170 : size_t AllocationLength() const { return allocation_length_; }
5171 : Allocator::AllocationMode AllocationMode() const {
5172 : return allocation_mode_;
5173 : }
5174 :
5175 : void* Data() const { return data_; }
5176 : size_t ByteLength() const { return byte_length_; }
5177 : DeleterCallback Deleter() const { return deleter_; }
5178 : void* DeleterData() const { return deleter_data_; }
5179 :
5180 : private:
5181 : Contents(void* data, size_t byte_length, void* allocation_base,
5182 : size_t allocation_length,
5183 : Allocator::AllocationMode allocation_mode, DeleterCallback deleter,
5184 : void* deleter_data);
5185 :
5186 : void* data_;
5187 : size_t byte_length_;
5188 : void* allocation_base_;
5189 : size_t allocation_length_;
5190 : Allocator::AllocationMode allocation_mode_;
5191 : DeleterCallback deleter_;
5192 : void* deleter_data_;
5193 :
5194 : friend class SharedArrayBuffer;
5195 : };
5196 :
5197 : /**
5198 : * Data length in bytes.
5199 : */
5200 : size_t ByteLength() const;
5201 :
5202 : /**
5203 : * Create a new SharedArrayBuffer. Allocate |byte_length| bytes.
5204 : * Allocated memory will be owned by a created SharedArrayBuffer and
5205 : * will be deallocated when it is garbage-collected,
5206 : * unless the object is externalized.
5207 : */
5208 : static Local<SharedArrayBuffer> New(Isolate* isolate, size_t byte_length);
5209 :
5210 : /**
5211 : * Create a new SharedArrayBuffer over an existing memory block. The created
5212 : * array buffer is immediately in externalized state unless otherwise
5213 : * specified. The memory block will not be reclaimed when a created
5214 : * SharedArrayBuffer is garbage-collected.
5215 : */
5216 : static Local<SharedArrayBuffer> New(
5217 : Isolate* isolate, void* data, size_t byte_length,
5218 : ArrayBufferCreationMode mode = ArrayBufferCreationMode::kExternalized);
5219 :
5220 : /**
5221 : * Create a new SharedArrayBuffer over an existing memory block. Propagate
5222 : * flags to indicate whether the underlying buffer can be grown.
5223 : */
5224 : V8_DEPRECATED("Use New method with data, and byte_length instead.",
5225 : static Local<SharedArrayBuffer> New(
5226 : Isolate* isolate, const SharedArrayBuffer::Contents&,
5227 : ArrayBufferCreationMode mode =
5228 : ArrayBufferCreationMode::kExternalized));
5229 :
5230 : /**
5231 : * Returns true if SharedArrayBuffer is externalized, that is, does not
5232 : * own its memory block.
5233 : */
5234 : bool IsExternal() const;
5235 :
5236 : /**
5237 : * Make this SharedArrayBuffer external. The pointer to underlying memory
5238 : * block and byte length are returned as |Contents| structure. After
5239 : * SharedArrayBuffer had been externalized, it does no longer own the memory
5240 : * block. The caller should take steps to free memory when it is no longer
5241 : * needed.
5242 : *
5243 : * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5244 : * by the allocator specified in
5245 : * v8::Isolate::CreateParams::array_buffer_allocator.
5246 : *
5247 : */
5248 : Contents Externalize();
5249 :
5250 : /**
5251 : * Get a pointer to the ArrayBuffer's underlying memory block without
5252 : * externalizing it. If the ArrayBuffer is not externalized, this pointer
5253 : * will become invalid as soon as the ArrayBuffer became garbage collected.
5254 : *
5255 : * The embedder should make sure to hold a strong reference to the
5256 : * ArrayBuffer while accessing this pointer.
5257 : *
5258 : * The memory block is guaranteed to be allocated with |Allocator::Allocate|
5259 : * by the allocator specified in
5260 : * v8::Isolate::CreateParams::array_buffer_allocator.
5261 : */
5262 : Contents GetContents();
5263 :
5264 : V8_INLINE static SharedArrayBuffer* Cast(Value* obj);
5265 :
5266 : static const int kInternalFieldCount = V8_ARRAY_BUFFER_INTERNAL_FIELD_COUNT;
5267 :
5268 : private:
5269 : SharedArrayBuffer();
5270 : static void CheckCast(Value* obj);
5271 : };
5272 :
5273 :
5274 : /**
5275 : * An instance of the built-in Date constructor (ECMA-262, 15.9).
5276 : */
5277 : class V8_EXPORT Date : public Object {
5278 : public:
5279 : static V8_WARN_UNUSED_RESULT MaybeLocal<Value> New(Local<Context> context,
5280 : double time);
5281 :
5282 : /**
5283 : * A specialization of Value::NumberValue that is more efficient
5284 : * because we know the structure of this object.
5285 : */
5286 : double ValueOf() const;
5287 :
5288 : V8_INLINE static Date* Cast(Value* obj);
5289 :
5290 : /**
5291 : * Time zone redetection indicator for
5292 : * DateTimeConfigurationChangeNotification.
5293 : *
5294 : * kSkip indicates V8 that the notification should not trigger redetecting
5295 : * host time zone. kRedetect indicates V8 that host time zone should be
5296 : * redetected, and used to set the default time zone.
5297 : *
5298 : * The host time zone detection may require file system access or similar
5299 : * operations unlikely to be available inside a sandbox. If v8 is run inside a
5300 : * sandbox, the host time zone has to be detected outside the sandbox before
5301 : * calling DateTimeConfigurationChangeNotification function.
5302 : */
5303 : enum class TimeZoneDetection { kSkip, kRedetect };
5304 :
5305 : /**
5306 : * Notification that the embedder has changed the time zone,
5307 : * daylight savings time, or other date / time configuration
5308 : * parameters. V8 keeps a cache of various values used for
5309 : * date / time computation. This notification will reset
5310 : * those cached values for the current context so that date /
5311 : * time configuration changes would be reflected in the Date
5312 : * object.
5313 : *
5314 : * This API should not be called more than needed as it will
5315 : * negatively impact the performance of date operations.
5316 : */
5317 : V8_DEPRECATED("Use Isolate::DateTimeConfigurationChangeNotification",
5318 : static void DateTimeConfigurationChangeNotification(
5319 : Isolate* isolate, TimeZoneDetection time_zone_detection =
5320 : TimeZoneDetection::kSkip));
5321 :
5322 : private:
5323 : static void CheckCast(Value* obj);
5324 : };
5325 :
5326 :
5327 : /**
5328 : * A Number object (ECMA-262, 4.3.21).
5329 : */
5330 : class V8_EXPORT NumberObject : public Object {
5331 : public:
5332 : static Local<Value> New(Isolate* isolate, double value);
5333 :
5334 : double ValueOf() const;
5335 :
5336 : V8_INLINE static NumberObject* Cast(Value* obj);
5337 :
5338 : private:
5339 : static void CheckCast(Value* obj);
5340 : };
5341 :
5342 : /**
5343 : * A BigInt object (https://tc39.github.io/proposal-bigint)
5344 : */
5345 : class V8_EXPORT BigIntObject : public Object {
5346 : public:
5347 : static Local<Value> New(Isolate* isolate, int64_t value);
5348 :
5349 : Local<BigInt> ValueOf() const;
5350 :
5351 : V8_INLINE static BigIntObject* Cast(Value* obj);
5352 :
5353 : private:
5354 : static void CheckCast(Value* obj);
5355 : };
5356 :
5357 : /**
5358 : * A Boolean object (ECMA-262, 4.3.15).
5359 : */
5360 : class V8_EXPORT BooleanObject : public Object {
5361 : public:
5362 : static Local<Value> New(Isolate* isolate, bool value);
5363 :
5364 : bool ValueOf() const;
5365 :
5366 : V8_INLINE static BooleanObject* Cast(Value* obj);
5367 :
5368 : private:
5369 : static void CheckCast(Value* obj);
5370 : };
5371 :
5372 :
5373 : /**
5374 : * A String object (ECMA-262, 4.3.18).
5375 : */
5376 : class V8_EXPORT StringObject : public Object {
5377 : public:
5378 : static Local<Value> New(Isolate* isolate, Local<String> value);
5379 :
5380 : Local<String> ValueOf() const;
5381 :
5382 : V8_INLINE static StringObject* Cast(Value* obj);
5383 :
5384 : private:
5385 : static void CheckCast(Value* obj);
5386 : };
5387 :
5388 :
5389 : /**
5390 : * A Symbol object (ECMA-262 edition 6).
5391 : */
5392 : class V8_EXPORT SymbolObject : public Object {
5393 : public:
5394 : static Local<Value> New(Isolate* isolate, Local<Symbol> value);
5395 :
5396 : Local<Symbol> ValueOf() const;
5397 :
5398 : V8_INLINE static SymbolObject* Cast(Value* obj);
5399 :
5400 : private:
5401 : static void CheckCast(Value* obj);
5402 : };
5403 :
5404 :
5405 : /**
5406 : * An instance of the built-in RegExp constructor (ECMA-262, 15.10).
5407 : */
5408 : class V8_EXPORT RegExp : public Object {
5409 : public:
5410 : /**
5411 : * Regular expression flag bits. They can be or'ed to enable a set
5412 : * of flags.
5413 : */
5414 : enum Flags {
5415 : kNone = 0,
5416 : kGlobal = 1 << 0,
5417 : kIgnoreCase = 1 << 1,
5418 : kMultiline = 1 << 2,
5419 : kSticky = 1 << 3,
5420 : kUnicode = 1 << 4,
5421 : kDotAll = 1 << 5,
5422 : };
5423 :
5424 : /**
5425 : * Creates a regular expression from the given pattern string and
5426 : * the flags bit field. May throw a JavaScript exception as
5427 : * described in ECMA-262, 15.10.4.1.
5428 : *
5429 : * For example,
5430 : * RegExp::New(v8::String::New("foo"),
5431 : * static_cast<RegExp::Flags>(kGlobal | kMultiline))
5432 : * is equivalent to evaluating "/foo/gm".
5433 : */
5434 : static V8_WARN_UNUSED_RESULT MaybeLocal<RegExp> New(Local<Context> context,
5435 : Local<String> pattern,
5436 : Flags flags);
5437 :
5438 : /**
5439 : * Returns the value of the source property: a string representing
5440 : * the regular expression.
5441 : */
5442 : Local<String> GetSource() const;
5443 :
5444 : /**
5445 : * Returns the flags bit field.
5446 : */
5447 : Flags GetFlags() const;
5448 :
5449 : V8_INLINE static RegExp* Cast(Value* obj);
5450 :
5451 : private:
5452 : static void CheckCast(Value* obj);
5453 : };
5454 :
5455 :
5456 : /**
5457 : * A JavaScript value that wraps a C++ void*. This type of value is mainly used
5458 : * to associate C++ data structures with JavaScript objects.
5459 : */
5460 : class V8_EXPORT External : public Value {
5461 : public:
5462 : static Local<External> New(Isolate* isolate, void* value);
5463 : V8_INLINE static External* Cast(Value* obj);
5464 : void* Value() const;
5465 : private:
5466 : static void CheckCast(v8::Value* obj);
5467 : };
5468 :
5469 : #define V8_INTRINSICS_LIST(F) \
5470 : F(ArrayProto_entries, array_entries_iterator) \
5471 : F(ArrayProto_forEach, array_for_each_iterator) \
5472 : F(ArrayProto_keys, array_keys_iterator) \
5473 : F(ArrayProto_values, array_values_iterator) \
5474 : F(ErrorPrototype, initial_error_prototype) \
5475 : F(IteratorPrototype, initial_iterator_prototype)
5476 :
5477 : enum Intrinsic {
5478 : #define V8_DECL_INTRINSIC(name, iname) k##name,
5479 : V8_INTRINSICS_LIST(V8_DECL_INTRINSIC)
5480 : #undef V8_DECL_INTRINSIC
5481 : };
5482 :
5483 :
5484 : // --- Templates ---
5485 :
5486 :
5487 : /**
5488 : * The superclass of object and function templates.
5489 : */
5490 : class V8_EXPORT Template : public Data {
5491 : public:
5492 : /**
5493 : * Adds a property to each instance created by this template.
5494 : *
5495 : * The property must be defined either as a primitive value, or a template.
5496 : */
5497 : void Set(Local<Name> name, Local<Data> value,
5498 : PropertyAttribute attributes = None);
5499 : void SetPrivate(Local<Private> name, Local<Data> value,
5500 : PropertyAttribute attributes = None);
5501 : V8_INLINE void Set(Isolate* isolate, const char* name, Local<Data> value);
5502 :
5503 : void SetAccessorProperty(
5504 : Local<Name> name,
5505 : Local<FunctionTemplate> getter = Local<FunctionTemplate>(),
5506 : Local<FunctionTemplate> setter = Local<FunctionTemplate>(),
5507 : PropertyAttribute attribute = None,
5508 : AccessControl settings = DEFAULT);
5509 :
5510 : /**
5511 : * Whenever the property with the given name is accessed on objects
5512 : * created from this Template the getter and setter callbacks
5513 : * are called instead of getting and setting the property directly
5514 : * on the JavaScript object.
5515 : *
5516 : * \param name The name of the property for which an accessor is added.
5517 : * \param getter The callback to invoke when getting the property.
5518 : * \param setter The callback to invoke when setting the property.
5519 : * \param data A piece of data that will be passed to the getter and setter
5520 : * callbacks whenever they are invoked.
5521 : * \param settings Access control settings for the accessor. This is a bit
5522 : * field consisting of one of more of
5523 : * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
5524 : * The default is to not allow cross-context access.
5525 : * ALL_CAN_READ means that all cross-context reads are allowed.
5526 : * ALL_CAN_WRITE means that all cross-context writes are allowed.
5527 : * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
5528 : * cross-context access.
5529 : * \param attribute The attributes of the property for which an accessor
5530 : * is added.
5531 : * \param signature The signature describes valid receivers for the accessor
5532 : * and is used to perform implicit instance checks against them. If the
5533 : * receiver is incompatible (i.e. is not an instance of the constructor as
5534 : * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
5535 : * thrown and no callback is invoked.
5536 : */
5537 : void SetNativeDataProperty(
5538 : Local<String> name, AccessorGetterCallback getter,
5539 : AccessorSetterCallback setter = nullptr,
5540 : // TODO(dcarney): gcc can't handle Local below
5541 : Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5542 : Local<AccessorSignature> signature = Local<AccessorSignature>(),
5543 : AccessControl settings = DEFAULT,
5544 : SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
5545 : SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
5546 : void SetNativeDataProperty(
5547 : Local<Name> name, AccessorNameGetterCallback getter,
5548 : AccessorNameSetterCallback setter = nullptr,
5549 : // TODO(dcarney): gcc can't handle Local below
5550 : Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5551 : Local<AccessorSignature> signature = Local<AccessorSignature>(),
5552 : AccessControl settings = DEFAULT,
5553 : SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
5554 : SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
5555 :
5556 : /**
5557 : * Like SetNativeDataProperty, but V8 will replace the native data property
5558 : * with a real data property on first access.
5559 : */
5560 : void SetLazyDataProperty(
5561 : Local<Name> name, AccessorNameGetterCallback getter,
5562 : Local<Value> data = Local<Value>(), PropertyAttribute attribute = None,
5563 : SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
5564 : SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
5565 :
5566 : /**
5567 : * During template instantiation, sets the value with the intrinsic property
5568 : * from the correct context.
5569 : */
5570 : void SetIntrinsicDataProperty(Local<Name> name, Intrinsic intrinsic,
5571 : PropertyAttribute attribute = None);
5572 :
5573 : private:
5574 : Template();
5575 :
5576 : friend class ObjectTemplate;
5577 : friend class FunctionTemplate;
5578 : };
5579 :
5580 : // TODO(dcarney): Replace GenericNamedPropertyFooCallback with just
5581 : // NamedPropertyFooCallback.
5582 :
5583 : /**
5584 : * Interceptor for get requests on an object.
5585 : *
5586 : * Use `info.GetReturnValue().Set()` to set the return value of the
5587 : * intercepted get request.
5588 : *
5589 : * \param property The name of the property for which the request was
5590 : * intercepted.
5591 : * \param info Information about the intercepted request, such as
5592 : * isolate, receiver, return value, or whether running in `'use strict`' mode.
5593 : * See `PropertyCallbackInfo`.
5594 : *
5595 : * \code
5596 : * void GetterCallback(
5597 : * Local<Name> name,
5598 : * const v8::PropertyCallbackInfo<v8::Value>& info) {
5599 : * info.GetReturnValue().Set(v8_num(42));
5600 : * }
5601 : *
5602 : * v8::Local<v8::FunctionTemplate> templ =
5603 : * v8::FunctionTemplate::New(isolate);
5604 : * templ->InstanceTemplate()->SetHandler(
5605 : * v8::NamedPropertyHandlerConfiguration(GetterCallback));
5606 : * LocalContext env;
5607 : * env->Global()
5608 : * ->Set(env.local(), v8_str("obj"), templ->GetFunction(env.local())
5609 : * .ToLocalChecked()
5610 : * ->NewInstance(env.local())
5611 : * .ToLocalChecked())
5612 : * .FromJust();
5613 : * v8::Local<v8::Value> result = CompileRun("obj.a = 17; obj.a");
5614 : * CHECK(v8_num(42)->Equals(env.local(), result).FromJust());
5615 : * \endcode
5616 : *
5617 : * See also `ObjectTemplate::SetHandler`.
5618 : */
5619 : typedef void (*GenericNamedPropertyGetterCallback)(
5620 : Local<Name> property, const PropertyCallbackInfo<Value>& info);
5621 :
5622 : /**
5623 : * Interceptor for set requests on an object.
5624 : *
5625 : * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5626 : * or not. If the setter successfully intercepts the request, i.e., if the
5627 : * request should not be further executed, call
5628 : * `info.GetReturnValue().Set(value)`. If the setter
5629 : * did not intercept the request, i.e., if the request should be handled as
5630 : * if no interceptor is present, do not not call `Set()`.
5631 : *
5632 : * \param property The name of the property for which the request was
5633 : * intercepted.
5634 : * \param value The value which the property will have if the request
5635 : * is not intercepted.
5636 : * \param info Information about the intercepted request, such as
5637 : * isolate, receiver, return value, or whether running in `'use strict'` mode.
5638 : * See `PropertyCallbackInfo`.
5639 : *
5640 : * See also
5641 : * `ObjectTemplate::SetHandler.`
5642 : */
5643 : typedef void (*GenericNamedPropertySetterCallback)(
5644 : Local<Name> property, Local<Value> value,
5645 : const PropertyCallbackInfo<Value>& info);
5646 :
5647 : /**
5648 : * Intercepts all requests that query the attributes of the
5649 : * property, e.g., getOwnPropertyDescriptor(), propertyIsEnumerable(), and
5650 : * defineProperty().
5651 : *
5652 : * Use `info.GetReturnValue().Set(value)` to set the property attributes. The
5653 : * value is an integer encoding a `v8::PropertyAttribute`.
5654 : *
5655 : * \param property The name of the property for which the request was
5656 : * intercepted.
5657 : * \param info Information about the intercepted request, such as
5658 : * isolate, receiver, return value, or whether running in `'use strict'` mode.
5659 : * See `PropertyCallbackInfo`.
5660 : *
5661 : * \note Some functions query the property attributes internally, even though
5662 : * they do not return the attributes. For example, `hasOwnProperty()` can
5663 : * trigger this interceptor depending on the state of the object.
5664 : *
5665 : * See also
5666 : * `ObjectTemplate::SetHandler.`
5667 : */
5668 : typedef void (*GenericNamedPropertyQueryCallback)(
5669 : Local<Name> property, const PropertyCallbackInfo<Integer>& info);
5670 :
5671 : /**
5672 : * Interceptor for delete requests on an object.
5673 : *
5674 : * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5675 : * or not. If the deleter successfully intercepts the request, i.e., if the
5676 : * request should not be further executed, call
5677 : * `info.GetReturnValue().Set(value)` with a boolean `value`. The `value` is
5678 : * used as the return value of `delete`.
5679 : *
5680 : * \param property The name of the property for which the request was
5681 : * intercepted.
5682 : * \param info Information about the intercepted request, such as
5683 : * isolate, receiver, return value, or whether running in `'use strict'` mode.
5684 : * See `PropertyCallbackInfo`.
5685 : *
5686 : * \note If you need to mimic the behavior of `delete`, i.e., throw in strict
5687 : * mode instead of returning false, use `info.ShouldThrowOnError()` to determine
5688 : * if you are in strict mode.
5689 : *
5690 : * See also `ObjectTemplate::SetHandler.`
5691 : */
5692 : typedef void (*GenericNamedPropertyDeleterCallback)(
5693 : Local<Name> property, const PropertyCallbackInfo<Boolean>& info);
5694 :
5695 : /**
5696 : * Returns an array containing the names of the properties the named
5697 : * property getter intercepts.
5698 : *
5699 : * Note: The values in the array must be of type v8::Name.
5700 : */
5701 : typedef void (*GenericNamedPropertyEnumeratorCallback)(
5702 : const PropertyCallbackInfo<Array>& info);
5703 :
5704 : /**
5705 : * Interceptor for defineProperty requests on an object.
5706 : *
5707 : * Use `info.GetReturnValue()` to indicate whether the request was intercepted
5708 : * or not. If the definer successfully intercepts the request, i.e., if the
5709 : * request should not be further executed, call
5710 : * `info.GetReturnValue().Set(value)`. If the definer
5711 : * did not intercept the request, i.e., if the request should be handled as
5712 : * if no interceptor is present, do not not call `Set()`.
5713 : *
5714 : * \param property The name of the property for which the request was
5715 : * intercepted.
5716 : * \param desc The property descriptor which is used to define the
5717 : * property if the request is not intercepted.
5718 : * \param info Information about the intercepted request, such as
5719 : * isolate, receiver, return value, or whether running in `'use strict'` mode.
5720 : * See `PropertyCallbackInfo`.
5721 : *
5722 : * See also `ObjectTemplate::SetHandler`.
5723 : */
5724 : typedef void (*GenericNamedPropertyDefinerCallback)(
5725 : Local<Name> property, const PropertyDescriptor& desc,
5726 : const PropertyCallbackInfo<Value>& info);
5727 :
5728 : /**
5729 : * Interceptor for getOwnPropertyDescriptor requests on an object.
5730 : *
5731 : * Use `info.GetReturnValue().Set()` to set the return value of the
5732 : * intercepted request. The return value must be an object that
5733 : * can be converted to a PropertyDescriptor, e.g., a `v8::value` returned from
5734 : * `v8::Object::getOwnPropertyDescriptor`.
5735 : *
5736 : * \param property The name of the property for which the request was
5737 : * intercepted.
5738 : * \info Information about the intercepted request, such as
5739 : * isolate, receiver, return value, or whether running in `'use strict'` mode.
5740 : * See `PropertyCallbackInfo`.
5741 : *
5742 : * \note If GetOwnPropertyDescriptor is intercepted, it will
5743 : * always return true, i.e., indicate that the property was found.
5744 : *
5745 : * See also `ObjectTemplate::SetHandler`.
5746 : */
5747 : typedef void (*GenericNamedPropertyDescriptorCallback)(
5748 : Local<Name> property, const PropertyCallbackInfo<Value>& info);
5749 :
5750 : /**
5751 : * See `v8::GenericNamedPropertyGetterCallback`.
5752 : */
5753 : typedef void (*IndexedPropertyGetterCallback)(
5754 : uint32_t index,
5755 : const PropertyCallbackInfo<Value>& info);
5756 :
5757 : /**
5758 : * See `v8::GenericNamedPropertySetterCallback`.
5759 : */
5760 : typedef void (*IndexedPropertySetterCallback)(
5761 : uint32_t index,
5762 : Local<Value> value,
5763 : const PropertyCallbackInfo<Value>& info);
5764 :
5765 : /**
5766 : * See `v8::GenericNamedPropertyQueryCallback`.
5767 : */
5768 : typedef void (*IndexedPropertyQueryCallback)(
5769 : uint32_t index,
5770 : const PropertyCallbackInfo<Integer>& info);
5771 :
5772 : /**
5773 : * See `v8::GenericNamedPropertyDeleterCallback`.
5774 : */
5775 : typedef void (*IndexedPropertyDeleterCallback)(
5776 : uint32_t index,
5777 : const PropertyCallbackInfo<Boolean>& info);
5778 :
5779 : /**
5780 : * Returns an array containing the indices of the properties the indexed
5781 : * property getter intercepts.
5782 : *
5783 : * Note: The values in the array must be uint32_t.
5784 : */
5785 : typedef void (*IndexedPropertyEnumeratorCallback)(
5786 : const PropertyCallbackInfo<Array>& info);
5787 :
5788 : /**
5789 : * See `v8::GenericNamedPropertyDefinerCallback`.
5790 : */
5791 : typedef void (*IndexedPropertyDefinerCallback)(
5792 : uint32_t index, const PropertyDescriptor& desc,
5793 : const PropertyCallbackInfo<Value>& info);
5794 :
5795 : /**
5796 : * See `v8::GenericNamedPropertyDescriptorCallback`.
5797 : */
5798 : typedef void (*IndexedPropertyDescriptorCallback)(
5799 : uint32_t index, const PropertyCallbackInfo<Value>& info);
5800 :
5801 : /**
5802 : * Access type specification.
5803 : */
5804 : enum AccessType {
5805 : ACCESS_GET,
5806 : ACCESS_SET,
5807 : ACCESS_HAS,
5808 : ACCESS_DELETE,
5809 : ACCESS_KEYS
5810 : };
5811 :
5812 :
5813 : /**
5814 : * Returns true if the given context should be allowed to access the given
5815 : * object.
5816 : */
5817 : typedef bool (*AccessCheckCallback)(Local<Context> accessing_context,
5818 : Local<Object> accessed_object,
5819 : Local<Value> data);
5820 :
5821 : /**
5822 : * A FunctionTemplate is used to create functions at runtime. There
5823 : * can only be one function created from a FunctionTemplate in a
5824 : * context. The lifetime of the created function is equal to the
5825 : * lifetime of the context. So in case the embedder needs to create
5826 : * temporary functions that can be collected using Scripts is
5827 : * preferred.
5828 : *
5829 : * Any modification of a FunctionTemplate after first instantiation will trigger
5830 : * a crash.
5831 : *
5832 : * A FunctionTemplate can have properties, these properties are added to the
5833 : * function object when it is created.
5834 : *
5835 : * A FunctionTemplate has a corresponding instance template which is
5836 : * used to create object instances when the function is used as a
5837 : * constructor. Properties added to the instance template are added to
5838 : * each object instance.
5839 : *
5840 : * A FunctionTemplate can have a prototype template. The prototype template
5841 : * is used to create the prototype object of the function.
5842 : *
5843 : * The following example shows how to use a FunctionTemplate:
5844 : *
5845 : * \code
5846 : * v8::Local<v8::FunctionTemplate> t = v8::FunctionTemplate::New(isolate);
5847 : * t->Set(isolate, "func_property", v8::Number::New(isolate, 1));
5848 : *
5849 : * v8::Local<v8::Template> proto_t = t->PrototypeTemplate();
5850 : * proto_t->Set(isolate,
5851 : * "proto_method",
5852 : * v8::FunctionTemplate::New(isolate, InvokeCallback));
5853 : * proto_t->Set(isolate, "proto_const", v8::Number::New(isolate, 2));
5854 : *
5855 : * v8::Local<v8::ObjectTemplate> instance_t = t->InstanceTemplate();
5856 : * instance_t->SetAccessor(String::NewFromUtf8(isolate, "instance_accessor"),
5857 : * InstanceAccessorCallback);
5858 : * instance_t->SetHandler(
5859 : * NamedPropertyHandlerConfiguration(PropertyHandlerCallback));
5860 : * instance_t->Set(String::NewFromUtf8(isolate, "instance_property"),
5861 : * Number::New(isolate, 3));
5862 : *
5863 : * v8::Local<v8::Function> function = t->GetFunction();
5864 : * v8::Local<v8::Object> instance = function->NewInstance();
5865 : * \endcode
5866 : *
5867 : * Let's use "function" as the JS variable name of the function object
5868 : * and "instance" for the instance object created above. The function
5869 : * and the instance will have the following properties:
5870 : *
5871 : * \code
5872 : * func_property in function == true;
5873 : * function.func_property == 1;
5874 : *
5875 : * function.prototype.proto_method() invokes 'InvokeCallback'
5876 : * function.prototype.proto_const == 2;
5877 : *
5878 : * instance instanceof function == true;
5879 : * instance.instance_accessor calls 'InstanceAccessorCallback'
5880 : * instance.instance_property == 3;
5881 : * \endcode
5882 : *
5883 : * A FunctionTemplate can inherit from another one by calling the
5884 : * FunctionTemplate::Inherit method. The following graph illustrates
5885 : * the semantics of inheritance:
5886 : *
5887 : * \code
5888 : * FunctionTemplate Parent -> Parent() . prototype -> { }
5889 : * ^ ^
5890 : * | Inherit(Parent) | .__proto__
5891 : * | |
5892 : * FunctionTemplate Child -> Child() . prototype -> { }
5893 : * \endcode
5894 : *
5895 : * A FunctionTemplate 'Child' inherits from 'Parent', the prototype
5896 : * object of the Child() function has __proto__ pointing to the
5897 : * Parent() function's prototype object. An instance of the Child
5898 : * function has all properties on Parent's instance templates.
5899 : *
5900 : * Let Parent be the FunctionTemplate initialized in the previous
5901 : * section and create a Child FunctionTemplate by:
5902 : *
5903 : * \code
5904 : * Local<FunctionTemplate> parent = t;
5905 : * Local<FunctionTemplate> child = FunctionTemplate::New();
5906 : * child->Inherit(parent);
5907 : *
5908 : * Local<Function> child_function = child->GetFunction();
5909 : * Local<Object> child_instance = child_function->NewInstance();
5910 : * \endcode
5911 : *
5912 : * The Child function and Child instance will have the following
5913 : * properties:
5914 : *
5915 : * \code
5916 : * child_func.prototype.__proto__ == function.prototype;
5917 : * child_instance.instance_accessor calls 'InstanceAccessorCallback'
5918 : * child_instance.instance_property == 3;
5919 : * \endcode
5920 : */
5921 : class V8_EXPORT FunctionTemplate : public Template {
5922 : public:
5923 : /** Creates a function template.*/
5924 : static Local<FunctionTemplate> New(
5925 : Isolate* isolate, FunctionCallback callback = nullptr,
5926 : Local<Value> data = Local<Value>(),
5927 : Local<Signature> signature = Local<Signature>(), int length = 0,
5928 : ConstructorBehavior behavior = ConstructorBehavior::kAllow,
5929 : SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5930 :
5931 : /** Get a template included in the snapshot by index. */
5932 : static MaybeLocal<FunctionTemplate> FromSnapshot(Isolate* isolate,
5933 : size_t index);
5934 :
5935 : /**
5936 : * Creates a function template backed/cached by a private property.
5937 : */
5938 : static Local<FunctionTemplate> NewWithCache(
5939 : Isolate* isolate, FunctionCallback callback,
5940 : Local<Private> cache_property, Local<Value> data = Local<Value>(),
5941 : Local<Signature> signature = Local<Signature>(), int length = 0,
5942 : SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5943 :
5944 : /** Returns the unique function instance in the current execution context.*/
5945 : V8_WARN_UNUSED_RESULT MaybeLocal<Function> GetFunction(
5946 : Local<Context> context);
5947 :
5948 : /**
5949 : * Similar to Context::NewRemoteContext, this creates an instance that
5950 : * isn't backed by an actual object.
5951 : *
5952 : * The InstanceTemplate of this FunctionTemplate must have access checks with
5953 : * handlers installed.
5954 : */
5955 : V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewRemoteInstance();
5956 :
5957 : /**
5958 : * Set the call-handler callback for a FunctionTemplate. This
5959 : * callback is called whenever the function created from this
5960 : * FunctionTemplate is called.
5961 : */
5962 : void SetCallHandler(
5963 : FunctionCallback callback, Local<Value> data = Local<Value>(),
5964 : SideEffectType side_effect_type = SideEffectType::kHasSideEffect);
5965 :
5966 : /** Set the predefined length property for the FunctionTemplate. */
5967 : void SetLength(int length);
5968 :
5969 : /** Get the InstanceTemplate. */
5970 : Local<ObjectTemplate> InstanceTemplate();
5971 :
5972 : /**
5973 : * Causes the function template to inherit from a parent function template.
5974 : * This means the function's prototype.__proto__ is set to the parent
5975 : * function's prototype.
5976 : **/
5977 : void Inherit(Local<FunctionTemplate> parent);
5978 :
5979 : /**
5980 : * A PrototypeTemplate is the template used to create the prototype object
5981 : * of the function created by this template.
5982 : */
5983 : Local<ObjectTemplate> PrototypeTemplate();
5984 :
5985 : /**
5986 : * A PrototypeProviderTemplate is another function template whose prototype
5987 : * property is used for this template. This is mutually exclusive with setting
5988 : * a prototype template indirectly by calling PrototypeTemplate() or using
5989 : * Inherit().
5990 : **/
5991 : void SetPrototypeProviderTemplate(Local<FunctionTemplate> prototype_provider);
5992 :
5993 : /**
5994 : * Set the class name of the FunctionTemplate. This is used for
5995 : * printing objects created with the function created from the
5996 : * FunctionTemplate as its constructor.
5997 : */
5998 : void SetClassName(Local<String> name);
5999 :
6000 :
6001 : /**
6002 : * When set to true, no access check will be performed on the receiver of a
6003 : * function call. Currently defaults to true, but this is subject to change.
6004 : */
6005 : void SetAcceptAnyReceiver(bool value);
6006 :
6007 : /**
6008 : * Determines whether the __proto__ accessor ignores instances of
6009 : * the function template. If instances of the function template are
6010 : * ignored, __proto__ skips all instances and instead returns the
6011 : * next object in the prototype chain.
6012 : *
6013 : * Call with a value of true to make the __proto__ accessor ignore
6014 : * instances of the function template. Call with a value of false
6015 : * to make the __proto__ accessor not ignore instances of the
6016 : * function template. By default, instances of a function template
6017 : * are not ignored.
6018 : */
6019 : V8_DEPRECATED("This feature is incompatible with ES6+.",
6020 : void SetHiddenPrototype(bool value));
6021 :
6022 : /**
6023 : * Sets the ReadOnly flag in the attributes of the 'prototype' property
6024 : * of functions created from this FunctionTemplate to true.
6025 : */
6026 : void ReadOnlyPrototype();
6027 :
6028 : /**
6029 : * Removes the prototype property from functions created from this
6030 : * FunctionTemplate.
6031 : */
6032 : void RemovePrototype();
6033 :
6034 : /**
6035 : * Returns true if the given object is an instance of this function
6036 : * template.
6037 : */
6038 : bool HasInstance(Local<Value> object);
6039 :
6040 : V8_INLINE static FunctionTemplate* Cast(Data* data);
6041 :
6042 : private:
6043 : FunctionTemplate();
6044 :
6045 : static void CheckCast(Data* that);
6046 : friend class Context;
6047 : friend class ObjectTemplate;
6048 : };
6049 :
6050 : /**
6051 : * Configuration flags for v8::NamedPropertyHandlerConfiguration or
6052 : * v8::IndexedPropertyHandlerConfiguration.
6053 : */
6054 : enum class PropertyHandlerFlags {
6055 : /**
6056 : * None.
6057 : */
6058 : kNone = 0,
6059 :
6060 : /**
6061 : * See ALL_CAN_READ above.
6062 : */
6063 : kAllCanRead = 1,
6064 :
6065 : /** Will not call into interceptor for properties on the receiver or prototype
6066 : * chain, i.e., only call into interceptor for properties that do not exist.
6067 : * Currently only valid for named interceptors.
6068 : */
6069 : kNonMasking = 1 << 1,
6070 :
6071 : /**
6072 : * Will not call into interceptor for symbol lookup. Only meaningful for
6073 : * named interceptors.
6074 : */
6075 : kOnlyInterceptStrings = 1 << 2,
6076 :
6077 : /**
6078 : * The getter, query, enumerator callbacks do not produce side effects.
6079 : */
6080 : kHasNoSideEffect = 1 << 3,
6081 : };
6082 :
6083 : struct NamedPropertyHandlerConfiguration {
6084 : NamedPropertyHandlerConfiguration(
6085 : GenericNamedPropertyGetterCallback getter,
6086 : GenericNamedPropertySetterCallback setter,
6087 : GenericNamedPropertyQueryCallback query,
6088 : GenericNamedPropertyDeleterCallback deleter,
6089 : GenericNamedPropertyEnumeratorCallback enumerator,
6090 : GenericNamedPropertyDefinerCallback definer,
6091 : GenericNamedPropertyDescriptorCallback descriptor,
6092 : Local<Value> data = Local<Value>(),
6093 : PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6094 : : getter(getter),
6095 : setter(setter),
6096 : query(query),
6097 : deleter(deleter),
6098 : enumerator(enumerator),
6099 : definer(definer),
6100 : descriptor(descriptor),
6101 : data(data),
6102 1 : flags(flags) {}
6103 :
6104 : NamedPropertyHandlerConfiguration(
6105 : /** Note: getter is required */
6106 : GenericNamedPropertyGetterCallback getter = nullptr,
6107 : GenericNamedPropertySetterCallback setter = nullptr,
6108 : GenericNamedPropertyQueryCallback query = nullptr,
6109 : GenericNamedPropertyDeleterCallback deleter = nullptr,
6110 : GenericNamedPropertyEnumeratorCallback enumerator = nullptr,
6111 : Local<Value> data = Local<Value>(),
6112 : PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6113 : : getter(getter),
6114 : setter(setter),
6115 : query(query),
6116 : deleter(deleter),
6117 : enumerator(enumerator),
6118 : definer(nullptr),
6119 : descriptor(nullptr),
6120 : data(data),
6121 893 : flags(flags) {}
6122 :
6123 : NamedPropertyHandlerConfiguration(
6124 : GenericNamedPropertyGetterCallback getter,
6125 : GenericNamedPropertySetterCallback setter,
6126 : GenericNamedPropertyDescriptorCallback descriptor,
6127 : GenericNamedPropertyDeleterCallback deleter,
6128 : GenericNamedPropertyEnumeratorCallback enumerator,
6129 : GenericNamedPropertyDefinerCallback definer,
6130 : Local<Value> data = Local<Value>(),
6131 : PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6132 : : getter(getter),
6133 : setter(setter),
6134 : query(nullptr),
6135 : deleter(deleter),
6136 : enumerator(enumerator),
6137 : definer(definer),
6138 : descriptor(descriptor),
6139 : data(data),
6140 83 : flags(flags) {}
6141 :
6142 : GenericNamedPropertyGetterCallback getter;
6143 : GenericNamedPropertySetterCallback setter;
6144 : GenericNamedPropertyQueryCallback query;
6145 : GenericNamedPropertyDeleterCallback deleter;
6146 : GenericNamedPropertyEnumeratorCallback enumerator;
6147 : GenericNamedPropertyDefinerCallback definer;
6148 : GenericNamedPropertyDescriptorCallback descriptor;
6149 : Local<Value> data;
6150 : PropertyHandlerFlags flags;
6151 : };
6152 :
6153 :
6154 : struct IndexedPropertyHandlerConfiguration {
6155 : IndexedPropertyHandlerConfiguration(
6156 : IndexedPropertyGetterCallback getter,
6157 : IndexedPropertySetterCallback setter, IndexedPropertyQueryCallback query,
6158 : IndexedPropertyDeleterCallback deleter,
6159 : IndexedPropertyEnumeratorCallback enumerator,
6160 : IndexedPropertyDefinerCallback definer,
6161 : IndexedPropertyDescriptorCallback descriptor,
6162 : Local<Value> data = Local<Value>(),
6163 : PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6164 : : getter(getter),
6165 : setter(setter),
6166 : query(query),
6167 : deleter(deleter),
6168 : enumerator(enumerator),
6169 : definer(definer),
6170 : descriptor(descriptor),
6171 : data(data),
6172 1 : flags(flags) {}
6173 :
6174 : IndexedPropertyHandlerConfiguration(
6175 : /** Note: getter is required */
6176 : IndexedPropertyGetterCallback getter = nullptr,
6177 : IndexedPropertySetterCallback setter = nullptr,
6178 : IndexedPropertyQueryCallback query = nullptr,
6179 : IndexedPropertyDeleterCallback deleter = nullptr,
6180 : IndexedPropertyEnumeratorCallback enumerator = nullptr,
6181 : Local<Value> data = Local<Value>(),
6182 : PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6183 : : getter(getter),
6184 : setter(setter),
6185 : query(query),
6186 : deleter(deleter),
6187 : enumerator(enumerator),
6188 : definer(nullptr),
6189 : descriptor(nullptr),
6190 : data(data),
6191 224 : flags(flags) {}
6192 :
6193 : IndexedPropertyHandlerConfiguration(
6194 : IndexedPropertyGetterCallback getter,
6195 : IndexedPropertySetterCallback setter,
6196 : IndexedPropertyDescriptorCallback descriptor,
6197 : IndexedPropertyDeleterCallback deleter,
6198 : IndexedPropertyEnumeratorCallback enumerator,
6199 : IndexedPropertyDefinerCallback definer,
6200 : Local<Value> data = Local<Value>(),
6201 : PropertyHandlerFlags flags = PropertyHandlerFlags::kNone)
6202 : : getter(getter),
6203 : setter(setter),
6204 : query(nullptr),
6205 : deleter(deleter),
6206 : enumerator(enumerator),
6207 : definer(definer),
6208 : descriptor(descriptor),
6209 : data(data),
6210 23 : flags(flags) {}
6211 :
6212 : IndexedPropertyGetterCallback getter;
6213 : IndexedPropertySetterCallback setter;
6214 : IndexedPropertyQueryCallback query;
6215 : IndexedPropertyDeleterCallback deleter;
6216 : IndexedPropertyEnumeratorCallback enumerator;
6217 : IndexedPropertyDefinerCallback definer;
6218 : IndexedPropertyDescriptorCallback descriptor;
6219 : Local<Value> data;
6220 : PropertyHandlerFlags flags;
6221 : };
6222 :
6223 :
6224 : /**
6225 : * An ObjectTemplate is used to create objects at runtime.
6226 : *
6227 : * Properties added to an ObjectTemplate are added to each object
6228 : * created from the ObjectTemplate.
6229 : */
6230 : class V8_EXPORT ObjectTemplate : public Template {
6231 : public:
6232 : /** Creates an ObjectTemplate. */
6233 : static Local<ObjectTemplate> New(
6234 : Isolate* isolate,
6235 : Local<FunctionTemplate> constructor = Local<FunctionTemplate>());
6236 :
6237 : /** Get a template included in the snapshot by index. */
6238 : static MaybeLocal<ObjectTemplate> FromSnapshot(Isolate* isolate,
6239 : size_t index);
6240 :
6241 : /** Creates a new instance of this template.*/
6242 : V8_WARN_UNUSED_RESULT MaybeLocal<Object> NewInstance(Local<Context> context);
6243 :
6244 : /**
6245 : * Sets an accessor on the object template.
6246 : *
6247 : * Whenever the property with the given name is accessed on objects
6248 : * created from this ObjectTemplate the getter and setter callbacks
6249 : * are called instead of getting and setting the property directly
6250 : * on the JavaScript object.
6251 : *
6252 : * \param name The name of the property for which an accessor is added.
6253 : * \param getter The callback to invoke when getting the property.
6254 : * \param setter The callback to invoke when setting the property.
6255 : * \param data A piece of data that will be passed to the getter and setter
6256 : * callbacks whenever they are invoked.
6257 : * \param settings Access control settings for the accessor. This is a bit
6258 : * field consisting of one of more of
6259 : * DEFAULT = 0, ALL_CAN_READ = 1, or ALL_CAN_WRITE = 2.
6260 : * The default is to not allow cross-context access.
6261 : * ALL_CAN_READ means that all cross-context reads are allowed.
6262 : * ALL_CAN_WRITE means that all cross-context writes are allowed.
6263 : * The combination ALL_CAN_READ | ALL_CAN_WRITE can be used to allow all
6264 : * cross-context access.
6265 : * \param attribute The attributes of the property for which an accessor
6266 : * is added.
6267 : * \param signature The signature describes valid receivers for the accessor
6268 : * and is used to perform implicit instance checks against them. If the
6269 : * receiver is incompatible (i.e. is not an instance of the constructor as
6270 : * defined by FunctionTemplate::HasInstance()), an implicit TypeError is
6271 : * thrown and no callback is invoked.
6272 : */
6273 : void SetAccessor(
6274 : Local<String> name, AccessorGetterCallback getter,
6275 : AccessorSetterCallback setter = nullptr,
6276 : Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
6277 : PropertyAttribute attribute = None,
6278 : Local<AccessorSignature> signature = Local<AccessorSignature>(),
6279 : SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6280 : SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6281 : void SetAccessor(
6282 : Local<Name> name, AccessorNameGetterCallback getter,
6283 : AccessorNameSetterCallback setter = nullptr,
6284 : Local<Value> data = Local<Value>(), AccessControl settings = DEFAULT,
6285 : PropertyAttribute attribute = None,
6286 : Local<AccessorSignature> signature = Local<AccessorSignature>(),
6287 : SideEffectType getter_side_effect_type = SideEffectType::kHasSideEffect,
6288 : SideEffectType setter_side_effect_type = SideEffectType::kHasSideEffect);
6289 :
6290 : /**
6291 : * Sets a named property handler on the object template.
6292 : *
6293 : * Whenever a property whose name is a string or a symbol is accessed on
6294 : * objects created from this object template, the provided callback is
6295 : * invoked instead of accessing the property directly on the JavaScript
6296 : * object.
6297 : *
6298 : * @param configuration The NamedPropertyHandlerConfiguration that defines the
6299 : * callbacks to invoke when accessing a property.
6300 : */
6301 : void SetHandler(const NamedPropertyHandlerConfiguration& configuration);
6302 :
6303 : /**
6304 : * Sets an indexed property handler on the object template.
6305 : *
6306 : * Whenever an indexed property is accessed on objects created from
6307 : * this object template, the provided callback is invoked instead of
6308 : * accessing the property directly on the JavaScript object.
6309 : *
6310 : * \param getter The callback to invoke when getting a property.
6311 : * \param setter The callback to invoke when setting a property.
6312 : * \param query The callback to invoke to check if an object has a property.
6313 : * \param deleter The callback to invoke when deleting a property.
6314 : * \param enumerator The callback to invoke to enumerate all the indexed
6315 : * properties of an object.
6316 : * \param data A piece of data that will be passed to the callbacks
6317 : * whenever they are invoked.
6318 : */
6319 : // TODO(dcarney): deprecate
6320 : void SetIndexedPropertyHandler(
6321 : IndexedPropertyGetterCallback getter,
6322 : IndexedPropertySetterCallback setter = nullptr,
6323 : IndexedPropertyQueryCallback query = nullptr,
6324 : IndexedPropertyDeleterCallback deleter = nullptr,
6325 : IndexedPropertyEnumeratorCallback enumerator = nullptr,
6326 : Local<Value> data = Local<Value>()) {
6327 : SetHandler(IndexedPropertyHandlerConfiguration(getter, setter, query,
6328 : deleter, enumerator, data));
6329 : }
6330 :
6331 : /**
6332 : * Sets an indexed property handler on the object template.
6333 : *
6334 : * Whenever an indexed property is accessed on objects created from
6335 : * this object template, the provided callback is invoked instead of
6336 : * accessing the property directly on the JavaScript object.
6337 : *
6338 : * @param configuration The IndexedPropertyHandlerConfiguration that defines
6339 : * the callbacks to invoke when accessing a property.
6340 : */
6341 : void SetHandler(const IndexedPropertyHandlerConfiguration& configuration);
6342 :
6343 : /**
6344 : * Sets the callback to be used when calling instances created from
6345 : * this template as a function. If no callback is set, instances
6346 : * behave like normal JavaScript objects that cannot be called as a
6347 : * function.
6348 : */
6349 : void SetCallAsFunctionHandler(FunctionCallback callback,
6350 : Local<Value> data = Local<Value>());
6351 :
6352 : /**
6353 : * Mark object instances of the template as undetectable.
6354 : *
6355 : * In many ways, undetectable objects behave as though they are not
6356 : * there. They behave like 'undefined' in conditionals and when
6357 : * printed. However, properties can be accessed and called as on
6358 : * normal objects.
6359 : */
6360 : void MarkAsUndetectable();
6361 :
6362 : /**
6363 : * Sets access check callback on the object template and enables access
6364 : * checks.
6365 : *
6366 : * When accessing properties on instances of this object template,
6367 : * the access check callback will be called to determine whether or
6368 : * not to allow cross-context access to the properties.
6369 : */
6370 : void SetAccessCheckCallback(AccessCheckCallback callback,
6371 : Local<Value> data = Local<Value>());
6372 :
6373 : /**
6374 : * Like SetAccessCheckCallback but invokes an interceptor on failed access
6375 : * checks instead of looking up all-can-read properties. You can only use
6376 : * either this method or SetAccessCheckCallback, but not both at the same
6377 : * time.
6378 : */
6379 : void SetAccessCheckCallbackAndHandler(
6380 : AccessCheckCallback callback,
6381 : const NamedPropertyHandlerConfiguration& named_handler,
6382 : const IndexedPropertyHandlerConfiguration& indexed_handler,
6383 : Local<Value> data = Local<Value>());
6384 :
6385 : /**
6386 : * Gets the number of internal fields for objects generated from
6387 : * this template.
6388 : */
6389 : int InternalFieldCount();
6390 :
6391 : /**
6392 : * Sets the number of internal fields for objects generated from
6393 : * this template.
6394 : */
6395 : void SetInternalFieldCount(int value);
6396 :
6397 : /**
6398 : * Returns true if the object will be an immutable prototype exotic object.
6399 : */
6400 : bool IsImmutableProto();
6401 :
6402 : /**
6403 : * Makes the ObjectTemplate for an immutable prototype exotic object, with an
6404 : * immutable __proto__.
6405 : */
6406 : void SetImmutableProto();
6407 :
6408 : V8_INLINE static ObjectTemplate* Cast(Data* data);
6409 :
6410 : private:
6411 : ObjectTemplate();
6412 : static Local<ObjectTemplate> New(internal::Isolate* isolate,
6413 : Local<FunctionTemplate> constructor);
6414 : static void CheckCast(Data* that);
6415 : friend class FunctionTemplate;
6416 : };
6417 :
6418 : /**
6419 : * A Signature specifies which receiver is valid for a function.
6420 : *
6421 : * A receiver matches a given signature if the receiver (or any of its
6422 : * hidden prototypes) was created from the signature's FunctionTemplate, or
6423 : * from a FunctionTemplate that inherits directly or indirectly from the
6424 : * signature's FunctionTemplate.
6425 : */
6426 : class V8_EXPORT Signature : public Data {
6427 : public:
6428 : static Local<Signature> New(
6429 : Isolate* isolate,
6430 : Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
6431 :
6432 : V8_INLINE static Signature* Cast(Data* data);
6433 :
6434 : private:
6435 : Signature();
6436 :
6437 : static void CheckCast(Data* that);
6438 : };
6439 :
6440 :
6441 : /**
6442 : * An AccessorSignature specifies which receivers are valid parameters
6443 : * to an accessor callback.
6444 : */
6445 : class V8_EXPORT AccessorSignature : public Data {
6446 : public:
6447 : static Local<AccessorSignature> New(
6448 : Isolate* isolate,
6449 : Local<FunctionTemplate> receiver = Local<FunctionTemplate>());
6450 :
6451 : V8_INLINE static AccessorSignature* Cast(Data* data);
6452 :
6453 : private:
6454 : AccessorSignature();
6455 :
6456 : static void CheckCast(Data* that);
6457 : };
6458 :
6459 :
6460 : // --- Extensions ---
6461 :
6462 : /**
6463 : * Ignore
6464 : */
6465 : class V8_EXPORT Extension { // NOLINT
6466 : public:
6467 : // Note that the strings passed into this constructor must live as long
6468 : // as the Extension itself.
6469 : Extension(const char* name, const char* source = nullptr, int dep_count = 0,
6470 : const char** deps = nullptr, int source_length = -1);
6471 439218 : virtual ~Extension() { delete source_; }
6472 0 : virtual Local<FunctionTemplate> GetNativeFunctionTemplate(
6473 : Isolate* isolate, Local<String> name) {
6474 0 : return Local<FunctionTemplate>();
6475 : }
6476 :
6477 : const char* name() const { return name_; }
6478 : size_t source_length() const { return source_length_; }
6479 : const String::ExternalOneByteStringResource* source() const {
6480 : return source_;
6481 : }
6482 : int dependency_count() const { return dep_count_; }
6483 : const char** dependencies() const { return deps_; }
6484 10 : void set_auto_enable(bool value) { auto_enable_ = value; }
6485 : bool auto_enable() { return auto_enable_; }
6486 :
6487 : // Disallow copying and assigning.
6488 : Extension(const Extension&) = delete;
6489 : void operator=(const Extension&) = delete;
6490 :
6491 : private:
6492 : const char* name_;
6493 : size_t source_length_; // expected to initialize before source_
6494 : String::ExternalOneByteStringResource* source_;
6495 : int dep_count_;
6496 : const char** deps_;
6497 : bool auto_enable_;
6498 : };
6499 :
6500 : void V8_EXPORT RegisterExtension(std::unique_ptr<Extension>);
6501 :
6502 : // --- Statics ---
6503 :
6504 : V8_INLINE Local<Primitive> Undefined(Isolate* isolate);
6505 : V8_INLINE Local<Primitive> Null(Isolate* isolate);
6506 : V8_INLINE Local<Boolean> True(Isolate* isolate);
6507 : V8_INLINE Local<Boolean> False(Isolate* isolate);
6508 :
6509 : /**
6510 : * A set of constraints that specifies the limits of the runtime's memory use.
6511 : * You must set the heap size before initializing the VM - the size cannot be
6512 : * adjusted after the VM is initialized.
6513 : *
6514 : * If you are using threads then you should hold the V8::Locker lock while
6515 : * setting the stack limit and you must set a non-default stack limit separately
6516 : * for each thread.
6517 : *
6518 : * The arguments for set_max_semi_space_size, set_max_old_space_size,
6519 : * set_max_executable_size, set_code_range_size specify limits in MB.
6520 : *
6521 : * The argument for set_max_semi_space_size_in_kb is in KB.
6522 : */
6523 : class V8_EXPORT ResourceConstraints {
6524 : public:
6525 : ResourceConstraints();
6526 :
6527 : /**
6528 : * Configures the constraints with reasonable default values based on the
6529 : * capabilities of the current device the VM is running on.
6530 : *
6531 : * \param physical_memory The total amount of physical memory on the current
6532 : * device, in bytes.
6533 : * \param virtual_memory_limit The amount of virtual memory on the current
6534 : * device, in bytes, or zero, if there is no limit.
6535 : */
6536 : void ConfigureDefaults(uint64_t physical_memory,
6537 : uint64_t virtual_memory_limit);
6538 :
6539 : // Returns the max semi-space size in KB.
6540 : size_t max_semi_space_size_in_kb() const {
6541 : return max_semi_space_size_in_kb_;
6542 : }
6543 :
6544 : // Sets the max semi-space size in KB.
6545 : void set_max_semi_space_size_in_kb(size_t limit_in_kb) {
6546 30117 : max_semi_space_size_in_kb_ = limit_in_kb;
6547 : }
6548 :
6549 : size_t max_old_space_size() const { return max_old_space_size_; }
6550 : void set_max_old_space_size(size_t limit_in_mb) {
6551 30121 : max_old_space_size_ = limit_in_mb;
6552 : }
6553 : uint32_t* stack_limit() const { return stack_limit_; }
6554 : // Sets an address beyond which the VM's stack may not grow.
6555 : void set_stack_limit(uint32_t* value) { stack_limit_ = value; }
6556 : size_t code_range_size() const { return code_range_size_; }
6557 : void set_code_range_size(size_t limit_in_mb) {
6558 0 : code_range_size_ = limit_in_mb;
6559 : }
6560 : V8_DEPRECATE_SOON("Zone does not pool memory any more.",
6561 : size_t max_zone_pool_size() const) {
6562 : return max_zone_pool_size_;
6563 : }
6564 : V8_DEPRECATE_SOON("Zone does not pool memory any more.",
6565 : void set_max_zone_pool_size(size_t bytes)) {
6566 : max_zone_pool_size_ = bytes;
6567 : }
6568 :
6569 : private:
6570 : // max_semi_space_size_ is in KB
6571 : size_t max_semi_space_size_in_kb_;
6572 :
6573 : // The remaining limits are in MB
6574 : size_t max_old_space_size_;
6575 : uint32_t* stack_limit_;
6576 : size_t code_range_size_;
6577 : size_t max_zone_pool_size_;
6578 : };
6579 :
6580 :
6581 : // --- Exceptions ---
6582 :
6583 :
6584 : typedef void (*FatalErrorCallback)(const char* location, const char* message);
6585 :
6586 : typedef void (*OOMErrorCallback)(const char* location, bool is_heap_oom);
6587 :
6588 : typedef void (*DcheckErrorCallback)(const char* file, int line,
6589 : const char* message);
6590 :
6591 : typedef void (*MessageCallback)(Local<Message> message, Local<Value> data);
6592 :
6593 : // --- Tracing ---
6594 :
6595 : typedef void (*LogEventCallback)(const char* name, int event);
6596 :
6597 : /**
6598 : * Create new error objects by calling the corresponding error object
6599 : * constructor with the message.
6600 : */
6601 : class V8_EXPORT Exception {
6602 : public:
6603 : static Local<Value> RangeError(Local<String> message);
6604 : static Local<Value> ReferenceError(Local<String> message);
6605 : static Local<Value> SyntaxError(Local<String> message);
6606 : static Local<Value> TypeError(Local<String> message);
6607 : static Local<Value> Error(Local<String> message);
6608 :
6609 : /**
6610 : * Creates an error message for the given exception.
6611 : * Will try to reconstruct the original stack trace from the exception value,
6612 : * or capture the current stack trace if not available.
6613 : */
6614 : static Local<Message> CreateMessage(Isolate* isolate, Local<Value> exception);
6615 :
6616 : /**
6617 : * Returns the original stack trace that was captured at the creation time
6618 : * of a given exception, or an empty handle if not available.
6619 : */
6620 : static Local<StackTrace> GetStackTrace(Local<Value> exception);
6621 : };
6622 :
6623 :
6624 : // --- Counters Callbacks ---
6625 :
6626 : typedef int* (*CounterLookupCallback)(const char* name);
6627 :
6628 : typedef void* (*CreateHistogramCallback)(const char* name,
6629 : int min,
6630 : int max,
6631 : size_t buckets);
6632 :
6633 : typedef void (*AddHistogramSampleCallback)(void* histogram, int sample);
6634 :
6635 : // --- Enter/Leave Script Callback ---
6636 : typedef void (*BeforeCallEnteredCallback)(Isolate*);
6637 : typedef void (*CallCompletedCallback)(Isolate*);
6638 :
6639 : /**
6640 : * HostImportModuleDynamicallyCallback is called when we require the
6641 : * embedder to load a module. This is used as part of the dynamic
6642 : * import syntax.
6643 : *
6644 : * The referrer contains metadata about the script/module that calls
6645 : * import.
6646 : *
6647 : * The specifier is the name of the module that should be imported.
6648 : *
6649 : * The embedder must compile, instantiate, evaluate the Module, and
6650 : * obtain it's namespace object.
6651 : *
6652 : * The Promise returned from this function is forwarded to userland
6653 : * JavaScript. The embedder must resolve this promise with the module
6654 : * namespace object. In case of an exception, the embedder must reject
6655 : * this promise with the exception. If the promise creation itself
6656 : * fails (e.g. due to stack overflow), the embedder must propagate
6657 : * that exception by returning an empty MaybeLocal.
6658 : */
6659 : typedef MaybeLocal<Promise> (*HostImportModuleDynamicallyCallback)(
6660 : Local<Context> context, Local<ScriptOrModule> referrer,
6661 : Local<String> specifier);
6662 :
6663 : /**
6664 : * HostInitializeImportMetaObjectCallback is called the first time import.meta
6665 : * is accessed for a module. Subsequent access will reuse the same value.
6666 : *
6667 : * The method combines two implementation-defined abstract operations into one:
6668 : * HostGetImportMetaProperties and HostFinalizeImportMeta.
6669 : *
6670 : * The embedder should use v8::Object::CreateDataProperty to add properties on
6671 : * the meta object.
6672 : */
6673 : typedef void (*HostInitializeImportMetaObjectCallback)(Local<Context> context,
6674 : Local<Module> module,
6675 : Local<Object> meta);
6676 :
6677 : /**
6678 : * PrepareStackTraceCallback is called when the stack property of an error is
6679 : * first accessed. The return value will be used as the stack value. If this
6680 : * callback is registed, the |Error.prepareStackTrace| API will be disabled.
6681 : * |sites| is an array of call sites, specified in
6682 : * https://v8.dev/docs/stack-trace-api
6683 : */
6684 : typedef MaybeLocal<Value> (*PrepareStackTraceCallback)(Local<Context> context,
6685 : Local<Value> error,
6686 : Local<Array> sites);
6687 :
6688 : /**
6689 : * PromiseHook with type kInit is called when a new promise is
6690 : * created. When a new promise is created as part of the chain in the
6691 : * case of Promise.then or in the intermediate promises created by
6692 : * Promise.{race, all}/AsyncFunctionAwait, we pass the parent promise
6693 : * otherwise we pass undefined.
6694 : *
6695 : * PromiseHook with type kResolve is called at the beginning of
6696 : * resolve or reject function defined by CreateResolvingFunctions.
6697 : *
6698 : * PromiseHook with type kBefore is called at the beginning of the
6699 : * PromiseReactionJob.
6700 : *
6701 : * PromiseHook with type kAfter is called right at the end of the
6702 : * PromiseReactionJob.
6703 : */
6704 : enum class PromiseHookType { kInit, kResolve, kBefore, kAfter };
6705 :
6706 : typedef void (*PromiseHook)(PromiseHookType type, Local<Promise> promise,
6707 : Local<Value> parent);
6708 :
6709 : // --- Promise Reject Callback ---
6710 : enum PromiseRejectEvent {
6711 : kPromiseRejectWithNoHandler = 0,
6712 : kPromiseHandlerAddedAfterReject = 1,
6713 : kPromiseRejectAfterResolved = 2,
6714 : kPromiseResolveAfterResolved = 3,
6715 : };
6716 :
6717 : class PromiseRejectMessage {
6718 : public:
6719 : PromiseRejectMessage(Local<Promise> promise, PromiseRejectEvent event,
6720 : Local<Value> value)
6721 490 : : promise_(promise), event_(event), value_(value) {}
6722 :
6723 170 : V8_INLINE Local<Promise> GetPromise() const { return promise_; }
6724 140 : V8_INLINE PromiseRejectEvent GetEvent() const { return event_; }
6725 125 : V8_INLINE Local<Value> GetValue() const { return value_; }
6726 :
6727 : private:
6728 : Local<Promise> promise_;
6729 : PromiseRejectEvent event_;
6730 : Local<Value> value_;
6731 : };
6732 :
6733 : typedef void (*PromiseRejectCallback)(PromiseRejectMessage message);
6734 :
6735 : // --- Microtasks Callbacks ---
6736 : V8_DEPRECATE_SOON("Use *WithData version.",
6737 : typedef void (*MicrotasksCompletedCallback)(Isolate*));
6738 : typedef void (*MicrotasksCompletedCallbackWithData)(Isolate*, void*);
6739 : typedef void (*MicrotaskCallback)(void* data);
6740 :
6741 :
6742 : /**
6743 : * Policy for running microtasks:
6744 : * - explicit: microtasks are invoked with Isolate::RunMicrotasks() method;
6745 : * - scoped: microtasks invocation is controlled by MicrotasksScope objects;
6746 : * - auto: microtasks are invoked when the script call depth decrements
6747 : * to zero.
6748 : */
6749 : enum class MicrotasksPolicy { kExplicit, kScoped, kAuto };
6750 :
6751 : /**
6752 : * Represents the microtask queue, where microtasks are stored and processed.
6753 : * https://html.spec.whatwg.org/multipage/webappapis.html#microtask-queue
6754 : * https://html.spec.whatwg.org/multipage/webappapis.html#enqueuejob(queuename,-job,-arguments)
6755 : * https://html.spec.whatwg.org/multipage/webappapis.html#perform-a-microtask-checkpoint
6756 : *
6757 : * A MicrotaskQueue instance may be associated to multiple Contexts by passing
6758 : * it to Context::New(), and they can be detached by Context::DetachGlobal().
6759 : * The embedder must keep the MicrotaskQueue instance alive until all associated
6760 : * Contexts are gone or detached.
6761 : *
6762 : * Use the same instance of MicrotaskQueue for all Contexts that may access each
6763 : * other synchronously. E.g. for Web embedding, use the same instance for all
6764 : * origins that share the same URL scheme and eTLD+1.
6765 : */
6766 : class V8_EXPORT MicrotaskQueue {
6767 : public:
6768 : /**
6769 : * Creates an empty MicrotaskQueue instance.
6770 : */
6771 : static std::unique_ptr<MicrotaskQueue> New(
6772 : Isolate* isolate, MicrotasksPolicy policy = MicrotasksPolicy::kAuto);
6773 :
6774 62442 : virtual ~MicrotaskQueue() = default;
6775 :
6776 : /**
6777 : * Enqueues the callback to the queue.
6778 : */
6779 : virtual void EnqueueMicrotask(Isolate* isolate,
6780 : Local<Function> microtask) = 0;
6781 :
6782 : /**
6783 : * Enqueues the callback to the queue.
6784 : */
6785 : virtual void EnqueueMicrotask(v8::Isolate* isolate,
6786 : MicrotaskCallback callback,
6787 : void* data = nullptr) = 0;
6788 :
6789 : /**
6790 : * Adds a callback to notify the embedder after microtasks were run. The
6791 : * callback is triggered by explicit RunMicrotasks call or automatic
6792 : * microtasks execution (see Isolate::SetMicrotasksPolicy).
6793 : *
6794 : * Callback will trigger even if microtasks were attempted to run,
6795 : * but the microtasks queue was empty and no single microtask was actually
6796 : * executed.
6797 : *
6798 : * Executing scripts inside the callback will not re-trigger microtasks and
6799 : * the callback.
6800 : */
6801 : virtual void AddMicrotasksCompletedCallback(
6802 : MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
6803 :
6804 : /**
6805 : * Removes callback that was installed by AddMicrotasksCompletedCallback.
6806 : */
6807 : virtual void RemoveMicrotasksCompletedCallback(
6808 : MicrotasksCompletedCallbackWithData callback, void* data = nullptr) = 0;
6809 :
6810 : /**
6811 : * Runs microtasks if no microtask is running on this MicrotaskQueue instance.
6812 : */
6813 : virtual void PerformCheckpoint(Isolate* isolate) = 0;
6814 :
6815 : /**
6816 : * Returns true if a microtask is running on this MicrotaskQueue instance.
6817 : */
6818 : virtual bool IsRunningMicrotasks() const = 0;
6819 :
6820 : /**
6821 : * Returns the current depth of nested MicrotasksScope that has
6822 : * kRunMicrotasks.
6823 : */
6824 : virtual int GetMicrotasksScopeDepth() const = 0;
6825 :
6826 : private:
6827 : friend class internal::MicrotaskQueue;
6828 62455 : MicrotaskQueue() = default;
6829 : MicrotaskQueue(const MicrotaskQueue&) = delete;
6830 : MicrotaskQueue& operator=(const MicrotaskQueue&) = delete;
6831 : };
6832 :
6833 : /**
6834 : * This scope is used to control microtasks when kScopeMicrotasksInvocation
6835 : * is used on Isolate. In this mode every non-primitive call to V8 should be
6836 : * done inside some MicrotasksScope.
6837 : * Microtasks are executed when topmost MicrotasksScope marked as kRunMicrotasks
6838 : * exits.
6839 : * kDoNotRunMicrotasks should be used to annotate calls not intended to trigger
6840 : * microtasks.
6841 : */
6842 : class V8_EXPORT MicrotasksScope {
6843 : public:
6844 : enum Type { kRunMicrotasks, kDoNotRunMicrotasks };
6845 :
6846 : MicrotasksScope(Isolate* isolate, Type type);
6847 : MicrotasksScope(Isolate* isolate, MicrotaskQueue* microtask_queue, Type type);
6848 : ~MicrotasksScope();
6849 :
6850 : /**
6851 : * Runs microtasks if no kRunMicrotasks scope is currently active.
6852 : */
6853 : static void PerformCheckpoint(Isolate* isolate);
6854 :
6855 : /**
6856 : * Returns current depth of nested kRunMicrotasks scopes.
6857 : */
6858 : static int GetCurrentDepth(Isolate* isolate);
6859 :
6860 : /**
6861 : * Returns true while microtasks are being executed.
6862 : */
6863 : static bool IsRunningMicrotasks(Isolate* isolate);
6864 :
6865 : // Prevent copying.
6866 : MicrotasksScope(const MicrotasksScope&) = delete;
6867 : MicrotasksScope& operator=(const MicrotasksScope&) = delete;
6868 :
6869 : private:
6870 : internal::Isolate* const isolate_;
6871 : internal::MicrotaskQueue* const microtask_queue_;
6872 : bool run_;
6873 : };
6874 :
6875 :
6876 : // --- Failed Access Check Callback ---
6877 : typedef void (*FailedAccessCheckCallback)(Local<Object> target,
6878 : AccessType type,
6879 : Local<Value> data);
6880 :
6881 : // --- AllowCodeGenerationFromStrings callbacks ---
6882 :
6883 : /**
6884 : * Callback to check if code generation from strings is allowed. See
6885 : * Context::AllowCodeGenerationFromStrings.
6886 : */
6887 : typedef bool (*AllowCodeGenerationFromStringsCallback)(Local<Context> context,
6888 : Local<String> source);
6889 :
6890 : // --- WebAssembly compilation callbacks ---
6891 : typedef bool (*ExtensionCallback)(const FunctionCallbackInfo<Value>&);
6892 :
6893 : typedef bool (*AllowWasmCodeGenerationCallback)(Local<Context> context,
6894 : Local<String> source);
6895 :
6896 : // --- Callback for APIs defined on v8-supported objects, but implemented
6897 : // by the embedder. Example: WebAssembly.{compile|instantiate}Streaming ---
6898 : typedef void (*ApiImplementationCallback)(const FunctionCallbackInfo<Value>&);
6899 :
6900 : // --- Callback for WebAssembly.compileStreaming ---
6901 : typedef void (*WasmStreamingCallback)(const FunctionCallbackInfo<Value>&);
6902 :
6903 : // --- Callback for checking if WebAssembly threads are enabled ---
6904 : typedef bool (*WasmThreadsEnabledCallback)(Local<Context> context);
6905 :
6906 : // --- Garbage Collection Callbacks ---
6907 :
6908 : /**
6909 : * Applications can register callback functions which will be called before and
6910 : * after certain garbage collection operations. Allocations are not allowed in
6911 : * the callback functions, you therefore cannot manipulate objects (set or
6912 : * delete properties for example) since it is possible such operations will
6913 : * result in the allocation of objects.
6914 : */
6915 : enum GCType {
6916 : kGCTypeScavenge = 1 << 0,
6917 : kGCTypeMarkSweepCompact = 1 << 1,
6918 : kGCTypeIncrementalMarking = 1 << 2,
6919 : kGCTypeProcessWeakCallbacks = 1 << 3,
6920 : kGCTypeAll = kGCTypeScavenge | kGCTypeMarkSweepCompact |
6921 : kGCTypeIncrementalMarking | kGCTypeProcessWeakCallbacks
6922 : };
6923 :
6924 : /**
6925 : * GCCallbackFlags is used to notify additional information about the GC
6926 : * callback.
6927 : * - kGCCallbackFlagConstructRetainedObjectInfos: The GC callback is for
6928 : * constructing retained object infos.
6929 : * - kGCCallbackFlagForced: The GC callback is for a forced GC for testing.
6930 : * - kGCCallbackFlagSynchronousPhantomCallbackProcessing: The GC callback
6931 : * is called synchronously without getting posted to an idle task.
6932 : * - kGCCallbackFlagCollectAllAvailableGarbage: The GC callback is called
6933 : * in a phase where V8 is trying to collect all available garbage
6934 : * (e.g., handling a low memory notification).
6935 : * - kGCCallbackScheduleIdleGarbageCollection: The GC callback is called to
6936 : * trigger an idle garbage collection.
6937 : */
6938 : enum GCCallbackFlags {
6939 : kNoGCCallbackFlags = 0,
6940 : kGCCallbackFlagConstructRetainedObjectInfos = 1 << 1,
6941 : kGCCallbackFlagForced = 1 << 2,
6942 : kGCCallbackFlagSynchronousPhantomCallbackProcessing = 1 << 3,
6943 : kGCCallbackFlagCollectAllAvailableGarbage = 1 << 4,
6944 : kGCCallbackFlagCollectAllExternalMemory = 1 << 5,
6945 : kGCCallbackScheduleIdleGarbageCollection = 1 << 6,
6946 : };
6947 :
6948 : typedef void (*GCCallback)(GCType type, GCCallbackFlags flags);
6949 :
6950 : typedef void (*InterruptCallback)(Isolate* isolate, void* data);
6951 :
6952 : /**
6953 : * This callback is invoked when the heap size is close to the heap limit and
6954 : * V8 is likely to abort with out-of-memory error.
6955 : * The callback can extend the heap limit by returning a value that is greater
6956 : * than the current_heap_limit. The initial heap limit is the limit that was
6957 : * set after heap setup.
6958 : */
6959 : typedef size_t (*NearHeapLimitCallback)(void* data, size_t current_heap_limit,
6960 : size_t initial_heap_limit);
6961 :
6962 : /**
6963 : * Collection of V8 heap information.
6964 : *
6965 : * Instances of this class can be passed to v8::V8::HeapStatistics to
6966 : * get heap statistics from V8.
6967 : */
6968 : class V8_EXPORT HeapStatistics {
6969 : public:
6970 : HeapStatistics();
6971 : size_t total_heap_size() { return total_heap_size_; }
6972 : size_t total_heap_size_executable() { return total_heap_size_executable_; }
6973 : size_t total_physical_size() { return total_physical_size_; }
6974 : size_t total_available_size() { return total_available_size_; }
6975 : size_t used_heap_size() { return used_heap_size_; }
6976 : size_t heap_size_limit() { return heap_size_limit_; }
6977 : size_t malloced_memory() { return malloced_memory_; }
6978 : size_t external_memory() { return external_memory_; }
6979 : size_t peak_malloced_memory() { return peak_malloced_memory_; }
6980 : size_t number_of_native_contexts() { return number_of_native_contexts_; }
6981 : size_t number_of_detached_contexts() { return number_of_detached_contexts_; }
6982 :
6983 : /**
6984 : * Returns a 0/1 boolean, which signifies whether the V8 overwrite heap
6985 : * garbage with a bit pattern.
6986 : */
6987 : size_t does_zap_garbage() { return does_zap_garbage_; }
6988 :
6989 : private:
6990 : size_t total_heap_size_;
6991 : size_t total_heap_size_executable_;
6992 : size_t total_physical_size_;
6993 : size_t total_available_size_;
6994 : size_t used_heap_size_;
6995 : size_t heap_size_limit_;
6996 : size_t malloced_memory_;
6997 : size_t external_memory_;
6998 : size_t peak_malloced_memory_;
6999 : bool does_zap_garbage_;
7000 : size_t number_of_native_contexts_;
7001 : size_t number_of_detached_contexts_;
7002 :
7003 : friend class V8;
7004 : friend class Isolate;
7005 : };
7006 :
7007 :
7008 : class V8_EXPORT HeapSpaceStatistics {
7009 : public:
7010 : HeapSpaceStatistics();
7011 : const char* space_name() { return space_name_; }
7012 : size_t space_size() { return space_size_; }
7013 : size_t space_used_size() { return space_used_size_; }
7014 : size_t space_available_size() { return space_available_size_; }
7015 : size_t physical_space_size() { return physical_space_size_; }
7016 :
7017 : private:
7018 : const char* space_name_;
7019 : size_t space_size_;
7020 : size_t space_used_size_;
7021 : size_t space_available_size_;
7022 : size_t physical_space_size_;
7023 :
7024 : friend class Isolate;
7025 : };
7026 :
7027 :
7028 : class V8_EXPORT HeapObjectStatistics {
7029 : public:
7030 : HeapObjectStatistics();
7031 : const char* object_type() { return object_type_; }
7032 : const char* object_sub_type() { return object_sub_type_; }
7033 : size_t object_count() { return object_count_; }
7034 : size_t object_size() { return object_size_; }
7035 :
7036 : private:
7037 : const char* object_type_;
7038 : const char* object_sub_type_;
7039 : size_t object_count_;
7040 : size_t object_size_;
7041 :
7042 : friend class Isolate;
7043 : };
7044 :
7045 : class V8_EXPORT HeapCodeStatistics {
7046 : public:
7047 : HeapCodeStatistics();
7048 : size_t code_and_metadata_size() { return code_and_metadata_size_; }
7049 : size_t bytecode_and_metadata_size() { return bytecode_and_metadata_size_; }
7050 : size_t external_script_source_size() { return external_script_source_size_; }
7051 :
7052 : private:
7053 : size_t code_and_metadata_size_;
7054 : size_t bytecode_and_metadata_size_;
7055 : size_t external_script_source_size_;
7056 :
7057 : friend class Isolate;
7058 : };
7059 :
7060 : /**
7061 : * A JIT code event is issued each time code is added, moved or removed.
7062 : *
7063 : * \note removal events are not currently issued.
7064 : */
7065 : struct JitCodeEvent {
7066 : enum EventType {
7067 : CODE_ADDED,
7068 : CODE_MOVED,
7069 : CODE_REMOVED,
7070 : CODE_ADD_LINE_POS_INFO,
7071 : CODE_START_LINE_INFO_RECORDING,
7072 : CODE_END_LINE_INFO_RECORDING
7073 : };
7074 : // Definition of the code position type. The "POSITION" type means the place
7075 : // in the source code which are of interest when making stack traces to
7076 : // pin-point the source location of a stack frame as close as possible.
7077 : // The "STATEMENT_POSITION" means the place at the beginning of each
7078 : // statement, and is used to indicate possible break locations.
7079 : enum PositionType { POSITION, STATEMENT_POSITION };
7080 :
7081 : // There are two different kinds of JitCodeEvents, one for JIT code generated
7082 : // by the optimizing compiler, and one for byte code generated for the
7083 : // interpreter. For JIT_CODE events, the |code_start| member of the event
7084 : // points to the beginning of jitted assembly code, while for BYTE_CODE
7085 : // events, |code_start| points to the first bytecode of the interpreted
7086 : // function.
7087 : enum CodeType { BYTE_CODE, JIT_CODE };
7088 :
7089 : // Type of event.
7090 : EventType type;
7091 : CodeType code_type;
7092 : // Start of the instructions.
7093 : void* code_start;
7094 : // Size of the instructions.
7095 : size_t code_len;
7096 : // Script info for CODE_ADDED event.
7097 : Local<UnboundScript> script;
7098 : // User-defined data for *_LINE_INFO_* event. It's used to hold the source
7099 : // code line information which is returned from the
7100 : // CODE_START_LINE_INFO_RECORDING event. And it's passed to subsequent
7101 : // CODE_ADD_LINE_POS_INFO and CODE_END_LINE_INFO_RECORDING events.
7102 : void* user_data;
7103 :
7104 : struct name_t {
7105 : // Name of the object associated with the code, note that the string is not
7106 : // zero-terminated.
7107 : const char* str;
7108 : // Number of chars in str.
7109 : size_t len;
7110 : };
7111 :
7112 : struct line_info_t {
7113 : // PC offset
7114 : size_t offset;
7115 : // Code position
7116 : size_t pos;
7117 : // The position type.
7118 : PositionType position_type;
7119 : };
7120 :
7121 : union {
7122 : // Only valid for CODE_ADDED.
7123 : struct name_t name;
7124 :
7125 : // Only valid for CODE_ADD_LINE_POS_INFO
7126 : struct line_info_t line_info;
7127 :
7128 : // New location of instructions. Only valid for CODE_MOVED.
7129 : void* new_code_start;
7130 : };
7131 :
7132 : Isolate* isolate;
7133 : };
7134 :
7135 : /**
7136 : * Option flags passed to the SetRAILMode function.
7137 : * See documentation https://developers.google.com/web/tools/chrome-devtools/
7138 : * profile/evaluate-performance/rail
7139 : */
7140 : enum RAILMode : unsigned {
7141 : // Response performance mode: In this mode very low virtual machine latency
7142 : // is provided. V8 will try to avoid JavaScript execution interruptions.
7143 : // Throughput may be throttled.
7144 : PERFORMANCE_RESPONSE,
7145 : // Animation performance mode: In this mode low virtual machine latency is
7146 : // provided. V8 will try to avoid as many JavaScript execution interruptions
7147 : // as possible. Throughput may be throttled. This is the default mode.
7148 : PERFORMANCE_ANIMATION,
7149 : // Idle performance mode: The embedder is idle. V8 can complete deferred work
7150 : // in this mode.
7151 : PERFORMANCE_IDLE,
7152 : // Load performance mode: In this mode high throughput is provided. V8 may
7153 : // turn off latency optimizations.
7154 : PERFORMANCE_LOAD
7155 : };
7156 :
7157 : /**
7158 : * Option flags passed to the SetJitCodeEventHandler function.
7159 : */
7160 : enum JitCodeEventOptions {
7161 : kJitCodeEventDefault = 0,
7162 : // Generate callbacks for already existent code.
7163 : kJitCodeEventEnumExisting = 1
7164 : };
7165 :
7166 :
7167 : /**
7168 : * Callback function passed to SetJitCodeEventHandler.
7169 : *
7170 : * \param event code add, move or removal event.
7171 : */
7172 : typedef void (*JitCodeEventHandler)(const JitCodeEvent* event);
7173 :
7174 : /**
7175 : * Callback function passed to SetUnhandledExceptionCallback.
7176 : */
7177 : #if defined(V8_OS_WIN)
7178 : typedef int (*UnhandledExceptionCallback)(
7179 : _EXCEPTION_POINTERS* exception_pointers);
7180 : #endif
7181 :
7182 : /**
7183 : * Interface for iterating through all external resources in the heap.
7184 : */
7185 5 : class V8_EXPORT ExternalResourceVisitor { // NOLINT
7186 : public:
7187 5 : virtual ~ExternalResourceVisitor() = default;
7188 0 : virtual void VisitExternalString(Local<String> string) {}
7189 : };
7190 :
7191 :
7192 : /**
7193 : * Interface for iterating through all the persistent handles in the heap.
7194 : */
7195 10 : class V8_EXPORT PersistentHandleVisitor { // NOLINT
7196 : public:
7197 10 : virtual ~PersistentHandleVisitor() = default;
7198 0 : virtual void VisitPersistentHandle(Persistent<Value>* value,
7199 0 : uint16_t class_id) {}
7200 : };
7201 :
7202 : /**
7203 : * Memory pressure level for the MemoryPressureNotification.
7204 : * kNone hints V8 that there is no memory pressure.
7205 : * kModerate hints V8 to speed up incremental garbage collection at the cost of
7206 : * of higher latency due to garbage collection pauses.
7207 : * kCritical hints V8 to free memory as soon as possible. Garbage collection
7208 : * pauses at this level will be large.
7209 : */
7210 : enum class MemoryPressureLevel { kNone, kModerate, kCritical };
7211 :
7212 : /**
7213 : * Interface for tracing through the embedder heap. During a V8 garbage
7214 : * collection, V8 collects hidden fields of all potential wrappers, and at the
7215 : * end of its marking phase iterates the collection and asks the embedder to
7216 : * trace through its heap and use reporter to report each JavaScript object
7217 : * reachable from any of the given wrappers.
7218 : */
7219 89 : class V8_EXPORT EmbedderHeapTracer {
7220 : public:
7221 : // Indicator for the stack state of the embedder.
7222 : enum EmbedderStackState {
7223 : kUnknown,
7224 : kNonEmpty,
7225 : kEmpty,
7226 : };
7227 :
7228 : /**
7229 : * Interface for iterating through TracedGlobal handles.
7230 : */
7231 : class V8_EXPORT TracedGlobalHandleVisitor {
7232 : public:
7233 5 : virtual ~TracedGlobalHandleVisitor() = default;
7234 : virtual void VisitTracedGlobalHandle(const TracedGlobal<Value>& value) = 0;
7235 : };
7236 :
7237 89 : virtual ~EmbedderHeapTracer() = default;
7238 :
7239 : /**
7240 : * Iterates all TracedGlobal handles created for the v8::Isolate the tracer is
7241 : * attached to.
7242 : */
7243 : void IterateTracedGlobalHandles(TracedGlobalHandleVisitor* visitor);
7244 :
7245 : /**
7246 : * Called by v8 to register internal fields of found wrappers.
7247 : *
7248 : * The embedder is expected to store them somewhere and trace reachable
7249 : * wrappers from them when called through |AdvanceTracing|.
7250 : */
7251 : virtual void RegisterV8References(
7252 : const std::vector<std::pair<void*, void*> >& embedder_fields) = 0;
7253 :
7254 : void RegisterEmbedderReference(const TracedGlobal<v8::Value>& ref);
7255 :
7256 : /**
7257 : * Called at the beginning of a GC cycle.
7258 : */
7259 : virtual void TracePrologue() = 0;
7260 :
7261 : /**
7262 : * Called to advance tracing in the embedder.
7263 : *
7264 : * The embedder is expected to trace its heap starting from wrappers reported
7265 : * by RegisterV8References method, and report back all reachable wrappers.
7266 : * Furthermore, the embedder is expected to stop tracing by the given
7267 : * deadline. A deadline of infinity means that tracing should be finished.
7268 : *
7269 : * Returns |true| if tracing is done, and false otherwise.
7270 : */
7271 : virtual bool AdvanceTracing(double deadline_in_ms) = 0;
7272 :
7273 : /*
7274 : * Returns true if there no more tracing work to be done (see AdvanceTracing)
7275 : * and false otherwise.
7276 : */
7277 : virtual bool IsTracingDone() = 0;
7278 :
7279 : /**
7280 : * Called at the end of a GC cycle.
7281 : *
7282 : * Note that allocation is *not* allowed within |TraceEpilogue|.
7283 : */
7284 : virtual void TraceEpilogue() = 0;
7285 :
7286 : /**
7287 : * Called upon entering the final marking pause. No more incremental marking
7288 : * steps will follow this call.
7289 : */
7290 : virtual void EnterFinalPause(EmbedderStackState stack_state) = 0;
7291 :
7292 : /*
7293 : * Called by the embedder to request immediate finalization of the currently
7294 : * running tracing phase that has been started with TracePrologue and not
7295 : * yet finished with TraceEpilogue.
7296 : *
7297 : * Will be a noop when currently not in tracing.
7298 : *
7299 : * This is an experimental feature.
7300 : */
7301 : void FinalizeTracing();
7302 :
7303 : /**
7304 : * Returns true if the TracedGlobal handle should be considered as root for
7305 : * the currently running non-tracing garbage collection and false otherwise.
7306 : *
7307 : * Default implementation will keep all TracedGlobal references as roots.
7308 : */
7309 0 : virtual bool IsRootForNonTracingGC(
7310 : const v8::TracedGlobal<v8::Value>& handle) {
7311 0 : return true;
7312 : }
7313 :
7314 : /*
7315 : * Called by the embedder to immediately perform a full garbage collection.
7316 : *
7317 : * Should only be used in testing code.
7318 : */
7319 : void GarbageCollectionForTesting(EmbedderStackState stack_state);
7320 :
7321 : /*
7322 : * Returns the v8::Isolate this tracer is attached too and |nullptr| if it
7323 : * is not attached to any v8::Isolate.
7324 : */
7325 : v8::Isolate* isolate() const { return isolate_; }
7326 :
7327 : protected:
7328 : v8::Isolate* isolate_ = nullptr;
7329 :
7330 : friend class internal::LocalEmbedderHeapTracer;
7331 : };
7332 :
7333 : /**
7334 : * Callback and supporting data used in SnapshotCreator to implement embedder
7335 : * logic to serialize internal fields.
7336 : * Internal fields that directly reference V8 objects are serialized without
7337 : * calling this callback. Internal fields that contain aligned pointers are
7338 : * serialized by this callback if it returns non-zero result. Otherwise it is
7339 : * serialized verbatim.
7340 : */
7341 : struct SerializeInternalFieldsCallback {
7342 : typedef StartupData (*CallbackFunction)(Local<Object> holder, int index,
7343 : void* data);
7344 : SerializeInternalFieldsCallback(CallbackFunction function = nullptr,
7345 : void* data_arg = nullptr)
7346 432 : : callback(function), data(data_arg) {}
7347 : CallbackFunction callback;
7348 : void* data;
7349 : };
7350 : // Note that these fields are called "internal fields" in the API and called
7351 : // "embedder fields" within V8.
7352 : typedef SerializeInternalFieldsCallback SerializeEmbedderFieldsCallback;
7353 :
7354 : /**
7355 : * Callback and supporting data used to implement embedder logic to deserialize
7356 : * internal fields.
7357 : */
7358 : struct DeserializeInternalFieldsCallback {
7359 : typedef void (*CallbackFunction)(Local<Object> holder, int index,
7360 : StartupData payload, void* data);
7361 : DeserializeInternalFieldsCallback(CallbackFunction function = nullptr,
7362 : void* data_arg = nullptr)
7363 89430 : : callback(function), data(data_arg) {}
7364 : void (*callback)(Local<Object> holder, int index, StartupData payload,
7365 : void* data);
7366 : void* data;
7367 : };
7368 : typedef DeserializeInternalFieldsCallback DeserializeEmbedderFieldsCallback;
7369 :
7370 : /**
7371 : * Isolate represents an isolated instance of the V8 engine. V8 isolates have
7372 : * completely separate states. Objects from one isolate must not be used in
7373 : * other isolates. The embedder can create multiple isolates and use them in
7374 : * parallel in multiple threads. An isolate can be entered by at most one
7375 : * thread at any given time. The Locker/Unlocker API must be used to
7376 : * synchronize.
7377 : */
7378 : class V8_EXPORT Isolate {
7379 : public:
7380 : /**
7381 : * Initial configuration parameters for a new Isolate.
7382 : */
7383 : struct CreateParams {
7384 : CreateParams()
7385 : : code_event_handler(nullptr),
7386 : snapshot_blob(nullptr),
7387 : counter_lookup_callback(nullptr),
7388 : create_histogram_callback(nullptr),
7389 : add_histogram_sample_callback(nullptr),
7390 : array_buffer_allocator(nullptr),
7391 : external_references(nullptr),
7392 : allow_atomics_wait(true),
7393 59543 : only_terminate_in_safe_scope(false) {}
7394 :
7395 : /**
7396 : * Allows the host application to provide the address of a function that is
7397 : * notified each time code is added, moved or removed.
7398 : */
7399 : JitCodeEventHandler code_event_handler;
7400 :
7401 : /**
7402 : * ResourceConstraints to use for the new Isolate.
7403 : */
7404 : ResourceConstraints constraints;
7405 :
7406 : /**
7407 : * Explicitly specify a startup snapshot blob. The embedder owns the blob.
7408 : */
7409 : StartupData* snapshot_blob;
7410 :
7411 :
7412 : /**
7413 : * Enables the host application to provide a mechanism for recording
7414 : * statistics counters.
7415 : */
7416 : CounterLookupCallback counter_lookup_callback;
7417 :
7418 : /**
7419 : * Enables the host application to provide a mechanism for recording
7420 : * histograms. The CreateHistogram function returns a
7421 : * histogram which will later be passed to the AddHistogramSample
7422 : * function.
7423 : */
7424 : CreateHistogramCallback create_histogram_callback;
7425 : AddHistogramSampleCallback add_histogram_sample_callback;
7426 :
7427 : /**
7428 : * The ArrayBuffer::Allocator to use for allocating and freeing the backing
7429 : * store of ArrayBuffers.
7430 : */
7431 : ArrayBuffer::Allocator* array_buffer_allocator;
7432 :
7433 : /**
7434 : * Specifies an optional nullptr-terminated array of raw addresses in the
7435 : * embedder that V8 can match against during serialization and use for
7436 : * deserialization. This array and its content must stay valid for the
7437 : * entire lifetime of the isolate.
7438 : */
7439 : const intptr_t* external_references;
7440 :
7441 : /**
7442 : * Whether calling Atomics.wait (a function that may block) is allowed in
7443 : * this isolate. This can also be configured via SetAllowAtomicsWait.
7444 : */
7445 : bool allow_atomics_wait;
7446 :
7447 : /**
7448 : * Termination is postponed when there is no active SafeForTerminationScope.
7449 : */
7450 : bool only_terminate_in_safe_scope;
7451 : };
7452 :
7453 :
7454 : /**
7455 : * Stack-allocated class which sets the isolate for all operations
7456 : * executed within a local scope.
7457 : */
7458 : class V8_EXPORT Scope {
7459 : public:
7460 1325 : explicit Scope(Isolate* isolate) : isolate_(isolate) {
7461 39851 : isolate->Enter();
7462 : }
7463 :
7464 39851 : ~Scope() { isolate_->Exit(); }
7465 :
7466 : // Prevent copying of Scope objects.
7467 : Scope(const Scope&) = delete;
7468 : Scope& operator=(const Scope&) = delete;
7469 :
7470 : private:
7471 : Isolate* const isolate_;
7472 : };
7473 :
7474 :
7475 : /**
7476 : * Assert that no Javascript code is invoked.
7477 : */
7478 : class V8_EXPORT DisallowJavascriptExecutionScope {
7479 : public:
7480 : enum OnFailure { CRASH_ON_FAILURE, THROW_ON_FAILURE, DUMP_ON_FAILURE };
7481 :
7482 : DisallowJavascriptExecutionScope(Isolate* isolate, OnFailure on_failure);
7483 : ~DisallowJavascriptExecutionScope();
7484 :
7485 : // Prevent copying of Scope objects.
7486 : DisallowJavascriptExecutionScope(const DisallowJavascriptExecutionScope&) =
7487 : delete;
7488 : DisallowJavascriptExecutionScope& operator=(
7489 : const DisallowJavascriptExecutionScope&) = delete;
7490 :
7491 : private:
7492 : OnFailure on_failure_;
7493 : void* internal_;
7494 : };
7495 :
7496 :
7497 : /**
7498 : * Introduce exception to DisallowJavascriptExecutionScope.
7499 : */
7500 : class V8_EXPORT AllowJavascriptExecutionScope {
7501 : public:
7502 : explicit AllowJavascriptExecutionScope(Isolate* isolate);
7503 : ~AllowJavascriptExecutionScope();
7504 :
7505 : // Prevent copying of Scope objects.
7506 : AllowJavascriptExecutionScope(const AllowJavascriptExecutionScope&) =
7507 : delete;
7508 : AllowJavascriptExecutionScope& operator=(
7509 : const AllowJavascriptExecutionScope&) = delete;
7510 :
7511 : private:
7512 : void* internal_throws_;
7513 : void* internal_assert_;
7514 : void* internal_dump_;
7515 : };
7516 :
7517 : /**
7518 : * Do not run microtasks while this scope is active, even if microtasks are
7519 : * automatically executed otherwise.
7520 : */
7521 : class V8_EXPORT SuppressMicrotaskExecutionScope {
7522 : public:
7523 : explicit SuppressMicrotaskExecutionScope(Isolate* isolate);
7524 : explicit SuppressMicrotaskExecutionScope(MicrotaskQueue* microtask_queue);
7525 : ~SuppressMicrotaskExecutionScope();
7526 :
7527 : // Prevent copying of Scope objects.
7528 : SuppressMicrotaskExecutionScope(const SuppressMicrotaskExecutionScope&) =
7529 : delete;
7530 : SuppressMicrotaskExecutionScope& operator=(
7531 : const SuppressMicrotaskExecutionScope&) = delete;
7532 :
7533 : private:
7534 : internal::Isolate* const isolate_;
7535 : internal::MicrotaskQueue* const microtask_queue_;
7536 : };
7537 :
7538 : /**
7539 : * This scope allows terminations inside direct V8 API calls and forbid them
7540 : * inside any recursice API calls without explicit SafeForTerminationScope.
7541 : */
7542 : class V8_EXPORT SafeForTerminationScope {
7543 : public:
7544 : explicit SafeForTerminationScope(v8::Isolate* isolate);
7545 : ~SafeForTerminationScope();
7546 :
7547 : // Prevent copying of Scope objects.
7548 : SafeForTerminationScope(const SafeForTerminationScope&) = delete;
7549 : SafeForTerminationScope& operator=(const SafeForTerminationScope&) = delete;
7550 :
7551 : private:
7552 : internal::Isolate* isolate_;
7553 : bool prev_value_;
7554 : };
7555 :
7556 : /**
7557 : * Types of garbage collections that can be requested via
7558 : * RequestGarbageCollectionForTesting.
7559 : */
7560 : enum GarbageCollectionType {
7561 : kFullGarbageCollection,
7562 : kMinorGarbageCollection
7563 : };
7564 :
7565 : /**
7566 : * Features reported via the SetUseCounterCallback callback. Do not change
7567 : * assigned numbers of existing items; add new features to the end of this
7568 : * list.
7569 : */
7570 : enum UseCounterFeature {
7571 : kUseAsm = 0,
7572 : kBreakIterator = 1,
7573 : kLegacyConst = 2,
7574 : kMarkDequeOverflow = 3,
7575 : kStoreBufferOverflow = 4,
7576 : kSlotsBufferOverflow = 5,
7577 : kObjectObserve = 6,
7578 : kForcedGC = 7,
7579 : kSloppyMode = 8,
7580 : kStrictMode = 9,
7581 : kStrongMode = 10,
7582 : kRegExpPrototypeStickyGetter = 11,
7583 : kRegExpPrototypeToString = 12,
7584 : kRegExpPrototypeUnicodeGetter = 13,
7585 : kIntlV8Parse = 14,
7586 : kIntlPattern = 15,
7587 : kIntlResolved = 16,
7588 : kPromiseChain = 17,
7589 : kPromiseAccept = 18,
7590 : kPromiseDefer = 19,
7591 : kHtmlCommentInExternalScript = 20,
7592 : kHtmlComment = 21,
7593 : kSloppyModeBlockScopedFunctionRedefinition = 22,
7594 : kForInInitializer = 23,
7595 : kArrayProtectorDirtied = 24,
7596 : kArraySpeciesModified = 25,
7597 : kArrayPrototypeConstructorModified = 26,
7598 : kArrayInstanceProtoModified = 27,
7599 : kArrayInstanceConstructorModified = 28,
7600 : kLegacyFunctionDeclaration = 29,
7601 : kRegExpPrototypeSourceGetter = 30,
7602 : kRegExpPrototypeOldFlagGetter = 31,
7603 : kDecimalWithLeadingZeroInStrictMode = 32,
7604 : kLegacyDateParser = 33,
7605 : kDefineGetterOrSetterWouldThrow = 34,
7606 : kFunctionConstructorReturnedUndefined = 35,
7607 : kAssigmentExpressionLHSIsCallInSloppy = 36,
7608 : kAssigmentExpressionLHSIsCallInStrict = 37,
7609 : kPromiseConstructorReturnedUndefined = 38,
7610 : kConstructorNonUndefinedPrimitiveReturn = 39,
7611 : kLabeledExpressionStatement = 40,
7612 : kLineOrParagraphSeparatorAsLineTerminator = 41,
7613 : kIndexAccessor = 42,
7614 : kErrorCaptureStackTrace = 43,
7615 : kErrorPrepareStackTrace = 44,
7616 : kErrorStackTraceLimit = 45,
7617 : kWebAssemblyInstantiation = 46,
7618 : kDeoptimizerDisableSpeculation = 47,
7619 : kArrayPrototypeSortJSArrayModifiedPrototype = 48,
7620 : kFunctionTokenOffsetTooLongForToString = 49,
7621 : kWasmSharedMemory = 50,
7622 : kWasmThreadOpcodes = 51,
7623 : kAtomicsNotify = 52,
7624 : kAtomicsWake = 53,
7625 : kCollator = 54,
7626 : kNumberFormat = 55,
7627 : kDateTimeFormat = 56,
7628 : kPluralRules = 57,
7629 : kRelativeTimeFormat = 58,
7630 : kLocale = 59,
7631 : kListFormat = 60,
7632 : kSegmenter = 61,
7633 : kStringLocaleCompare = 62,
7634 : kStringToLocaleUpperCase = 63,
7635 : kStringToLocaleLowerCase = 64,
7636 : kNumberToLocaleString = 65,
7637 : kDateToLocaleString = 66,
7638 : kDateToLocaleDateString = 67,
7639 : kDateToLocaleTimeString = 68,
7640 : kAttemptOverrideReadOnlyOnPrototypeSloppy = 69,
7641 : kAttemptOverrideReadOnlyOnPrototypeStrict = 70,
7642 : kOptimizedFunctionWithOneShotBytecode = 71,
7643 : kRegExpMatchIsTrueishOnNonJSRegExp = 72,
7644 : kRegExpMatchIsFalseishOnJSRegExp = 73,
7645 : kDateGetTimezoneOffset = 74,
7646 : kStringNormalize = 75,
7647 :
7648 : // If you add new values here, you'll also need to update Chromium's:
7649 : // web_feature.mojom, UseCounterCallback.cpp, and enums.xml. V8 changes to
7650 : // this list need to be landed first, then changes on the Chromium side.
7651 : kUseCounterFeatureCount // This enum value must be last.
7652 : };
7653 :
7654 : enum MessageErrorLevel {
7655 : kMessageLog = (1 << 0),
7656 : kMessageDebug = (1 << 1),
7657 : kMessageInfo = (1 << 2),
7658 : kMessageError = (1 << 3),
7659 : kMessageWarning = (1 << 4),
7660 : kMessageAll = kMessageLog | kMessageDebug | kMessageInfo | kMessageError |
7661 : kMessageWarning,
7662 : };
7663 :
7664 : typedef void (*UseCounterCallback)(Isolate* isolate,
7665 : UseCounterFeature feature);
7666 :
7667 : /**
7668 : * Allocates a new isolate but does not initialize it. Does not change the
7669 : * currently entered isolate.
7670 : *
7671 : * Only Isolate::GetData() and Isolate::SetData(), which access the
7672 : * embedder-controlled parts of the isolate, are allowed to be called on the
7673 : * uninitialized isolate. To initialize the isolate, call
7674 : * Isolate::Initialize().
7675 : *
7676 : * When an isolate is no longer used its resources should be freed
7677 : * by calling Dispose(). Using the delete operator is not allowed.
7678 : *
7679 : * V8::Initialize() must have run prior to this.
7680 : */
7681 : static Isolate* Allocate();
7682 :
7683 : /**
7684 : * Initialize an Isolate previously allocated by Isolate::Allocate().
7685 : */
7686 : static void Initialize(Isolate* isolate, const CreateParams& params);
7687 :
7688 : /**
7689 : * Creates a new isolate. Does not change the currently entered
7690 : * isolate.
7691 : *
7692 : * When an isolate is no longer used its resources should be freed
7693 : * by calling Dispose(). Using the delete operator is not allowed.
7694 : *
7695 : * V8::Initialize() must have run prior to this.
7696 : */
7697 : static Isolate* New(const CreateParams& params);
7698 :
7699 : /**
7700 : * Returns the entered isolate for the current thread or NULL in
7701 : * case there is no current isolate.
7702 : *
7703 : * This method must not be invoked before V8::Initialize() was invoked.
7704 : */
7705 : static Isolate* GetCurrent();
7706 :
7707 : /**
7708 : * Custom callback used by embedders to help V8 determine if it should abort
7709 : * when it throws and no internal handler is predicted to catch the
7710 : * exception. If --abort-on-uncaught-exception is used on the command line,
7711 : * then V8 will abort if either:
7712 : * - no custom callback is set.
7713 : * - the custom callback set returns true.
7714 : * Otherwise, the custom callback will not be called and V8 will not abort.
7715 : */
7716 : typedef bool (*AbortOnUncaughtExceptionCallback)(Isolate*);
7717 : void SetAbortOnUncaughtExceptionCallback(
7718 : AbortOnUncaughtExceptionCallback callback);
7719 :
7720 : /**
7721 : * This specifies the callback called by the upcoming dynamic
7722 : * import() language feature to load modules.
7723 : */
7724 : void SetHostImportModuleDynamicallyCallback(
7725 : HostImportModuleDynamicallyCallback callback);
7726 :
7727 : /**
7728 : * This specifies the callback called by the upcoming importa.meta
7729 : * language feature to retrieve host-defined meta data for a module.
7730 : */
7731 : void SetHostInitializeImportMetaObjectCallback(
7732 : HostInitializeImportMetaObjectCallback callback);
7733 :
7734 : /**
7735 : * This specifies the callback called when the stack property of Error
7736 : * is accessed.
7737 : */
7738 : void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback);
7739 :
7740 : /**
7741 : * Optional notification that the system is running low on memory.
7742 : * V8 uses these notifications to guide heuristics.
7743 : * It is allowed to call this function from another thread while
7744 : * the isolate is executing long running JavaScript code.
7745 : */
7746 : void MemoryPressureNotification(MemoryPressureLevel level);
7747 :
7748 : /**
7749 : * Methods below this point require holding a lock (using Locker) in
7750 : * a multi-threaded environment.
7751 : */
7752 :
7753 : /**
7754 : * Sets this isolate as the entered one for the current thread.
7755 : * Saves the previously entered one (if any), so that it can be
7756 : * restored when exiting. Re-entering an isolate is allowed.
7757 : */
7758 : void Enter();
7759 :
7760 : /**
7761 : * Exits this isolate by restoring the previously entered one in the
7762 : * current thread. The isolate may still stay the same, if it was
7763 : * entered more than once.
7764 : *
7765 : * Requires: this == Isolate::GetCurrent().
7766 : */
7767 : void Exit();
7768 :
7769 : /**
7770 : * Disposes the isolate. The isolate must not be entered by any
7771 : * thread to be disposable.
7772 : */
7773 : void Dispose();
7774 :
7775 : /**
7776 : * Dumps activated low-level V8 internal stats. This can be used instead
7777 : * of performing a full isolate disposal.
7778 : */
7779 : void DumpAndResetStats();
7780 :
7781 : /**
7782 : * Discards all V8 thread-specific data for the Isolate. Should be used
7783 : * if a thread is terminating and it has used an Isolate that will outlive
7784 : * the thread -- all thread-specific data for an Isolate is discarded when
7785 : * an Isolate is disposed so this call is pointless if an Isolate is about
7786 : * to be Disposed.
7787 : */
7788 : void DiscardThreadSpecificMetadata();
7789 :
7790 : /**
7791 : * Associate embedder-specific data with the isolate. |slot| has to be
7792 : * between 0 and GetNumberOfDataSlots() - 1.
7793 : */
7794 : V8_INLINE void SetData(uint32_t slot, void* data);
7795 :
7796 : /**
7797 : * Retrieve embedder-specific data from the isolate.
7798 : * Returns NULL if SetData has never been called for the given |slot|.
7799 : */
7800 : V8_INLINE void* GetData(uint32_t slot);
7801 :
7802 : /**
7803 : * Returns the maximum number of available embedder data slots. Valid slots
7804 : * are in the range of 0 - GetNumberOfDataSlots() - 1.
7805 : */
7806 : V8_INLINE static uint32_t GetNumberOfDataSlots();
7807 :
7808 : /**
7809 : * Return data that was previously attached to the isolate snapshot via
7810 : * SnapshotCreator, and removes the reference to it.
7811 : * Repeated call with the same index returns an empty MaybeLocal.
7812 : */
7813 : template <class T>
7814 : V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
7815 :
7816 : /**
7817 : * Get statistics about the heap memory usage.
7818 : */
7819 : void GetHeapStatistics(HeapStatistics* heap_statistics);
7820 :
7821 : /**
7822 : * Returns the number of spaces in the heap.
7823 : */
7824 : size_t NumberOfHeapSpaces();
7825 :
7826 : /**
7827 : * Get the memory usage of a space in the heap.
7828 : *
7829 : * \param space_statistics The HeapSpaceStatistics object to fill in
7830 : * statistics.
7831 : * \param index The index of the space to get statistics from, which ranges
7832 : * from 0 to NumberOfHeapSpaces() - 1.
7833 : * \returns true on success.
7834 : */
7835 : bool GetHeapSpaceStatistics(HeapSpaceStatistics* space_statistics,
7836 : size_t index);
7837 :
7838 : /**
7839 : * Returns the number of types of objects tracked in the heap at GC.
7840 : */
7841 : size_t NumberOfTrackedHeapObjectTypes();
7842 :
7843 : /**
7844 : * Get statistics about objects in the heap.
7845 : *
7846 : * \param object_statistics The HeapObjectStatistics object to fill in
7847 : * statistics of objects of given type, which were live in the previous GC.
7848 : * \param type_index The index of the type of object to fill details about,
7849 : * which ranges from 0 to NumberOfTrackedHeapObjectTypes() - 1.
7850 : * \returns true on success.
7851 : */
7852 : bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics* object_statistics,
7853 : size_t type_index);
7854 :
7855 : /**
7856 : * Get statistics about code and its metadata in the heap.
7857 : *
7858 : * \param object_statistics The HeapCodeStatistics object to fill in
7859 : * statistics of code, bytecode and their metadata.
7860 : * \returns true on success.
7861 : */
7862 : bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics* object_statistics);
7863 :
7864 : /**
7865 : * Get a call stack sample from the isolate.
7866 : * \param state Execution state.
7867 : * \param frames Caller allocated buffer to store stack frames.
7868 : * \param frames_limit Maximum number of frames to capture. The buffer must
7869 : * be large enough to hold the number of frames.
7870 : * \param sample_info The sample info is filled up by the function
7871 : * provides number of actual captured stack frames and
7872 : * the current VM state.
7873 : * \note GetStackSample should only be called when the JS thread is paused or
7874 : * interrupted. Otherwise the behavior is undefined.
7875 : */
7876 : void GetStackSample(const RegisterState& state, void** frames,
7877 : size_t frames_limit, SampleInfo* sample_info);
7878 :
7879 : /**
7880 : * Adjusts the amount of registered external memory. Used to give V8 an
7881 : * indication of the amount of externally allocated memory that is kept alive
7882 : * by JavaScript objects. V8 uses this to decide when to perform global
7883 : * garbage collections. Registering externally allocated memory will trigger
7884 : * global garbage collections more often than it would otherwise in an attempt
7885 : * to garbage collect the JavaScript objects that keep the externally
7886 : * allocated memory alive.
7887 : *
7888 : * \param change_in_bytes the change in externally allocated memory that is
7889 : * kept alive by JavaScript objects.
7890 : * \returns the adjusted value.
7891 : */
7892 : V8_INLINE int64_t
7893 : AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes);
7894 :
7895 : /**
7896 : * Returns the number of phantom handles without callbacks that were reset
7897 : * by the garbage collector since the last call to this function.
7898 : */
7899 : size_t NumberOfPhantomHandleResetsSinceLastCall();
7900 :
7901 : /**
7902 : * Returns heap profiler for this isolate. Will return NULL until the isolate
7903 : * is initialized.
7904 : */
7905 : HeapProfiler* GetHeapProfiler();
7906 :
7907 : /**
7908 : * Tells the VM whether the embedder is idle or not.
7909 : */
7910 : void SetIdle(bool is_idle);
7911 :
7912 : /** Returns the ArrayBuffer::Allocator used in this isolate. */
7913 : ArrayBuffer::Allocator* GetArrayBufferAllocator();
7914 :
7915 : /** Returns true if this isolate has a current context. */
7916 : bool InContext();
7917 :
7918 : /**
7919 : * Returns the context of the currently running JavaScript, or the context
7920 : * on the top of the stack if no JavaScript is running.
7921 : */
7922 : Local<Context> GetCurrentContext();
7923 :
7924 : /** Returns the last context entered through V8's C++ API. */
7925 : V8_DEPRECATED("Use GetEnteredOrMicrotaskContext().",
7926 : Local<Context> GetEnteredContext());
7927 :
7928 : /**
7929 : * Returns either the last context entered through V8's C++ API, or the
7930 : * context of the currently running microtask while processing microtasks.
7931 : * If a context is entered while executing a microtask, that context is
7932 : * returned.
7933 : */
7934 : Local<Context> GetEnteredOrMicrotaskContext();
7935 :
7936 : /**
7937 : * Returns the Context that corresponds to the Incumbent realm in HTML spec.
7938 : * https://html.spec.whatwg.org/multipage/webappapis.html#incumbent
7939 : */
7940 : Local<Context> GetIncumbentContext();
7941 :
7942 : /**
7943 : * Schedules an exception to be thrown when returning to JavaScript. When an
7944 : * exception has been scheduled it is illegal to invoke any JavaScript
7945 : * operation; the caller must return immediately and only after the exception
7946 : * has been handled does it become legal to invoke JavaScript operations.
7947 : */
7948 : Local<Value> ThrowException(Local<Value> exception);
7949 :
7950 : typedef void (*GCCallback)(Isolate* isolate, GCType type,
7951 : GCCallbackFlags flags);
7952 : typedef void (*GCCallbackWithData)(Isolate* isolate, GCType type,
7953 : GCCallbackFlags flags, void* data);
7954 :
7955 : /**
7956 : * Enables the host application to receive a notification before a
7957 : * garbage collection. Allocations are allowed in the callback function,
7958 : * but the callback is not re-entrant: if the allocation inside it will
7959 : * trigger the garbage collection, the callback won't be called again.
7960 : * It is possible to specify the GCType filter for your callback. But it is
7961 : * not possible to register the same callback function two times with
7962 : * different GCType filters.
7963 : */
7964 : void AddGCPrologueCallback(GCCallbackWithData callback, void* data = nullptr,
7965 : GCType gc_type_filter = kGCTypeAll);
7966 : void AddGCPrologueCallback(GCCallback callback,
7967 : GCType gc_type_filter = kGCTypeAll);
7968 :
7969 : /**
7970 : * This function removes callback which was installed by
7971 : * AddGCPrologueCallback function.
7972 : */
7973 : void RemoveGCPrologueCallback(GCCallbackWithData, void* data = nullptr);
7974 : void RemoveGCPrologueCallback(GCCallback callback);
7975 :
7976 : /**
7977 : * Sets the embedder heap tracer for the isolate.
7978 : */
7979 : void SetEmbedderHeapTracer(EmbedderHeapTracer* tracer);
7980 :
7981 : /*
7982 : * Gets the currently active heap tracer for the isolate.
7983 : */
7984 : EmbedderHeapTracer* GetEmbedderHeapTracer();
7985 :
7986 : /**
7987 : * Use for |AtomicsWaitCallback| to indicate the type of event it receives.
7988 : */
7989 : enum class AtomicsWaitEvent {
7990 : /** Indicates that this call is happening before waiting. */
7991 : kStartWait,
7992 : /** `Atomics.wait()` finished because of an `Atomics.wake()` call. */
7993 : kWokenUp,
7994 : /** `Atomics.wait()` finished because it timed out. */
7995 : kTimedOut,
7996 : /** `Atomics.wait()` was interrupted through |TerminateExecution()|. */
7997 : kTerminatedExecution,
7998 : /** `Atomics.wait()` was stopped through |AtomicsWaitWakeHandle|. */
7999 : kAPIStopped,
8000 : /** `Atomics.wait()` did not wait, as the initial condition was not met. */
8001 : kNotEqual
8002 : };
8003 :
8004 : /**
8005 : * Passed to |AtomicsWaitCallback| as a means of stopping an ongoing
8006 : * `Atomics.wait` call.
8007 : */
8008 : class V8_EXPORT AtomicsWaitWakeHandle {
8009 : public:
8010 : /**
8011 : * Stop this `Atomics.wait()` call and call the |AtomicsWaitCallback|
8012 : * with |kAPIStopped|.
8013 : *
8014 : * This function may be called from another thread. The caller has to ensure
8015 : * through proper synchronization that it is not called after
8016 : * the finishing |AtomicsWaitCallback|.
8017 : *
8018 : * Note that the ECMAScript specification does not plan for the possibility
8019 : * of wakeups that are neither coming from a timeout or an `Atomics.wake()`
8020 : * call, so this may invalidate assumptions made by existing code.
8021 : * The embedder may accordingly wish to schedule an exception in the
8022 : * finishing |AtomicsWaitCallback|.
8023 : */
8024 : void Wake();
8025 : };
8026 :
8027 : /**
8028 : * Embedder callback for `Atomics.wait()` that can be added through
8029 : * |SetAtomicsWaitCallback|.
8030 : *
8031 : * This will be called just before starting to wait with the |event| value
8032 : * |kStartWait| and after finishing waiting with one of the other
8033 : * values of |AtomicsWaitEvent| inside of an `Atomics.wait()` call.
8034 : *
8035 : * |array_buffer| will refer to the underlying SharedArrayBuffer,
8036 : * |offset_in_bytes| to the location of the waited-on memory address inside
8037 : * the SharedArrayBuffer.
8038 : *
8039 : * |value| and |timeout_in_ms| will be the values passed to
8040 : * the `Atomics.wait()` call. If no timeout was used, |timeout_in_ms|
8041 : * will be `INFINITY`.
8042 : *
8043 : * In the |kStartWait| callback, |stop_handle| will be an object that
8044 : * is only valid until the corresponding finishing callback and that
8045 : * can be used to stop the wait process while it is happening.
8046 : *
8047 : * This callback may schedule exceptions, *unless* |event| is equal to
8048 : * |kTerminatedExecution|.
8049 : */
8050 : typedef void (*AtomicsWaitCallback)(AtomicsWaitEvent event,
8051 : Local<SharedArrayBuffer> array_buffer,
8052 : size_t offset_in_bytes, int64_t value,
8053 : double timeout_in_ms,
8054 : AtomicsWaitWakeHandle* stop_handle,
8055 : void* data);
8056 :
8057 : /**
8058 : * Set a new |AtomicsWaitCallback|. This overrides an earlier
8059 : * |AtomicsWaitCallback|, if there was any. If |callback| is nullptr,
8060 : * this unsets the callback. |data| will be passed to the callback
8061 : * as its last parameter.
8062 : */
8063 : void SetAtomicsWaitCallback(AtomicsWaitCallback callback, void* data);
8064 :
8065 : /**
8066 : * Enables the host application to receive a notification after a
8067 : * garbage collection. Allocations are allowed in the callback function,
8068 : * but the callback is not re-entrant: if the allocation inside it will
8069 : * trigger the garbage collection, the callback won't be called again.
8070 : * It is possible to specify the GCType filter for your callback. But it is
8071 : * not possible to register the same callback function two times with
8072 : * different GCType filters.
8073 : */
8074 : void AddGCEpilogueCallback(GCCallbackWithData callback, void* data = nullptr,
8075 : GCType gc_type_filter = kGCTypeAll);
8076 : void AddGCEpilogueCallback(GCCallback callback,
8077 : GCType gc_type_filter = kGCTypeAll);
8078 :
8079 : /**
8080 : * This function removes callback which was installed by
8081 : * AddGCEpilogueCallback function.
8082 : */
8083 : void RemoveGCEpilogueCallback(GCCallbackWithData callback,
8084 : void* data = nullptr);
8085 : void RemoveGCEpilogueCallback(GCCallback callback);
8086 :
8087 : typedef size_t (*GetExternallyAllocatedMemoryInBytesCallback)();
8088 :
8089 : /**
8090 : * Set the callback that tells V8 how much memory is currently allocated
8091 : * externally of the V8 heap. Ideally this memory is somehow connected to V8
8092 : * objects and may get freed-up when the corresponding V8 objects get
8093 : * collected by a V8 garbage collection.
8094 : */
8095 : void SetGetExternallyAllocatedMemoryInBytesCallback(
8096 : GetExternallyAllocatedMemoryInBytesCallback callback);
8097 :
8098 : /**
8099 : * Forcefully terminate the current thread of JavaScript execution
8100 : * in the given isolate.
8101 : *
8102 : * This method can be used by any thread even if that thread has not
8103 : * acquired the V8 lock with a Locker object.
8104 : */
8105 : void TerminateExecution();
8106 :
8107 : /**
8108 : * Is V8 terminating JavaScript execution.
8109 : *
8110 : * Returns true if JavaScript execution is currently terminating
8111 : * because of a call to TerminateExecution. In that case there are
8112 : * still JavaScript frames on the stack and the termination
8113 : * exception is still active.
8114 : */
8115 : bool IsExecutionTerminating();
8116 :
8117 : /**
8118 : * Resume execution capability in the given isolate, whose execution
8119 : * was previously forcefully terminated using TerminateExecution().
8120 : *
8121 : * When execution is forcefully terminated using TerminateExecution(),
8122 : * the isolate can not resume execution until all JavaScript frames
8123 : * have propagated the uncatchable exception which is generated. This
8124 : * method allows the program embedding the engine to handle the
8125 : * termination event and resume execution capability, even if
8126 : * JavaScript frames remain on the stack.
8127 : *
8128 : * This method can be used by any thread even if that thread has not
8129 : * acquired the V8 lock with a Locker object.
8130 : */
8131 : void CancelTerminateExecution();
8132 :
8133 : /**
8134 : * Request V8 to interrupt long running JavaScript code and invoke
8135 : * the given |callback| passing the given |data| to it. After |callback|
8136 : * returns control will be returned to the JavaScript code.
8137 : * There may be a number of interrupt requests in flight.
8138 : * Can be called from another thread without acquiring a |Locker|.
8139 : * Registered |callback| must not reenter interrupted Isolate.
8140 : */
8141 : void RequestInterrupt(InterruptCallback callback, void* data);
8142 :
8143 : /**
8144 : * Request garbage collection in this Isolate. It is only valid to call this
8145 : * function if --expose_gc was specified.
8146 : *
8147 : * This should only be used for testing purposes and not to enforce a garbage
8148 : * collection schedule. It has strong negative impact on the garbage
8149 : * collection performance. Use IdleNotificationDeadline() or
8150 : * LowMemoryNotification() instead to influence the garbage collection
8151 : * schedule.
8152 : */
8153 : void RequestGarbageCollectionForTesting(GarbageCollectionType type);
8154 :
8155 : /**
8156 : * Set the callback to invoke for logging event.
8157 : */
8158 : void SetEventLogger(LogEventCallback that);
8159 :
8160 : /**
8161 : * Adds a callback to notify the host application right before a script
8162 : * is about to run. If a script re-enters the runtime during executing, the
8163 : * BeforeCallEnteredCallback is invoked for each re-entrance.
8164 : * Executing scripts inside the callback will re-trigger the callback.
8165 : */
8166 : void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
8167 :
8168 : /**
8169 : * Removes callback that was installed by AddBeforeCallEnteredCallback.
8170 : */
8171 : void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback);
8172 :
8173 : /**
8174 : * Adds a callback to notify the host application when a script finished
8175 : * running. If a script re-enters the runtime during executing, the
8176 : * CallCompletedCallback is only invoked when the outer-most script
8177 : * execution ends. Executing scripts inside the callback do not trigger
8178 : * further callbacks.
8179 : */
8180 : void AddCallCompletedCallback(CallCompletedCallback callback);
8181 :
8182 : /**
8183 : * Removes callback that was installed by AddCallCompletedCallback.
8184 : */
8185 : void RemoveCallCompletedCallback(CallCompletedCallback callback);
8186 :
8187 : /**
8188 : * Set the PromiseHook callback for various promise lifecycle
8189 : * events.
8190 : */
8191 : void SetPromiseHook(PromiseHook hook);
8192 :
8193 : /**
8194 : * Set callback to notify about promise reject with no handler, or
8195 : * revocation of such a previous notification once the handler is added.
8196 : */
8197 : void SetPromiseRejectCallback(PromiseRejectCallback callback);
8198 :
8199 : /**
8200 : * Runs the default MicrotaskQueue until it gets empty.
8201 : * Any exceptions thrown by microtask callbacks are swallowed.
8202 : */
8203 : void RunMicrotasks();
8204 :
8205 : /**
8206 : * Enqueues the callback to the default MicrotaskQueue
8207 : */
8208 : void EnqueueMicrotask(Local<Function> microtask);
8209 :
8210 : /**
8211 : * Enqueues the callback to the default MicrotaskQueue
8212 : */
8213 : void EnqueueMicrotask(MicrotaskCallback callback, void* data = nullptr);
8214 :
8215 : /**
8216 : * Controls how Microtasks are invoked. See MicrotasksPolicy for details.
8217 : */
8218 : void SetMicrotasksPolicy(MicrotasksPolicy policy);
8219 :
8220 : /**
8221 : * Returns the policy controlling how Microtasks are invoked.
8222 : */
8223 : MicrotasksPolicy GetMicrotasksPolicy() const;
8224 :
8225 : /**
8226 : * Adds a callback to notify the host application after
8227 : * microtasks were run on the default MicrotaskQueue. The callback is
8228 : * triggered by explicit RunMicrotasks call or automatic microtasks execution
8229 : * (see SetMicrotaskPolicy).
8230 : *
8231 : * Callback will trigger even if microtasks were attempted to run,
8232 : * but the microtasks queue was empty and no single microtask was actually
8233 : * executed.
8234 : *
8235 : * Executing scripts inside the callback will not re-trigger microtasks and
8236 : * the callback.
8237 : */
8238 : V8_DEPRECATE_SOON("Use *WithData version.",
8239 : void AddMicrotasksCompletedCallback(
8240 : MicrotasksCompletedCallback callback));
8241 : void AddMicrotasksCompletedCallback(
8242 : MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
8243 :
8244 : /**
8245 : * Removes callback that was installed by AddMicrotasksCompletedCallback.
8246 : */
8247 : V8_DEPRECATE_SOON("Use *WithData version.",
8248 : void RemoveMicrotasksCompletedCallback(
8249 : MicrotasksCompletedCallback callback));
8250 : void RemoveMicrotasksCompletedCallback(
8251 : MicrotasksCompletedCallbackWithData callback, void* data = nullptr);
8252 :
8253 : /**
8254 : * Sets a callback for counting the number of times a feature of V8 is used.
8255 : */
8256 : void SetUseCounterCallback(UseCounterCallback callback);
8257 :
8258 : /**
8259 : * Enables the host application to provide a mechanism for recording
8260 : * statistics counters.
8261 : */
8262 : void SetCounterFunction(CounterLookupCallback);
8263 :
8264 : /**
8265 : * Enables the host application to provide a mechanism for recording
8266 : * histograms. The CreateHistogram function returns a
8267 : * histogram which will later be passed to the AddHistogramSample
8268 : * function.
8269 : */
8270 : void SetCreateHistogramFunction(CreateHistogramCallback);
8271 : void SetAddHistogramSampleFunction(AddHistogramSampleCallback);
8272 :
8273 : /**
8274 : * Optional notification that the embedder is idle.
8275 : * V8 uses the notification to perform garbage collection.
8276 : * This call can be used repeatedly if the embedder remains idle.
8277 : * Returns true if the embedder should stop calling IdleNotificationDeadline
8278 : * until real work has been done. This indicates that V8 has done
8279 : * as much cleanup as it will be able to do.
8280 : *
8281 : * The deadline_in_seconds argument specifies the deadline V8 has to finish
8282 : * garbage collection work. deadline_in_seconds is compared with
8283 : * MonotonicallyIncreasingTime() and should be based on the same timebase as
8284 : * that function. There is no guarantee that the actual work will be done
8285 : * within the time limit.
8286 : */
8287 : bool IdleNotificationDeadline(double deadline_in_seconds);
8288 :
8289 : /**
8290 : * Optional notification that the system is running low on memory.
8291 : * V8 uses these notifications to attempt to free memory.
8292 : */
8293 : void LowMemoryNotification();
8294 :
8295 : /**
8296 : * Optional notification that a context has been disposed. V8 uses
8297 : * these notifications to guide the GC heuristic. Returns the number
8298 : * of context disposals - including this one - since the last time
8299 : * V8 had a chance to clean up.
8300 : *
8301 : * The optional parameter |dependant_context| specifies whether the disposed
8302 : * context was depending on state from other contexts or not.
8303 : */
8304 : int ContextDisposedNotification(bool dependant_context = true);
8305 :
8306 : /**
8307 : * Optional notification that the isolate switched to the foreground.
8308 : * V8 uses these notifications to guide heuristics.
8309 : */
8310 : void IsolateInForegroundNotification();
8311 :
8312 : /**
8313 : * Optional notification that the isolate switched to the background.
8314 : * V8 uses these notifications to guide heuristics.
8315 : */
8316 : void IsolateInBackgroundNotification();
8317 :
8318 : /**
8319 : * Optional notification which will enable the memory savings mode.
8320 : * V8 uses this notification to guide heuristics which may result in a
8321 : * smaller memory footprint at the cost of reduced runtime performance.
8322 : */
8323 : void EnableMemorySavingsMode();
8324 :
8325 : /**
8326 : * Optional notification which will disable the memory savings mode.
8327 : */
8328 : void DisableMemorySavingsMode();
8329 :
8330 : /**
8331 : * Optional notification to tell V8 the current performance requirements
8332 : * of the embedder based on RAIL.
8333 : * V8 uses these notifications to guide heuristics.
8334 : * This is an unfinished experimental feature. Semantics and implementation
8335 : * may change frequently.
8336 : */
8337 : void SetRAILMode(RAILMode rail_mode);
8338 :
8339 : /**
8340 : * Optional notification to tell V8 the current isolate is used for debugging
8341 : * and requires higher heap limit.
8342 : */
8343 : void IncreaseHeapLimitForDebugging();
8344 :
8345 : /**
8346 : * Restores the original heap limit after IncreaseHeapLimitForDebugging().
8347 : */
8348 : void RestoreOriginalHeapLimit();
8349 :
8350 : /**
8351 : * Returns true if the heap limit was increased for debugging and the
8352 : * original heap limit was not restored yet.
8353 : */
8354 : bool IsHeapLimitIncreasedForDebugging();
8355 :
8356 : /**
8357 : * Allows the host application to provide the address of a function that is
8358 : * notified each time code is added, moved or removed.
8359 : *
8360 : * \param options options for the JIT code event handler.
8361 : * \param event_handler the JIT code event handler, which will be invoked
8362 : * each time code is added, moved or removed.
8363 : * \note \p event_handler won't get notified of existent code.
8364 : * \note since code removal notifications are not currently issued, the
8365 : * \p event_handler may get notifications of code that overlaps earlier
8366 : * code notifications. This happens when code areas are reused, and the
8367 : * earlier overlapping code areas should therefore be discarded.
8368 : * \note the events passed to \p event_handler and the strings they point to
8369 : * are not guaranteed to live past each call. The \p event_handler must
8370 : * copy strings and other parameters it needs to keep around.
8371 : * \note the set of events declared in JitCodeEvent::EventType is expected to
8372 : * grow over time, and the JitCodeEvent structure is expected to accrue
8373 : * new members. The \p event_handler function must ignore event codes
8374 : * it does not recognize to maintain future compatibility.
8375 : * \note Use Isolate::CreateParams to get events for code executed during
8376 : * Isolate setup.
8377 : */
8378 : void SetJitCodeEventHandler(JitCodeEventOptions options,
8379 : JitCodeEventHandler event_handler);
8380 :
8381 : /**
8382 : * Modifies the stack limit for this Isolate.
8383 : *
8384 : * \param stack_limit An address beyond which the Vm's stack may not grow.
8385 : *
8386 : * \note If you are using threads then you should hold the V8::Locker lock
8387 : * while setting the stack limit and you must set a non-default stack
8388 : * limit separately for each thread.
8389 : */
8390 : void SetStackLimit(uintptr_t stack_limit);
8391 :
8392 : /**
8393 : * Returns a memory range that can potentially contain jitted code. Code for
8394 : * V8's 'builtins' will not be in this range if embedded builtins is enabled.
8395 : *
8396 : * On Win64, embedders are advised to install function table callbacks for
8397 : * these ranges, as default SEH won't be able to unwind through jitted code.
8398 : * The first page of the code range is reserved for the embedder and is
8399 : * committed, writable, and executable, to be used to store unwind data, as
8400 : * documented in
8401 : * https://docs.microsoft.com/en-us/cpp/build/exception-handling-x64.
8402 : *
8403 : * Might be empty on other platforms.
8404 : *
8405 : * https://code.google.com/p/v8/issues/detail?id=3598
8406 : */
8407 : void GetCodeRange(void** start, size_t* length_in_bytes);
8408 :
8409 : /**
8410 : * Returns the UnwindState necessary for use with the Unwinder API.
8411 : */
8412 : UnwindState GetUnwindState();
8413 :
8414 : /** Set the callback to invoke in case of fatal errors. */
8415 : void SetFatalErrorHandler(FatalErrorCallback that);
8416 :
8417 : /** Set the callback to invoke in case of OOM errors. */
8418 : void SetOOMErrorHandler(OOMErrorCallback that);
8419 :
8420 : /**
8421 : * Add a callback to invoke in case the heap size is close to the heap limit.
8422 : * If multiple callbacks are added, only the most recently added callback is
8423 : * invoked.
8424 : */
8425 : void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void* data);
8426 :
8427 : /**
8428 : * Remove the given callback and restore the heap limit to the
8429 : * given limit. If the given limit is zero, then it is ignored.
8430 : * If the current heap size is greater than the given limit,
8431 : * then the heap limit is restored to the minimal limit that
8432 : * is possible for the current heap size.
8433 : */
8434 : void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback,
8435 : size_t heap_limit);
8436 :
8437 : /**
8438 : * If the heap limit was changed by the NearHeapLimitCallback, then the
8439 : * initial heap limit will be restored once the heap size falls below the
8440 : * given threshold percentage of the initial heap limit.
8441 : * The threshold percentage is a number in (0.0, 1.0) range.
8442 : */
8443 : void AutomaticallyRestoreInitialHeapLimit(double threshold_percent = 0.5);
8444 :
8445 : /**
8446 : * Set the callback to invoke to check if code generation from
8447 : * strings should be allowed.
8448 : */
8449 : void SetAllowCodeGenerationFromStringsCallback(
8450 : AllowCodeGenerationFromStringsCallback callback);
8451 :
8452 : /**
8453 : * Set the callback to invoke to check if wasm code generation should
8454 : * be allowed.
8455 : */
8456 : void SetAllowWasmCodeGenerationCallback(
8457 : AllowWasmCodeGenerationCallback callback);
8458 :
8459 : /**
8460 : * Embedder over{ride|load} injection points for wasm APIs. The expectation
8461 : * is that the embedder sets them at most once.
8462 : */
8463 : void SetWasmModuleCallback(ExtensionCallback callback);
8464 : void SetWasmInstanceCallback(ExtensionCallback callback);
8465 :
8466 : void SetWasmStreamingCallback(WasmStreamingCallback callback);
8467 :
8468 : void SetWasmThreadsEnabledCallback(WasmThreadsEnabledCallback callback);
8469 :
8470 : /**
8471 : * Check if V8 is dead and therefore unusable. This is the case after
8472 : * fatal errors such as out-of-memory situations.
8473 : */
8474 : bool IsDead();
8475 :
8476 : /**
8477 : * Adds a message listener (errors only).
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 : bool AddMessageListener(MessageCallback that,
8486 : Local<Value> data = Local<Value>());
8487 :
8488 : /**
8489 : * Adds a message listener.
8490 : *
8491 : * The same message listener can be added more than once and in that
8492 : * case it will be called more than once for each message.
8493 : *
8494 : * If data is specified, it will be passed to the callback when it is called.
8495 : * Otherwise, the exception object will be passed to the callback instead.
8496 : *
8497 : * A listener can listen for particular error levels by providing a mask.
8498 : */
8499 : bool AddMessageListenerWithErrorLevel(MessageCallback that,
8500 : int message_levels,
8501 : Local<Value> data = Local<Value>());
8502 :
8503 : /**
8504 : * Remove all message listeners from the specified callback function.
8505 : */
8506 : void RemoveMessageListeners(MessageCallback that);
8507 :
8508 : /** Callback function for reporting failed access checks.*/
8509 : void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback);
8510 :
8511 : /**
8512 : * Tells V8 to capture current stack trace when uncaught exception occurs
8513 : * and report it to the message listeners. The option is off by default.
8514 : */
8515 : void SetCaptureStackTraceForUncaughtExceptions(
8516 : bool capture, int frame_limit = 10,
8517 : StackTrace::StackTraceOptions options = StackTrace::kOverview);
8518 :
8519 : /**
8520 : * Iterates through all external resources referenced from current isolate
8521 : * heap. GC is not invoked prior to iterating, therefore there is no
8522 : * guarantee that visited objects are still alive.
8523 : */
8524 : void VisitExternalResources(ExternalResourceVisitor* visitor);
8525 :
8526 : /**
8527 : * Iterates through all the persistent handles in the current isolate's heap
8528 : * that have class_ids.
8529 : */
8530 : void VisitHandlesWithClassIds(PersistentHandleVisitor* visitor);
8531 :
8532 : /**
8533 : * Iterates through all the persistent handles in the current isolate's heap
8534 : * that have class_ids and are weak to be marked as inactive if there is no
8535 : * pending activity for the handle.
8536 : */
8537 : void VisitWeakHandles(PersistentHandleVisitor* visitor);
8538 :
8539 : /**
8540 : * Check if this isolate is in use.
8541 : * True if at least one thread Enter'ed this isolate.
8542 : */
8543 : bool IsInUse();
8544 :
8545 : /**
8546 : * Set whether calling Atomics.wait (a function that may block) is allowed in
8547 : * this isolate. This can also be configured via
8548 : * CreateParams::allow_atomics_wait.
8549 : */
8550 : void SetAllowAtomicsWait(bool allow);
8551 :
8552 : /**
8553 : * Time zone redetection indicator for
8554 : * DateTimeConfigurationChangeNotification.
8555 : *
8556 : * kSkip indicates V8 that the notification should not trigger redetecting
8557 : * host time zone. kRedetect indicates V8 that host time zone should be
8558 : * redetected, and used to set the default time zone.
8559 : *
8560 : * The host time zone detection may require file system access or similar
8561 : * operations unlikely to be available inside a sandbox. If v8 is run inside a
8562 : * sandbox, the host time zone has to be detected outside the sandbox before
8563 : * calling DateTimeConfigurationChangeNotification function.
8564 : */
8565 : enum class TimeZoneDetection { kSkip, kRedetect };
8566 :
8567 : /**
8568 : * Notification that the embedder has changed the time zone, daylight savings
8569 : * time or other date / time configuration parameters. V8 keeps a cache of
8570 : * various values used for date / time computation. This notification will
8571 : * reset those cached values for the current context so that date / time
8572 : * configuration changes would be reflected.
8573 : *
8574 : * This API should not be called more than needed as it will negatively impact
8575 : * the performance of date operations.
8576 : */
8577 : void DateTimeConfigurationChangeNotification(
8578 : TimeZoneDetection time_zone_detection = TimeZoneDetection::kSkip);
8579 :
8580 : /**
8581 : * Notification that the embedder has changed the locale. V8 keeps a cache of
8582 : * various values used for locale computation. This notification will reset
8583 : * those cached values for the current context so that locale configuration
8584 : * changes would be reflected.
8585 : *
8586 : * This API should not be called more than needed as it will negatively impact
8587 : * the performance of locale operations.
8588 : */
8589 : void LocaleConfigurationChangeNotification();
8590 :
8591 : Isolate() = delete;
8592 : ~Isolate() = delete;
8593 : Isolate(const Isolate&) = delete;
8594 : Isolate& operator=(const Isolate&) = delete;
8595 : // Deleting operator new and delete here is allowed as ctor and dtor is also
8596 : // deleted.
8597 : void* operator new(size_t size) = delete;
8598 : void* operator new[](size_t size) = delete;
8599 : void operator delete(void*, size_t) = delete;
8600 : void operator delete[](void*, size_t) = delete;
8601 :
8602 : private:
8603 : template <class K, class V, class Traits>
8604 : friend class PersistentValueMapBase;
8605 :
8606 : internal::Address* GetDataFromSnapshotOnce(size_t index);
8607 : void ReportExternalAllocationLimitReached();
8608 : void CheckMemoryPressure();
8609 : };
8610 :
8611 : class V8_EXPORT StartupData {
8612 : public:
8613 : const char* data;
8614 : int raw_size;
8615 : };
8616 :
8617 :
8618 : /**
8619 : * EntropySource is used as a callback function when v8 needs a source
8620 : * of entropy.
8621 : */
8622 : typedef bool (*EntropySource)(unsigned char* buffer, size_t length);
8623 :
8624 : /**
8625 : * ReturnAddressLocationResolver is used as a callback function when v8 is
8626 : * resolving the location of a return address on the stack. Profilers that
8627 : * change the return address on the stack can use this to resolve the stack
8628 : * location to wherever the profiler stashed the original return address.
8629 : *
8630 : * \param return_addr_location A location on stack where a machine
8631 : * return address resides.
8632 : * \returns Either return_addr_location, or else a pointer to the profiler's
8633 : * copy of the original return address.
8634 : *
8635 : * \note The resolver function must not cause garbage collection.
8636 : */
8637 : typedef uintptr_t (*ReturnAddressLocationResolver)(
8638 : uintptr_t return_addr_location);
8639 :
8640 :
8641 : /**
8642 : * Container class for static utility functions.
8643 : */
8644 : class V8_EXPORT V8 {
8645 : public:
8646 : /**
8647 : * Hand startup data to V8, in case the embedder has chosen to build
8648 : * V8 with external startup data.
8649 : *
8650 : * Note:
8651 : * - By default the startup data is linked into the V8 library, in which
8652 : * case this function is not meaningful.
8653 : * - If this needs to be called, it needs to be called before V8
8654 : * tries to make use of its built-ins.
8655 : * - To avoid unnecessary copies of data, V8 will point directly into the
8656 : * given data blob, so pretty please keep it around until V8 exit.
8657 : * - Compression of the startup blob might be useful, but needs to
8658 : * handled entirely on the embedders' side.
8659 : * - The call will abort if the data is invalid.
8660 : */
8661 : static void SetNativesDataBlob(StartupData* startup_blob);
8662 : static void SetSnapshotDataBlob(StartupData* startup_blob);
8663 :
8664 : /** Set the callback to invoke in case of Dcheck failures. */
8665 : static void SetDcheckErrorHandler(DcheckErrorCallback that);
8666 :
8667 :
8668 : /**
8669 : * Sets V8 flags from a string.
8670 : */
8671 : static void SetFlagsFromString(const char* str, int length);
8672 :
8673 : /**
8674 : * Sets V8 flags from the command line.
8675 : */
8676 : static void SetFlagsFromCommandLine(int* argc,
8677 : char** argv,
8678 : bool remove_flags);
8679 :
8680 : /** Get the version string. */
8681 : static const char* GetVersion();
8682 :
8683 : /**
8684 : * Initializes V8. This function needs to be called before the first Isolate
8685 : * is created. It always returns true.
8686 : */
8687 : static bool Initialize();
8688 :
8689 : /**
8690 : * Allows the host application to provide a callback which can be used
8691 : * as a source of entropy for random number generators.
8692 : */
8693 : static void SetEntropySource(EntropySource source);
8694 :
8695 : /**
8696 : * Allows the host application to provide a callback that allows v8 to
8697 : * cooperate with a profiler that rewrites return addresses on stack.
8698 : */
8699 : static void SetReturnAddressLocationResolver(
8700 : ReturnAddressLocationResolver return_address_resolver);
8701 :
8702 : /**
8703 : * Releases any resources used by v8 and stops any utility threads
8704 : * that may be running. Note that disposing v8 is permanent, it
8705 : * cannot be reinitialized.
8706 : *
8707 : * It should generally not be necessary to dispose v8 before exiting
8708 : * a process, this should happen automatically. It is only necessary
8709 : * to use if the process needs the resources taken up by v8.
8710 : */
8711 : static bool Dispose();
8712 :
8713 : /**
8714 : * Initialize the ICU library bundled with V8. The embedder should only
8715 : * invoke this method when using the bundled ICU. Returns true on success.
8716 : *
8717 : * If V8 was compiled with the ICU data in an external file, the location
8718 : * of the data file has to be provided.
8719 : */
8720 : static bool InitializeICU(const char* icu_data_file = nullptr);
8721 :
8722 : /**
8723 : * Initialize the ICU library bundled with V8. The embedder should only
8724 : * invoke this method when using the bundled ICU. If V8 was compiled with
8725 : * the ICU data in an external file and when the default location of that
8726 : * file should be used, a path to the executable must be provided.
8727 : * Returns true on success.
8728 : *
8729 : * The default is a file called icudtl.dat side-by-side with the executable.
8730 : *
8731 : * Optionally, the location of the data file can be provided to override the
8732 : * default.
8733 : */
8734 : static bool InitializeICUDefaultLocation(const char* exec_path,
8735 : const char* icu_data_file = nullptr);
8736 :
8737 : /**
8738 : * Initialize the external startup data. The embedder only needs to
8739 : * invoke this method when external startup data was enabled in a build.
8740 : *
8741 : * If V8 was compiled with the startup data in an external file, then
8742 : * V8 needs to be given those external files during startup. There are
8743 : * three ways to do this:
8744 : * - InitializeExternalStartupData(const char*)
8745 : * This will look in the given directory for files "natives_blob.bin"
8746 : * and "snapshot_blob.bin" - which is what the default build calls them.
8747 : * - InitializeExternalStartupData(const char*, const char*)
8748 : * As above, but will directly use the two given file names.
8749 : * - Call SetNativesDataBlob, SetNativesDataBlob.
8750 : * This will read the blobs from the given data structures and will
8751 : * not perform any file IO.
8752 : */
8753 : static void InitializeExternalStartupData(const char* directory_path);
8754 : static void InitializeExternalStartupData(const char* natives_blob,
8755 : const char* snapshot_blob);
8756 : /**
8757 : * Sets the v8::Platform to use. This should be invoked before V8 is
8758 : * initialized.
8759 : */
8760 : static void InitializePlatform(Platform* platform);
8761 :
8762 : /**
8763 : * Clears all references to the v8::Platform. This should be invoked after
8764 : * V8 was disposed.
8765 : */
8766 : static void ShutdownPlatform();
8767 :
8768 : #if V8_OS_POSIX
8769 : /**
8770 : * Give the V8 signal handler a chance to handle a fault.
8771 : *
8772 : * This function determines whether a memory access violation can be recovered
8773 : * by V8. If so, it will return true and modify context to return to a code
8774 : * fragment that can recover from the fault. Otherwise, TryHandleSignal will
8775 : * return false.
8776 : *
8777 : * The parameters to this function correspond to those passed to a Linux
8778 : * signal handler.
8779 : *
8780 : * \param signal_number The signal number.
8781 : *
8782 : * \param info A pointer to the siginfo_t structure provided to the signal
8783 : * handler.
8784 : *
8785 : * \param context The third argument passed to the Linux signal handler, which
8786 : * points to a ucontext_t structure.
8787 : */
8788 : V8_DEPRECATE_SOON("Use TryHandleWebAssemblyTrapPosix",
8789 : static bool TryHandleSignal(int signal_number, void* info,
8790 : void* context));
8791 : #endif // V8_OS_POSIX
8792 :
8793 : /**
8794 : * Activate trap-based bounds checking for WebAssembly.
8795 : *
8796 : * \param use_v8_signal_handler Whether V8 should install its own signal
8797 : * handler or rely on the embedder's.
8798 : */
8799 : static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler);
8800 :
8801 : #if defined(V8_OS_WIN)
8802 : /**
8803 : * On Win64, by default V8 does not emit unwinding data for jitted code,
8804 : * which means the OS cannot walk the stack frames and the system Structured
8805 : * Exception Handling (SEH) cannot unwind through V8-generated code:
8806 : * https://code.google.com/p/v8/issues/detail?id=3598.
8807 : *
8808 : * This function allows embedders to register a custom exception handler for
8809 : * exceptions in V8-generated code.
8810 : */
8811 : static void SetUnhandledExceptionCallback(
8812 : UnhandledExceptionCallback unhandled_exception_callback);
8813 : #endif
8814 :
8815 : private:
8816 : V8();
8817 :
8818 : static internal::Address* GlobalizeReference(internal::Isolate* isolate,
8819 : internal::Address* handle);
8820 : static internal::Address* GlobalizeTracedReference(internal::Isolate* isolate,
8821 : internal::Address* handle,
8822 : internal::Address* slot);
8823 : static void MoveGlobalReference(internal::Address** from,
8824 : internal::Address** to);
8825 : static void MoveTracedGlobalReference(internal::Address** from,
8826 : internal::Address** to);
8827 : static internal::Address* CopyGlobalReference(internal::Address* from);
8828 : static void DisposeGlobal(internal::Address* global_handle);
8829 : static void DisposeTracedGlobal(internal::Address* global_handle);
8830 : static void MakeWeak(internal::Address* location, void* data,
8831 : WeakCallbackInfo<void>::Callback weak_callback,
8832 : WeakCallbackType type);
8833 : static void MakeWeak(internal::Address** location_addr);
8834 : static void* ClearWeak(internal::Address* location);
8835 : static void SetFinalizationCallbackTraced(
8836 : internal::Address* location, void* parameter,
8837 : WeakCallbackInfo<void>::Callback callback);
8838 : static void AnnotateStrongRetainer(internal::Address* location,
8839 : const char* label);
8840 : static Value* Eternalize(Isolate* isolate, Value* handle);
8841 :
8842 : static void RegisterExternallyReferencedObject(internal::Address* location,
8843 : internal::Isolate* isolate);
8844 :
8845 : template <class K, class V, class T>
8846 : friend class PersistentValueMapBase;
8847 :
8848 : static void FromJustIsNothing();
8849 : static void ToLocalEmpty();
8850 : static void InternalFieldOutOfBounds(int index);
8851 : template <class T>
8852 : friend class Global;
8853 : template <class T> friend class Local;
8854 : template <class T>
8855 : friend class MaybeLocal;
8856 : template <class T>
8857 : friend class Maybe;
8858 : template <class T>
8859 : friend class TracedGlobal;
8860 : template <class T>
8861 : friend class WeakCallbackInfo;
8862 : template <class T> friend class Eternal;
8863 : template <class T> friend class PersistentBase;
8864 : template <class T, class M> friend class Persistent;
8865 : friend class Context;
8866 : };
8867 :
8868 : /**
8869 : * Helper class to create a snapshot data blob.
8870 : */
8871 : class V8_EXPORT SnapshotCreator {
8872 : public:
8873 : enum class FunctionCodeHandling { kClear, kKeep };
8874 :
8875 : /**
8876 : * Initialize and enter an isolate, and set it up for serialization.
8877 : * The isolate is either created from scratch or from an existing snapshot.
8878 : * The caller keeps ownership of the argument snapshot.
8879 : * \param existing_blob existing snapshot from which to create this one.
8880 : * \param external_references a null-terminated array of external references
8881 : * that must be equivalent to CreateParams::external_references.
8882 : */
8883 : SnapshotCreator(Isolate* isolate,
8884 : const intptr_t* external_references = nullptr,
8885 : StartupData* existing_blob = nullptr);
8886 :
8887 : /**
8888 : * Create and enter an isolate, and set it up for serialization.
8889 : * The isolate is either created from scratch or from an existing snapshot.
8890 : * The caller keeps ownership of the argument snapshot.
8891 : * \param existing_blob existing snapshot from which to create this one.
8892 : * \param external_references a null-terminated array of external references
8893 : * that must be equivalent to CreateParams::external_references.
8894 : */
8895 : SnapshotCreator(const intptr_t* external_references = nullptr,
8896 : StartupData* existing_blob = nullptr);
8897 :
8898 : ~SnapshotCreator();
8899 :
8900 : /**
8901 : * \returns the isolate prepared by the snapshot creator.
8902 : */
8903 : Isolate* GetIsolate();
8904 :
8905 : /**
8906 : * Set the default context to be included in the snapshot blob.
8907 : * The snapshot will not contain the global proxy, and we expect one or a
8908 : * global object template to create one, to be provided upon deserialization.
8909 : *
8910 : * \param callback optional callback to serialize internal fields.
8911 : */
8912 : void SetDefaultContext(Local<Context> context,
8913 : SerializeInternalFieldsCallback callback =
8914 : SerializeInternalFieldsCallback());
8915 :
8916 : /**
8917 : * Add additional context to be included in the snapshot blob.
8918 : * The snapshot will include the global proxy.
8919 : *
8920 : * \param callback optional callback to serialize internal fields.
8921 : *
8922 : * \returns the index of the context in the snapshot blob.
8923 : */
8924 : size_t AddContext(Local<Context> context,
8925 : SerializeInternalFieldsCallback callback =
8926 : SerializeInternalFieldsCallback());
8927 :
8928 : /**
8929 : * Add a template to be included in the snapshot blob.
8930 : * \returns the index of the template in the snapshot blob.
8931 : */
8932 : size_t AddTemplate(Local<Template> template_obj);
8933 :
8934 : /**
8935 : * Attach arbitrary V8::Data to the context snapshot, which can be retrieved
8936 : * via Context::GetDataFromSnapshot after deserialization. This data does not
8937 : * survive when a new snapshot is created from an existing snapshot.
8938 : * \returns the index for retrieval.
8939 : */
8940 : template <class T>
8941 : V8_INLINE size_t AddData(Local<Context> context, Local<T> object);
8942 :
8943 : /**
8944 : * Attach arbitrary V8::Data to the isolate snapshot, which can be retrieved
8945 : * via Isolate::GetDataFromSnapshot after deserialization. This data does not
8946 : * survive when a new snapshot is created from an existing snapshot.
8947 : * \returns the index for retrieval.
8948 : */
8949 : template <class T>
8950 : V8_INLINE size_t AddData(Local<T> object);
8951 :
8952 : /**
8953 : * Created a snapshot data blob.
8954 : * This must not be called from within a handle scope.
8955 : * \param function_code_handling whether to include compiled function code
8956 : * in the snapshot.
8957 : * \returns { nullptr, 0 } on failure, and a startup snapshot on success. The
8958 : * caller acquires ownership of the data array in the return value.
8959 : */
8960 : StartupData CreateBlob(FunctionCodeHandling function_code_handling);
8961 :
8962 : // Disallow copying and assigning.
8963 : SnapshotCreator(const SnapshotCreator&) = delete;
8964 : void operator=(const SnapshotCreator&) = delete;
8965 :
8966 : private:
8967 : size_t AddData(Local<Context> context, internal::Address object);
8968 : size_t AddData(internal::Address object);
8969 :
8970 : void* data_;
8971 : };
8972 :
8973 : /**
8974 : * A simple Maybe type, representing an object which may or may not have a
8975 : * value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html.
8976 : *
8977 : * If an API method returns a Maybe<>, the API method can potentially fail
8978 : * either because an exception is thrown, or because an exception is pending,
8979 : * e.g. because a previous API call threw an exception that hasn't been caught
8980 : * yet, or because a TerminateExecution exception was thrown. In that case, a
8981 : * "Nothing" value is returned.
8982 : */
8983 : template <class T>
8984 858750 : class Maybe {
8985 : public:
8986 103882896 : V8_INLINE bool IsNothing() const { return !has_value_; }
8987 311980681 : V8_INLINE bool IsJust() const { return has_value_; }
8988 :
8989 : /**
8990 : * An alias for |FromJust|. Will crash if the Maybe<> is nothing.
8991 : */
8992 : V8_INLINE T ToChecked() const { return FromJust(); }
8993 :
8994 : /**
8995 : * Short-hand for ToChecked(), which doesn't return a value. To be used, where
8996 : * the actual value of the Maybe is not needed like Object::Set.
8997 : */
8998 : V8_INLINE void Check() const {
8999 5 : if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
9000 : }
9001 :
9002 : /**
9003 : * Converts this Maybe<> to a value of type T. If this Maybe<> is
9004 : * nothing (empty), |false| is returned and |out| is left untouched.
9005 : */
9006 : V8_WARN_UNUSED_RESULT V8_INLINE bool To(T* out) const {
9007 7768589 : if (V8_LIKELY(IsJust())) *out = value_;
9008 : return IsJust();
9009 : }
9010 :
9011 : /**
9012 : * Converts this Maybe<> to a value of type T. If this Maybe<> is
9013 : * nothing (empty), V8 will crash the process.
9014 : */
9015 : V8_INLINE T FromJust() const {
9016 181170298 : if (V8_UNLIKELY(!IsJust())) V8::FromJustIsNothing();
9017 166184699 : return value_;
9018 : }
9019 :
9020 : /**
9021 : * Converts this Maybe<> to a value of type T, using a default value if this
9022 : * Maybe<> is nothing (empty).
9023 : */
9024 : V8_INLINE T FromMaybe(const T& default_value) const {
9025 416068 : return has_value_ ? value_ : default_value;
9026 : }
9027 :
9028 : V8_INLINE bool operator==(const Maybe& other) const {
9029 : return (IsJust() == other.IsJust()) &&
9030 330 : (!IsJust() || FromJust() == other.FromJust());
9031 : }
9032 :
9033 : V8_INLINE bool operator!=(const Maybe& other) const {
9034 : return !operator==(other);
9035 : }
9036 :
9037 : private:
9038 30311 : Maybe() : has_value_(false) {}
9039 26315712 : explicit Maybe(const T& t) : has_value_(true), value_(t) {}
9040 :
9041 : bool has_value_;
9042 : T value_;
9043 :
9044 : template <class U>
9045 : friend Maybe<U> Nothing();
9046 : template <class U>
9047 : friend Maybe<U> Just(const U& u);
9048 : };
9049 :
9050 : template <class T>
9051 3786619 : inline Maybe<T> Nothing() {
9052 3786619 : return Maybe<T>();
9053 : }
9054 :
9055 : template <class T>
9056 1023204 : inline Maybe<T> Just(const T& t) {
9057 1023204 : return Maybe<T>(t);
9058 : }
9059 :
9060 : // A template specialization of Maybe<T> for the case of T = void.
9061 : template <>
9062 : class Maybe<void> {
9063 : public:
9064 : V8_INLINE bool IsNothing() const { return !is_valid_; }
9065 : V8_INLINE bool IsJust() const { return is_valid_; }
9066 :
9067 : V8_INLINE bool operator==(const Maybe& other) const {
9068 : return IsJust() == other.IsJust();
9069 : }
9070 :
9071 : V8_INLINE bool operator!=(const Maybe& other) const {
9072 : return !operator==(other);
9073 : }
9074 :
9075 : private:
9076 : struct JustTag {};
9077 :
9078 : Maybe() : is_valid_(false) {}
9079 : explicit Maybe(JustTag) : is_valid_(true) {}
9080 :
9081 : bool is_valid_;
9082 :
9083 : template <class U>
9084 : friend Maybe<U> Nothing();
9085 : friend Maybe<void> JustVoid();
9086 : };
9087 :
9088 : inline Maybe<void> JustVoid() { return Maybe<void>(Maybe<void>::JustTag()); }
9089 :
9090 : /**
9091 : * An external exception handler.
9092 : */
9093 : class V8_EXPORT TryCatch {
9094 : public:
9095 : /**
9096 : * Creates a new try/catch block and registers it with v8. Note that
9097 : * all TryCatch blocks should be stack allocated because the memory
9098 : * location itself is compared against JavaScript try/catch blocks.
9099 : */
9100 : explicit TryCatch(Isolate* isolate);
9101 :
9102 : /**
9103 : * Unregisters and deletes this try/catch block.
9104 : */
9105 : ~TryCatch();
9106 :
9107 : /**
9108 : * Returns true if an exception has been caught by this try/catch block.
9109 : */
9110 : bool HasCaught() const;
9111 :
9112 : /**
9113 : * For certain types of exceptions, it makes no sense to continue execution.
9114 : *
9115 : * If CanContinue returns false, the correct action is to perform any C++
9116 : * cleanup needed and then return. If CanContinue returns false and
9117 : * HasTerminated returns true, it is possible to call
9118 : * CancelTerminateExecution in order to continue calling into the engine.
9119 : */
9120 : bool CanContinue() const;
9121 :
9122 : /**
9123 : * Returns true if an exception has been caught due to script execution
9124 : * being terminated.
9125 : *
9126 : * There is no JavaScript representation of an execution termination
9127 : * exception. Such exceptions are thrown when the TerminateExecution
9128 : * methods are called to terminate a long-running script.
9129 : *
9130 : * If such an exception has been thrown, HasTerminated will return true,
9131 : * indicating that it is possible to call CancelTerminateExecution in order
9132 : * to continue calling into the engine.
9133 : */
9134 : bool HasTerminated() const;
9135 :
9136 : /**
9137 : * Throws the exception caught by this TryCatch in a way that avoids
9138 : * it being caught again by this same TryCatch. As with ThrowException
9139 : * it is illegal to execute any JavaScript operations after calling
9140 : * ReThrow; the caller must return immediately to where the exception
9141 : * is caught.
9142 : */
9143 : Local<Value> ReThrow();
9144 :
9145 : /**
9146 : * Returns the exception caught by this try/catch block. If no exception has
9147 : * been caught an empty handle is returned.
9148 : *
9149 : * The returned handle is valid until this TryCatch block has been destroyed.
9150 : */
9151 : Local<Value> Exception() const;
9152 :
9153 : /**
9154 : * Returns the .stack property of the thrown object. If no .stack
9155 : * property is present an empty handle is returned.
9156 : */
9157 : V8_WARN_UNUSED_RESULT MaybeLocal<Value> StackTrace(
9158 : Local<Context> context) const;
9159 :
9160 : /**
9161 : * Returns the message associated with this exception. If there is
9162 : * no message associated an empty handle is returned.
9163 : *
9164 : * The returned handle is valid until this TryCatch block has been
9165 : * destroyed.
9166 : */
9167 : Local<v8::Message> Message() const;
9168 :
9169 : /**
9170 : * Clears any exceptions that may have been caught by this try/catch block.
9171 : * After this method has been called, HasCaught() will return false. Cancels
9172 : * the scheduled exception if it is caught and ReThrow() is not called before.
9173 : *
9174 : * It is not necessary to clear a try/catch block before using it again; if
9175 : * another exception is thrown the previously caught exception will just be
9176 : * overwritten. However, it is often a good idea since it makes it easier
9177 : * to determine which operation threw a given exception.
9178 : */
9179 : void Reset();
9180 :
9181 : /**
9182 : * Set verbosity of the external exception handler.
9183 : *
9184 : * By default, exceptions that are caught by an external exception
9185 : * handler are not reported. Call SetVerbose with true on an
9186 : * external exception handler to have exceptions caught by the
9187 : * handler reported as if they were not caught.
9188 : */
9189 : void SetVerbose(bool value);
9190 :
9191 : /**
9192 : * Returns true if verbosity is enabled.
9193 : */
9194 : bool IsVerbose() const;
9195 :
9196 : /**
9197 : * Set whether or not this TryCatch should capture a Message object
9198 : * which holds source information about where the exception
9199 : * occurred. True by default.
9200 : */
9201 : void SetCaptureMessage(bool value);
9202 :
9203 : /**
9204 : * There are cases when the raw address of C++ TryCatch object cannot be
9205 : * used for comparisons with addresses into the JS stack. The cases are:
9206 : * 1) ARM, ARM64 and MIPS simulators which have separate JS stack.
9207 : * 2) Address sanitizer allocates local C++ object in the heap when
9208 : * UseAfterReturn mode is enabled.
9209 : * This method returns address that can be used for comparisons with
9210 : * addresses into the JS stack. When neither simulator nor ASAN's
9211 : * UseAfterReturn is enabled, then the address returned will be the address
9212 : * of the C++ try catch handler itself.
9213 : */
9214 : static void* JSStackComparableAddress(TryCatch* handler) {
9215 221507 : if (handler == nullptr) return nullptr;
9216 212940 : return handler->js_stack_comparable_address_;
9217 : }
9218 :
9219 : TryCatch(const TryCatch&) = delete;
9220 : void operator=(const TryCatch&) = delete;
9221 :
9222 : private:
9223 : // Declaring operator new and delete as deleted is not spec compliant.
9224 : // Therefore declare them private instead to disable dynamic alloc
9225 : void* operator new(size_t size);
9226 : void* operator new[](size_t size);
9227 : void operator delete(void*, size_t);
9228 : void operator delete[](void*, size_t);
9229 :
9230 : void ResetInternal();
9231 :
9232 : internal::Isolate* isolate_;
9233 : TryCatch* next_;
9234 : void* exception_;
9235 : void* message_obj_;
9236 : void* js_stack_comparable_address_;
9237 : bool is_verbose_ : 1;
9238 : bool can_continue_ : 1;
9239 : bool capture_message_ : 1;
9240 : bool rethrow_ : 1;
9241 : bool has_terminated_ : 1;
9242 :
9243 : friend class internal::Isolate;
9244 : };
9245 :
9246 :
9247 : // --- Context ---
9248 :
9249 :
9250 : /**
9251 : * A container for extension names.
9252 : */
9253 : class V8_EXPORT ExtensionConfiguration {
9254 : public:
9255 91772 : ExtensionConfiguration() : name_count_(0), names_(nullptr) {}
9256 : ExtensionConfiguration(int name_count, const char* names[])
9257 452 : : name_count_(name_count), names_(names) { }
9258 :
9259 : const char** begin() const { return &names_[0]; }
9260 93293 : const char** end() const { return &names_[name_count_]; }
9261 :
9262 : private:
9263 : const int name_count_;
9264 : const char** names_;
9265 : };
9266 :
9267 : /**
9268 : * A sandboxed execution context with its own set of built-in objects
9269 : * and functions.
9270 : */
9271 : class V8_EXPORT Context {
9272 : public:
9273 : /**
9274 : * Returns the global proxy object.
9275 : *
9276 : * Global proxy object is a thin wrapper whose prototype points to actual
9277 : * context's global object with the properties like Object, etc. This is done
9278 : * that way for security reasons (for more details see
9279 : * https://wiki.mozilla.org/Gecko:SplitWindow).
9280 : *
9281 : * Please note that changes to global proxy object prototype most probably
9282 : * would break VM---v8 expects only global object as a prototype of global
9283 : * proxy object.
9284 : */
9285 : Local<Object> Global();
9286 :
9287 : /**
9288 : * Detaches the global object from its context before
9289 : * the global object can be reused to create a new context.
9290 : */
9291 : void DetachGlobal();
9292 :
9293 : /**
9294 : * Creates a new context and returns a handle to the newly allocated
9295 : * context.
9296 : *
9297 : * \param isolate The isolate in which to create the context.
9298 : *
9299 : * \param extensions An optional extension configuration containing
9300 : * the extensions to be installed in the newly created context.
9301 : *
9302 : * \param global_template An optional object template from which the
9303 : * global object for the newly created context will be created.
9304 : *
9305 : * \param global_object An optional global object to be reused for
9306 : * the newly created context. This global object must have been
9307 : * created by a previous call to Context::New with the same global
9308 : * template. The state of the global object will be completely reset
9309 : * and only object identify will remain.
9310 : */
9311 : static Local<Context> New(
9312 : Isolate* isolate, ExtensionConfiguration* extensions = nullptr,
9313 : MaybeLocal<ObjectTemplate> global_template = MaybeLocal<ObjectTemplate>(),
9314 : MaybeLocal<Value> global_object = MaybeLocal<Value>(),
9315 : DeserializeInternalFieldsCallback internal_fields_deserializer =
9316 : DeserializeInternalFieldsCallback(),
9317 : MicrotaskQueue* microtask_queue = nullptr);
9318 :
9319 : /**
9320 : * Create a new context from a (non-default) context snapshot. There
9321 : * is no way to provide a global object template since we do not create
9322 : * a new global object from template, but we can reuse a global object.
9323 : *
9324 : * \param isolate See v8::Context::New.
9325 : *
9326 : * \param context_snapshot_index The index of the context snapshot to
9327 : * deserialize from. Use v8::Context::New for the default snapshot.
9328 : *
9329 : * \param embedder_fields_deserializer Optional callback to deserialize
9330 : * internal fields. It should match the SerializeInternalFieldCallback used
9331 : * to serialize.
9332 : *
9333 : * \param extensions See v8::Context::New.
9334 : *
9335 : * \param global_object See v8::Context::New.
9336 : */
9337 : static MaybeLocal<Context> FromSnapshot(
9338 : Isolate* isolate, size_t context_snapshot_index,
9339 : DeserializeInternalFieldsCallback embedder_fields_deserializer =
9340 : DeserializeInternalFieldsCallback(),
9341 : ExtensionConfiguration* extensions = nullptr,
9342 : MaybeLocal<Value> global_object = MaybeLocal<Value>(),
9343 : MicrotaskQueue* microtask_queue = nullptr);
9344 :
9345 : /**
9346 : * Returns an global object that isn't backed by an actual context.
9347 : *
9348 : * The global template needs to have access checks with handlers installed.
9349 : * If an existing global object is passed in, the global object is detached
9350 : * from its context.
9351 : *
9352 : * Note that this is different from a detached context where all accesses to
9353 : * the global proxy will fail. Instead, the access check handlers are invoked.
9354 : *
9355 : * It is also not possible to detach an object returned by this method.
9356 : * Instead, the access check handlers need to return nothing to achieve the
9357 : * same effect.
9358 : *
9359 : * It is possible, however, to create a new context from the global object
9360 : * returned by this method.
9361 : */
9362 : static MaybeLocal<Object> NewRemoteContext(
9363 : Isolate* isolate, Local<ObjectTemplate> global_template,
9364 : MaybeLocal<Value> global_object = MaybeLocal<Value>());
9365 :
9366 : /**
9367 : * Sets the security token for the context. To access an object in
9368 : * another context, the security tokens must match.
9369 : */
9370 : void SetSecurityToken(Local<Value> token);
9371 :
9372 : /** Restores the security token to the default value. */
9373 : void UseDefaultSecurityToken();
9374 :
9375 : /** Returns the security token of this context.*/
9376 : Local<Value> GetSecurityToken();
9377 :
9378 : /**
9379 : * Enter this context. After entering a context, all code compiled
9380 : * and run is compiled and run in this context. If another context
9381 : * is already entered, this old context is saved so it can be
9382 : * restored when the new context is exited.
9383 : */
9384 : void Enter();
9385 :
9386 : /**
9387 : * Exit this context. Exiting the current context restores the
9388 : * context that was in place when entering the current context.
9389 : */
9390 : void Exit();
9391 :
9392 : /** Returns an isolate associated with a current context. */
9393 : Isolate* GetIsolate();
9394 :
9395 : /**
9396 : * The field at kDebugIdIndex used to be reserved for the inspector.
9397 : * It now serves no purpose.
9398 : */
9399 : enum EmbedderDataFields { kDebugIdIndex = 0 };
9400 :
9401 : /**
9402 : * Return the number of fields allocated for embedder data.
9403 : */
9404 : uint32_t GetNumberOfEmbedderDataFields();
9405 :
9406 : /**
9407 : * Gets the embedder data with the given index, which must have been set by a
9408 : * previous call to SetEmbedderData with the same index.
9409 : */
9410 : V8_INLINE Local<Value> GetEmbedderData(int index);
9411 :
9412 : /**
9413 : * Gets the binding object used by V8 extras. Extra natives get a reference
9414 : * to this object and can use it to "export" functionality by adding
9415 : * properties. Extra natives can also "import" functionality by accessing
9416 : * properties added by the embedder using the V8 API.
9417 : */
9418 : Local<Object> GetExtrasBindingObject();
9419 :
9420 : /**
9421 : * Sets the embedder data with the given index, growing the data as
9422 : * needed. Note that index 0 currently has a special meaning for Chrome's
9423 : * debugger.
9424 : */
9425 : void SetEmbedderData(int index, Local<Value> value);
9426 :
9427 : /**
9428 : * Gets a 2-byte-aligned native pointer from the embedder data with the given
9429 : * index, which must have been set by a previous call to
9430 : * SetAlignedPointerInEmbedderData with the same index. Note that index 0
9431 : * currently has a special meaning for Chrome's debugger.
9432 : */
9433 : V8_INLINE void* GetAlignedPointerFromEmbedderData(int index);
9434 :
9435 : /**
9436 : * Sets a 2-byte-aligned native pointer in the embedder data with the given
9437 : * index, growing the data as needed. Note that index 0 currently has a
9438 : * special meaning for Chrome's debugger.
9439 : */
9440 : void SetAlignedPointerInEmbedderData(int index, void* value);
9441 :
9442 : /**
9443 : * Control whether code generation from strings is allowed. Calling
9444 : * this method with false will disable 'eval' and the 'Function'
9445 : * constructor for code running in this context. If 'eval' or the
9446 : * 'Function' constructor are used an exception will be thrown.
9447 : *
9448 : * If code generation from strings is not allowed the
9449 : * V8::AllowCodeGenerationFromStrings callback will be invoked if
9450 : * set before blocking the call to 'eval' or the 'Function'
9451 : * constructor. If that callback returns true, the call will be
9452 : * allowed, otherwise an exception will be thrown. If no callback is
9453 : * set an exception will be thrown.
9454 : */
9455 : void AllowCodeGenerationFromStrings(bool allow);
9456 :
9457 : /**
9458 : * Returns true if code generation from strings is allowed for the context.
9459 : * For more details see AllowCodeGenerationFromStrings(bool) documentation.
9460 : */
9461 : bool IsCodeGenerationFromStringsAllowed();
9462 :
9463 : /**
9464 : * Sets the error description for the exception that is thrown when
9465 : * code generation from strings is not allowed and 'eval' or the 'Function'
9466 : * constructor are called.
9467 : */
9468 : void SetErrorMessageForCodeGenerationFromStrings(Local<String> message);
9469 :
9470 : /**
9471 : * Return data that was previously attached to the context snapshot via
9472 : * SnapshotCreator, and removes the reference to it.
9473 : * Repeated call with the same index returns an empty MaybeLocal.
9474 : */
9475 : template <class T>
9476 : V8_INLINE MaybeLocal<T> GetDataFromSnapshotOnce(size_t index);
9477 :
9478 : /**
9479 : * Stack-allocated class which sets the execution context for all
9480 : * operations executed within a local scope.
9481 : */
9482 : class Scope {
9483 : public:
9484 842 : explicit V8_INLINE Scope(Local<Context> context) : context_(context) {
9485 4159854 : context_->Enter();
9486 : }
9487 4157763 : V8_INLINE ~Scope() { context_->Exit(); }
9488 :
9489 : private:
9490 : Local<Context> context_;
9491 : };
9492 :
9493 : /**
9494 : * Stack-allocated class to support the backup incumbent settings object
9495 : * stack.
9496 : * https://html.spec.whatwg.org/multipage/webappapis.html#backup-incumbent-settings-object-stack
9497 : */
9498 : class V8_EXPORT BackupIncumbentScope final {
9499 : public:
9500 : /**
9501 : * |backup_incumbent_context| is pushed onto the backup incumbent settings
9502 : * object stack.
9503 : */
9504 : explicit BackupIncumbentScope(Local<Context> backup_incumbent_context);
9505 : ~BackupIncumbentScope();
9506 :
9507 : /**
9508 : * Returns address that is comparable with JS stack address. Note that JS
9509 : * stack may be allocated separately from the native stack. See also
9510 : * |TryCatch::JSStackComparableAddress| for details.
9511 : */
9512 : uintptr_t JSStackComparableAddress() const {
9513 : return js_stack_comparable_address_;
9514 : }
9515 :
9516 : private:
9517 : friend class internal::Isolate;
9518 :
9519 : Local<Context> backup_incumbent_context_;
9520 : uintptr_t js_stack_comparable_address_ = 0;
9521 : const BackupIncumbentScope* prev_ = nullptr;
9522 : };
9523 :
9524 : private:
9525 : friend class Value;
9526 : friend class Script;
9527 : friend class Object;
9528 : friend class Function;
9529 :
9530 : internal::Address* GetDataFromSnapshotOnce(size_t index);
9531 : Local<Value> SlowGetEmbedderData(int index);
9532 : void* SlowGetAlignedPointerFromEmbedderData(int index);
9533 : };
9534 :
9535 :
9536 : /**
9537 : * Multiple threads in V8 are allowed, but only one thread at a time is allowed
9538 : * to use any given V8 isolate, see the comments in the Isolate class. The
9539 : * definition of 'using a V8 isolate' includes accessing handles or holding onto
9540 : * object pointers obtained from V8 handles while in the particular V8 isolate.
9541 : * It is up to the user of V8 to ensure, perhaps with locking, that this
9542 : * constraint is not violated. In addition to any other synchronization
9543 : * mechanism that may be used, the v8::Locker and v8::Unlocker classes must be
9544 : * used to signal thread switches to V8.
9545 : *
9546 : * v8::Locker is a scoped lock object. While it's active, i.e. between its
9547 : * construction and destruction, the current thread is allowed to use the locked
9548 : * isolate. V8 guarantees that an isolate can be locked by at most one thread at
9549 : * any time. In other words, the scope of a v8::Locker is a critical section.
9550 : *
9551 : * Sample usage:
9552 : * \code
9553 : * ...
9554 : * {
9555 : * v8::Locker locker(isolate);
9556 : * v8::Isolate::Scope isolate_scope(isolate);
9557 : * ...
9558 : * // Code using V8 and isolate goes here.
9559 : * ...
9560 : * } // Destructor called here
9561 : * \endcode
9562 : *
9563 : * If you wish to stop using V8 in a thread A you can do this either by
9564 : * destroying the v8::Locker object as above or by constructing a v8::Unlocker
9565 : * object:
9566 : *
9567 : * \code
9568 : * {
9569 : * isolate->Exit();
9570 : * v8::Unlocker unlocker(isolate);
9571 : * ...
9572 : * // Code not using V8 goes here while V8 can run in another thread.
9573 : * ...
9574 : * } // Destructor called here.
9575 : * isolate->Enter();
9576 : * \endcode
9577 : *
9578 : * The Unlocker object is intended for use in a long-running callback from V8,
9579 : * where you want to release the V8 lock for other threads to use.
9580 : *
9581 : * The v8::Locker is a recursive lock, i.e. you can lock more than once in a
9582 : * given thread. This can be useful if you have code that can be called either
9583 : * from code that holds the lock or from code that does not. The Unlocker is
9584 : * not recursive so you can not have several Unlockers on the stack at once, and
9585 : * you can not use an Unlocker in a thread that is not inside a Locker's scope.
9586 : *
9587 : * An unlocker will unlock several lockers if it has to and reinstate the
9588 : * correct depth of locking on its destruction, e.g.:
9589 : *
9590 : * \code
9591 : * // V8 not locked.
9592 : * {
9593 : * v8::Locker locker(isolate);
9594 : * Isolate::Scope isolate_scope(isolate);
9595 : * // V8 locked.
9596 : * {
9597 : * v8::Locker another_locker(isolate);
9598 : * // V8 still locked (2 levels).
9599 : * {
9600 : * isolate->Exit();
9601 : * v8::Unlocker unlocker(isolate);
9602 : * // V8 not locked.
9603 : * }
9604 : * isolate->Enter();
9605 : * // V8 locked again (2 levels).
9606 : * }
9607 : * // V8 still locked (1 level).
9608 : * }
9609 : * // V8 Now no longer locked.
9610 : * \endcode
9611 : */
9612 : class V8_EXPORT Unlocker {
9613 : public:
9614 : /**
9615 : * Initialize Unlocker for a given Isolate.
9616 : */
9617 33375 : V8_INLINE explicit Unlocker(Isolate* isolate) { Initialize(isolate); }
9618 :
9619 : ~Unlocker();
9620 : private:
9621 : void Initialize(Isolate* isolate);
9622 :
9623 : internal::Isolate* isolate_;
9624 : };
9625 :
9626 :
9627 : class V8_EXPORT Locker {
9628 : public:
9629 : /**
9630 : * Initialize Locker for a given Isolate.
9631 : */
9632 8433 : V8_INLINE explicit Locker(Isolate* isolate) { Initialize(isolate); }
9633 :
9634 : ~Locker();
9635 :
9636 : /**
9637 : * Returns whether or not the locker for a given isolate, is locked by the
9638 : * current thread.
9639 : */
9640 : static bool IsLocked(Isolate* isolate);
9641 :
9642 : /**
9643 : * Returns whether v8::Locker is being used by this V8 instance.
9644 : */
9645 : static bool IsActive();
9646 :
9647 : // Disallow copying and assigning.
9648 : Locker(const Locker&) = delete;
9649 : void operator=(const Locker&) = delete;
9650 :
9651 : private:
9652 : void Initialize(Isolate* isolate);
9653 :
9654 : bool has_lock_;
9655 : bool top_level_;
9656 : internal::Isolate* isolate_;
9657 : };
9658 :
9659 : /**
9660 : * Various helpers for skipping over V8 frames in a given stack.
9661 : *
9662 : * The unwinder API is only supported on the x64 architecture.
9663 : */
9664 : class V8_EXPORT Unwinder {
9665 : public:
9666 : /**
9667 : * Attempt to unwind the stack to the most recent C++ frame. This function is
9668 : * signal-safe and does not access any V8 state and thus doesn't require an
9669 : * Isolate.
9670 : *
9671 : * The unwinder needs to know the location of the JS Entry Stub (a piece of
9672 : * code that is run when C++ code calls into generated JS code). This is used
9673 : * for edge cases where the current frame is being constructed or torn down
9674 : * when the stack sample occurs.
9675 : *
9676 : * The unwinder also needs the virtual memory range of all possible V8 code
9677 : * objects. There are two ranges required - the heap code range and the range
9678 : * for code embedded in the binary. The V8 API provides all required inputs
9679 : * via an UnwindState object through the Isolate::GetUnwindState() API. These
9680 : * values will not change after Isolate initialization, so the same
9681 : * |unwind_state| can be used for multiple calls.
9682 : *
9683 : * \param unwind_state Input state for the Isolate that the stack comes from.
9684 : * \param register_state The current registers. This is an in-out param that
9685 : * will be overwritten with the register values after unwinding, on success.
9686 : * \param stack_base The resulting stack pointer and frame pointer values are
9687 : * bounds-checked against the stack_base and the original stack pointer value
9688 : * to ensure that they are valid locations in the given stack. If these values
9689 : * or any intermediate frame pointer values used during unwinding are ever out
9690 : * of these bounds, unwinding will fail.
9691 : *
9692 : * \return True on success.
9693 : */
9694 : static bool TryUnwindV8Frames(const UnwindState& unwind_state,
9695 : RegisterState* register_state,
9696 : const void* stack_base);
9697 :
9698 : /**
9699 : * Whether the PC is within the V8 code range represented by code_range or
9700 : * embedded_code_range in |unwind_state|.
9701 : *
9702 : * If this returns false, then calling UnwindV8Frames() with the same PC
9703 : * and unwind_state will always fail. If it returns true, then unwinding may
9704 : * (but not necessarily) be successful.
9705 : */
9706 : static bool PCIsInV8(const UnwindState& unwind_state, void* pc);
9707 : };
9708 :
9709 : // --- Implementation ---
9710 :
9711 : template <class T>
9712 : Local<T> Local<T>::New(Isolate* isolate, Local<T> that) {
9713 : return New(isolate, that.val_);
9714 : }
9715 :
9716 : template <class T>
9717 : Local<T> Local<T>::New(Isolate* isolate, const PersistentBase<T>& that) {
9718 4997782 : return New(isolate, that.val_);
9719 : }
9720 :
9721 : template <class T>
9722 : Local<T> Local<T>::New(Isolate* isolate, const TracedGlobal<T>& that) {
9723 45 : return New(isolate, that.val_);
9724 : }
9725 :
9726 : template <class T>
9727 : Local<T> Local<T>::New(Isolate* isolate, T* that) {
9728 5057876 : if (that == nullptr) return Local<T>();
9729 : T* that_ptr = that;
9730 : internal::Address* p = reinterpret_cast<internal::Address*>(that_ptr);
9731 5057039 : return Local<T>(reinterpret_cast<T*>(HandleScope::CreateHandle(
9732 : reinterpret_cast<internal::Isolate*>(isolate), *p)));
9733 : }
9734 :
9735 :
9736 : template<class T>
9737 : template<class S>
9738 : void Eternal<T>::Set(Isolate* isolate, Local<S> handle) {
9739 : TYPE_CHECK(T, S);
9740 10235 : val_ = reinterpret_cast<T*>(
9741 10245 : V8::Eternalize(isolate, reinterpret_cast<Value*>(*handle)));
9742 : }
9743 :
9744 : template <class T>
9745 : Local<T> Eternal<T>::Get(Isolate* isolate) const {
9746 : // The eternal handle will never go away, so as with the roots, we don't even
9747 : // need to open a handle.
9748 10235 : return Local<T>(val_);
9749 : }
9750 :
9751 :
9752 : template <class T>
9753 : Local<T> MaybeLocal<T>::ToLocalChecked() {
9754 11341784 : if (V8_UNLIKELY(val_ == nullptr)) V8::ToLocalEmpty();
9755 : return Local<T>(val_);
9756 : }
9757 :
9758 :
9759 : template <class T>
9760 : void* WeakCallbackInfo<T>::GetInternalField(int index) const {
9761 : #ifdef V8_ENABLE_CHECKS
9762 : if (index < 0 || index >= kEmbedderFieldsInWeakCallback) {
9763 : V8::InternalFieldOutOfBounds(index);
9764 : }
9765 : #endif
9766 37 : return embedder_fields_[index];
9767 : }
9768 :
9769 :
9770 : template <class T>
9771 : T* PersistentBase<T>::New(Isolate* isolate, T* that) {
9772 3042105 : if (that == nullptr) return nullptr;
9773 : internal::Address* p = reinterpret_cast<internal::Address*>(that);
9774 : return reinterpret_cast<T*>(
9775 : V8::GlobalizeReference(reinterpret_cast<internal::Isolate*>(isolate),
9776 3042105 : p));
9777 : }
9778 :
9779 :
9780 : template <class T, class M>
9781 : template <class S, class M2>
9782 : void Persistent<T, M>::Copy(const Persistent<S, M2>& that) {
9783 : TYPE_CHECK(T, S);
9784 : this->Reset();
9785 10 : if (that.IsEmpty()) return;
9786 : internal::Address* p = reinterpret_cast<internal::Address*>(that.val_);
9787 10 : this->val_ = reinterpret_cast<T*>(V8::CopyGlobalReference(p));
9788 : M::Copy(that, this);
9789 : }
9790 :
9791 : template <class T>
9792 : bool PersistentBase<T>::IsIndependent() const {
9793 : typedef internal::Internals I;
9794 46 : if (this->IsEmpty()) return false;
9795 : return I::GetNodeFlag(reinterpret_cast<internal::Address*>(this->val_),
9796 46 : I::kNodeIsIndependentShift);
9797 : }
9798 :
9799 : template <class T>
9800 : bool PersistentBase<T>::IsWeak() const {
9801 : typedef internal::Internals I;
9802 40 : if (this->IsEmpty()) return false;
9803 : return I::GetNodeState(reinterpret_cast<internal::Address*>(this->val_)) ==
9804 20 : I::kNodeStateIsWeakValue;
9805 : }
9806 :
9807 :
9808 : template <class T>
9809 : void PersistentBase<T>::Reset() {
9810 6254788 : if (this->IsEmpty()) return;
9811 3039387 : V8::DisposeGlobal(reinterpret_cast<internal::Address*>(this->val_));
9812 3005228 : val_ = nullptr;
9813 : }
9814 :
9815 :
9816 : template <class T>
9817 : template <class S>
9818 : void PersistentBase<T>::Reset(Isolate* isolate, const Local<S>& other) {
9819 : TYPE_CHECK(T, S);
9820 : Reset();
9821 2880172 : if (other.IsEmpty()) return;
9822 2879977 : this->val_ = New(isolate, other.val_);
9823 : }
9824 :
9825 :
9826 : template <class T>
9827 : template <class S>
9828 : void PersistentBase<T>::Reset(Isolate* isolate,
9829 : const PersistentBase<S>& other) {
9830 : TYPE_CHECK(T, S);
9831 : Reset();
9832 3147 : if (other.IsEmpty()) return;
9833 843 : this->val_ = New(isolate, other.val_);
9834 : }
9835 :
9836 :
9837 : template <class T>
9838 : template <typename P>
9839 : V8_INLINE void PersistentBase<T>::SetWeak(
9840 : P* parameter, typename WeakCallbackInfo<P>::Callback callback,
9841 : WeakCallbackType type) {
9842 : typedef typename WeakCallbackInfo<void>::Callback Callback;
9843 166953 : V8::MakeWeak(reinterpret_cast<internal::Address*>(this->val_), parameter,
9844 : reinterpret_cast<Callback>(callback), type);
9845 : }
9846 :
9847 : template <class T>
9848 : void PersistentBase<T>::SetWeak() {
9849 36 : V8::MakeWeak(reinterpret_cast<internal::Address**>(&this->val_));
9850 : }
9851 :
9852 : template <class T>
9853 : template <typename P>
9854 : P* PersistentBase<T>::ClearWeak() {
9855 : return reinterpret_cast<P*>(
9856 21093 : V8::ClearWeak(reinterpret_cast<internal::Address*>(this->val_)));
9857 : }
9858 :
9859 : template <class T>
9860 : void PersistentBase<T>::AnnotateStrongRetainer(const char* label) {
9861 2813366 : V8::AnnotateStrongRetainer(reinterpret_cast<internal::Address*>(this->val_),
9862 : label);
9863 : }
9864 :
9865 : template <class T>
9866 : void PersistentBase<T>::RegisterExternalReference(Isolate* isolate) const {
9867 : if (IsEmpty()) return;
9868 : V8::RegisterExternallyReferencedObject(
9869 : reinterpret_cast<internal::Address*>(this->val_),
9870 : reinterpret_cast<internal::Isolate*>(isolate));
9871 : }
9872 :
9873 : template <class T>
9874 : void PersistentBase<T>::MarkIndependent() {
9875 : typedef internal::Internals I;
9876 106071 : if (this->IsEmpty()) return;
9877 : I::UpdateNodeFlag(reinterpret_cast<internal::Address*>(this->val_), true,
9878 : I::kNodeIsIndependentShift);
9879 : }
9880 :
9881 : template <class T>
9882 : void PersistentBase<T>::MarkActive() {
9883 : typedef internal::Internals I;
9884 15 : if (this->IsEmpty()) return;
9885 : I::UpdateNodeFlag(reinterpret_cast<internal::Address*>(this->val_), true,
9886 : I::kNodeIsActiveShift);
9887 : }
9888 :
9889 :
9890 : template <class T>
9891 : void PersistentBase<T>::SetWrapperClassId(uint16_t class_id) {
9892 : typedef internal::Internals I;
9893 25 : if (this->IsEmpty()) return;
9894 : internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
9895 : uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9896 25 : *reinterpret_cast<uint16_t*>(addr) = class_id;
9897 : }
9898 :
9899 :
9900 : template <class T>
9901 : uint16_t PersistentBase<T>::WrapperClassId() const {
9902 : typedef internal::Internals I;
9903 25 : if (this->IsEmpty()) return 0;
9904 : internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
9905 : uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9906 25 : return *reinterpret_cast<uint16_t*>(addr);
9907 : }
9908 :
9909 : template <class T>
9910 5718 : Global<T>::Global(Global&& other) : PersistentBase<T>(other.val_) {
9911 5803 : if (other.val_ != nullptr) {
9912 5713 : V8::MoveGlobalReference(reinterpret_cast<internal::Address**>(&other.val_),
9913 : reinterpret_cast<internal::Address**>(&this->val_));
9914 5713 : other.val_ = nullptr;
9915 : }
9916 : }
9917 :
9918 : template <class T>
9919 : template <class S>
9920 : Global<T>& Global<T>::operator=(Global<S>&& rhs) {
9921 : TYPE_CHECK(T, S);
9922 5 : if (this != &rhs) {
9923 : this->Reset();
9924 53 : if (rhs.val_ != nullptr) {
9925 43 : this->val_ = rhs.val_;
9926 43 : V8::MoveGlobalReference(
9927 : reinterpret_cast<internal::Address**>(&rhs.val_),
9928 : reinterpret_cast<internal::Address**>(&this->val_));
9929 43 : rhs.val_ = nullptr;
9930 : }
9931 : }
9932 : return *this;
9933 : }
9934 :
9935 : template <class T>
9936 : T* TracedGlobal<T>::New(Isolate* isolate, T* that, T** slot) {
9937 70 : if (that == nullptr) return nullptr;
9938 : internal::Address* p = reinterpret_cast<internal::Address*>(that);
9939 : return reinterpret_cast<T*>(V8::GlobalizeTracedReference(
9940 : reinterpret_cast<internal::Isolate*>(isolate), p,
9941 70 : reinterpret_cast<internal::Address*>(slot)));
9942 : }
9943 :
9944 : template <class T>
9945 : void TracedGlobal<T>::Reset() {
9946 200 : if (IsEmpty()) return;
9947 50 : V8::DisposeTracedGlobal(reinterpret_cast<internal::Address*>(val_));
9948 50 : val_ = nullptr;
9949 : }
9950 :
9951 : template <class T>
9952 : template <class S>
9953 : void TracedGlobal<T>::Reset(Isolate* isolate, const Local<S>& other) {
9954 : TYPE_CHECK(T, S);
9955 : Reset();
9956 5 : if (other.IsEmpty()) return;
9957 5 : this->val_ = New(isolate, other.val_, &val_);
9958 : }
9959 :
9960 : template <class T>
9961 0 : TracedGlobal<T>::TracedGlobal(TracedGlobal&& other) : val_(other.val_) {
9962 0 : if (other.val_ != nullptr) {
9963 0 : V8::MoveTracedGlobalReference(
9964 : reinterpret_cast<internal::Address**>(&other.val_),
9965 : reinterpret_cast<internal::Address**>(&this->val_));
9966 0 : other.val_ = nullptr;
9967 : }
9968 : }
9969 :
9970 : template <class T>
9971 : template <class S>
9972 : TracedGlobal<T>& TracedGlobal<T>::operator=(TracedGlobal<S>&& rhs) {
9973 : TYPE_CHECK(T, S);
9974 : if (this != &rhs) {
9975 : this->Reset();
9976 55 : if (rhs.val_ != nullptr) {
9977 55 : this->val_ = rhs.val_;
9978 55 : V8::MoveTracedGlobalReference(
9979 : reinterpret_cast<internal::Address**>(&rhs.val_),
9980 : reinterpret_cast<internal::Address**>(&this->val_));
9981 55 : rhs.val_ = nullptr;
9982 : }
9983 : }
9984 : return *this;
9985 : }
9986 :
9987 : template <class T>
9988 : void TracedGlobal<T>::SetWrapperClassId(uint16_t class_id) {
9989 : typedef internal::Internals I;
9990 10 : if (IsEmpty()) return;
9991 : internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
9992 : uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
9993 10 : *reinterpret_cast<uint16_t*>(addr) = class_id;
9994 : }
9995 :
9996 : template <class T>
9997 : uint16_t TracedGlobal<T>::WrapperClassId() const {
9998 : typedef internal::Internals I;
9999 15 : if (IsEmpty()) return 0;
10000 5 : internal::Address* obj = reinterpret_cast<internal::Address*>(this->val_);
10001 : uint8_t* addr = reinterpret_cast<uint8_t*>(obj) + I::kNodeClassIdOffset;
10002 15 : return *reinterpret_cast<uint16_t*>(addr);
10003 : }
10004 :
10005 : template <class T>
10006 : void TracedGlobal<T>::SetFinalizationCallback(
10007 : void* parameter, typename WeakCallbackInfo<void>::Callback callback) {
10008 10 : V8::SetFinalizationCallbackTraced(
10009 : reinterpret_cast<internal::Address*>(this->val_), parameter, callback);
10010 : }
10011 :
10012 : template <typename T>
10013 : ReturnValue<T>::ReturnValue(internal::Address* slot) : value_(slot) {}
10014 :
10015 : template<typename T>
10016 : template<typename S>
10017 : void ReturnValue<T>::Set(const Persistent<S>& handle) {
10018 : TYPE_CHECK(T, S);
10019 : if (V8_UNLIKELY(handle.IsEmpty())) {
10020 : *value_ = GetDefaultValue();
10021 : } else {
10022 : *value_ = *reinterpret_cast<internal::Address*>(*handle);
10023 : }
10024 : }
10025 :
10026 : template <typename T>
10027 : template <typename S>
10028 : void ReturnValue<T>::Set(const Global<S>& handle) {
10029 : TYPE_CHECK(T, S);
10030 5137 : if (V8_UNLIKELY(handle.IsEmpty())) {
10031 0 : *value_ = GetDefaultValue();
10032 : } else {
10033 5137 : *value_ = *reinterpret_cast<internal::Address*>(*handle);
10034 : }
10035 : }
10036 :
10037 : template <typename T>
10038 : template <typename S>
10039 : void ReturnValue<T>::Set(const TracedGlobal<S>& handle) {
10040 : TYPE_CHECK(T, S);
10041 : if (V8_UNLIKELY(handle.IsEmpty())) {
10042 : *value_ = GetDefaultValue();
10043 : } else {
10044 : *value_ = *reinterpret_cast<internal::Address*>(*handle);
10045 : }
10046 : }
10047 :
10048 : template <typename T>
10049 : template <typename S>
10050 : void ReturnValue<T>::Set(const Local<S> handle) {
10051 : TYPE_CHECK(T, S);
10052 62366746 : if (V8_UNLIKELY(handle.IsEmpty())) {
10053 43417 : *value_ = GetDefaultValue();
10054 : } else {
10055 62330072 : *value_ = *reinterpret_cast<internal::Address*>(*handle);
10056 : }
10057 : }
10058 :
10059 : template<typename T>
10060 : void ReturnValue<T>::Set(double i) {
10061 : TYPE_CHECK(T, Number);
10062 5054 : Set(Number::New(GetIsolate(), i));
10063 : }
10064 :
10065 : template<typename T>
10066 : void ReturnValue<T>::Set(int32_t i) {
10067 : TYPE_CHECK(T, Integer);
10068 : typedef internal::Internals I;
10069 : if (V8_LIKELY(I::IsValidSmi(i))) {
10070 19110 : *value_ = I::IntToSmi(i);
10071 : return;
10072 : }
10073 : Set(Integer::New(GetIsolate(), i));
10074 : }
10075 :
10076 : template<typename T>
10077 : void ReturnValue<T>::Set(uint32_t i) {
10078 : TYPE_CHECK(T, Integer);
10079 : // Can't simply use INT32_MAX here for whatever reason.
10080 10797 : bool fits_into_int32_t = (i & (1U << 31)) == 0;
10081 10797 : if (V8_LIKELY(fits_into_int32_t)) {
10082 : Set(static_cast<int32_t>(i));
10083 : return;
10084 : }
10085 77 : Set(Integer::NewFromUnsigned(GetIsolate(), i));
10086 : }
10087 :
10088 : template<typename T>
10089 : void ReturnValue<T>::Set(bool value) {
10090 : TYPE_CHECK(T, Boolean);
10091 : typedef internal::Internals I;
10092 : int root_index;
10093 1133551 : if (value) {
10094 : root_index = I::kTrueValueRootIndex;
10095 : } else {
10096 : root_index = I::kFalseValueRootIndex;
10097 : }
10098 1765219 : *value_ = *I::GetRoot(GetIsolate(), root_index);
10099 : }
10100 :
10101 : template<typename T>
10102 : void ReturnValue<T>::SetNull() {
10103 : TYPE_CHECK(T, Primitive);
10104 : typedef internal::Internals I;
10105 191 : *value_ = *I::GetRoot(GetIsolate(), I::kNullValueRootIndex);
10106 : }
10107 :
10108 : template<typename T>
10109 : void ReturnValue<T>::SetUndefined() {
10110 : TYPE_CHECK(T, Primitive);
10111 : typedef internal::Internals I;
10112 88 : *value_ = *I::GetRoot(GetIsolate(), I::kUndefinedValueRootIndex);
10113 : }
10114 :
10115 : template<typename T>
10116 : void ReturnValue<T>::SetEmptyString() {
10117 : TYPE_CHECK(T, String);
10118 : typedef internal::Internals I;
10119 11 : *value_ = *I::GetRoot(GetIsolate(), I::kEmptyStringRootIndex);
10120 : }
10121 :
10122 : template <typename T>
10123 : Isolate* ReturnValue<T>::GetIsolate() const {
10124 : // Isolate is always the pointer below the default value on the stack.
10125 1777231 : return *reinterpret_cast<Isolate**>(&value_[-2]);
10126 : }
10127 :
10128 : template <typename T>
10129 : Local<Value> ReturnValue<T>::Get() const {
10130 : typedef internal::Internals I;
10131 6591 : if (*value_ == *I::GetRoot(GetIsolate(), I::kTheHoleValueRootIndex))
10132 : return Local<Value>(*Undefined(GetIsolate()));
10133 : return Local<Value>::New(GetIsolate(), reinterpret_cast<Value*>(value_));
10134 : }
10135 :
10136 : template <typename T>
10137 : template <typename S>
10138 : void ReturnValue<T>::Set(S* whatever) {
10139 : // Uncompilable to prevent inadvertent misuse.
10140 : TYPE_CHECK(S*, Primitive);
10141 : }
10142 :
10143 : template <typename T>
10144 : internal::Address ReturnValue<T>::GetDefaultValue() {
10145 : // Default value is always the pointer below value_ on the stack.
10146 43417 : return value_[-1];
10147 : }
10148 :
10149 : template <typename T>
10150 : FunctionCallbackInfo<T>::FunctionCallbackInfo(internal::Address* implicit_args,
10151 : internal::Address* values,
10152 : int length)
10153 2562227 : : implicit_args_(implicit_args), values_(values), length_(length) {}
10154 :
10155 : template<typename T>
10156 : Local<Value> FunctionCallbackInfo<T>::operator[](int i) const {
10157 3324364 : if (i < 0 || length_ <= i) return Local<Value>(*Undefined(GetIsolate()));
10158 3296126 : return Local<Value>(reinterpret_cast<Value*>(values_ - i));
10159 : }
10160 :
10161 :
10162 : template<typename T>
10163 : Local<Object> FunctionCallbackInfo<T>::This() const {
10164 60597554 : return Local<Object>(reinterpret_cast<Object*>(values_ + 1));
10165 : }
10166 :
10167 :
10168 : template<typename T>
10169 : Local<Object> FunctionCallbackInfo<T>::Holder() const {
10170 : return Local<Object>(reinterpret_cast<Object*>(
10171 8108 : &implicit_args_[kHolderIndex]));
10172 : }
10173 :
10174 : template <typename T>
10175 : Local<Value> FunctionCallbackInfo<T>::NewTarget() const {
10176 : return Local<Value>(
10177 294008 : reinterpret_cast<Value*>(&implicit_args_[kNewTargetIndex]));
10178 : }
10179 :
10180 : template <typename T>
10181 : Local<Value> FunctionCallbackInfo<T>::Data() const {
10182 1042636 : return Local<Value>(reinterpret_cast<Value*>(&implicit_args_[kDataIndex]));
10183 : }
10184 :
10185 :
10186 : template<typename T>
10187 : Isolate* FunctionCallbackInfo<T>::GetIsolate() const {
10188 70349074 : return *reinterpret_cast<Isolate**>(&implicit_args_[kIsolateIndex]);
10189 : }
10190 :
10191 :
10192 : template<typename T>
10193 : ReturnValue<T> FunctionCallbackInfo<T>::GetReturnValue() const {
10194 62311782 : return ReturnValue<T>(&implicit_args_[kReturnValueIndex]);
10195 : }
10196 :
10197 :
10198 : template<typename T>
10199 : bool FunctionCallbackInfo<T>::IsConstructCall() const {
10200 258 : return !NewTarget()->IsUndefined();
10201 : }
10202 :
10203 :
10204 : template<typename T>
10205 : int FunctionCallbackInfo<T>::Length() const {
10206 3523329 : return length_;
10207 : }
10208 :
10209 : ScriptOrigin::ScriptOrigin(Local<Value> resource_name,
10210 : Local<Integer> resource_line_offset,
10211 : Local<Integer> resource_column_offset,
10212 : Local<Boolean> resource_is_shared_cross_origin,
10213 : Local<Integer> script_id,
10214 : Local<Value> source_map_url,
10215 : Local<Boolean> resource_is_opaque,
10216 : Local<Boolean> is_wasm, Local<Boolean> is_module,
10217 : Local<PrimitiveArray> host_defined_options)
10218 : : resource_name_(resource_name),
10219 : resource_line_offset_(resource_line_offset),
10220 : resource_column_offset_(resource_column_offset),
10221 34276 : options_(!resource_is_shared_cross_origin.IsEmpty() &&
10222 1029 : resource_is_shared_cross_origin->IsTrue(),
10223 33172 : !resource_is_opaque.IsEmpty() && resource_is_opaque->IsTrue(),
10224 32224 : !is_wasm.IsEmpty() && is_wasm->IsTrue(),
10225 34144 : !is_module.IsEmpty() && is_module->IsTrue()),
10226 : script_id_(script_id),
10227 : source_map_url_(source_map_url),
10228 266132 : host_defined_options_(host_defined_options) {}
10229 :
10230 38998 : Local<Value> ScriptOrigin::ResourceName() const { return resource_name_; }
10231 :
10232 : Local<PrimitiveArray> ScriptOrigin::HostDefinedOptions() const {
10233 31903 : return host_defined_options_;
10234 : }
10235 :
10236 : Local<Integer> ScriptOrigin::ResourceLineOffset() const {
10237 31903 : return resource_line_offset_;
10238 : }
10239 :
10240 :
10241 : Local<Integer> ScriptOrigin::ResourceColumnOffset() const {
10242 31891 : return resource_column_offset_;
10243 : }
10244 :
10245 :
10246 1515 : Local<Integer> ScriptOrigin::ScriptID() const { return script_id_; }
10247 :
10248 :
10249 31908 : Local<Value> ScriptOrigin::SourceMapUrl() const { return source_map_url_; }
10250 :
10251 : ScriptCompiler::Source::Source(Local<String> string, const ScriptOrigin& origin,
10252 : CachedData* data)
10253 : : source_string(string),
10254 : resource_name(origin.ResourceName()),
10255 : resource_line_offset(origin.ResourceLineOffset()),
10256 : resource_column_offset(origin.ResourceColumnOffset()),
10257 : resource_options(origin.Options()),
10258 : source_map_url(origin.SourceMapUrl()),
10259 : host_defined_options(origin.HostDefinedOptions()),
10260 236000 : cached_data(data) {}
10261 :
10262 : ScriptCompiler::Source::Source(Local<String> string,
10263 : CachedData* data)
10264 266626 : : source_string(string), cached_data(data) {}
10265 :
10266 :
10267 258379 : ScriptCompiler::Source::~Source() {
10268 258379 : delete cached_data;
10269 : }
10270 :
10271 :
10272 : const ScriptCompiler::CachedData* ScriptCompiler::Source::GetCachedData()
10273 : const {
10274 : return cached_data;
10275 : }
10276 :
10277 : const ScriptOriginOptions& ScriptCompiler::Source::GetResourceOptions() const {
10278 : return resource_options;
10279 : }
10280 :
10281 : Local<Boolean> Boolean::New(Isolate* isolate, bool value) {
10282 192462 : return value ? True(isolate) : False(isolate);
10283 : }
10284 :
10285 : void Template::Set(Isolate* isolate, const char* name, Local<Data> value) {
10286 1290 : Set(String::NewFromUtf8(isolate, name, NewStringType::kInternalized)
10287 : .ToLocalChecked(),
10288 648 : value);
10289 : }
10290 :
10291 : FunctionTemplate* FunctionTemplate::Cast(Data* data) {
10292 : #ifdef V8_ENABLE_CHECKS
10293 : CheckCast(data);
10294 : #endif
10295 : return reinterpret_cast<FunctionTemplate*>(data);
10296 : }
10297 :
10298 : ObjectTemplate* ObjectTemplate::Cast(Data* data) {
10299 : #ifdef V8_ENABLE_CHECKS
10300 : CheckCast(data);
10301 : #endif
10302 : return reinterpret_cast<ObjectTemplate*>(data);
10303 : }
10304 :
10305 : Signature* Signature::Cast(Data* data) {
10306 : #ifdef V8_ENABLE_CHECKS
10307 : CheckCast(data);
10308 : #endif
10309 : return reinterpret_cast<Signature*>(data);
10310 : }
10311 :
10312 : AccessorSignature* AccessorSignature::Cast(Data* data) {
10313 : #ifdef V8_ENABLE_CHECKS
10314 : CheckCast(data);
10315 : #endif
10316 : return reinterpret_cast<AccessorSignature*>(data);
10317 : }
10318 :
10319 : Local<Value> Object::GetInternalField(int index) {
10320 : #ifndef V8_ENABLE_CHECKS
10321 : typedef internal::Address A;
10322 : typedef internal::Internals I;
10323 1400 : A obj = *reinterpret_cast<A*>(this);
10324 : // Fast path: If the object is a plain JSObject, which is the common case, we
10325 : // know where to find the internal fields and can return the value directly.
10326 : auto instance_type = I::GetInstanceType(obj);
10327 2800 : if (instance_type == I::kJSObjectType ||
10328 1400 : instance_type == I::kJSApiObjectType ||
10329 1400 : instance_type == I::kJSSpecialApiObjectType) {
10330 660 : int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
10331 : A value = I::ReadRawField<A>(obj, offset);
10332 : #ifdef V8_COMPRESS_POINTERS
10333 : // We read the full pointer value and then decompress it in order to avoid
10334 : // dealing with potential endiannes issues.
10335 : value = I::DecompressTaggedAnyField(obj, static_cast<int32_t>(value));
10336 : #endif
10337 : internal::Isolate* isolate =
10338 824 : internal::IsolateFromNeverReadOnlySpaceObject(obj);
10339 824 : A* result = HandleScope::CreateHandle(isolate, value);
10340 : return Local<Value>(reinterpret_cast<Value*>(result));
10341 : }
10342 : #endif
10343 576 : return SlowGetInternalField(index);
10344 : }
10345 :
10346 :
10347 : void* Object::GetAlignedPointerFromInternalField(int index) {
10348 : #ifndef V8_ENABLE_CHECKS
10349 : typedef internal::Address A;
10350 : typedef internal::Internals I;
10351 2924 : A obj = *reinterpret_cast<A*>(this);
10352 : // Fast path: If the object is a plain JSObject, which is the common case, we
10353 : // know where to find the internal fields and can return the value directly.
10354 : auto instance_type = I::GetInstanceType(obj);
10355 2924 : if (V8_LIKELY(instance_type == I::kJSObjectType ||
10356 : instance_type == I::kJSApiObjectType ||
10357 : instance_type == I::kJSSpecialApiObjectType)) {
10358 15 : int offset = I::kJSObjectHeaderSize + (I::kEmbedderDataSlotSize * index);
10359 : return I::ReadRawField<void*>(obj, offset);
10360 : }
10361 : #endif
10362 135 : return SlowGetAlignedPointerFromInternalField(index);
10363 : }
10364 :
10365 : String* String::Cast(v8::Value* value) {
10366 : #ifdef V8_ENABLE_CHECKS
10367 : CheckCast(value);
10368 : #endif
10369 : return static_cast<String*>(value);
10370 : }
10371 :
10372 :
10373 : Local<String> String::Empty(Isolate* isolate) {
10374 : typedef internal::Address S;
10375 : typedef internal::Internals I;
10376 : I::CheckInitialized(isolate);
10377 : S* slot = I::GetRoot(isolate, I::kEmptyStringRootIndex);
10378 : return Local<String>(reinterpret_cast<String*>(slot));
10379 : }
10380 :
10381 :
10382 : String::ExternalStringResource* String::GetExternalStringResource() const {
10383 : typedef internal::Address A;
10384 : typedef internal::Internals I;
10385 31 : A obj = *reinterpret_cast<const A*>(this);
10386 :
10387 : ExternalStringResource* result;
10388 31 : if (I::IsExternalTwoByteString(I::GetInstanceType(obj))) {
10389 : void* value = I::ReadRawField<void*>(obj, I::kStringResourceOffset);
10390 : result = reinterpret_cast<String::ExternalStringResource*>(value);
10391 : } else {
10392 0 : result = GetExternalStringResourceSlow();
10393 : }
10394 : #ifdef V8_ENABLE_CHECKS
10395 : VerifyExternalStringResource(result);
10396 : #endif
10397 : return result;
10398 : }
10399 :
10400 :
10401 : String::ExternalStringResourceBase* String::GetExternalStringResourceBase(
10402 : String::Encoding* encoding_out) const {
10403 : typedef internal::Address A;
10404 : typedef internal::Internals I;
10405 28 : A obj = *reinterpret_cast<const A*>(this);
10406 28 : int type = I::GetInstanceType(obj) & I::kFullStringRepresentationMask;
10407 28 : *encoding_out = static_cast<Encoding>(type & I::kStringEncodingMask);
10408 : ExternalStringResourceBase* resource;
10409 56 : if (type == I::kExternalOneByteRepresentationTag ||
10410 28 : type == I::kExternalTwoByteRepresentationTag) {
10411 : void* value = I::ReadRawField<void*>(obj, I::kStringResourceOffset);
10412 : resource = static_cast<ExternalStringResourceBase*>(value);
10413 : } else {
10414 6 : resource = GetExternalStringResourceBaseSlow(encoding_out);
10415 : }
10416 : #ifdef V8_ENABLE_CHECKS
10417 : VerifyExternalStringResourceBase(resource, *encoding_out);
10418 : #endif
10419 : return resource;
10420 : }
10421 :
10422 :
10423 : bool Value::IsUndefined() const {
10424 : #ifdef V8_ENABLE_CHECKS
10425 : return FullIsUndefined();
10426 : #else
10427 : return QuickIsUndefined();
10428 : #endif
10429 : }
10430 :
10431 : bool Value::QuickIsUndefined() const {
10432 : typedef internal::Address A;
10433 : typedef internal::Internals I;
10434 7282644 : A obj = *reinterpret_cast<const A*>(this);
10435 7370049 : if (!I::HasHeapObjectTag(obj)) return false;
10436 7359167 : if (I::GetInstanceType(obj) != I::kOddballType) return false;
10437 265979 : return (I::GetOddballKind(obj) == I::kUndefinedOddballKind);
10438 : }
10439 :
10440 :
10441 : bool Value::IsNull() const {
10442 : #ifdef V8_ENABLE_CHECKS
10443 : return FullIsNull();
10444 : #else
10445 : return QuickIsNull();
10446 : #endif
10447 : }
10448 :
10449 : bool Value::QuickIsNull() const {
10450 : typedef internal::Address A;
10451 : typedef internal::Internals I;
10452 3937114 : A obj = *reinterpret_cast<const A*>(this);
10453 3957479 : if (!I::HasHeapObjectTag(obj)) return false;
10454 3817524 : if (I::GetInstanceType(obj) != I::kOddballType) return false;
10455 203448 : return (I::GetOddballKind(obj) == I::kNullOddballKind);
10456 : }
10457 :
10458 : bool Value::IsNullOrUndefined() const {
10459 : #ifdef V8_ENABLE_CHECKS
10460 : return FullIsNull() || FullIsUndefined();
10461 : #else
10462 : return QuickIsNullOrUndefined();
10463 : #endif
10464 : }
10465 :
10466 : bool Value::QuickIsNullOrUndefined() const {
10467 : typedef internal::Address A;
10468 : typedef internal::Internals I;
10469 9049801 : A obj = *reinterpret_cast<const A*>(this);
10470 9049801 : if (!I::HasHeapObjectTag(obj)) return false;
10471 9049801 : if (I::GetInstanceType(obj) != I::kOddballType) return false;
10472 : int kind = I::GetOddballKind(obj);
10473 0 : return kind == I::kNullOddballKind || kind == I::kUndefinedOddballKind;
10474 : }
10475 :
10476 : bool Value::IsString() const {
10477 : #ifdef V8_ENABLE_CHECKS
10478 : return FullIsString();
10479 : #else
10480 : return QuickIsString();
10481 : #endif
10482 : }
10483 :
10484 : bool Value::QuickIsString() const {
10485 : typedef internal::Address A;
10486 : typedef internal::Internals I;
10487 8873050 : A obj = *reinterpret_cast<const A*>(this);
10488 8873062 : if (!I::HasHeapObjectTag(obj)) return false;
10489 8872315 : return (I::GetInstanceType(obj) < I::kFirstNonstringType);
10490 : }
10491 :
10492 :
10493 : template <class T> Value* Value::Cast(T* value) {
10494 : return static_cast<Value*>(value);
10495 : }
10496 :
10497 :
10498 : Boolean* Boolean::Cast(v8::Value* value) {
10499 : #ifdef V8_ENABLE_CHECKS
10500 : CheckCast(value);
10501 : #endif
10502 : return static_cast<Boolean*>(value);
10503 : }
10504 :
10505 :
10506 : Name* Name::Cast(v8::Value* value) {
10507 : #ifdef V8_ENABLE_CHECKS
10508 : CheckCast(value);
10509 : #endif
10510 : return static_cast<Name*>(value);
10511 : }
10512 :
10513 :
10514 : Symbol* Symbol::Cast(v8::Value* value) {
10515 : #ifdef V8_ENABLE_CHECKS
10516 : CheckCast(value);
10517 : #endif
10518 : return static_cast<Symbol*>(value);
10519 : }
10520 :
10521 :
10522 : Private* Private::Cast(Data* data) {
10523 : #ifdef V8_ENABLE_CHECKS
10524 : CheckCast(data);
10525 : #endif
10526 : return reinterpret_cast<Private*>(data);
10527 : }
10528 :
10529 :
10530 : Number* Number::Cast(v8::Value* value) {
10531 : #ifdef V8_ENABLE_CHECKS
10532 : CheckCast(value);
10533 : #endif
10534 : return static_cast<Number*>(value);
10535 : }
10536 :
10537 :
10538 : Integer* Integer::Cast(v8::Value* value) {
10539 : #ifdef V8_ENABLE_CHECKS
10540 : CheckCast(value);
10541 : #endif
10542 : return static_cast<Integer*>(value);
10543 : }
10544 :
10545 :
10546 : Int32* Int32::Cast(v8::Value* value) {
10547 : #ifdef V8_ENABLE_CHECKS
10548 : CheckCast(value);
10549 : #endif
10550 : return static_cast<Int32*>(value);
10551 : }
10552 :
10553 :
10554 : Uint32* Uint32::Cast(v8::Value* value) {
10555 : #ifdef V8_ENABLE_CHECKS
10556 : CheckCast(value);
10557 : #endif
10558 : return static_cast<Uint32*>(value);
10559 : }
10560 :
10561 : BigInt* BigInt::Cast(v8::Value* value) {
10562 : #ifdef V8_ENABLE_CHECKS
10563 : CheckCast(value);
10564 : #endif
10565 : return static_cast<BigInt*>(value);
10566 : }
10567 :
10568 : Date* Date::Cast(v8::Value* value) {
10569 : #ifdef V8_ENABLE_CHECKS
10570 : CheckCast(value);
10571 : #endif
10572 : return static_cast<Date*>(value);
10573 : }
10574 :
10575 :
10576 : StringObject* StringObject::Cast(v8::Value* value) {
10577 : #ifdef V8_ENABLE_CHECKS
10578 : CheckCast(value);
10579 : #endif
10580 : return static_cast<StringObject*>(value);
10581 : }
10582 :
10583 :
10584 : SymbolObject* SymbolObject::Cast(v8::Value* value) {
10585 : #ifdef V8_ENABLE_CHECKS
10586 : CheckCast(value);
10587 : #endif
10588 : return static_cast<SymbolObject*>(value);
10589 : }
10590 :
10591 :
10592 : NumberObject* NumberObject::Cast(v8::Value* value) {
10593 : #ifdef V8_ENABLE_CHECKS
10594 : CheckCast(value);
10595 : #endif
10596 : return static_cast<NumberObject*>(value);
10597 : }
10598 :
10599 : BigIntObject* BigIntObject::Cast(v8::Value* value) {
10600 : #ifdef V8_ENABLE_CHECKS
10601 : CheckCast(value);
10602 : #endif
10603 : return static_cast<BigIntObject*>(value);
10604 : }
10605 :
10606 : BooleanObject* BooleanObject::Cast(v8::Value* value) {
10607 : #ifdef V8_ENABLE_CHECKS
10608 : CheckCast(value);
10609 : #endif
10610 : return static_cast<BooleanObject*>(value);
10611 : }
10612 :
10613 :
10614 : RegExp* RegExp::Cast(v8::Value* value) {
10615 : #ifdef V8_ENABLE_CHECKS
10616 : CheckCast(value);
10617 : #endif
10618 : return static_cast<RegExp*>(value);
10619 : }
10620 :
10621 :
10622 : Object* Object::Cast(v8::Value* value) {
10623 : #ifdef V8_ENABLE_CHECKS
10624 : CheckCast(value);
10625 : #endif
10626 : return static_cast<Object*>(value);
10627 : }
10628 :
10629 :
10630 : Array* Array::Cast(v8::Value* value) {
10631 : #ifdef V8_ENABLE_CHECKS
10632 : CheckCast(value);
10633 : #endif
10634 : return static_cast<Array*>(value);
10635 : }
10636 :
10637 :
10638 : Map* Map::Cast(v8::Value* value) {
10639 : #ifdef V8_ENABLE_CHECKS
10640 : CheckCast(value);
10641 : #endif
10642 : return static_cast<Map*>(value);
10643 : }
10644 :
10645 :
10646 : Set* Set::Cast(v8::Value* value) {
10647 : #ifdef V8_ENABLE_CHECKS
10648 : CheckCast(value);
10649 : #endif
10650 : return static_cast<Set*>(value);
10651 : }
10652 :
10653 :
10654 : Promise* Promise::Cast(v8::Value* value) {
10655 : #ifdef V8_ENABLE_CHECKS
10656 : CheckCast(value);
10657 : #endif
10658 : return static_cast<Promise*>(value);
10659 : }
10660 :
10661 :
10662 : Proxy* Proxy::Cast(v8::Value* value) {
10663 : #ifdef V8_ENABLE_CHECKS
10664 : CheckCast(value);
10665 : #endif
10666 : return static_cast<Proxy*>(value);
10667 : }
10668 :
10669 : WasmModuleObject* WasmModuleObject::Cast(v8::Value* value) {
10670 : #ifdef V8_ENABLE_CHECKS
10671 : CheckCast(value);
10672 : #endif
10673 : return static_cast<WasmModuleObject*>(value);
10674 : }
10675 :
10676 : Promise::Resolver* Promise::Resolver::Cast(v8::Value* value) {
10677 : #ifdef V8_ENABLE_CHECKS
10678 : CheckCast(value);
10679 : #endif
10680 : return static_cast<Promise::Resolver*>(value);
10681 : }
10682 :
10683 :
10684 : ArrayBuffer* ArrayBuffer::Cast(v8::Value* value) {
10685 : #ifdef V8_ENABLE_CHECKS
10686 : CheckCast(value);
10687 : #endif
10688 : return static_cast<ArrayBuffer*>(value);
10689 : }
10690 :
10691 :
10692 : ArrayBufferView* ArrayBufferView::Cast(v8::Value* value) {
10693 : #ifdef V8_ENABLE_CHECKS
10694 : CheckCast(value);
10695 : #endif
10696 : return static_cast<ArrayBufferView*>(value);
10697 : }
10698 :
10699 :
10700 : TypedArray* TypedArray::Cast(v8::Value* value) {
10701 : #ifdef V8_ENABLE_CHECKS
10702 : CheckCast(value);
10703 : #endif
10704 : return static_cast<TypedArray*>(value);
10705 : }
10706 :
10707 :
10708 : Uint8Array* Uint8Array::Cast(v8::Value* value) {
10709 : #ifdef V8_ENABLE_CHECKS
10710 : CheckCast(value);
10711 : #endif
10712 : return static_cast<Uint8Array*>(value);
10713 : }
10714 :
10715 :
10716 : Int8Array* Int8Array::Cast(v8::Value* value) {
10717 : #ifdef V8_ENABLE_CHECKS
10718 : CheckCast(value);
10719 : #endif
10720 : return static_cast<Int8Array*>(value);
10721 : }
10722 :
10723 :
10724 : Uint16Array* Uint16Array::Cast(v8::Value* value) {
10725 : #ifdef V8_ENABLE_CHECKS
10726 : CheckCast(value);
10727 : #endif
10728 : return static_cast<Uint16Array*>(value);
10729 : }
10730 :
10731 :
10732 : Int16Array* Int16Array::Cast(v8::Value* value) {
10733 : #ifdef V8_ENABLE_CHECKS
10734 : CheckCast(value);
10735 : #endif
10736 : return static_cast<Int16Array*>(value);
10737 : }
10738 :
10739 :
10740 : Uint32Array* Uint32Array::Cast(v8::Value* value) {
10741 : #ifdef V8_ENABLE_CHECKS
10742 : CheckCast(value);
10743 : #endif
10744 : return static_cast<Uint32Array*>(value);
10745 : }
10746 :
10747 :
10748 : Int32Array* Int32Array::Cast(v8::Value* value) {
10749 : #ifdef V8_ENABLE_CHECKS
10750 : CheckCast(value);
10751 : #endif
10752 : return static_cast<Int32Array*>(value);
10753 : }
10754 :
10755 :
10756 : Float32Array* Float32Array::Cast(v8::Value* value) {
10757 : #ifdef V8_ENABLE_CHECKS
10758 : CheckCast(value);
10759 : #endif
10760 : return static_cast<Float32Array*>(value);
10761 : }
10762 :
10763 :
10764 : Float64Array* Float64Array::Cast(v8::Value* value) {
10765 : #ifdef V8_ENABLE_CHECKS
10766 : CheckCast(value);
10767 : #endif
10768 : return static_cast<Float64Array*>(value);
10769 : }
10770 :
10771 : BigInt64Array* BigInt64Array::Cast(v8::Value* value) {
10772 : #ifdef V8_ENABLE_CHECKS
10773 : CheckCast(value);
10774 : #endif
10775 : return static_cast<BigInt64Array*>(value);
10776 : }
10777 :
10778 : BigUint64Array* BigUint64Array::Cast(v8::Value* value) {
10779 : #ifdef V8_ENABLE_CHECKS
10780 : CheckCast(value);
10781 : #endif
10782 : return static_cast<BigUint64Array*>(value);
10783 : }
10784 :
10785 : Uint8ClampedArray* Uint8ClampedArray::Cast(v8::Value* value) {
10786 : #ifdef V8_ENABLE_CHECKS
10787 : CheckCast(value);
10788 : #endif
10789 : return static_cast<Uint8ClampedArray*>(value);
10790 : }
10791 :
10792 :
10793 : DataView* DataView::Cast(v8::Value* value) {
10794 : #ifdef V8_ENABLE_CHECKS
10795 : CheckCast(value);
10796 : #endif
10797 : return static_cast<DataView*>(value);
10798 : }
10799 :
10800 :
10801 : SharedArrayBuffer* SharedArrayBuffer::Cast(v8::Value* value) {
10802 : #ifdef V8_ENABLE_CHECKS
10803 : CheckCast(value);
10804 : #endif
10805 : return static_cast<SharedArrayBuffer*>(value);
10806 : }
10807 :
10808 :
10809 : Function* Function::Cast(v8::Value* value) {
10810 : #ifdef V8_ENABLE_CHECKS
10811 : CheckCast(value);
10812 : #endif
10813 : return static_cast<Function*>(value);
10814 : }
10815 :
10816 :
10817 : External* External::Cast(v8::Value* value) {
10818 : #ifdef V8_ENABLE_CHECKS
10819 : CheckCast(value);
10820 : #endif
10821 : return static_cast<External*>(value);
10822 : }
10823 :
10824 :
10825 : template<typename T>
10826 : Isolate* PropertyCallbackInfo<T>::GetIsolate() const {
10827 9358841 : return *reinterpret_cast<Isolate**>(&args_[kIsolateIndex]);
10828 : }
10829 :
10830 :
10831 : template<typename T>
10832 : Local<Value> PropertyCallbackInfo<T>::Data() const {
10833 129162 : return Local<Value>(reinterpret_cast<Value*>(&args_[kDataIndex]));
10834 : }
10835 :
10836 :
10837 : template<typename T>
10838 : Local<Object> PropertyCallbackInfo<T>::This() const {
10839 520413 : return Local<Object>(reinterpret_cast<Object*>(&args_[kThisIndex]));
10840 : }
10841 :
10842 :
10843 : template<typename T>
10844 : Local<Object> PropertyCallbackInfo<T>::Holder() const {
10845 1127371 : return Local<Object>(reinterpret_cast<Object*>(&args_[kHolderIndex]));
10846 : }
10847 :
10848 :
10849 : template<typename T>
10850 : ReturnValue<T> PropertyCallbackInfo<T>::GetReturnValue() const {
10851 1844912 : return ReturnValue<T>(&args_[kReturnValueIndex]);
10852 : }
10853 :
10854 : template <typename T>
10855 : bool PropertyCallbackInfo<T>::ShouldThrowOnError() const {
10856 : typedef internal::Internals I;
10857 202 : if (args_[kShouldThrowOnErrorIndex] !=
10858 : I::IntToSmi(I::kInferShouldThrowMode)) {
10859 102 : return args_[kShouldThrowOnErrorIndex] != I::IntToSmi(I::kDontThrow);
10860 : }
10861 : return v8::internal::ShouldThrowOnError(
10862 100 : reinterpret_cast<v8::internal::Isolate*>(GetIsolate()));
10863 : }
10864 :
10865 : Local<Primitive> Undefined(Isolate* isolate) {
10866 : typedef internal::Address S;
10867 : typedef internal::Internals I;
10868 : I::CheckInitialized(isolate);
10869 : S* slot = I::GetRoot(isolate, I::kUndefinedValueRootIndex);
10870 : return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10871 : }
10872 :
10873 :
10874 : Local<Primitive> Null(Isolate* isolate) {
10875 : typedef internal::Address S;
10876 : typedef internal::Internals I;
10877 : I::CheckInitialized(isolate);
10878 : S* slot = I::GetRoot(isolate, I::kNullValueRootIndex);
10879 : return Local<Primitive>(reinterpret_cast<Primitive*>(slot));
10880 : }
10881 :
10882 :
10883 : Local<Boolean> True(Isolate* isolate) {
10884 : typedef internal::Address S;
10885 : typedef internal::Internals I;
10886 : I::CheckInitialized(isolate);
10887 : S* slot = I::GetRoot(isolate, I::kTrueValueRootIndex);
10888 : return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10889 : }
10890 :
10891 :
10892 : Local<Boolean> False(Isolate* isolate) {
10893 : typedef internal::Address S;
10894 : typedef internal::Internals I;
10895 : I::CheckInitialized(isolate);
10896 : S* slot = I::GetRoot(isolate, I::kFalseValueRootIndex);
10897 : return Local<Boolean>(reinterpret_cast<Boolean*>(slot));
10898 : }
10899 :
10900 :
10901 : void Isolate::SetData(uint32_t slot, void* data) {
10902 : typedef internal::Internals I;
10903 : I::SetEmbedderData(this, slot, data);
10904 : }
10905 :
10906 :
10907 : void* Isolate::GetData(uint32_t slot) {
10908 : typedef internal::Internals I;
10909 : return I::GetEmbedderData(this, slot);
10910 : }
10911 :
10912 :
10913 : uint32_t Isolate::GetNumberOfDataSlots() {
10914 : typedef internal::Internals I;
10915 : return I::kNumIsolateDataSlots;
10916 : }
10917 :
10918 : template <class T>
10919 : MaybeLocal<T> Isolate::GetDataFromSnapshotOnce(size_t index) {
10920 85 : T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
10921 85 : if (data) internal::PerformCastCheck(data);
10922 : return Local<T>(data);
10923 : }
10924 :
10925 : int64_t Isolate::AdjustAmountOfExternalAllocatedMemory(
10926 : int64_t change_in_bytes) {
10927 : typedef internal::Internals I;
10928 : constexpr int64_t kMemoryReducerActivationLimit = 32 * 1024 * 1024;
10929 : int64_t* external_memory = reinterpret_cast<int64_t*>(
10930 : reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryOffset);
10931 : int64_t* external_memory_limit = reinterpret_cast<int64_t*>(
10932 : reinterpret_cast<uint8_t*>(this) + I::kExternalMemoryLimitOffset);
10933 : int64_t* external_memory_at_last_mc =
10934 : reinterpret_cast<int64_t*>(reinterpret_cast<uint8_t*>(this) +
10935 : I::kExternalMemoryAtLastMarkCompactOffset);
10936 :
10937 : // Embedders are weird: we see both over- and underflows here. Perform the
10938 : // addition with unsigned types to avoid undefined behavior.
10939 : const int64_t amount =
10940 6513173 : static_cast<int64_t>(static_cast<uint64_t>(change_in_bytes) +
10941 6513168 : static_cast<uint64_t>(*external_memory));
10942 6513168 : *external_memory = amount;
10943 :
10944 : int64_t allocation_diff_since_last_mc =
10945 6513173 : *external_memory - *external_memory_at_last_mc;
10946 : // Only check memory pressure and potentially trigger GC if the amount of
10947 : // external memory increased.
10948 6513173 : if (allocation_diff_since_last_mc > kMemoryReducerActivationLimit) {
10949 1832517 : CheckMemoryPressure();
10950 : }
10951 :
10952 6513153 : if (change_in_bytes < 0) {
10953 2590867 : const int64_t lower_limit = *external_memory_limit + change_in_bytes;
10954 2590867 : if (lower_limit > I::kExternalAllocationSoftLimit)
10955 1523534 : *external_memory_limit = lower_limit;
10956 3922303 : } else if (change_in_bytes > 0 && amount > *external_memory_limit) {
10957 993804 : ReportExternalAllocationLimitReached();
10958 : }
10959 25 : return *external_memory;
10960 : }
10961 :
10962 : Local<Value> Context::GetEmbedderData(int index) {
10963 : #ifndef V8_ENABLE_CHECKS
10964 : typedef internal::Address A;
10965 : typedef internal::Internals I;
10966 135 : A ctx = *reinterpret_cast<const A*>(this);
10967 : A embedder_data =
10968 : I::ReadTaggedPointerField(ctx, I::kNativeContextEmbedderDataOffset);
10969 : int value_offset =
10970 30 : I::kEmbedderDataArrayHeaderSize + (I::kEmbedderDataSlotSize * index);
10971 : A value = I::ReadRawField<A>(embedder_data, value_offset);
10972 : #ifdef V8_COMPRESS_POINTERS
10973 : // We read the full pointer value and then decompress it in order to avoid
10974 : // dealing with potential endiannes issues.
10975 : value =
10976 : I::DecompressTaggedAnyField(embedder_data, static_cast<int32_t>(value));
10977 : #endif
10978 : internal::Isolate* isolate = internal::IsolateFromNeverReadOnlySpaceObject(
10979 135 : *reinterpret_cast<A*>(this));
10980 135 : A* result = HandleScope::CreateHandle(isolate, value);
10981 : return Local<Value>(reinterpret_cast<Value*>(result));
10982 : #else
10983 : return SlowGetEmbedderData(index);
10984 : #endif
10985 : }
10986 :
10987 :
10988 : void* Context::GetAlignedPointerFromEmbedderData(int index) {
10989 : #ifndef V8_ENABLE_CHECKS
10990 : typedef internal::Address A;
10991 : typedef internal::Internals I;
10992 184735 : A ctx = *reinterpret_cast<const A*>(this);
10993 : A embedder_data =
10994 : I::ReadTaggedPointerField(ctx, I::kNativeContextEmbedderDataOffset);
10995 : int value_offset =
10996 624 : I::kEmbedderDataArrayHeaderSize + (I::kEmbedderDataSlotSize * index);
10997 : return I::ReadRawField<void*>(embedder_data, value_offset);
10998 : #else
10999 : return SlowGetAlignedPointerFromEmbedderData(index);
11000 : #endif
11001 : }
11002 :
11003 : template <class T>
11004 : MaybeLocal<T> Context::GetDataFromSnapshotOnce(size_t index) {
11005 90 : T* data = reinterpret_cast<T*>(GetDataFromSnapshotOnce(index));
11006 90 : if (data) internal::PerformCastCheck(data);
11007 : return Local<T>(data);
11008 : }
11009 :
11010 : template <class T>
11011 : size_t SnapshotCreator::AddData(Local<Context> context, Local<T> object) {
11012 : T* object_ptr = *object;
11013 : internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
11014 35 : return AddData(context, *p);
11015 : }
11016 :
11017 : template <class T>
11018 : size_t SnapshotCreator::AddData(Local<T> object) {
11019 : T* object_ptr = *object;
11020 : internal::Address* p = reinterpret_cast<internal::Address*>(object_ptr);
11021 50 : return AddData(*p);
11022 : }
11023 :
11024 : /**
11025 : * \example shell.cc
11026 : * A simple shell that takes a list of expressions on the
11027 : * command-line and executes them.
11028 : */
11029 :
11030 :
11031 : /**
11032 : * \example process.cc
11033 : */
11034 :
11035 :
11036 : } // namespace v8
11037 :
11038 :
11039 : #undef TYPE_CHECK
11040 :
11041 :
11042 : #endif // INCLUDE_V8_H_
|