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 #ifndef V8_API_API_H_
6 #define V8_API_API_H_
7
8 #include <memory>
9
10 #include "include/v8-container.h"
11 #include "include/v8-external.h"
12 #include "include/v8-proxy.h"
13 #include "include/v8-typed-array.h"
14 #include "include/v8-wasm.h"
15 #include "src/execution/isolate.h"
16 #include "src/heap/factory.h"
17 #include "src/objects/bigint.h"
18 #include "src/objects/contexts.h"
19 #include "src/objects/js-collection.h"
20 #include "src/objects/js-generator.h"
21 #include "src/objects/js-promise.h"
22 #include "src/objects/js-proxy.h"
23 #include "src/objects/objects.h"
24 #include "src/objects/shared-function-info.h"
25 #include "src/objects/source-text-module.h"
26 #include "src/objects/templates.h"
27 #include "src/utils/detachable-vector.h"
28
29 namespace v8 {
30
31 class AccessorSignature;
32 class Extension;
33 class Signature;
34 class Template;
35
36 namespace internal {
37 class JSArrayBufferView;
38 class JSFinalizationRegistry;
39 } // namespace internal
40
41 namespace debug {
42 class AccessorPair;
43 class GeneratorObject;
44 class Script;
45 class EphemeronTable;
46 } // namespace debug
47
48 // Constants used in the implementation of the API. The most natural thing
49 // would usually be to place these with the classes that use them, but
50 // we want to keep them out of v8.h because it is an externally
51 // visible file.
52 class Consts {
53 public:
54 enum TemplateType { FUNCTION_TEMPLATE = 0, OBJECT_TEMPLATE = 1 };
55 };
56
57 template <typename T>
58 inline T ToCData(v8::internal::Object obj);
59
60 template <>
61 inline v8::internal::Address ToCData(v8::internal::Object obj);
62
63 template <typename T>
64 inline v8::internal::Handle<v8::internal::Object> FromCData(
65 v8::internal::Isolate* isolate, T obj);
66
67 template <>
68 inline v8::internal::Handle<v8::internal::Object> FromCData(
69 v8::internal::Isolate* isolate, v8::internal::Address obj);
70
71 class ApiFunction {
72 public:
ApiFunction(v8::internal::Address addr)73 explicit ApiFunction(v8::internal::Address addr) : addr_(addr) {}
address()74 v8::internal::Address address() { return addr_; }
75
76 private:
77 v8::internal::Address addr_;
78 };
79
80 class RegisteredExtension {
81 public:
82 static void Register(std::unique_ptr<Extension>);
83 static void UnregisterAll();
extension()84 Extension* extension() const { return extension_.get(); }
next()85 RegisteredExtension* next() const { return next_; }
first_extension()86 static RegisteredExtension* first_extension() { return first_extension_; }
87
88 private:
89 explicit RegisteredExtension(Extension*);
90 explicit RegisteredExtension(std::unique_ptr<Extension>);
91 std::unique_ptr<Extension> extension_;
92 RegisteredExtension* next_ = nullptr;
93 static RegisteredExtension* first_extension_;
94 };
95
96 #define OPEN_HANDLE_LIST(V) \
97 V(Template, TemplateInfo) \
98 V(FunctionTemplate, FunctionTemplateInfo) \
99 V(ObjectTemplate, ObjectTemplateInfo) \
100 V(Signature, FunctionTemplateInfo) \
101 V(AccessorSignature, FunctionTemplateInfo) \
102 V(Data, Object) \
103 V(RegExp, JSRegExp) \
104 V(Object, JSReceiver) \
105 V(Array, JSArray) \
106 V(Map, JSMap) \
107 V(Set, JSSet) \
108 V(ArrayBuffer, JSArrayBuffer) \
109 V(ArrayBufferView, JSArrayBufferView) \
110 V(TypedArray, JSTypedArray) \
111 V(Uint8Array, JSTypedArray) \
112 V(Uint8ClampedArray, JSTypedArray) \
113 V(Int8Array, JSTypedArray) \
114 V(Uint16Array, JSTypedArray) \
115 V(Int16Array, JSTypedArray) \
116 V(Uint32Array, JSTypedArray) \
117 V(Int32Array, JSTypedArray) \
118 V(Float32Array, JSTypedArray) \
119 V(Float64Array, JSTypedArray) \
120 V(DataView, JSDataView) \
121 V(SharedArrayBuffer, JSArrayBuffer) \
122 V(Name, Name) \
123 V(String, String) \
124 V(Symbol, Symbol) \
125 V(Script, JSFunction) \
126 V(UnboundModuleScript, SharedFunctionInfo) \
127 V(UnboundScript, SharedFunctionInfo) \
128 V(Module, Module) \
129 V(Function, JSReceiver) \
130 V(Message, JSMessageObject) \
131 V(Context, Context) \
132 V(External, Object) \
133 V(StackTrace, FixedArray) \
134 V(StackFrame, StackFrameInfo) \
135 V(Proxy, JSProxy) \
136 V(debug::GeneratorObject, JSGeneratorObject) \
137 V(debug::Script, Script) \
138 V(debug::EphemeronTable, EphemeronHashTable) \
139 V(debug::AccessorPair, AccessorPair) \
140 V(Promise, JSPromise) \
141 V(Primitive, Object) \
142 V(PrimitiveArray, FixedArray) \
143 V(BigInt, BigInt) \
144 V(ScriptOrModule, Script) \
145 V(FixedArray, FixedArray) \
146 V(ModuleRequest, ModuleRequest) \
147 IF_WASM(V, WasmMemoryObject, WasmMemoryObject)
148
149 class Utils {
150 public:
ApiCheck(bool condition,const char * location,const char * message)151 static inline bool ApiCheck(bool condition, const char* location,
152 const char* message) {
153 if (!condition) Utils::ReportApiFailure(location, message);
154 return condition;
155 }
156 static void ReportOOMFailure(v8::internal::Isolate* isolate,
157 const char* location, bool is_heap_oom);
158
159 static inline Local<debug::AccessorPair> ToLocal(
160 v8::internal::Handle<v8::internal::AccessorPair> obj);
161 static inline Local<Context> ToLocal(
162 v8::internal::Handle<v8::internal::Context> obj);
163 static inline Local<Value> ToLocal(
164 v8::internal::Handle<v8::internal::Object> obj);
165 static inline Local<Module> ToLocal(
166 v8::internal::Handle<v8::internal::Module> obj);
167 static inline Local<Name> ToLocal(
168 v8::internal::Handle<v8::internal::Name> obj);
169 static inline Local<String> ToLocal(
170 v8::internal::Handle<v8::internal::String> obj);
171 static inline Local<Symbol> ToLocal(
172 v8::internal::Handle<v8::internal::Symbol> obj);
173 static inline Local<RegExp> ToLocal(
174 v8::internal::Handle<v8::internal::JSRegExp> obj);
175 static inline Local<Object> ToLocal(
176 v8::internal::Handle<v8::internal::JSReceiver> obj);
177 static inline Local<Object> ToLocal(
178 v8::internal::Handle<v8::internal::JSObject> obj);
179 static inline Local<Function> ToLocal(
180 v8::internal::Handle<v8::internal::JSFunction> obj);
181 static inline Local<Array> ToLocal(
182 v8::internal::Handle<v8::internal::JSArray> obj);
183 static inline Local<Map> ToLocal(
184 v8::internal::Handle<v8::internal::JSMap> obj);
185 static inline Local<Set> ToLocal(
186 v8::internal::Handle<v8::internal::JSSet> obj);
187 static inline Local<Proxy> ToLocal(
188 v8::internal::Handle<v8::internal::JSProxy> obj);
189 static inline Local<ArrayBuffer> ToLocal(
190 v8::internal::Handle<v8::internal::JSArrayBuffer> obj);
191 static inline Local<ArrayBufferView> ToLocal(
192 v8::internal::Handle<v8::internal::JSArrayBufferView> obj);
193 static inline Local<DataView> ToLocal(
194 v8::internal::Handle<v8::internal::JSDataView> obj);
195 static inline Local<TypedArray> ToLocal(
196 v8::internal::Handle<v8::internal::JSTypedArray> obj);
197 static inline Local<Uint8Array> ToLocalUint8Array(
198 v8::internal::Handle<v8::internal::JSTypedArray> obj);
199 static inline Local<Uint8ClampedArray> ToLocalUint8ClampedArray(
200 v8::internal::Handle<v8::internal::JSTypedArray> obj);
201 static inline Local<Int8Array> ToLocalInt8Array(
202 v8::internal::Handle<v8::internal::JSTypedArray> obj);
203 static inline Local<Uint16Array> ToLocalUint16Array(
204 v8::internal::Handle<v8::internal::JSTypedArray> obj);
205 static inline Local<Int16Array> ToLocalInt16Array(
206 v8::internal::Handle<v8::internal::JSTypedArray> obj);
207 static inline Local<Uint32Array> ToLocalUint32Array(
208 v8::internal::Handle<v8::internal::JSTypedArray> obj);
209 static inline Local<Int32Array> ToLocalInt32Array(
210 v8::internal::Handle<v8::internal::JSTypedArray> obj);
211 static inline Local<Float32Array> ToLocalFloat32Array(
212 v8::internal::Handle<v8::internal::JSTypedArray> obj);
213 static inline Local<Float64Array> ToLocalFloat64Array(
214 v8::internal::Handle<v8::internal::JSTypedArray> obj);
215 static inline Local<BigInt64Array> ToLocalBigInt64Array(
216 v8::internal::Handle<v8::internal::JSTypedArray> obj);
217 static inline Local<BigUint64Array> ToLocalBigUint64Array(
218 v8::internal::Handle<v8::internal::JSTypedArray> obj);
219
220 static inline Local<SharedArrayBuffer> ToLocalShared(
221 v8::internal::Handle<v8::internal::JSArrayBuffer> obj);
222
223 static inline Local<Message> MessageToLocal(
224 v8::internal::Handle<v8::internal::Object> obj);
225 static inline Local<Promise> PromiseToLocal(
226 v8::internal::Handle<v8::internal::JSObject> obj);
227 static inline Local<StackTrace> StackTraceToLocal(
228 v8::internal::Handle<v8::internal::FixedArray> obj);
229 static inline Local<StackFrame> StackFrameToLocal(
230 v8::internal::Handle<v8::internal::StackFrameInfo> obj);
231 static inline Local<Number> NumberToLocal(
232 v8::internal::Handle<v8::internal::Object> obj);
233 static inline Local<Integer> IntegerToLocal(
234 v8::internal::Handle<v8::internal::Object> obj);
235 static inline Local<Uint32> Uint32ToLocal(
236 v8::internal::Handle<v8::internal::Object> obj);
237 static inline Local<BigInt> ToLocal(
238 v8::internal::Handle<v8::internal::BigInt> obj);
239 static inline Local<FunctionTemplate> ToLocal(
240 v8::internal::Handle<v8::internal::FunctionTemplateInfo> obj);
241 static inline Local<ObjectTemplate> ToLocal(
242 v8::internal::Handle<v8::internal::ObjectTemplateInfo> obj);
243 static inline Local<Signature> SignatureToLocal(
244 v8::internal::Handle<v8::internal::FunctionTemplateInfo> obj);
245 static inline Local<AccessorSignature> AccessorSignatureToLocal(
246 v8::internal::Handle<v8::internal::FunctionTemplateInfo> obj);
247 static inline Local<External> ExternalToLocal(
248 v8::internal::Handle<v8::internal::JSObject> obj);
249 static inline Local<Function> CallableToLocal(
250 v8::internal::Handle<v8::internal::JSReceiver> obj);
251 static inline Local<Primitive> ToLocalPrimitive(
252 v8::internal::Handle<v8::internal::Object> obj);
253 static inline Local<FixedArray> FixedArrayToLocal(
254 v8::internal::Handle<v8::internal::FixedArray> obj);
255 static inline Local<PrimitiveArray> PrimitiveArrayToLocal(
256 v8::internal::Handle<v8::internal::FixedArray> obj);
257 static inline Local<ScriptOrModule> ScriptOrModuleToLocal(
258 v8::internal::Handle<v8::internal::Script> obj);
259
260 #define DECLARE_OPEN_HANDLE(From, To) \
261 static inline v8::internal::Handle<v8::internal::To> OpenHandle( \
262 const From* that, bool allow_empty_handle = false);
263
264 OPEN_HANDLE_LIST(DECLARE_OPEN_HANDLE)
265
266 #undef DECLARE_OPEN_HANDLE
267
268 template <class From, class To>
269 static inline Local<To> Convert(v8::internal::Handle<From> obj);
270
271 template <class T, class M>
OpenPersistent(const v8::Persistent<T,M> & persistent)272 static inline v8::internal::Handle<v8::internal::Object> OpenPersistent(
273 const v8::Persistent<T, M>& persistent) {
274 return v8::internal::Handle<v8::internal::Object>(
275 reinterpret_cast<v8::internal::Address*>(persistent.val_));
276 }
277
278 template <class T>
OpenPersistent(v8::Persistent<T> * persistent)279 static inline v8::internal::Handle<v8::internal::Object> OpenPersistent(
280 v8::Persistent<T>* persistent) {
281 return OpenPersistent(*persistent);
282 }
283
284 template <class From, class To>
OpenHandle(v8::Local<From> handle)285 static inline v8::internal::Handle<To> OpenHandle(v8::Local<From> handle) {
286 return OpenHandle(*handle);
287 }
288
289 private:
290 static void ReportApiFailure(const char* location, const char* message);
291 };
292
293 template <class T>
ToApi(v8::internal::Handle<v8::internal::Object> obj)294 inline T* ToApi(v8::internal::Handle<v8::internal::Object> obj) {
295 return reinterpret_cast<T*>(obj.location());
296 }
297
298 template <class T>
ToApiHandle(v8::internal::Handle<v8::internal::Object> obj)299 inline v8::Local<T> ToApiHandle(
300 v8::internal::Handle<v8::internal::Object> obj) {
301 return Utils::Convert<v8::internal::Object, T>(obj);
302 }
303
304 template <class T>
ToLocal(v8::internal::MaybeHandle<v8::internal::Object> maybe,Local<T> * local)305 inline bool ToLocal(v8::internal::MaybeHandle<v8::internal::Object> maybe,
306 Local<T>* local) {
307 v8::internal::Handle<v8::internal::Object> handle;
308 if (maybe.ToHandle(&handle)) {
309 *local = Utils::Convert<v8::internal::Object, T>(handle);
310 return true;
311 }
312 return false;
313 }
314
315 namespace internal {
316
317 class PersistentHandles;
318
319 // This class is here in order to be able to declare it a friend of
320 // HandleScope. Moving these methods to be members of HandleScope would be
321 // neat in some ways, but it would expose internal implementation details in
322 // our public header file, which is undesirable.
323 //
324 // An isolate has a single instance of this class to hold the current thread's
325 // data. In multithreaded V8 programs this data is copied in and out of storage
326 // so that the currently executing thread always has its own copy of this
327 // data.
328 class HandleScopeImplementer {
329 public:
330 class V8_NODISCARD EnteredContextRewindScope {
331 public:
EnteredContextRewindScope(HandleScopeImplementer * hsi)332 explicit EnteredContextRewindScope(HandleScopeImplementer* hsi)
333 : hsi_(hsi), saved_entered_context_count_(hsi->EnteredContextCount()) {}
334
~EnteredContextRewindScope()335 ~EnteredContextRewindScope() {
336 DCHECK_LE(saved_entered_context_count_, hsi_->EnteredContextCount());
337 while (saved_entered_context_count_ < hsi_->EnteredContextCount())
338 hsi_->LeaveContext();
339 }
340
341 private:
342 HandleScopeImplementer* hsi_;
343 size_t saved_entered_context_count_;
344 };
345
HandleScopeImplementer(Isolate * isolate)346 explicit HandleScopeImplementer(Isolate* isolate)
347 : isolate_(isolate),
348 spare_(nullptr),
349 last_handle_before_deferred_block_(nullptr) {}
350
~HandleScopeImplementer()351 ~HandleScopeImplementer() { DeleteArray(spare_); }
352
353 HandleScopeImplementer(const HandleScopeImplementer&) = delete;
354 HandleScopeImplementer& operator=(const HandleScopeImplementer&) = delete;
355
356 // Threading support for handle data.
357 static int ArchiveSpacePerThread();
358 char* RestoreThread(char* from);
359 char* ArchiveThread(char* to);
360 void FreeThreadResources();
361
362 // Garbage collection support.
363 V8_EXPORT_PRIVATE void Iterate(v8::internal::RootVisitor* v);
364 V8_EXPORT_PRIVATE static char* Iterate(v8::internal::RootVisitor* v,
365 char* data);
366
367 inline internal::Address* GetSpareOrNewBlock();
368 inline void DeleteExtensions(internal::Address* prev_limit);
369
370 inline void EnterContext(Context context);
371 inline void LeaveContext();
372 inline bool LastEnteredContextWas(Context context);
EnteredContextCount()373 inline size_t EnteredContextCount() const { return entered_contexts_.size(); }
374
375 inline void EnterMicrotaskContext(Context context);
376
377 // Returns the last entered context or an empty handle if no
378 // contexts have been entered.
379 inline Handle<Context> LastEnteredContext();
380 inline Handle<Context> LastEnteredOrMicrotaskContext();
381
382 inline void SaveContext(Context context);
383 inline Context RestoreContext();
384 inline bool HasSavedContexts();
385
blocks()386 inline DetachableVector<Address*>* blocks() { return &blocks_; }
isolate()387 Isolate* isolate() const { return isolate_; }
388
ReturnBlock(Address * block)389 void ReturnBlock(Address* block) {
390 DCHECK_NOT_NULL(block);
391 if (spare_ != nullptr) DeleteArray(spare_);
392 spare_ = block;
393 }
394
395 static const size_t kEnteredContextsOffset;
396 static const size_t kIsMicrotaskContextOffset;
397
398 private:
ResetAfterArchive()399 void ResetAfterArchive() {
400 blocks_.detach();
401 entered_contexts_.detach();
402 is_microtask_context_.detach();
403 saved_contexts_.detach();
404 spare_ = nullptr;
405 last_handle_before_deferred_block_ = nullptr;
406 }
407
Free()408 void Free() {
409 DCHECK(blocks_.empty());
410 DCHECK(entered_contexts_.empty());
411 DCHECK(is_microtask_context_.empty());
412 DCHECK(saved_contexts_.empty());
413
414 blocks_.free();
415 entered_contexts_.free();
416 is_microtask_context_.free();
417 saved_contexts_.free();
418 if (spare_ != nullptr) {
419 DeleteArray(spare_);
420 spare_ = nullptr;
421 }
422 DCHECK(isolate_->thread_local_top()->CallDepthIsZero());
423 }
424
425 void BeginDeferredScope();
426 std::unique_ptr<PersistentHandles> DetachPersistent(Address* prev_limit);
427
428 Isolate* isolate_;
429 DetachableVector<Address*> blocks_;
430
431 // Used as a stack to keep track of entered contexts.
432 // If |i|th item of |entered_contexts_| is added by EnterMicrotaskContext,
433 // `is_microtask_context_[i]` is 1.
434 // TODO(tzik): Remove |is_microtask_context_| after the deprecated
435 // v8::Isolate::GetEnteredContext() is removed.
436 DetachableVector<Context> entered_contexts_;
437 DetachableVector<int8_t> is_microtask_context_;
438
439 // Used as a stack to keep track of saved contexts.
440 DetachableVector<Context> saved_contexts_;
441 Address* spare_;
442 Address* last_handle_before_deferred_block_;
443 // This is only used for threading support.
444 HandleScopeData handle_scope_data_;
445
446 void IterateThis(RootVisitor* v);
447 char* RestoreThreadHelper(char* from);
448 char* ArchiveThreadHelper(char* to);
449
450 friend class HandleScopeImplementerOffsets;
451 friend class PersistentHandlesScope;
452 };
453
454 const int kHandleBlockSize = v8::internal::KB - 2; // fit in one page
455
SaveContext(Context context)456 void HandleScopeImplementer::SaveContext(Context context) {
457 saved_contexts_.push_back(context);
458 }
459
RestoreContext()460 Context HandleScopeImplementer::RestoreContext() {
461 Context last_context = saved_contexts_.back();
462 saved_contexts_.pop_back();
463 return last_context;
464 }
465
HasSavedContexts()466 bool HandleScopeImplementer::HasSavedContexts() {
467 return !saved_contexts_.empty();
468 }
469
EnterContext(Context context)470 void HandleScopeImplementer::EnterContext(Context context) {
471 DCHECK_EQ(entered_contexts_.size(), is_microtask_context_.size());
472 entered_contexts_.push_back(context);
473 is_microtask_context_.push_back(0);
474 }
475
LeaveContext()476 void HandleScopeImplementer::LeaveContext() {
477 DCHECK(!entered_contexts_.empty());
478 DCHECK_EQ(entered_contexts_.size(), is_microtask_context_.size());
479 entered_contexts_.pop_back();
480 is_microtask_context_.pop_back();
481 }
482
LastEnteredContextWas(Context context)483 bool HandleScopeImplementer::LastEnteredContextWas(Context context) {
484 return !entered_contexts_.empty() && entered_contexts_.back() == context;
485 }
486
EnterMicrotaskContext(Context context)487 void HandleScopeImplementer::EnterMicrotaskContext(Context context) {
488 DCHECK_EQ(entered_contexts_.size(), is_microtask_context_.size());
489 entered_contexts_.push_back(context);
490 is_microtask_context_.push_back(1);
491 }
492
493 // If there's a spare block, use it for growing the current scope.
GetSpareOrNewBlock()494 internal::Address* HandleScopeImplementer::GetSpareOrNewBlock() {
495 internal::Address* block =
496 (spare_ != nullptr) ? spare_
497 : NewArray<internal::Address>(kHandleBlockSize);
498 spare_ = nullptr;
499 return block;
500 }
501
DeleteExtensions(internal::Address * prev_limit)502 void HandleScopeImplementer::DeleteExtensions(internal::Address* prev_limit) {
503 while (!blocks_.empty()) {
504 internal::Address* block_start = blocks_.back();
505 internal::Address* block_limit = block_start + kHandleBlockSize;
506
507 // SealHandleScope may make the prev_limit to point inside the block.
508 // Cast possibly-unrelated pointers to plain Addres before comparing them
509 // to avoid undefined behavior.
510 if (reinterpret_cast<Address>(block_start) <=
511 reinterpret_cast<Address>(prev_limit) &&
512 reinterpret_cast<Address>(prev_limit) <=
513 reinterpret_cast<Address>(block_limit)) {
514 #ifdef ENABLE_HANDLE_ZAPPING
515 internal::HandleScope::ZapRange(prev_limit, block_limit);
516 #endif
517 break;
518 }
519
520 blocks_.pop_back();
521 #ifdef ENABLE_HANDLE_ZAPPING
522 internal::HandleScope::ZapRange(block_start, block_limit);
523 #endif
524 if (spare_ != nullptr) {
525 DeleteArray(spare_);
526 }
527 spare_ = block_start;
528 }
529 DCHECK((blocks_.empty() && prev_limit == nullptr) ||
530 (!blocks_.empty() && prev_limit != nullptr));
531 }
532
533 // Interceptor functions called from generated inline caches to notify
534 // CPU profiler that external callbacks are invoked.
535 void InvokeAccessorGetterCallback(
536 v8::Local<v8::Name> property,
537 const v8::PropertyCallbackInfo<v8::Value>& info,
538 v8::AccessorNameGetterCallback getter);
539
540 void InvokeFunctionCallback(const v8::FunctionCallbackInfo<v8::Value>& info,
541 v8::FunctionCallback callback);
542
543 void InvokeFinalizationRegistryCleanupFromTask(
544 Handle<Context> context,
545 Handle<JSFinalizationRegistry> finalization_registry,
546 Handle<Object> callback);
547
548 template <typename T>
549 EXPORT_TEMPLATE_DECLARE(V8_EXPORT_PRIVATE)
550 T ConvertDouble(double d);
551
552 } // namespace internal
553 } // namespace v8
554
555 #endif // V8_API_API_H_
556