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 */
35namespace v8 {
36
37class AccessorSignature;
38class Array;
39class ArrayBuffer;
40class BigInt;
41class BigIntObject;
42class Boolean;
43class BooleanObject;
44class Context;
45class Data;
46class Date;
47class External;
48class Function;
49class FunctionTemplate;
50class HeapProfiler;
51class ImplementationUtilities;
52class Int32;
53class Integer;
54class Isolate;
55template <class T>
56class Maybe;
57class MicrotaskQueue;
58class Name;
59class Number;
60class NumberObject;
61class Object;
62class ObjectOperationDescriptor;
63class ObjectTemplate;
64class Platform;
65class Primitive;
66class Promise;
67class PropertyDescriptor;
68class Proxy;
69class RawOperationDescriptor;
70class Script;
71class SharedArrayBuffer;
72class Signature;
73class StartupData;
74class StackFrame;
75class StackTrace;
76class String;
77class StringObject;
78class Symbol;
79class SymbolObject;
80class PrimitiveArray;
81class Private;
82class Uint32;
83class Utils;
84class Value;
85class WasmModuleObject;
86template <class T> class Local;
87template <class T>
88class MaybeLocal;
89template <class T> class Eternal;
90template<class T> class NonCopyablePersistentTraits;
91template<class T> class PersistentBase;
92template <class T, class M = NonCopyablePersistentTraits<T> >
93class Persistent;
94template <class T>
95class Global;
96template <class T>
97class TracedGlobal;
98template<class K, class V, class T> class PersistentValueMap;
99template <class K, class V, class T>
100class PersistentValueMapBase;
101template <class K, class V, class T>
102class GlobalValueMap;
103template<class V, class T> class PersistentValueVector;
104template<class T, class P> class WeakCallbackObject;
105class FunctionTemplate;
106class ObjectTemplate;
107template<typename T> class FunctionCallbackInfo;
108template<typename T> class PropertyCallbackInfo;
109class StackTrace;
110class StackFrame;
111class Isolate;
112class CallHandlerHelper;
113class EscapableHandleScope;
114template<typename T> class ReturnValue;
115
116namespace internal {
117class Arguments;
118class DeferredHandles;
119class Heap;
120class HeapObject;
121class ExternalString;
122class Isolate;
123class LocalEmbedderHeapTracer;
124class MicrotaskQueue;
125class NeverReadOnlySpaceObject;
126struct ScriptStreamingData;
127template<typename T> class CustomArguments;
128class PropertyCallbackArguments;
129class FunctionCallbackArguments;
130class GlobalHandles;
131class ScopedExternalStringLock;
132
133namespace wasm {
134class NativeModule;
135class StreamingDecoder;
136} // namespace wasm
137
138} // namespace internal
139
140namespace debug {
141class 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 */
182template <class T>
183class Local {
184 public:
185 V8_INLINE Local() : val_(nullptr) {}
186 template <class S>
187 V8_INLINE Local(Local<S> that)
188 : 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 V8_INLINE bool IsEmpty() const { return val_ == nullptr; }
201
202 /**
203 * Sets the handle to be empty. IsEmpty() will then return true.
204 */
205 V8_INLINE void Clear() { val_ = nullptr; }
206
207 V8_INLINE T* operator->() const { return val_; }
208
209 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 internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
220 internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
221 if (a == nullptr) return b == nullptr;
222 if (b == nullptr) return false;
223 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 internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
230 if (a == nullptr) return b == nullptr;
231 if (b == nullptr) return false;
232 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 return !operator==(that);
244 }
245
246 template <class S> V8_INLINE bool operator!=(
247 const Persistent<S>& that) const {
248 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 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 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.
323template <class T>
324using 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 */
338template <class T>
339class MaybeLocal {
340 public:
341 V8_INLINE MaybeLocal() : val_(nullptr) {}
342 template <class S>
343 V8_INLINE MaybeLocal(Local<S> that)
344 : val_(reinterpret_cast<T*>(*that)) {
345 TYPE_CHECK(T, S);
346 }
347
348 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 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 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 */
383template <class T> class Eternal {
384 public:
385 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 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
400static const int kInternalFieldsInWeakCallback = 2;
401static const int kEmbedderFieldsInWeakCallback = 2;
402
403template <typename T>
404class 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 : isolate_(isolate), parameter_(parameter), callback_(callback) {
412 for (int i = 0; i < kEmbedderFieldsInWeakCallback; ++i) {
413 embedder_fields_[i] = embedder_fields[i];
414 }
415 }
416
417 V8_INLINE Isolate* GetIsolate() const { return isolate_; }
418 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 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.
442enum 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 */
457template <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 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 internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
488 internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
489 if (a == nullptr) return b == nullptr;
490 if (b == nullptr) return false;
491 return *a == *b;
492 }
493
494 template <class S>
495 V8_INLINE bool operator==(const Local<S>& that) const {
496 internal::Address* a = reinterpret_cast<internal::Address*>(this->val_);
497 internal::Address* b = reinterpret_cast<internal::Address*>(that.val_);
498 if (a == nullptr) return b == nullptr;
499 if (b == nullptr) return false;
500 return *a == *b;
501 }
502
503 template <class S>
504 V8_INLINE bool operator!=(const PersistentBase<S>& that) const {
505 return !operator==(that);
506 }
507
508 template <class S>
509 V8_INLINE bool operator!=(const Local<S>& that) const {
510 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 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 */
624template<class T>
625class 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 */
645template<class T>
646struct 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 */
665template <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 V8_INLINE ~Persistent() {
719 if (M::kResetInDestructor) this->Reset();
720 }
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 */
758template <class T>
759class 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 : 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 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.
822template <class T>
823using 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 */
836template <typename T>
837class V8_EXPORT TracedGlobal {
838 public:
839 /**
840 * An empty TracedGlobal without storage cell.
841 */
842 TracedGlobal() = default;
843 ~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 : 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 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 */
985class 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 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 */
1037class V8_EXPORT EscapableHandleScope : public HandleScope {
1038 public:
1039 explicit EscapableHandleScope(Isolate* isolate);
1040 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 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 */
1078class 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 */
1106class 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 */
1117class 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 */
1140class 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 */
1151class 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 : flags_((is_shared_cross_origin ? kIsSharedCrossOrigin : 0) |
1157 (is_wasm ? kIsWasm : 0) | (is_opaque ? kIsOpaque : 0) |
1158 (is_module ? kIsModule : 0)) {}
1159 V8_INLINE ScriptOriginOptions(int flags)
1160 : flags_(flags &
1161 (kIsSharedCrossOrigin | kIsOpaque | kIsWasm | kIsModule)) {}
1162
1163 bool IsSharedCrossOrigin() const {
1164 return (flags_ & kIsSharedCrossOrigin) != 0;
1165 }
1166 bool IsOpaque() const { return (flags_ & kIsOpaque) != 0; }
1167 bool IsWasm() const { return (flags_ & kIsWasm) != 0; }
1168 bool IsModule() const { return (flags_ & kIsModule) != 0; }
1169
1170 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 */
1185class 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 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 */
1220class 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 */
1251class V8_EXPORT UnboundModuleScript {
1252 // Only used as a container for code caching.
1253};
1254
1255/**
1256 * A location in JavaScript source.
1257 */
1258class 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 */
1274class 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 */
1368class 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 */
1394class 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 class V8_EXPORT ExternalSourceStream {
1481 public:
1482 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 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 : 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 */
1739class 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 */
1827class 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 */
1874class 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.
1940enum 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.
1953struct RegisterState {
1954 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.
1961struct 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
1968struct MemoryRange {
1969 const void* start = nullptr;
1970 size_t length_in_bytes = 0;
1971};
1972
1973struct JSEntryStub {
1974 MemoryRange code;
1975};
1976
1977struct 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 */
1986class 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 */
2015class V8_EXPORT ValueSerializer {
2016 public:
2017 class V8_EXPORT Delegate {
2018 public:
2019 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 */
2135class V8_EXPORT ValueDeserializer {
2136 public:
2137 class V8_EXPORT Delegate {
2138 public:
2139 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 */
2240class 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 */
2597class 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 */
2604class 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 */
2618class 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 */
2641enum 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 */
2658class 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 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 virtual bool IsCacheable() const { return true; }
2766
2767 protected:
2768 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 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 virtual void Lock() const {}
2790
2791 /**
2792 * Unlocks the string.
2793 */
2794 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 ~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 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 ~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 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 */
3048class 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 */
3102class 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 */
3138class 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 */
3152class 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 */
3167class 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 */
3181class 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 */
3194class 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 */
3249enum 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 */
3265typedef void (*AccessorGetterCallback)(
3266 Local<String> property,
3267 const PropertyCallbackInfo<Value>& info);
3268typedef void (*AccessorNameGetterCallback)(
3269 Local<Name> property,
3270 const PropertyCallbackInfo<Value>& info);
3271
3272
3273typedef void (*AccessorSetterCallback)(
3274 Local<String> property,
3275 Local<Value> value,
3276 const PropertyCallbackInfo<void>& info);
3277typedef 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 */
3292enum 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 */
3302enum 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 */
3321enum 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 */
3334enum 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 */
3340enum class IndexFilter { kIncludeIndices, kSkipIndices };
3341
3342/**
3343 * kConvertToString will convert integer indices to strings.
3344 * kKeepNumbers will return numbers for integer indices.
3345 */
3346enum class KeyConversionMode { kConvertToString, kKeepNumbers };
3347
3348/**
3349 * Integrity level for objects.
3350 */
3351enum class IntegrityLevel { kFrozen, kSealed };
3352
3353/**
3354 * A JavaScript object (ECMA-262, 4.3.3)
3355 */
3356class 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 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 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 */
3800class 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 */
3826class 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 */
3862class 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
3891template<typename T>
3892class 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 */
3948template<typename T>
3949class 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 */
4004template<typename T>
4005class 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 V8_INLINE PropertyCallbackInfo(internal::Address* args) : args_(args) {}
4108 internal::Address* args_;
4109};
4110
4111
4112typedef void (*FunctionCallback)(const FunctionCallbackInfo<Value>& info);
4113
4114enum class ConstructorBehavior { kThrow, kAllow };
4115
4116/**
4117 * A JavaScript function object (ECMA-262, 15.3).
4118 */
4119class 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 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 */
4214class 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 */
4327class 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 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 */
4376class 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 */
4407template <typename T>
4408class V8_EXPORT MemorySpan {
4409 public:
4410 /** The default constructor creates an empty span. */
4411 constexpr MemorySpan() = default;
4412
4413 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 */
4428struct 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 : buffer(std::move(buffer)), size(size) {}
4433 OwnedBuffer() = default;
4434};
4435
4436// Wrapper around a compiled WebAssembly module, which is potentially shared by
4437// different WasmModuleObjects.
4438class 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.
4459class 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 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 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 */
4538class 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
4608class 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
4658enum class ArrayBufferCreationMode { kInternalized, kExternalized };
4659
4660
4661/**
4662 * An instance of the built-in ArrayBuffer constructor (ES6 draft 15.13.5).
4663 */
4664class 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 class V8_EXPORT Allocator { // NOLINT
4682 public:
4683 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 */
4867class 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 */
4916class 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 */
4940class 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 */
4957class 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 */
4974class 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 */
4991class 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 */
5008class 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 */
5025class 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 */
5042class 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 */
5059class 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 */
5076class 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 */
5092class 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 */
5108class 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 */
5124class 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 */
5142class 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