v8
V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++.
Loading...
Searching...
No Matches
api.cc
Go to the documentation of this file.
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#include "src/api/api.h"
6
7#include <algorithm> // For min
8#include <cmath> // For isnan.
9#include <limits>
10#include <optional>
11#include <sstream>
12#include <string>
13#include <utility> // For move
14#include <vector>
15
18#include "include/v8-cppgc.h"
19#include "include/v8-date.h"
24#include "include/v8-function.h"
25#include "include/v8-json.h"
26#include "include/v8-locker.h"
28#include "include/v8-profiler.h"
30#include "include/v8-template.h"
32#include "include/v8-util.h"
35#include "src/api/api-inl.h"
36#include "src/api/api-natives.h"
37#include "src/base/hashing.h"
38#include "src/base/logging.h"
44#include "src/base/vector.h"
52#include "src/common/globals.h"
54#include "src/date/date.h"
55#include "src/debug/debug.h"
70#include "src/heap/heap-inl.h"
73#include "src/heap/safepoint.h"
76#include "src/init/icu_util.h"
78#include "src/init/v8.h"
82#include "src/logging/metrics.h"
104#include "src/objects/oddball.h"
109#include "src/objects/property.h"
112#include "src/objects/slots.h"
113#include "src/objects/smi.h"
114#include "src/objects/string.h"
119#include "src/parsing/parser.h"
129#include "src/runtime/runtime.h"
131#include "src/sandbox/isolate.h"
132#include "src/sandbox/sandbox.h"
142#include "src/utils/version.h"
143
144#if V8_ENABLE_WEBASSEMBLY
148#include "src/wasm/value-type.h"
149#include "src/wasm/wasm-engine.h"
150#include "src/wasm/wasm-js.h"
152#include "src/wasm/wasm-result.h"
154#endif // V8_ENABLE_WEBASSEMBLY
155
156#if V8_OS_LINUX || V8_OS_DARWIN || V8_OS_FREEBSD
157#include <signal.h>
158#include <unistd.h>
159
160#if V8_ENABLE_WEBASSEMBLY
163#endif // V8_ENABLE_WEBASSEMBLY
164
165#endif // V8_OS_LINUX || V8_OS_DARWIN || V8_OS_FREEBSD
166
167#if V8_OS_WIN
170#if defined(V8_OS_WIN64)
173#endif // V8_OS_WIN64
174#endif // V8_OS_WIN
175
176#if defined(V8_ENABLE_ETW_STACK_WALKING)
178#endif // V8_ENABLE_ETW_STACK_WALKING
179
180// Has to be the last include (doesn't have include guards):
181#include "src/api/api-macros.h"
182
183namespace v8 {
184
186
188 i::Isolate* i_isolate, i::DirectHandle<i::Script> script) {
189 i::DirectHandle<i::Object> scriptName(script->GetNameOrSourceURL(),
190 i_isolate);
191 i::DirectHandle<i::Object> source_map_url(script->source_mapping_url(),
192 i_isolate);
193 i::DirectHandle<i::Object> host_defined_options(
194 script->host_defined_options(), i_isolate);
195 ScriptOriginOptions options(script->origin_options());
196 bool is_wasm = false;
197#if V8_ENABLE_WEBASSEMBLY
198 is_wasm = script->type() == i::Script::Type::kWasm;
199#endif // V8_ENABLE_WEBASSEMBLY
200 v8::ScriptOrigin origin(
201 Utils::ToLocal(scriptName), script->line_offset(),
202 script->column_offset(), options.IsSharedCrossOrigin(), script->id(),
203 Utils::ToLocal(source_map_url), options.IsOpaque(), is_wasm,
204 options.IsModule(), Utils::ToLocal(host_defined_options));
205 return origin;
206}
207
208// --- E x c e p t i o n B e h a v i o r ---
209
210// When V8 cannot allocate memory FatalProcessOutOfMemory is called. The default
211// OOM error handler is called and execution is stopped.
212void i::V8::FatalProcessOutOfMemory(i::Isolate* i_isolate, const char* location,
213 const OOMDetails& details) {
214 i::HeapStats heap_stats;
215
216 if (i_isolate == nullptr) {
217 i_isolate = Isolate::TryGetCurrent();
218 }
219
220 if (i_isolate == nullptr) {
221 // If the Isolate is not available for the current thread we cannot retrieve
222 // memory information from the Isolate. Write easy-to-recognize values on
223 // the stack.
224 memset(&heap_stats, 0xBADC0DE, sizeof(heap_stats));
225 // Give the embedder a chance to handle the condition. If it doesn't,
226 // just crash.
227 if (g_oom_error_callback) g_oom_error_callback(location, details);
229 UNREACHABLE();
230 }
231
232 memset(heap_stats.last_few_messages, 0, Heap::kTraceRingBufferSize + 1);
233
234 if (i_isolate->heap()->HasBeenSetUp()) {
235 i_isolate->heap()->RecordStats(&heap_stats);
236 if (!v8_flags.correctness_fuzzer_suppressions) {
237 char* first_newline = strchr(heap_stats.last_few_messages, '\n');
238 if (first_newline == nullptr || first_newline[1] == '\0')
239 first_newline = heap_stats.last_few_messages;
240 base::OS::PrintError("\n<--- Last few GCs --->\n%s\n", first_newline);
241 }
242 }
243 Utils::ReportOOMFailure(i_isolate, location, details);
244 if (g_oom_error_callback) g_oom_error_callback(location, details);
245 // If the fatal error handler returns, we stop execution.
246 FATAL("API fatal error handler returned after process out of memory");
247}
248
249void i::V8::FatalProcessOutOfMemory(i::Isolate* i_isolate, const char* location,
250 const char* detail) {
251 OOMDetails details;
252 details.detail = detail;
253 FatalProcessOutOfMemory(i_isolate, location, details);
254}
255
256void Utils::ReportApiFailure(const char* location, const char* message) {
257 i::Isolate* i_isolate = i::Isolate::TryGetCurrent();
259 if (i_isolate != nullptr) {
260 callback = i_isolate->exception_behavior();
261 }
262 if (callback == nullptr) {
263 base::OS::PrintError("\n#\n# Fatal error in %s\n# %s\n#\n\n", location,
264 message);
266 } else {
267 callback(location, message);
268 }
269 i_isolate->SignalFatalError();
270}
271
272void Utils::ReportOOMFailure(i::Isolate* i_isolate, const char* location,
273 const OOMDetails& details) {
274 if (auto oom_callback = i_isolate->oom_behavior()) {
275 oom_callback(location, details);
276 } else {
277 // TODO(wfh): Remove this fallback once Blink is setting OOM handler. See
278 // crbug.com/614440.
279 FatalErrorCallback fatal_callback = i_isolate->exception_behavior();
280 if (fatal_callback == nullptr) {
283 base::FatalOOM(type, location);
284 UNREACHABLE();
285 } else {
286 fatal_callback(location,
287 details.is_heap_oom
288 ? "Allocation failed - JavaScript heap out of memory"
289 : "Allocation failed - process out of memory");
290 }
291 }
292 i_isolate->SignalFatalError();
293}
294
296 i::V8::SetSnapshotBlob(snapshot_blob);
297}
298
299namespace {
300
301#ifdef V8_ENABLE_SANDBOX
302// ArrayBufferAllocator to use when the sandbox is enabled in which case all
303// ArrayBuffer backing stores need to be allocated inside the sandbox.
304class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
305 public:
306 explicit ArrayBufferAllocator(i::IsolateGroup* group)
307 : sandbox_(group->sandbox()),
308 allocator_(group->GetSandboxedArrayBufferAllocator()) {}
309
310 void* Allocate(size_t length) override {
311 return allocator_->Allocate(length);
312 }
313
314 void* AllocateUninitialized(size_t length) override {
315 return Allocate(length);
316 }
317
318 void Free(void* data, size_t length) override {
319 return allocator_->Free(data);
320 }
321
322 PageAllocator* GetPageAllocator() override {
323 return sandbox_->page_allocator();
324 }
325
326 private:
327 i::Sandbox* sandbox_ = nullptr;
328 i::SandboxedArrayBufferAllocator* allocator_ = nullptr;
329};
330
331#else
332
333class ArrayBufferAllocator : public v8::ArrayBuffer::Allocator {
334 public:
335 void* Allocate(size_t length) override { return base::Calloc(length, 1); }
336
337 void* AllocateUninitialized(size_t length) override {
338 return base::Malloc(length);
339 }
340
341 void Free(void* data, size_t) override { base::Free(data); }
342
343 PageAllocator* GetPageAllocator() override {
345 }
346};
347#endif // V8_ENABLE_SANDBOX
348
349} // namespace
350
352 const intptr_t* external_references,
353 const StartupData* existing_snapshot,
354 bool owns_isolate)
355 : impl_(new i::SnapshotCreatorImpl(
356 reinterpret_cast<i::Isolate*>(v8_isolate), external_references,
357 existing_snapshot, owns_isolate)) {}
358
359SnapshotCreator::SnapshotCreator(const intptr_t* external_references,
360 const StartupData* existing_snapshot)
361 : SnapshotCreator(nullptr, external_references, existing_snapshot) {}
362
364 : impl_(new i::SnapshotCreatorImpl(params)) {}
365
367 const v8::Isolate::CreateParams& params)
368 : impl_(new i::SnapshotCreatorImpl(reinterpret_cast<i::Isolate*>(isolate),
369 params)) {}
370
375
377 return reinterpret_cast<v8::Isolate*>(impl_->isolate());
378}
379
381 Local<Context> context,
382 SerializeInternalFieldsCallback internal_fields_serializer,
383 SerializeContextDataCallback context_data_serializer,
384 SerializeAPIWrapperCallback api_wrapper_serializer) {
386 Utils::OpenDirectHandle(*context),
387 i::SerializeEmbedderFieldsCallback(internal_fields_serializer,
388 context_data_serializer,
389 api_wrapper_serializer));
390}
391
393 Local<Context> context,
394 SerializeInternalFieldsCallback internal_fields_serializer,
395 SerializeContextDataCallback context_data_serializer,
396 SerializeAPIWrapperCallback api_wrapper_serializer) {
397 return impl_->AddContext(
398 Utils::OpenDirectHandle(*context),
399 i::SerializeEmbedderFieldsCallback(internal_fields_serializer,
400 context_data_serializer,
401 api_wrapper_serializer));
402}
403
405 return impl_->AddData(object);
406}
407
408size_t SnapshotCreator::AddData(Local<Context> context, i::Address object) {
409 return impl_->AddData(Utils::OpenDirectHandle(*context), object);
410}
411
413 SnapshotCreator::FunctionCodeHandling function_code_handling) {
414 return impl_->CreateBlob(function_code_handling);
415}
416
418 DCHECK(i::Snapshot::VerifyChecksum(this));
419 return i::Snapshot::ExtractRehashability(this);
420}
421
422bool StartupData::IsValid() const { return i::Snapshot::VersionIsValid(this); }
423
427
431
432void V8::SetFlagsFromString(const char* str) {
433 SetFlagsFromString(str, strlen(str));
434}
435
436void V8::SetFlagsFromString(const char* str, size_t length) {
437 i::FlagList::SetFlagsFromString(str, length);
438}
439
440void V8::SetFlagsFromCommandLine(int* argc, char** argv, bool remove_flags) {
441 using HelpOptions = i::FlagList::HelpOptions;
442 i::FlagList::SetFlagsFromCommandLine(argc, argv, remove_flags,
443 HelpOptions(HelpOptions::kDontExit));
444}
445
447
449 : extension_(std::move(extension)) {}
450
451// static
452void RegisteredExtension::Register(std::unique_ptr<Extension> extension) {
453 RegisteredExtension* new_extension =
454 new RegisteredExtension(std::move(extension));
455 new_extension->next_ = first_extension_;
456 first_extension_ = new_extension;
457}
458
459// static
462 while (re != nullptr) {
464 delete re;
465 re = next;
466 }
467 first_extension_ = nullptr;
468}
469
470namespace {
471class ExtensionResource : public String::ExternalOneByteStringResource {
472 public:
473 ExtensionResource() : data_(nullptr), length_(0) {}
474 ExtensionResource(const char* data, size_t length)
475 : data_(data), length_(length) {}
476 const char* data() const override { return data_; }
477 size_t length() const override { return length_; }
478 void Dispose() override {}
479
480 private:
481 const char* data_;
482 size_t length_;
483};
484} // anonymous namespace
485
486void RegisterExtension(std::unique_ptr<Extension> extension) {
488}
489
490Extension::Extension(const char* name, const char* source, int dep_count,
491 const char** deps, int source_length)
492 : name_(name),
493 source_length_(source_length >= 0
494 ? source_length
495 : (source ? static_cast<int>(strlen(source)) : 0)),
496 dep_count_(dep_count),
497 deps_(deps),
498 auto_enable_(false) {
499 source_ = new ExtensionResource(source, source_length_);
500 CHECK(source != nullptr || source_length_ == 0);
501}
502
504 size_t initial_heap_size_in_bytes, size_t maximum_heap_size_in_bytes) {
505 CHECK_LE(initial_heap_size_in_bytes, maximum_heap_size_in_bytes);
506 if (maximum_heap_size_in_bytes == 0) {
507 return;
508 }
509 size_t young_generation, old_generation;
510 i::Heap::GenerationSizesFromHeapSize(maximum_heap_size_in_bytes,
511 &young_generation, &old_generation);
513 std::max(young_generation, i::Heap::MinYoungGenerationSize()));
515 std::max(old_generation, i::Heap::MinOldGenerationSize()));
516 if (initial_heap_size_in_bytes > 0) {
517 i::Heap::GenerationSizesFromHeapSize(initial_heap_size_in_bytes,
518 &young_generation, &old_generation);
519 // We do not set lower bounds for the initial sizes.
522 }
525 std::min(i::kMaximalCodeRangeSize, maximum_heap_size_in_bytes));
526 }
527}
528
529void ResourceConstraints::ConfigureDefaults(uint64_t physical_memory,
530 uint64_t virtual_memory_limit) {
531 size_t heap_size = i::Heap::HeapSizeFromPhysicalMemory(physical_memory);
532 size_t young_generation, old_generation;
533 i::Heap::GenerationSizesFromHeapSize(heap_size, &young_generation,
534 &old_generation);
537
538 if (virtual_memory_limit > 0 && i::kPlatformRequiresCodeRange) {
541 static_cast<size_t>(virtual_memory_limit / 8)));
542 }
543}
544
545#ifdef ENABLE_SLOW_DCHECKS
546namespace api_internal {
548 if (internal::StackAllocatedCheck::Get()) {
550 }
551}
552} // namespace api_internal
553#endif
554
555namespace internal {
556
558 Utils::ApiCheck(!is_empty, "v8::ReturnValue",
559 "SetNonEmpty() called with empty handle.");
560}
561
563 i::Isolate* i_isolate, i::Address value, internal::Address* slot,
564 TracedReferenceStoreMode store_mode,
565 TracedReferenceHandling reference_handling) {
566 return i_isolate->traced_handles()
567 ->Create(value, slot, store_mode, reference_handling)
568 .location();
569}
570
574
576 internal::Address** to) {
577 TracedHandles::Copy(from, to);
578}
579
583
584#if V8_STATIC_ROOTS_BOOL
585
586// Check static root constants exposed in v8-internal.h.
587
588namespace {
589constexpr InstanceTypeChecker::TaggedAddressRange kStringMapRange =
590 *InstanceTypeChecker::UniqueMapRangeOfInstanceTypeRange(FIRST_STRING_TYPE,
592} // namespace
593
594#define EXPORTED_STATIC_ROOTS_PTR_MAPPING(V) \
595 V(UndefinedValue, i::StaticReadOnlyRoot::kUndefinedValue) \
596 V(NullValue, i::StaticReadOnlyRoot::kNullValue) \
597 V(TrueValue, i::StaticReadOnlyRoot::kTrueValue) \
598 V(FalseValue, i::StaticReadOnlyRoot::kFalseValue) \
599 V(EmptyString, i::StaticReadOnlyRoot::kempty_string) \
600 V(TheHoleValue, i::StaticReadOnlyRoot::kTheHoleValue) \
601 V(StringMapLowerBound, kStringMapRange.first) \
602 V(StringMapUpperBound, kStringMapRange.second)
603
604static_assert(std::is_same_v<Internals::Tagged_t, Tagged_t>);
605// Ensure they have the correct value.
606#define CHECK_STATIC_ROOT(name, value) \
607 static_assert(Internals::StaticReadOnlyRoot::k##name == value);
608EXPORTED_STATIC_ROOTS_PTR_MAPPING(CHECK_STATIC_ROOT)
609#undef CHECK_STATIC_ROOT
610#define PLUS_ONE(...) +1
611static constexpr int kNumberOfCheckedStaticRoots =
612 0 EXPORTED_STATIC_ROOTS_PTR_MAPPING(PLUS_ONE);
613#undef EXPORTED_STATIC_ROOTS_PTR_MAPPING
614static_assert(Internals::StaticReadOnlyRoot::kNumberOfExportedStaticRoots ==
615 kNumberOfCheckedStaticRoots);
616
617#endif // V8_STATIC_ROOTS_BOOL
618
619} // namespace internal
620
621namespace api_internal {
622
624 API_RCS_SCOPE(i_isolate, Persistent, New);
626 i_isolate->global_handles()->Create(value);
627#ifdef VERIFY_HEAP
628 if (i::v8_flags.verify_heap) {
629 i::Object::ObjectVerify(i::Tagged<i::Object>(value), i_isolate);
630 }
631#endif // VERIFY_HEAP
632 return result.location();
633}
634
636 i::IndirectHandle<i::Object> result = i::GlobalHandles::CopyGlobal(from);
637 return result.location();
638}
639
641 i::GlobalHandles::MoveGlobal(from, to);
642}
643
644void MakeWeak(i::Address* location, void* parameter,
646 WeakCallbackType type) {
647 i::GlobalHandles::MakeWeak(location, parameter, weak_callback, type);
648}
649
650void MakeWeak(i::Address** location_addr) {
651 i::GlobalHandles::MakeWeak(location_addr);
652}
653
654void* ClearWeak(i::Address* location) {
655 return i::GlobalHandles::ClearWeakness(location);
656}
657
658void AnnotateStrongRetainer(i::Address* location, const char* label) {
659 i::GlobalHandles::AnnotateStrongRetainer(location, label);
660}
661
662void DisposeGlobal(i::Address* location) {
663 i::GlobalHandles::Destroy(location);
664}
665
666i::Address* Eternalize(Isolate* v8_isolate, Value* value) {
667 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
669 int index = -1;
670 i_isolate->eternal_handles()->Create(i_isolate, object, &index);
671 return i_isolate->eternal_handles()->Get(index).location();
672}
673
675 Utils::ApiCheck(false, "v8::FromJust", "Maybe value is Nothing");
676}
677
679 Utils::ApiCheck(false, "v8::ToLocalChecked", "Empty MaybeLocal");
680}
681
684 "WeakCallbackInfo::GetInternalField",
685 "Internal field out of bounds");
686}
687
688} // namespace api_internal
689
690// --- H a n d l e s ---
691
692HandleScope::HandleScope(Isolate* v8_isolate) { Initialize(v8_isolate); }
693
695 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
696 // We do not want to check the correct usage of the Locker class all over the
697 // place, so we do it only here: Without a HandleScope, an embedder can do
698 // almost nothing, so it is enough to check in this central place.
699 // We make an exception if the serializer is enabled, which means that the
700 // Isolate is exclusively used to create a snapshot.
702 i_isolate->thread_manager()->IsLockedByCurrentThread() ||
703 i_isolate->serializer_enabled(),
704 "HandleScope::HandleScope",
705 "Entering the V8 API without proper locking in place");
706 i::HandleScopeData* current = i_isolate->handle_scope_data();
707 i_isolate_ = i_isolate;
708 prev_next_ = current->next;
709 prev_limit_ = current->limit;
710 current->level++;
711#ifdef V8_ENABLE_CHECKS
712 scope_level_ = current->level;
713#endif
714}
715
717#ifdef V8_ENABLE_CHECKS
718 CHECK_EQ(scope_level_, i_isolate_->handle_scope_data()->level);
719#endif
720 i::HandleScope::CloseScope(i_isolate_, prev_next_, prev_limit_);
721}
722
723void* HandleScope::operator new(size_t) { base::OS::Abort(); }
724void* HandleScope::operator new[](size_t) { base::OS::Abort(); }
725void HandleScope::operator delete(void*, size_t) { base::OS::Abort(); }
726void HandleScope::operator delete[](void*, size_t) { base::OS::Abort(); }
727
729 return i::HandleScope::NumberOfHandles(
730 reinterpret_cast<i::Isolate*>(v8_isolate));
731}
732
734 return i::HandleScope::CreateHandle(i_isolate, value);
735}
736
737#ifdef V8_ENABLE_DIRECT_HANDLE
738
740 i::Isolate* i_isolate = i::Isolate::Current();
741 return i::HandleScope::CreateHandle(i_isolate, value);
742}
743
744#endif // V8_ENABLE_DIRECT_HANDLE
745
747 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
749 i_isolate, i::ReadOnlyRoots(i_isolate).the_hole_value().ptr());
750 Initialize(v8_isolate);
751}
752
754 DCHECK_NOT_NULL(escape_value);
756 reinterpret_cast<i::Isolate*>(GetIsolate())));
757 *escape_slot_ = *escape_value;
758 return escape_slot_;
759}
760
762 : i_isolate_(reinterpret_cast<i::Isolate*>(v8_isolate)) {
764 prev_limit_ = current->limit;
765 current->limit = current->next;
766 prev_sealed_level_ = current->sealed_level;
767 current->sealed_level = current->level;
768}
769
772 DCHECK_EQ(current->next, current->limit);
773 current->limit = prev_limit_;
774 DCHECK_EQ(current->level, current->sealed_level);
775 current->sealed_level = prev_sealed_level_;
776}
777
778bool Data::IsModule() const {
780}
781
783 return i::IsModuleRequest(*Utils::OpenDirectHandle(this));
784}
785
786bool Data::IsFixedArray() const {
787 return i::IsFixedArray(*Utils::OpenDirectHandle(this));
788}
789
790bool Data::IsValue() const {
793 if (i::IsSmi(self)) return true;
795 DCHECK(!IsTheHole(heap_object));
796 if (i::IsSymbol(heap_object)) {
797 return !i::Cast<i::Symbol>(heap_object)->is_private();
798 }
799 return IsPrimitiveHeapObject(heap_object) || IsJSReceiver(heap_object);
800}
801
802bool Data::IsPrivate() const {
804}
805
807 return i::IsObjectTemplateInfo(*Utils::OpenDirectHandle(this));
808}
809
811 return i::IsFunctionTemplateInfo(*Utils::OpenDirectHandle(this));
812}
813
814bool Data::IsContext() const {
815 return i::IsContext(*Utils::OpenDirectHandle(this));
816}
817
821 i::Isolate* i_isolate = env->GetIsolate();
824 impl->EnterContext(env);
825 impl->SaveContext(i_isolate->context());
826 i_isolate->set_context(env);
827}
828
830 auto env = Utils::OpenDirectHandle(this);
831 i::Isolate* i_isolate = env->GetIsolate();
834 if (!Utils::ApiCheck(impl->LastEnteredContextWas(*env), "v8::Context::Exit()",
835 "Cannot exit non-entered context")) {
836 return;
837 }
838 impl->LeaveContext();
839 i_isolate->set_context(impl->RestoreContext());
840}
841
843 Local<Context> backup_incumbent_context)
844 : backup_incumbent_context_(backup_incumbent_context) {
846
848 i::Isolate* i_isolate = env->GetIsolate();
849
851 i::SimulatorStack::RegisterJSStackComparableAddress(i_isolate);
852
853 prev_ = i_isolate->top_backup_incumbent_scope();
854 i_isolate->set_top_backup_incumbent_scope(this);
855 // Enforce slow incumbent computation in order to make it find this
856 // BackupIncumbentScope.
858}
859
861 auto env = Utils::OpenDirectHandle(*backup_incumbent_context_);
862 i::Isolate* i_isolate = env->GetIsolate();
863
864 i::SimulatorStack::UnregisterJSStackComparableAddress(i_isolate);
865
867}
868
869static_assert(i::Internals::kEmbedderDataSlotSize == i::kEmbedderDataSlotSize);
870static_assert(i::Internals::kEmbedderDataSlotExternalPointerOffset ==
871 i::EmbedderDataSlot::kExternalPointerOffset);
872
874 Context* context, int index, bool can_grow, const char* location) {
875 auto env = Utils::OpenDirectHandle(context);
876 i::Isolate* i_isolate = env->GetIsolate();
878 bool ok = Utils::ApiCheck(i::IsNativeContext(*env), location,
879 "Not a native context") &&
880 Utils::ApiCheck(index >= 0, location, "Negative index");
881 if (!ok) return {};
882 // TODO(ishell): remove cast once embedder_data slot has a proper type.
884 i::Cast<i::EmbedderDataArray>(env->embedder_data()), i_isolate);
885 if (index < data->length()) return data;
886 if (!Utils::ApiCheck(can_grow && index < i::EmbedderDataArray::kMaxLength,
887 location, "Index too large")) {
888 return {};
889 }
890 data = i::EmbedderDataArray::EnsureCapacity(i_isolate, data, index);
891 env->set_embedder_data(*data);
892 return data;
893}
894
896 auto context = Utils::OpenDirectHandle(this);
897 DCHECK_NO_SCRIPT_NO_EXCEPTION(context->GetIsolate());
898 Utils::ApiCheck(i::IsNativeContext(*context),
899 "Context::GetNumberOfEmbedderDataFields",
900 "Not a native context");
901 // TODO(ishell): remove cast once embedder_data slot has a proper type.
902 return static_cast<uint32_t>(
903 i::Cast<i::EmbedderDataArray>(context->embedder_data())->length());
904}
905
907 const char* location = "v8::Context::GetEmbedderData()";
909 EmbedderDataFor(this, index, false, location);
910 if (data.is_null()) return Local<Value>();
911 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
912 return Utils::ToLocal(i::direct_handle(
913 i::EmbedderDataSlot(*data, index).load_tagged(), i_isolate));
914}
915
917 const char* location = "v8::Context::SetEmbedderData()";
919 EmbedderDataFor(this, index, true, location);
920 if (data.is_null()) return;
921 auto val = Utils::OpenDirectHandle(*value);
922 i::EmbedderDataSlot::store_tagged(*data, index, *val);
925}
926
928 const char* location = "v8::Context::GetAlignedPointerFromEmbedderData()";
929 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
930 i::HandleScope handle_scope(i_isolate);
932 EmbedderDataFor(this, index, false, location);
933 if (data.is_null()) return nullptr;
934 void* result;
936 i::EmbedderDataSlot(*data, index).ToAlignedPointer(i_isolate, &result),
937 location, "Pointer is not aligned");
938 return result;
939}
940
941void Context::SetAlignedPointerInEmbedderData(int index, void* value) {
942 const char* location = "v8::Context::SetAlignedPointerInEmbedderData()";
943 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
945 EmbedderDataFor(this, index, true, location);
946 bool ok = i::EmbedderDataSlot(*data, index)
947 .store_aligned_pointer(i_isolate, *data, value);
948 Utils::ApiCheck(ok, location, "Pointer is not aligned");
950}
951
952// --- T e m p l a t e ---
953
955 v8::PropertyAttribute attribute) {
956 auto templ = Utils::OpenDirectHandle(this);
957 i::Isolate* i_isolate = templ->GetIsolateChecked();
959 i::HandleScope scope(i_isolate);
960 auto value_obj = Utils::OpenDirectHandle(*value);
961
962 Utils::ApiCheck(!IsJSReceiver(*value_obj) || IsTemplateInfo(*value_obj),
963 "v8::Template::Set",
964 "Invalid value, must be a primitive or a Template");
965
966 // The template cache only performs shallow clones, if we set an
967 // ObjectTemplate as a property value then we can not cache the receiver
968 // template.
969 if (i::IsObjectTemplateInfo(*value_obj)) {
970 templ->set_is_cacheable(false);
971 }
972
973 i::ApiNatives::AddDataProperty(i_isolate, templ,
974 Utils::OpenDirectHandle(*name), value_obj,
975 static_cast<i::PropertyAttributes>(attribute));
976}
977
979 v8::PropertyAttribute attribute) {
980 Set(Local<Name>::Cast(name), value, attribute);
981}
982
986 v8::PropertyAttribute attribute) {
987 auto templ = Utils::OpenDirectHandle(this);
988 auto i_isolate = templ->GetIsolateChecked();
990 if (!getter.IsEmpty()) {
991 i_getter = Utils::OpenDirectHandle(*getter);
992 Utils::ApiCheck(i_getter->has_callback(i_isolate),
993 "v8::Template::SetAccessorProperty",
994 "Getter must have a call handler");
995 }
997 if (!setter.IsEmpty()) {
998 i_setter = Utils::OpenDirectHandle(*setter);
999 Utils::ApiCheck(i_setter->has_callback(i_isolate),
1000 "v8::Template::SetAccessorProperty",
1001 "Setter must have a call handler");
1002 }
1004 DCHECK(!name.IsEmpty());
1005 DCHECK(!getter.IsEmpty() || !setter.IsEmpty());
1006 i::HandleScope scope(i_isolate);
1007 i::ApiNatives::AddAccessorProperty(
1008 i_isolate, templ, Utils::OpenDirectHandle(*name), i_getter, i_setter,
1009 static_cast<i::PropertyAttributes>(attribute));
1010}
1011
1012// --- F u n c t i o n T e m p l a t e ---
1013
1015 auto self = Utils::OpenDirectHandle(this);
1016 i::Isolate* i_isolate = self->GetIsolateChecked();
1018 i::DirectHandle<i::HeapObject> heap_obj(self->GetPrototypeTemplate(),
1019 i_isolate);
1020 if (i::IsUndefined(*heap_obj, i_isolate)) {
1021 // Do not cache prototype objects.
1022 constexpr bool do_not_cache = true;
1024 i_isolate->factory()->NewObjectTemplateInfo({}, do_not_cache);
1025 i::FunctionTemplateInfo::SetPrototypeTemplate(i_isolate, self,
1026 proto_template);
1027 return Utils::ToLocal(proto_template);
1028 }
1029 return ToApiHandle<ObjectTemplate>(heap_obj);
1030}
1031
1033 Local<FunctionTemplate> prototype_provider) {
1034 auto self = Utils::OpenDirectHandle(this);
1035 i::Isolate* i_isolate = self->GetIsolateChecked();
1038 Utils::OpenDirectHandle(*prototype_provider);
1039 Utils::ApiCheck(i::IsUndefined(self->GetPrototypeTemplate(), i_isolate),
1040 "v8::FunctionTemplate::SetPrototypeProviderTemplate",
1041 "Protoype must be undefined");
1042 Utils::ApiCheck(i::IsUndefined(self->GetParentTemplate(), i_isolate),
1043 "v8::FunctionTemplate::SetPrototypeProviderTemplate",
1044 "Prototype provider must be empty");
1045 i::FunctionTemplateInfo::SetPrototypeProviderTemplate(i_isolate, self,
1046 result);
1047}
1048
1049namespace {
1050static void EnsureNotPublished(i::DirectHandle<i::FunctionTemplateInfo> info,
1051 const char* func) {
1052 DCHECK_IMPLIES(info->instantiated(), info->published());
1053 Utils::ApiCheck(!info->published(), func,
1054 "FunctionTemplate already instantiated");
1055}
1056
1059 v8::Local<Signature> signature, int length, ConstructorBehavior behavior,
1060 bool do_not_cache,
1061 v8::Local<Private> cached_property_name = v8::Local<Private>(),
1063 const MemorySpan<const CFunction>& c_function_overloads = {}) {
1065 i_isolate->factory()->NewFunctionTemplateInfo(length, do_not_cache);
1066 {
1067 // Disallow GC until all fields of obj have acceptable types.
1070 if (!signature.IsEmpty()) {
1071 raw->set_signature(*Utils::OpenDirectHandle(*signature));
1072 }
1073 if (!cached_property_name.IsEmpty()) {
1074 raw->set_cached_property_name(
1075 *Utils::OpenDirectHandle(*cached_property_name));
1076 }
1077 if (behavior == ConstructorBehavior::kThrow) {
1078 raw->set_remove_prototype(true);
1079 }
1080 }
1081 if (callback != nullptr) {
1082 Utils::ToLocal(obj)->SetCallHandler(callback, data, side_effect_type,
1083 c_function_overloads);
1084 }
1085 return obj;
1086}
1087} // namespace
1088
1090 auto info = Utils::OpenDirectHandle(this);
1091 EnsureNotPublished(info, "v8::FunctionTemplate::Inherit");
1092 i::Isolate* i_isolate = info->GetIsolateChecked();
1095 i::IsUndefined(info->GetPrototypeProviderTemplate(), i_isolate),
1096 "v8::FunctionTemplate::Inherit", "Protoype provider must be empty");
1097 i::FunctionTemplateInfo::SetParentTemplate(i_isolate, info,
1098 Utils::OpenDirectHandle(*value));
1099}
1100
1103 v8::Local<Signature> signature, int length, ConstructorBehavior behavior,
1104 SideEffectType side_effect_type, const CFunction* c_function,
1105 uint16_t instance_type, uint16_t allowed_receiver_instance_type_range_start,
1106 uint16_t allowed_receiver_instance_type_range_end) {
1107 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1108 // Changes to the environment cannot be captured in the snapshot. Expect no
1109 // function templates when the isolate is created for serialization.
1110 API_RCS_SCOPE(i_isolate, FunctionTemplate, New);
1111
1112 if (!Utils::ApiCheck(
1113 !c_function || behavior == ConstructorBehavior::kThrow,
1114 "FunctionTemplate::New",
1115 "Fast API calls are not supported for constructor functions")) {
1116 return Local<FunctionTemplate>();
1117 }
1118
1120 i::DirectHandle<i::FunctionTemplateInfo> templ = FunctionTemplateNew(
1121 i_isolate, callback, data, signature, length, behavior, false,
1122 Local<Private>(), side_effect_type,
1123 c_function ? MemorySpan<const CFunction>{c_function, 1}
1125
1126 if (instance_type) {
1127 if (!Utils::ApiCheck(
1128 base::IsInRange(static_cast<int>(instance_type),
1129 i::Internals::kFirstEmbedderJSApiObjectType,
1130 i::Internals::kLastEmbedderJSApiObjectType),
1131 "FunctionTemplate::New",
1132 "instance_type is outside the range of valid JSApiObject types")) {
1133 return Local<FunctionTemplate>();
1134 }
1135 templ->SetInstanceType(instance_type);
1136 }
1137
1138 if (allowed_receiver_instance_type_range_start ||
1139 allowed_receiver_instance_type_range_end) {
1140 if (!Utils::ApiCheck(i::Internals::kFirstEmbedderJSApiObjectType <=
1141 allowed_receiver_instance_type_range_start &&
1142 allowed_receiver_instance_type_range_start <=
1143 allowed_receiver_instance_type_range_end &&
1144 allowed_receiver_instance_type_range_end <=
1145 i::Internals::kLastEmbedderJSApiObjectType,
1146 "FunctionTemplate::New",
1147 "allowed receiver instance type range is outside the "
1148 "range of valid JSApiObject types")) {
1149 return Local<FunctionTemplate>();
1150 }
1151 templ->SetAllowedReceiverInstanceTypeRange(
1152 allowed_receiver_instance_type_range_start,
1153 allowed_receiver_instance_type_range_end);
1154 }
1155 return Utils::ToLocal(templ);
1156}
1157
1160 v8::Local<Signature> signature, int length, ConstructorBehavior behavior,
1161 SideEffectType side_effect_type,
1162 const MemorySpan<const CFunction>& c_function_overloads) {
1163 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1164 API_RCS_SCOPE(i_isolate, FunctionTemplate, New);
1165
1166 // Check that all overloads of the fast API callback have different numbers of
1167 // parameters. Since the number of overloads is supposed to be small, just
1168 // comparing them with each other should be fine.
1169 for (size_t i = 0; i < c_function_overloads.size(); ++i) {
1170 for (size_t j = i + 1; j < c_function_overloads.size(); ++j) {
1171 CHECK_NE(c_function_overloads.data()[i].ArgumentCount(),
1172 c_function_overloads.data()[j].ArgumentCount());
1173 }
1174 }
1175
1176 if (!Utils::ApiCheck(
1177 c_function_overloads.empty() ||
1178 behavior == ConstructorBehavior::kThrow,
1179 "FunctionTemplate::NewWithCFunctionOverloads",
1180 "Fast API calls are not supported for constructor functions")) {
1181 return Local<FunctionTemplate>();
1182 }
1183
1185 i::DirectHandle<i::FunctionTemplateInfo> templ = FunctionTemplateNew(
1186 i_isolate, callback, data, signature, length, behavior, false,
1187 Local<Private>(), side_effect_type, c_function_overloads);
1188 return Utils::ToLocal(templ);
1189}
1190
1192 Isolate* v8_isolate, FunctionCallback callback,
1193 Local<Private> cache_property, Local<Value> data,
1194 Local<Signature> signature, int length, SideEffectType side_effect_type) {
1195 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1196 API_RCS_SCOPE(i_isolate, FunctionTemplate, NewWithCache);
1198 i::DirectHandle<i::FunctionTemplateInfo> templ = FunctionTemplateNew(
1199 i_isolate, callback, data, signature, length, ConstructorBehavior::kAllow,
1200 false, cache_property, side_effect_type);
1201 return Utils::ToLocal(templ);
1202}
1203
1208
1209#define SET_FIELD_WRAPPED(i_isolate, obj, setter, cdata, tag) \
1210 do { \
1211 i::DirectHandle<i::UnionOf<i::Smi, i::Foreign>> foreign = \
1212 FromCData<tag>(i_isolate, cdata); \
1213 (obj)->setter(*foreign); \
1214 } while (false)
1215
1218 SideEffectType side_effect_type,
1219 const MemorySpan<const CFunction>& c_function_overloads) {
1220 auto info = Utils::OpenDirectHandle(this);
1221 EnsureNotPublished(info, "v8::FunctionTemplate::SetCallHandler");
1222 i::Isolate* i_isolate = info->GetIsolateChecked();
1224 i::HandleScope scope(i_isolate);
1225 info->set_has_side_effects(side_effect_type !=
1227 info->set_callback(i_isolate, reinterpret_cast<i::Address>(callback));
1228 if (data.IsEmpty()) {
1229 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
1230 }
1231 // "Release" callback and callback data fields.
1232 info->set_callback_data(*Utils::OpenDirectHandle(*data), kReleaseStore);
1233
1234 if (!c_function_overloads.empty()) {
1235 // Stores the data for a sequence of CFunction overloads into a single
1236 // FixedArray, as [address_0, signature_0, ... address_n-1, signature_n-1].
1237 i::DirectHandle<i::FixedArray> function_overloads =
1238 i_isolate->factory()->NewFixedArray(static_cast<int>(
1239 c_function_overloads.size() *
1240 i::FunctionTemplateInfo::kFunctionOverloadEntrySize));
1241 int function_count = static_cast<int>(c_function_overloads.size());
1242 for (int i = 0; i < function_count; i++) {
1243 const CFunction& c_function = c_function_overloads.data()[i];
1245 i_isolate, c_function.GetAddress());
1246 function_overloads->set(
1247 i::FunctionTemplateInfo::kFunctionOverloadEntrySize * i, *address);
1248 i::DirectHandle<i::Object> signature =
1250 c_function.GetTypeInfo());
1251 function_overloads->set(
1252 i::FunctionTemplateInfo::kFunctionOverloadEntrySize * i + 1,
1253 *signature);
1254 }
1255 i::FunctionTemplateInfo::SetCFunctionOverloads(i_isolate, info,
1256 function_overloads);
1257 }
1258}
1259
1260namespace {
1261
1262template <typename Getter, typename Setter>
1263i::DirectHandle<i::AccessorInfo> MakeAccessorInfo(i::Isolate* i_isolate,
1264 v8::Local<Name> name,
1265 Getter getter, Setter setter,
1266 v8::Local<Value> data,
1267 bool replace_on_access) {
1269 i_isolate->factory()->NewAccessorInfo();
1270 obj->set_getter(i_isolate, reinterpret_cast<i::Address>(getter));
1271 DCHECK_IMPLIES(replace_on_access, setter == nullptr);
1272 if (setter == nullptr) {
1273 setter = reinterpret_cast<Setter>(&i::Accessors::ReconfigureToDataProperty);
1274 }
1275 obj->set_setter(i_isolate, reinterpret_cast<i::Address>(setter));
1276
1277 auto accessor_name = Utils::OpenDirectHandle(*name);
1278 if (!IsUniqueName(*accessor_name)) {
1279 accessor_name = i_isolate->factory()->InternalizeString(
1280 i::Cast<i::String>(accessor_name));
1281 }
1283 i::Tagged<i::AccessorInfo> raw_obj = *obj;
1284 if (data.IsEmpty()) {
1285 raw_obj->set_data(i::ReadOnlyRoots(i_isolate).undefined_value());
1286 } else {
1287 raw_obj->set_data(*Utils::OpenDirectHandle(*data));
1288 }
1289 raw_obj->set_name(*accessor_name);
1290 raw_obj->set_replace_on_access(replace_on_access);
1291 raw_obj->set_initial_property_attributes(i::NONE);
1292 return obj;
1293}
1294
1295} // namespace
1296
1298 auto constructor = Utils::OpenDirectHandle(this, true);
1299 if (!Utils::ApiCheck(!constructor.is_null(),
1300 "v8::FunctionTemplate::InstanceTemplate()",
1301 "Reading from empty handle")) {
1302 return Local<ObjectTemplate>();
1303 }
1304 i::Isolate* i_isolate = constructor->GetIsolateChecked();
1306 auto maybe_templ = constructor->GetInstanceTemplate();
1307 if (!i::IsUndefined(maybe_templ, i_isolate)) {
1308 return Utils::ToLocal(i::direct_handle(
1309 i::Cast<i::ObjectTemplateInfo>(maybe_templ), i_isolate));
1310 }
1311 constexpr bool do_not_cache = false;
1313 i_isolate->factory()->NewObjectTemplateInfo(constructor, do_not_cache);
1314 i::FunctionTemplateInfo::SetInstanceTemplate(i_isolate, constructor, templ);
1315 return Utils::ToLocal(templ);
1316}
1317
1319 auto info = Utils::OpenDirectHandle(this);
1320 EnsureNotPublished(info, "v8::FunctionTemplate::SetLength");
1321 i::Isolate* i_isolate = info->GetIsolateChecked();
1323 info->set_length(length);
1324}
1325
1327 auto info = Utils::OpenDirectHandle(this);
1328 EnsureNotPublished(info, "v8::FunctionTemplate::SetClassName");
1329 i::Isolate* i_isolate = info->GetIsolateChecked();
1331 info->set_class_name(*Utils::OpenDirectHandle(*name));
1332}
1333
1335 auto info = Utils::OpenDirectHandle(this);
1336 EnsureNotPublished(info, "v8::FunctionTemplate::SetInterfaceName");
1337 i::Isolate* i_isolate = info->GetIsolateChecked();
1339 info->set_interface_name(*Utils::OpenDirectHandle(*name));
1340}
1341
1343 auto info = Utils::OpenDirectHandle(this);
1344 EnsureNotPublished(info, "v8::FunctionTemplate::SetExceptionContext");
1345 i::Isolate* i_isolate = info->GetIsolateChecked();
1347 info->set_exception_context(static_cast<uint32_t>(context));
1348}
1349
1351 auto info = Utils::OpenDirectHandle(this);
1352 EnsureNotPublished(info, "v8::FunctionTemplate::SetAcceptAnyReceiver");
1353 i::Isolate* i_isolate = info->GetIsolateChecked();
1355 info->set_accept_any_receiver(value);
1356}
1357
1359 auto info = Utils::OpenDirectHandle(this);
1360 EnsureNotPublished(info, "v8::FunctionTemplate::ReadOnlyPrototype");
1361 i::Isolate* i_isolate = info->GetIsolateChecked();
1363 info->set_read_only_prototype(true);
1364}
1365
1367 auto info = Utils::OpenDirectHandle(this);
1368 EnsureNotPublished(info, "v8::FunctionTemplate::RemovePrototype");
1369 i::Isolate* i_isolate = info->GetIsolateChecked();
1371 info->set_remove_prototype(true);
1372}
1373
1374// --- O b j e c t T e m p l a t e ---
1375
1377 Isolate* v8_isolate, v8::Local<FunctionTemplate> constructor) {
1378 auto i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1379 API_RCS_SCOPE(i_isolate, ObjectTemplate, New);
1381 constexpr bool do_not_cache = false;
1383 i_isolate->factory()->NewObjectTemplateInfo(
1384 Utils::OpenDirectHandle(*constructor, true), do_not_cache);
1385 return Utils::ToLocal(obj);
1386}
1387
1388namespace {
1389// Ensure that the object template has a constructor. If no
1390// constructor is available we create one.
1392 i::Isolate* i_isolate, ObjectTemplate* object_template) {
1394 Utils::OpenDirectHandle(object_template)->constructor();
1395 if (!IsUndefined(obj, i_isolate)) {
1398 return i::DirectHandle<i::FunctionTemplateInfo>(info, i_isolate);
1399 }
1400 Local<FunctionTemplate> templ =
1401 FunctionTemplate::New(reinterpret_cast<Isolate*>(i_isolate));
1402 auto constructor = Utils::OpenDirectHandle(*templ);
1403 i::FunctionTemplateInfo::SetInstanceTemplate(
1404 i_isolate, constructor, Utils::OpenDirectHandle(object_template));
1405 Utils::OpenDirectHandle(object_template)->set_constructor(*constructor);
1406 return constructor;
1407}
1408
1409template <typename Getter, typename Setter, typename Data, typename Template>
1410void TemplateSetAccessor(Template* template_obj, v8::Local<Name> name,
1411 Getter getter, Setter setter, Data data,
1412 PropertyAttribute attribute, bool replace_on_access,
1413 SideEffectType getter_side_effect_type,
1414 SideEffectType setter_side_effect_type) {
1415 auto info = Utils::OpenDirectHandle(template_obj);
1416 auto i_isolate = info->GetIsolateChecked();
1418 i::HandleScope scope(i_isolate);
1419 i::DirectHandle<i::AccessorInfo> accessor_info = MakeAccessorInfo(
1420 i_isolate, name, getter, setter, data, replace_on_access);
1421 {
1423 i::Tagged<i::AccessorInfo> raw = *accessor_info;
1424 raw->set_initial_property_attributes(
1425 static_cast<i::PropertyAttributes>(attribute));
1426 raw->set_getter_side_effect_type(getter_side_effect_type);
1427 raw->set_setter_side_effect_type(setter_side_effect_type);
1428 }
1429 i::ApiNatives::AddNativeDataProperty(i_isolate, info, accessor_info);
1430}
1431} // namespace
1432
1436 v8::Local<Value> data,
1437 PropertyAttribute attribute,
1438 SideEffectType getter_side_effect_type,
1439 SideEffectType setter_side_effect_type) {
1440 TemplateSetAccessor(this, name, getter, setter, data, attribute, false,
1441 getter_side_effect_type, setter_side_effect_type);
1442}
1443
1446 v8::Local<Value> data,
1447 PropertyAttribute attribute,
1448 SideEffectType getter_side_effect_type,
1449 SideEffectType setter_side_effect_type) {
1450 TemplateSetAccessor(
1451 this, name, getter, static_cast<AccessorNameSetterCallback>(nullptr),
1452 data, attribute, true, getter_side_effect_type, setter_side_effect_type);
1453}
1454
1456 PropertyAttribute attribute) {
1457 auto templ = Utils::OpenDirectHandle(this);
1458 i::Isolate* i_isolate = templ->GetIsolateChecked();
1460 i::HandleScope scope(i_isolate);
1461 i::ApiNatives::AddDataProperty(i_isolate, templ,
1462 Utils::OpenDirectHandle(*name), intrinsic,
1463 static_cast<i::PropertyAttributes>(attribute));
1464}
1465
1466namespace {
1467enum class PropertyType { kNamed, kIndexed };
1468template <PropertyType property_type, typename Getter, typename Setter,
1469 typename Query, typename Descriptor, typename Deleter,
1470 typename Enumerator, typename Definer>
1471i::DirectHandle<i::InterceptorInfo> CreateInterceptorInfo(
1472 i::Isolate* i_isolate, Getter getter, Setter setter, Query query,
1473 Descriptor descriptor, Deleter deleter, Enumerator enumerator,
1474 Definer definer, Local<Value> data,
1475 base::Flags<PropertyHandlerFlags> flags) {
1476 // TODO(saelo): instead of an in-sandbox struct with a lot of external
1477 // pointers (with different tags), consider creating an object in trusted
1478 // space instead. That way, only a single reference going out of the sandbox
1479 // would be required.
1480 auto obj = i_isolate->factory()->NewInterceptorInfo();
1481 obj->set_is_named(property_type == PropertyType::kNamed);
1482
1483#define SET_CALLBACK_FIELD(Name, name) \
1484 if (name != nullptr) { \
1485 if constexpr (property_type == PropertyType::kNamed) { \
1486 obj->set_named_##name(i_isolate, reinterpret_cast<i::Address>(name)); \
1487 } else { \
1488 obj->set_indexed_##name(i_isolate, reinterpret_cast<i::Address>(name)); \
1489 } \
1490 }
1492#undef SET_CALLBACK_FIELD
1493
1494 obj->set_can_intercept_symbols(
1496 obj->set_non_masking(flags & PropertyHandlerFlags::kNonMasking);
1497 obj->set_has_no_side_effect(flags & PropertyHandlerFlags::kHasNoSideEffect);
1498
1499 if (data.IsEmpty()) {
1500 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
1501 }
1502 obj->set_data(*Utils::OpenDirectHandle(*data));
1503 return obj;
1504}
1505
1506template <typename Getter, typename Setter, typename Query, typename Descriptor,
1507 typename Deleter, typename Enumerator, typename Definer>
1508i::DirectHandle<i::InterceptorInfo> CreateNamedInterceptorInfo(
1509 i::Isolate* i_isolate, Getter getter, Setter setter, Query query,
1510 Descriptor descriptor, Deleter remover, Enumerator enumerator,
1511 Definer definer, Local<Value> data,
1512 base::Flags<PropertyHandlerFlags> flags) {
1513 auto interceptor = CreateInterceptorInfo<PropertyType::kNamed>(
1514 i_isolate, getter, setter, query, descriptor, remover, enumerator,
1515 definer, data, flags);
1516 return interceptor;
1517}
1518
1519template <typename Getter, typename Setter, typename Query, typename Descriptor,
1520 typename Deleter, typename Enumerator, typename Definer>
1521i::DirectHandle<i::InterceptorInfo> CreateIndexedInterceptorInfo(
1522 i::Isolate* i_isolate, Getter getter, Setter setter, Query query,
1523 Descriptor descriptor, Deleter remover, Enumerator enumerator,
1524 Definer definer, Local<Value> data,
1525 base::Flags<PropertyHandlerFlags> flags) {
1526 auto interceptor = CreateInterceptorInfo<PropertyType::kIndexed>(
1527 i_isolate, getter, setter, query, descriptor, remover, enumerator,
1528 definer, data, flags);
1529 return interceptor;
1530}
1531
1532template <typename Getter, typename Setter, typename Query, typename Descriptor,
1533 typename Deleter, typename Enumerator, typename Definer>
1534void ObjectTemplateSetNamedPropertyHandler(
1535 ObjectTemplate* templ, Getter getter, Setter setter, Query query,
1536 Descriptor descriptor, Deleter remover, Enumerator enumerator,
1537 Definer definer, Local<Value> data, PropertyHandlerFlags flags) {
1538 i::Isolate* i_isolate = Utils::OpenDirectHandle(templ)->GetIsolate();
1540 i::HandleScope scope(i_isolate);
1541 auto cons = EnsureConstructor(i_isolate, templ);
1542 EnsureNotPublished(cons, "ObjectTemplateSetNamedPropertyHandler");
1543 auto obj =
1544 CreateNamedInterceptorInfo(i_isolate, getter, setter, query, descriptor,
1545 remover, enumerator, definer, data, flags);
1546 i::FunctionTemplateInfo::SetNamedPropertyHandler(i_isolate, cons, obj);
1547}
1548} // namespace
1549
1551 const NamedPropertyHandlerConfiguration& config) {
1552 ObjectTemplateSetNamedPropertyHandler(
1553 this, config.getter, config.setter, config.query, config.descriptor,
1554 config.deleter, config.enumerator, config.definer, config.data,
1555 config.flags);
1556}
1557
1559 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
1561 i::HandleScope scope(i_isolate);
1562 auto cons = EnsureConstructor(i_isolate, this);
1563 EnsureNotPublished(cons, "v8::ObjectTemplate::MarkAsUndetectable");
1564 cons->set_undetectable(true);
1565}
1566
1568 Local<Value> data) {
1569 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
1571 i::HandleScope scope(i_isolate);
1572 auto cons = EnsureConstructor(i_isolate, this);
1573 EnsureNotPublished(cons, "v8::ObjectTemplate::SetAccessCheckCallback");
1574
1575 i::DirectHandle<i::Struct> struct_info = i_isolate->factory()->NewStruct(
1576 i::ACCESS_CHECK_INFO_TYPE, i::AllocationType::kOld);
1577 auto info = i::Cast<i::AccessCheckInfo>(struct_info);
1578
1579 SET_FIELD_WRAPPED(i_isolate, info, set_callback, callback,
1581 info->set_named_interceptor(i::Smi::zero());
1582 info->set_indexed_interceptor(i::Smi::zero());
1583
1584 if (data.IsEmpty()) {
1585 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
1586 }
1587 info->set_data(*Utils::OpenDirectHandle(*data));
1588
1589 i::FunctionTemplateInfo::SetAccessCheckInfo(i_isolate, cons, info);
1590 cons->set_needs_access_check(true);
1591}
1592
1595 const NamedPropertyHandlerConfiguration& named_handler,
1596 const IndexedPropertyHandlerConfiguration& indexed_handler,
1597 Local<Value> data) {
1598 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
1600 i::HandleScope scope(i_isolate);
1601 auto cons = EnsureConstructor(i_isolate, this);
1602 EnsureNotPublished(cons,
1603 "v8::ObjectTemplate::SetAccessCheckCallbackWithHandler");
1604
1605 i::DirectHandle<i::Struct> struct_info = i_isolate->factory()->NewStruct(
1606 i::ACCESS_CHECK_INFO_TYPE, i::AllocationType::kOld);
1607 auto info = i::Cast<i::AccessCheckInfo>(struct_info);
1608
1609 SET_FIELD_WRAPPED(i_isolate, info, set_callback, callback,
1611 auto named_interceptor = CreateNamedInterceptorInfo(
1612 i_isolate, named_handler.getter, named_handler.setter,
1613 named_handler.query, named_handler.descriptor, named_handler.deleter,
1614 named_handler.enumerator, named_handler.definer, named_handler.data,
1615 named_handler.flags);
1616 info->set_named_interceptor(*named_interceptor);
1617 auto indexed_interceptor = CreateIndexedInterceptorInfo(
1618 i_isolate, indexed_handler.getter, indexed_handler.setter,
1619 indexed_handler.query, indexed_handler.descriptor,
1620 indexed_handler.deleter, indexed_handler.enumerator,
1621 indexed_handler.definer, indexed_handler.data, indexed_handler.flags);
1622 info->set_indexed_interceptor(*indexed_interceptor);
1623
1624 if (data.IsEmpty()) {
1625 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
1626 }
1627 info->set_data(*Utils::OpenDirectHandle(*data));
1628
1629 i::FunctionTemplateInfo::SetAccessCheckInfo(i_isolate, cons, info);
1630 cons->set_needs_access_check(true);
1631}
1632
1635 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
1637 i::HandleScope scope(i_isolate);
1638 auto cons = EnsureConstructor(i_isolate, this);
1639 EnsureNotPublished(cons, "v8::ObjectTemplate::SetHandler");
1640 auto obj = CreateIndexedInterceptorInfo(
1641 i_isolate, config.getter, config.setter, config.query, config.descriptor,
1642 config.deleter, config.enumerator, config.definer, config.data,
1643 config.flags);
1644 i::FunctionTemplateInfo::SetIndexedPropertyHandler(i_isolate, cons, obj);
1645}
1646
1648 Local<Value> data) {
1649 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
1651 i::HandleScope scope(i_isolate);
1652 auto cons = EnsureConstructor(i_isolate, this);
1653 EnsureNotPublished(cons, "v8::ObjectTemplate::SetCallAsFunctionHandler");
1655
1656 // This template is just a container for callback and data values and thus
1657 // it's not supposed to be instantiated. Don't cache it.
1658 constexpr bool do_not_cache = true;
1659 constexpr int length = 0;
1661 i_isolate->factory()->NewFunctionTemplateInfo(length, do_not_cache);
1662 templ->set_is_object_template_call_handler(true);
1663 Utils::ToLocal(templ)->SetCallHandler(callback, data);
1664 i::FunctionTemplateInfo::SetInstanceCallHandler(i_isolate, cons, templ);
1665}
1666
1668 return Utils::OpenDirectHandle(this)->embedder_field_count();
1669}
1670
1672 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
1673 if (!Utils::ApiCheck(i::Smi::IsValid(value),
1674 "v8::ObjectTemplate::SetInternalFieldCount()",
1675 "Invalid embedder field count")) {
1676 return;
1677 }
1679 if (value > 0) {
1680 // The embedder field count is set by the constructor function's
1681 // construct code, so we ensure that there is a constructor
1682 // function to do the setting.
1683 EnsureConstructor(i_isolate, this);
1684 }
1685 Utils::OpenDirectHandle(this)->set_embedder_field_count(value);
1686}
1687
1689 return Utils::OpenDirectHandle(this)->immutable_proto();
1690}
1691
1693 auto self = Utils::OpenDirectHandle(this);
1694 i::Isolate* i_isolate = self->GetIsolate();
1696 self->set_immutable_proto(true);
1697}
1698
1700 return Utils::OpenDirectHandle(this)->code_like();
1701}
1702
1704 auto self = Utils::OpenDirectHandle(this);
1705 i::Isolate* i_isolate = self->GetIsolate();
1707 self->set_code_like(true);
1708}
1709
1712 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1715 return Utils::ToLocal(i::DictionaryTemplateInfo::Create(i_isolate, names));
1716}
1717
1719 Local<Context> context, MemorySpan<MaybeLocal<Value>> property_values) {
1720 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
1721 API_RCS_SCOPE(i_isolate, DictionaryTemplate, NewInstance);
1723 auto self = Utils::OpenDirectHandle(this);
1724 return ToApiHandle<Object>(i::DictionaryTemplateInfo::NewInstance(
1725 Utils::OpenDirectHandle(*context), self, property_values));
1726}
1727
1728// --- S c r i p t s ---
1729
1730// Internally, UnboundScript and UnboundModuleScript are SharedFunctionInfos,
1731// and Script is a JSFunction.
1732
1734 BufferPolicy buffer_policy_)
1735 : data(data_),
1736 length(length_),
1737 rejected(false),
1738 buffer_policy(buffer_policy_) {}
1739
1741 if (buffer_policy == BufferOwned) {
1742 delete[] data;
1743 }
1744}
1745
1748 i::AlignedCachedData aligned(data, length);
1749 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
1752 i::SerializedCodeData::FromCachedDataWithoutSource(
1753 i_isolate->AsLocalIsolate(), &aligned, &result);
1755 result);
1756}
1757
1759 std::unique_ptr<ExternalSourceStream> stream, Encoding encoding)
1760 : impl_(new i::ScriptStreamingData(std::move(stream), encoding)) {}
1761
1763
1765 auto function_info = Utils::OpenDirectHandle(this);
1766 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is gone.
1767 DCHECK(!i::HeapLayout::InReadOnlySpace(*function_info));
1768 i::Isolate* i_isolate = i::GetIsolateFromWritableObject(*function_info);
1771 i::Factory::JSFunctionBuilder{i_isolate, function_info,
1772 i_isolate->native_context()}
1773 .Build();
1774 return ToApiHandle<Script>(function);
1775}
1776
1778 auto function_info = Utils::OpenDirectHandle(this);
1779 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is gone.
1780 DCHECK(!i::HeapLayout::InReadOnlySpace(*function_info));
1782 GetId);
1783 return i::Cast<i::Script>(function_info->script())->id();
1784}
1785
1787 auto obj = Utils::OpenDirectHandle(this);
1788 if (i::IsScript(obj->script())) {
1789 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1790 // gone.
1791 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1794 API_RCS_SCOPE(i_isolate, UnboundScript, GetLineNumber);
1795 i::DirectHandle<i::Script> script(i::Cast<i::Script>(obj->script()),
1796 i_isolate);
1797 return i::Script::GetLineNumber(script, code_pos);
1798 } else {
1799 return -1;
1800 }
1801}
1802
1804 auto obj = Utils::OpenDirectHandle(this);
1805 if (i::IsScript(obj->script())) {
1806 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1807 // gone.
1808 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1811 API_RCS_SCOPE(i_isolate, UnboundScript, GetColumnNumber);
1812 i::DirectHandle<i::Script> script(i::Cast<i::Script>(obj->script()),
1813 i_isolate);
1814 return i::Script::GetColumnNumber(script, code_pos);
1815 } else {
1816 return -1;
1817 }
1818}
1819
1821 auto obj = Utils::OpenDirectHandle(this);
1822 if (i::IsScript(obj->script())) {
1823 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1824 // gone.
1825 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1828 API_RCS_SCOPE(i_isolate, UnboundScript, GetName);
1829 i::Tagged<i::Object> name = i::Cast<i::Script>(obj->script())->name();
1830 return Utils::ToLocal(i::direct_handle(name, i_isolate));
1831 } else {
1832 return Local<String>();
1833 }
1834}
1835
1837 auto obj = Utils::OpenDirectHandle(this);
1838 if (i::IsScript(obj->script())) {
1839 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1840 // gone.
1841 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1843 API_RCS_SCOPE(i_isolate, UnboundScript, GetSourceURL);
1845 i::Tagged<i::Object> url = i::Cast<i::Script>(obj->script())->source_url();
1846 return Utils::ToLocal(i::direct_handle(url, i_isolate));
1847 } else {
1848 return Local<String>();
1849 }
1850}
1851
1853 auto obj = Utils::OpenDirectHandle(this);
1854 if (i::IsScript(obj->script())) {
1855 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1856 // gone.
1857 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1859 API_RCS_SCOPE(i_isolate, UnboundScript, GetSourceMappingURL);
1862 i::Cast<i::Script>(obj->script())->source_mapping_url();
1863 return Utils::ToLocal(i::direct_handle(url, i_isolate));
1864 } else {
1865 return Local<String>();
1866 }
1867}
1868
1870 auto obj = Utils::OpenDirectHandle(this);
1871 if (i::IsScript(obj->script())) {
1872 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1873 // gone.
1874 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1876 API_RCS_SCOPE(i_isolate, UnboundModuleScript, GetSourceURL);
1878 i::Tagged<i::Object> url = i::Cast<i::Script>(obj->script())->source_url();
1879 return Utils::ToLocal(i::direct_handle(url, i_isolate));
1880 } else {
1881 return Local<String>();
1882 }
1883}
1884
1886 auto obj = Utils::OpenDirectHandle(this);
1887 if (i::IsScript(obj->script())) {
1888 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is
1889 // gone.
1890 DCHECK(!i::HeapLayout::InReadOnlySpace(*obj));
1892 API_RCS_SCOPE(i_isolate, UnboundModuleScript, GetSourceMappingURL);
1895 i::Cast<i::Script>(obj->script())->source_mapping_url();
1896 return Utils::ToLocal(i::direct_handle(url, i_isolate));
1897 } else {
1898 return Local<String>();
1899 }
1900}
1901
1903 return Run(context, Local<Data>());
1904}
1905
1907 Local<Data> host_defined_options) {
1908 auto v8_isolate = context->GetIsolate();
1909 auto i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
1910 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.Execute");
1911 ENTER_V8(i_isolate, context, Script, Run, InternalEscapableScope);
1912 i::TimerEventScope<i::TimerEventExecute> timer_scope(i_isolate);
1913 i::NestedTimedHistogramScope execute_timer(i_isolate->counters()->execute(),
1914 i_isolate);
1915 i::AggregatingHistogramTimerScope histogram_timer(
1916 i_isolate->counters()->compile_lazy());
1917
1918#if defined(V8_ENABLE_ETW_STACK_WALKING)
1919 // In case ETW has been activated, tasks to log existing code are
1920 // created. But in case the task runner does not run those before
1921 // starting to execute code (as it happens in d8, that will run
1922 // first the code from prompt), then that code will not have
1923 // JIT instrumentation on time.
1924 //
1925 // To avoid this, on running scripts check first if JIT code log is
1926 // pending and generate immediately.
1927 if (i::v8_flags.enable_etw_stack_walking ||
1928 i::v8_flags.enable_etw_by_custom_filter_only) {
1929 i::ETWJITInterface::MaybeSetHandlerNow(i_isolate);
1930 }
1931#endif // V8_ENABLE_ETW_STACK_WALKING
1934 // TODO(cbruni, chromium:1244145): Remove once migrated to the context.
1936 i::Cast<i::Script>(fun->shared()->script())->host_defined_options(),
1937 i_isolate);
1939 has_exception = !ToLocal<Value>(
1940 i::Execution::CallScript(i_isolate, fun, receiver, options), &result);
1941
1944}
1945
1947 auto obj = Utils::OpenDirectHandle(this);
1950 return ToApiHandle<Value>(i::direct_handle(obj->resource_name(), i_isolate));
1951}
1952
1954 auto obj = Utils::OpenDirectHandle(this);
1957 return ToApiHandle<Data>(
1958 i::direct_handle(obj->host_defined_options(), i_isolate));
1959}
1960
1963 auto obj = Utils::OpenDirectHandle(this);
1964 i::DirectHandle<i::SharedFunctionInfo> sfi(obj->shared(), obj->GetIsolate());
1965 DCHECK(!i::HeapLayout::InReadOnlySpace(*sfi));
1966 return ToApiHandle<UnboundScript>(sfi);
1967}
1968
1971 auto func = Utils::OpenDirectHandle(this);
1972 i::Tagged<i::SharedFunctionInfo> sfi = func->shared();
1973 CHECK(IsScript(sfi->script()));
1974 i::Isolate* i_isolate = func->GetIsolate();
1975 return ToApiHandle<Value>(
1976 i::direct_handle(i::Cast<i::Script>(sfi->script())->name(), i_isolate));
1977}
1978
1979std::vector<int> Script::GetProducedCompileHints() const {
1981 auto func = Utils::OpenDirectHandle(this);
1982 i::Isolate* i_isolate = func->GetIsolate();
1983 i::Tagged<i::SharedFunctionInfo> sfi = func->shared();
1984 CHECK(IsScript(sfi->script()));
1985 i::Tagged<i::Script> script = i::Cast<i::Script>(sfi->script());
1986 i::Tagged<i::Object> maybe_array_list =
1987 script->compiled_lazy_function_positions();
1988 std::vector<int> result;
1989 if (!IsUndefined(maybe_array_list, i_isolate)) {
1990 i::Tagged<i::ArrayList> array_list =
1991 i::Cast<i::ArrayList>(maybe_array_list);
1992 result.reserve(array_list->length());
1993 for (int i = 0; i < array_list->length(); ++i) {
1994 i::Tagged<i::Object> item = array_list->get(i);
1995 CHECK(IsSmi(item));
1996 result.push_back(i::Smi::ToInt(item));
1997 }
1998 }
1999 return result;
2000}
2001
2004 auto func = Utils::OpenDirectHandle(this);
2005 i::Isolate* i_isolate = func->GetIsolate();
2006 i::Tagged<i::SharedFunctionInfo> sfi = func->shared();
2007 CHECK(IsScript(sfi->script()));
2008 i::DirectHandle<i::Script> script(i::Cast<i::Script>(sfi->script()),
2009 i_isolate);
2011}
2012
2014 Isolate* v8_isolate) const {
2016 auto script = Utils::OpenDirectHandle(this);
2017 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2018 i::Tagged<i::Object> maybe_array_list =
2019 script->compiled_lazy_function_positions();
2020 std::vector<int> result;
2021 if (!IsUndefined(maybe_array_list, i_isolate)) {
2022 i::Tagged<i::ArrayList> array_list =
2023 i::Cast<i::ArrayList>(maybe_array_list);
2024 result.reserve(array_list->length());
2025 for (int i = 0; i < array_list->length(); ++i) {
2026 i::Tagged<i::Object> item = array_list->get(i);
2027 CHECK(IsSmi(item));
2028 result.push_back(i::Smi::ToInt(item));
2029 }
2030 }
2031 return result;
2032}
2033
2034// static
2036 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2038 Utils::ApiCheck(length >= 0, "v8::PrimitiveArray::New",
2039 "length must be equal or greater than zero");
2041 i_isolate->factory()->NewFixedArray(length);
2042 return ToApiHandle<PrimitiveArray>(array);
2043}
2044
2046 return Utils::OpenDirectHandle(this)->length();
2047}
2048
2049void PrimitiveArray::Set(Isolate* v8_isolate, int index,
2050 Local<Primitive> item) {
2051 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2052 auto array = Utils::OpenDirectHandle(this);
2054 Utils::ApiCheck(index >= 0 && index < array->length(),
2055 "v8::PrimitiveArray::Set",
2056 "index must be greater than or equal to 0 and less than the "
2057 "array length");
2058 array->set(index, *Utils::OpenDirectHandle(*item));
2059}
2060
2062 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2063 auto array = Utils::OpenDirectHandle(this);
2065 Utils::ApiCheck(index >= 0 && index < array->length(),
2066 "v8::PrimitiveArray::Get",
2067 "index must be greater than or equal to 0 and less than the "
2068 "array length");
2069 return ToApiHandle<Primitive>(i::direct_handle(array->get(index), i_isolate));
2070}
2071
2073 auto obj = Utils::OpenDirectHandle(that);
2075 i::IsFixedArray(*obj), "v8::PrimitiveArray::Cast",
2076 "Value is not a PrimitiveArray; this is a temporary issue, v8::Data and "
2077 "v8::PrimitiveArray will not be compatible in the future");
2078}
2079
2081 return Utils::OpenDirectHandle(this)->length();
2082}
2083
2085 auto self = Utils::OpenDirectHandle(this);
2086 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2087 CHECK_LT(i, self->length());
2088 return ToApiHandle<Data>(i::direct_handle(self->get(i), i_isolate));
2089}
2090
2092 auto self = Utils::OpenDirectHandle(this);
2093 i::Isolate* i_isolate = self->GetIsolate();
2094 return ToApiHandle<String>(i::direct_handle(self->specifier(), i_isolate));
2095}
2096
2098 auto self = Utils::OpenDirectHandle(this);
2099 return self->phase();
2100}
2101
2103 return Utils::OpenDirectHandle(this)->position();
2104}
2105
2107 auto self = Utils::OpenDirectHandle(this);
2108 i::Isolate* i_isolate = self->GetIsolate();
2110 i::direct_handle(self->import_attributes(), i_isolate));
2111}
2112
2114 auto self = Utils::OpenDirectHandle(this);
2115 switch (self->status()) {
2116 case i::Module::kUnlinked:
2117 case i::Module::kPreLinking:
2118 return kUninstantiated;
2119 case i::Module::kLinking:
2120 return kInstantiating;
2121 case i::Module::kLinked:
2122 return kInstantiated;
2123 case i::Module::kEvaluating:
2124 return kEvaluating;
2125 case i::Module::kEvaluatingAsync:
2126 // TODO(syg): Expose kEvaluatingAsync in API as well.
2127 case i::Module::kEvaluated:
2128 return kEvaluated;
2129 case i::Module::kErrored:
2130 return kErrored;
2131 }
2132 UNREACHABLE();
2133}
2134
2136 Utils::ApiCheck(GetStatus() == kErrored, "v8::Module::GetException",
2137 "Module status must be kErrored");
2138 auto self = Utils::OpenDirectHandle(this);
2139 i::Isolate* i_isolate = self->GetIsolate();
2141 return ToApiHandle<Value>(i::direct_handle(self->GetException(), i_isolate));
2142}
2143
2145 auto self = Utils::OpenDirectHandle(this);
2146 i::Isolate* i_isolate = self->GetIsolate();
2148 if (i::IsSyntheticModule(*self)) {
2149 // Synthetic modules are leaf nodes in the module graph. They have no
2150 // ModuleRequests.
2151 return ToApiHandle<FixedArray>(i_isolate->factory()->empty_fixed_array());
2152 } else {
2154 i::Cast<i::SourceTextModule>(self)->info()->module_requests(),
2155 i_isolate));
2156 }
2157}
2158
2160 auto self = Utils::OpenDirectHandle(this);
2161 i::Isolate* i_isolate = self->GetIsolate();
2163 i::HandleScope scope(i_isolate);
2165 i::IsSourceTextModule(*self), "v8::Module::SourceOffsetToLocation",
2166 "v8::Module::SourceOffsetToLocation must be used on an SourceTextModule");
2168 i::Cast<i::SourceTextModule>(self)->GetScript(), i_isolate);
2169 i::Script::PositionInfo info;
2170 i::Script::GetPositionInfo(script, offset, &info);
2171 return v8::Location(info.line, info.column);
2172}
2173
2176 GetStatus() >= kInstantiated, "v8::Module::GetModuleNamespace",
2177 "v8::Module::GetModuleNamespace must be used on an instantiated module");
2178 auto self = Utils::OpenHandle(this);
2179 auto i_isolate = self->GetIsolate();
2181 i::DirectHandle<i::JSModuleNamespace> module_namespace =
2182 i::Module::GetModuleNamespace(i_isolate, self);
2183 return ToApiHandle<Value>(module_namespace);
2184}
2185
2187 auto self = Utils::OpenDirectHandle(this);
2189 i::IsSourceTextModule(*self), "v8::Module::GetUnboundModuleScript",
2190 "v8::Module::GetUnboundModuleScript must be used on an SourceTextModule");
2191 auto i_isolate = self->GetIsolate();
2194 i::Cast<i::SourceTextModule>(self)->GetSharedFunctionInfo(), i_isolate));
2195}
2196
2197int Module::ScriptId() const {
2199 Utils::ApiCheck(i::IsSourceTextModule(self), "v8::Module::ScriptId",
2200 "v8::Module::ScriptId must be used on an SourceTextModule");
2201 DCHECK_NO_SCRIPT_NO_EXCEPTION(self->GetIsolate());
2202 return i::Cast<i::SourceTextModule>(self)->GetScript()->id();
2203}
2204
2207 if (!i::IsSourceTextModule(self)) return false;
2208 return i::Cast<i::SourceTextModule>(self)->has_toplevel_await();
2209}
2210
2213 GetStatus() >= kInstantiated, "v8::Module::IsGraphAsync",
2214 "v8::Module::IsGraphAsync must be used on an instantiated module");
2216 auto i_isolate = self->GetIsolate();
2218 return self->IsGraphAsync(i_isolate);
2219}
2220
2222 auto self = Utils::OpenDirectHandle(this);
2223 DCHECK_NO_SCRIPT_NO_EXCEPTION(self->GetIsolate());
2224 return i::IsSourceTextModule(*self);
2225}
2226
2228 auto self = Utils::OpenDirectHandle(this);
2229 DCHECK_NO_SCRIPT_NO_EXCEPTION(self->GetIsolate());
2230 return i::IsSyntheticModule(*self);
2231}
2232
2234 auto self = Utils::OpenDirectHandle(this);
2235 DCHECK_NO_SCRIPT_NO_EXCEPTION(self->GetIsolate());
2236 return self->hash();
2237}
2238
2240 ResolveModuleCallback module_callback,
2241 ResolveSourceCallback source_callback) {
2242 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2243 ENTER_V8(i_isolate, context, Module, InstantiateModule, i::HandleScope);
2244 has_exception =
2245 !i::Module::Instantiate(i_isolate, Utils::OpenHandle(this), context,
2246 module_callback, source_callback);
2248 return Just(true);
2249}
2250
2252 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
2253 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.Execute");
2254 ENTER_V8(i_isolate, context, Module, Evaluate, InternalEscapableScope);
2255 i::TimerEventScope<i::TimerEventExecute> timer_scope(i_isolate);
2256 i::NestedTimedHistogramScope execute_timer(i_isolate->counters()->execute(),
2257 i_isolate);
2259 i_isolate->counters()->compile_lazy());
2260
2261 auto self = Utils::OpenHandle(this);
2262 Utils::ApiCheck(self->status() >= i::Module::kLinked, "Module::Evaluate",
2263 "Expected instantiated module");
2264
2266 has_exception = !ToLocal(i::Module::Evaluate(i_isolate, self), &result);
2269}
2270
2272 Isolate* v8_isolate, Local<String> module_name,
2273 const MemorySpan<const Local<String>>& export_names,
2275 auto i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2277 auto i_module_name = Utils::OpenDirectHandle(*module_name);
2278 i::DirectHandle<i::FixedArray> i_export_names =
2279 i_isolate->factory()->NewFixedArray(
2280 static_cast<int>(export_names.size()));
2281 for (int i = 0; i < i_export_names->length(); ++i) {
2283 Utils::OpenDirectHandle(*export_names[i]));
2284 i_export_names->set(i, *str);
2285 }
2286 return v8::Utils::ToLocal(
2288 i_module_name, i_export_names, evaluation_steps)));
2289}
2290
2292 Local<String> export_name,
2293 Local<v8::Value> export_value) {
2294 auto i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2295 auto i_export_name = Utils::OpenDirectHandle(*export_name);
2296 auto i_export_value = Utils::OpenDirectHandle(*export_value);
2297 auto self = Utils::OpenDirectHandle(this);
2298 Utils::ApiCheck(i::IsSyntheticModule(*self),
2299 "v8::Module::SyntheticModuleSetExport",
2300 "v8::Module::SyntheticModuleSetExport must only be called on "
2301 "a SyntheticModule");
2302 ENTER_V8_NO_SCRIPT(i_isolate, v8_isolate->GetCurrentContext(), Module,
2303 SetSyntheticModuleExport, i::HandleScope);
2304 has_exception = i::SyntheticModule::SetExport(
2305 i_isolate, i::Cast<i::SyntheticModule>(self),
2306 i_export_name, i_export_value)
2307 .IsNothing();
2309 return Just(true);
2310}
2311
2312std::pair<LocalVector<Module>, LocalVector<Message>>
2314 auto i_isolate = reinterpret_cast<i::Isolate*>(isolate);
2315 auto self = Utils::OpenDirectHandle(this);
2316 Utils::ApiCheck(i::IsSourceTextModule(*self),
2317 "v8::Module::GetStalledTopLevelAwaitMessages",
2318 "v8::Module::GetStalledTopLevelAwaitMessages must only be "
2319 "called on a SourceTextModule");
2320 std::pair<i::DirectHandleVector<i::SourceTextModule>,
2322 stalled_awaits =
2323 i::Cast<i::SourceTextModule>(self)->GetStalledTopLevelAwaitMessages(
2324 i_isolate);
2325
2326 LocalVector<Module> modules(isolate);
2327 if (size_t stalled_awaits_count = stalled_awaits.first.size();
2328 stalled_awaits_count > 0) {
2329 modules.reserve(stalled_awaits_count);
2330 for (auto module : stalled_awaits.first)
2331 modules.push_back(ToApiHandle<Module>(module));
2332 }
2333 LocalVector<Message> messages(isolate);
2334 if (size_t stalled_awaits_count = stalled_awaits.second.size();
2335 stalled_awaits_count > 0) {
2336 messages.reserve(stalled_awaits_count);
2337 for (auto message : stalled_awaits.second)
2338 messages.push_back(ToApiHandle<Message>(message));
2339 }
2340
2341 return {modules, messages};
2342}
2343
2344namespace {
2345
2346i::ScriptDetails GetScriptDetails(
2347 i::Isolate* i_isolate, Local<Value> resource_name, int resource_line_offset,
2348 int resource_column_offset, Local<Value> source_map_url,
2349 Local<Data> host_defined_options, ScriptOriginOptions origin_options) {
2350 i::ScriptDetails script_details(Utils::OpenHandle(*(resource_name), true),
2351 origin_options);
2352 script_details.line_offset = resource_line_offset;
2353 script_details.column_offset = resource_column_offset;
2354 script_details.host_defined_options =
2355 host_defined_options.IsEmpty()
2356 ? i_isolate->factory()->empty_fixed_array()
2357 : Utils::OpenHandle(*(host_defined_options));
2358 if (!source_map_url.IsEmpty()) {
2359 script_details.source_map_url = Utils::OpenHandle(*(source_map_url));
2360 }
2361 return script_details;
2362}
2363
2364} // namespace
2365
2367 Isolate* v8_isolate, Source* source, CompileOptions options,
2368 NoCacheReason no_cache_reason) {
2369 auto i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2370 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.ScriptCompiler");
2371 ENTER_V8_NO_SCRIPT(i_isolate, v8_isolate->GetCurrentContext(), ScriptCompiler,
2372 CompileUnbound, InternalEscapableScope);
2373
2374 auto str = Utils::OpenHandle(*(source->source_string));
2375
2377 TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileScript");
2378 i::ScriptDetails script_details = GetScriptDetails(
2379 i_isolate, source->resource_name, source->resource_line_offset,
2380 source->resource_column_offset, source->source_map_url,
2381 source->host_defined_options, source->resource_options);
2382
2384 if (options & kConsumeCodeCache) {
2385 if (source->consume_cache_task) {
2386 // Take ownership of the internal deserialization task and clear it off
2387 // the consume task on the source.
2388 DCHECK_NOT_NULL(source->consume_cache_task->impl_);
2389 std::unique_ptr<i::BackgroundDeserializeTask> deserialize_task =
2390 std::move(source->consume_cache_task->impl_);
2391 maybe_function_info =
2392 i::Compiler::GetSharedFunctionInfoForScriptWithDeserializeTask(
2393 i_isolate, str, script_details, deserialize_task.get(), options,
2394 no_cache_reason, i::NOT_NATIVES_CODE,
2395 &source->compilation_details);
2396 source->cached_data->rejected = deserialize_task->rejected();
2397 } else {
2398 DCHECK(source->cached_data);
2399 // AlignedCachedData takes care of pointer-aligning the data.
2400 auto cached_data = std::make_unique<i::AlignedCachedData>(
2401 source->cached_data->data, source->cached_data->length);
2402 maybe_function_info =
2403 i::Compiler::GetSharedFunctionInfoForScriptWithCachedData(
2404 i_isolate, str, script_details, cached_data.get(), options,
2405 no_cache_reason, i::NOT_NATIVES_CODE,
2406 &source->compilation_details);
2407 source->cached_data->rejected = cached_data->rejected();
2408 }
2409 } else if (options & kConsumeCompileHints) {
2410 maybe_function_info =
2411 i::Compiler::GetSharedFunctionInfoForScriptWithCompileHints(
2412 i_isolate, str, script_details, source->compile_hint_callback,
2413 source->compile_hint_callback_data, options, no_cache_reason,
2414 i::NOT_NATIVES_CODE, &source->compilation_details);
2415 } else {
2416 // Compile without any cache.
2417 maybe_function_info = i::Compiler::GetSharedFunctionInfoForScript(
2418 i_isolate, str, script_details, options, no_cache_reason,
2419 i::NOT_NATIVES_CODE, &source->compilation_details);
2420 }
2421
2422 has_exception = !maybe_function_info.ToHandle(&result);
2423 DCHECK_IMPLIES(!has_exception, !i::HeapLayout::InReadOnlySpace(*result));
2426}
2427
2429 Isolate* v8_isolate, Source* source, CompileOptions options,
2430 NoCacheReason no_cache_reason) {
2432 !source->GetResourceOptions().IsModule(),
2433 "v8::ScriptCompiler::CompileUnboundScript",
2434 "v8::ScriptCompiler::CompileModule must be used to compile modules");
2435 return CompileUnboundInternal(v8_isolate, source, options, no_cache_reason);
2436}
2437
2439 Source* source,
2440 CompileOptions options,
2441 NoCacheReason no_cache_reason) {
2443 !source->GetResourceOptions().IsModule(), "v8::ScriptCompiler::Compile",
2444 "v8::ScriptCompiler::CompileModule must be used to compile modules");
2445 auto i_isolate = context->GetIsolate();
2447 CompileUnboundInternal(i_isolate, source, options, no_cache_reason);
2449 if (!maybe.ToLocal(&result)) return MaybeLocal<Script>();
2450 v8::Context::Scope scope(context);
2451 return result->BindToCurrentContext();
2452}
2453
2455 Isolate* v8_isolate, Source* source, CompileOptions options,
2456 NoCacheReason no_cache_reason) {
2458 "v8::ScriptCompiler::CompileModule",
2459 "Invalid CompileOptions");
2460 Utils::ApiCheck(source->GetResourceOptions().IsModule(),
2461 "v8::ScriptCompiler::CompileModule",
2462 "Invalid ScriptOrigin: is_module must be true");
2464 CompileUnboundInternal(v8_isolate, source, options, no_cache_reason);
2465 Local<UnboundScript> unbound;
2466 if (!maybe.ToLocal(&unbound)) return MaybeLocal<Module>();
2467 auto shared = Utils::OpenDirectHandle(*unbound);
2468 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2469 return ToApiHandle<Module>(i_isolate->factory()->NewSourceTextModule(shared));
2470}
2471
2472// static
2474 Local<Context> v8_context, Source* source, size_t arguments_count,
2475 Local<String> arguments[], size_t context_extension_count,
2476 Local<Object> context_extensions[], CompileOptions options,
2477 NoCacheReason no_cache_reason) {
2479 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.ScriptCompiler");
2480
2482 options == CompileOptions::kEagerCompile ||
2484
2486
2487 DCHECK(IsNativeContext(*context));
2488
2489 i::Handle<i::FixedArray> arguments_list =
2490 i_isolate->factory()->NewFixedArray(static_cast<int>(arguments_count));
2491 for (int i = 0; i < static_cast<int>(arguments_count); i++) {
2492 auto argument = Utils::OpenDirectHandle(*arguments[i]);
2493 if (!i::String::IsIdentifier(i_isolate, argument)) return Local<Function>();
2494 arguments_list->set(i, *argument);
2495 }
2496
2497 for (size_t i = 0; i < context_extension_count; ++i) {
2499 Utils::OpenDirectHandle(*context_extensions[i]);
2500 if (!IsJSObject(*extension)) return Local<Function>();
2501 context = i_isolate->factory()->NewWithContext(
2502 context,
2503 i::ScopeInfo::CreateForWithScope(
2504 i_isolate,
2505 IsNativeContext(*context)
2507 : i::Handle<i::ScopeInfo>(context->scope_info(), i_isolate)),
2508 extension);
2509 }
2510
2511 i::ScriptDetails script_details = GetScriptDetails(
2512 i_isolate, source->resource_name, source->resource_line_offset,
2513 source->resource_column_offset, source->source_map_url,
2514 source->host_defined_options, source->resource_options);
2515 script_details.wrapped_arguments = arguments_list;
2516
2517 std::unique_ptr<i::AlignedCachedData> cached_data;
2518 if (options & kConsumeCodeCache) {
2519 DCHECK(source->cached_data);
2520 // ScriptData takes care of pointer-aligning the data.
2521 cached_data.reset(new i::AlignedCachedData(source->cached_data->data,
2522 source->cached_data->length));
2523 }
2524
2526 has_exception =
2527 !i::Compiler::GetWrappedFunction(
2528 Utils::OpenHandle(*source->source_string), context, script_details,
2529 cached_data.get(), options, no_cache_reason)
2530 .ToHandle(&result);
2531 if (options & kConsumeCodeCache) {
2532 source->cached_data->rejected = cached_data->rejected();
2533 }
2535 return handle_scope.Escape(Utils::CallableToLocal(result));
2536}
2537
2539
2541 Isolate* v8_isolate, StreamedSource* source, v8::ScriptType type,
2542 CompileOptions options, CompileHintCallback compile_hint_callback,
2543 void* compile_hint_callback_data) {
2545 "v8::ScriptCompiler::StartStreaming",
2546 "Invalid CompileOptions");
2547 if (!i::v8_flags.script_streaming) return nullptr;
2548 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2549 i::ScriptStreamingData* data = source->impl();
2550 std::unique_ptr<i::BackgroundCompileTask> task =
2551 std::make_unique<i::BackgroundCompileTask>(
2552 data, i_isolate, type, options, &source->compilation_details(),
2553 compile_hint_callback, compile_hint_callback_data);
2554 data->task = std::move(task);
2555 return new ScriptCompiler::ScriptStreamingTask(data);
2556}
2557
2559 std::unique_ptr<i::BackgroundDeserializeTask> impl)
2560 : impl_(std::move(impl)) {}
2561
2563
2565
2567 Isolate* v8_isolate, Local<String> source_text,
2568 const ScriptOrigin& origin) {
2569 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2571 auto str = Utils::OpenHandle(*source_text);
2572 i::ScriptDetails script_details =
2573 GetScriptDetails(i_isolate, origin.ResourceName(), origin.LineOffset(),
2574 origin.ColumnOffset(), origin.SourceMapUrl(),
2575 origin.GetHostDefinedOptions(), origin.Options());
2576 impl_->SourceTextAvailable(i_isolate, str, script_details);
2577}
2578
2580 const {
2581 if (!i::v8_flags
2582 .merge_background_deserialized_script_with_compilation_cache) {
2583 return false;
2584 }
2585 return impl_->ShouldMergeWithExistingScript();
2586}
2587
2589 DCHECK(
2590 i::v8_flags.merge_background_deserialized_script_with_compilation_cache);
2591 impl_->MergeWithExistingScript();
2592}
2593
2595 Isolate* v8_isolate, std::unique_ptr<CachedData> cached_data) {
2596 if (!i::v8_flags.concurrent_cache_deserialization) return nullptr;
2597 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2600 std::make_unique<i::BackgroundDeserializeTask>(i_isolate,
2601 std::move(cached_data)));
2602}
2603
2606 Isolate* v8_isolate, std::unique_ptr<CachedData> cached_data) {
2607 if (!i::v8_flags.concurrent_cache_deserialization) return nullptr;
2608 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
2610 std::make_unique<i::BackgroundDeserializeTask>(i_isolate,
2611 std::move(cached_data)));
2612}
2613
2614namespace {
2616 i::Isolate* i_isolate, ScriptCompiler::StreamedSource* v8_source,
2617 Local<String> full_source_string, const ScriptOrigin& origin) {
2618 auto str = Utils::OpenHandle(*full_source_string);
2619 i::ScriptDetails script_details =
2620 GetScriptDetails(i_isolate, origin.ResourceName(), origin.LineOffset(),
2621 origin.ColumnOffset(), origin.SourceMapUrl(),
2622 origin.GetHostDefinedOptions(), origin.Options());
2623 i::ScriptStreamingData* data = v8_source->impl();
2624 return i::Compiler::GetSharedFunctionInfoForStreamedScript(
2625 i_isolate, str, script_details, data, &v8_source->compilation_details());
2626}
2627
2628} // namespace
2629
2631 StreamedSource* v8_source,
2632 Local<String> full_source_string,
2633 const ScriptOrigin& origin) {
2635 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.ScriptCompiler");
2637 "V8.CompileStreamedScript");
2640 CompileStreamedSource(i_isolate, v8_source, full_source_string, origin);
2641 has_exception = !maybe_sfi.ToHandle(&sfi);
2642 if (has_exception) i_isolate->ReportPendingMessages();
2645 if (generic.IsEmpty()) return Local<Script>();
2646 Local<Script> bound = generic->BindToCurrentContext();
2647 if (bound.IsEmpty()) return Local<Script>();
2648 RETURN_ESCAPED(bound);
2649}
2650
2652 Local<Context> context, StreamedSource* v8_source,
2653 Local<String> full_source_string, const ScriptOrigin& origin) {
2655 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.ScriptCompiler");
2657 "V8.CompileStreamedModule");
2660 CompileStreamedSource(i_isolate, v8_source, full_source_string, origin);
2661 has_exception = !maybe_sfi.ToHandle(&sfi);
2662 if (has_exception) i_isolate->ReportPendingMessages();
2665 ToApiHandle<Module>(i_isolate->factory()->NewSourceTextModule(sfi)));
2666}
2667
2672
2674 Local<UnboundScript> unbound_script) {
2675 auto shared = Utils::OpenHandle(*unbound_script);
2676 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is gone.
2677 DCHECK(!i::HeapLayout::InReadOnlySpace(*shared));
2678 i::Isolate* i_isolate = i::GetIsolateFromWritableObject(*shared);
2679 Utils::ApiCheck(!i_isolate->serializer_enabled(),
2680 "ScriptCompiler::CreateCodeCache",
2681 "Cannot create code cache while creating a snapshot");
2683 DCHECK(shared->is_toplevel());
2684 return i::CodeSerializer::Serialize(i_isolate, shared);
2685}
2686
2687// static
2689 Local<UnboundModuleScript> unbound_module_script) {
2691 Utils::OpenHandle(*unbound_module_script);
2692 // TODO(jgruber): Remove this DCHECK once Function::GetUnboundScript is gone.
2693 DCHECK(!i::HeapLayout::InReadOnlySpace(*shared));
2694 i::Isolate* i_isolate = i::GetIsolateFromWritableObject(*shared);
2695 Utils::ApiCheck(!i_isolate->serializer_enabled(),
2696 "ScriptCompiler::CreateCodeCache",
2697 "Cannot create code cache while creating a snapshot");
2699 DCHECK(shared->is_toplevel());
2700 return i::CodeSerializer::Serialize(i_isolate, shared);
2701}
2702
2704 Local<Function> function) {
2705 auto js_function = i::Cast<i::JSFunction>(Utils::OpenDirectHandle(*function));
2706 i::Isolate* i_isolate = js_function->GetIsolate();
2707 Utils::ApiCheck(!i_isolate->serializer_enabled(),
2708 "ScriptCompiler::CreateCodeCacheForFunction",
2709 "Cannot create code cache while creating a snapshot");
2710 i::Handle<i::SharedFunctionInfo> shared(js_function->shared(), i_isolate);
2712 Utils::ApiCheck(shared->is_wrapped(),
2713 "v8::ScriptCompiler::CreateCodeCacheForFunction",
2714 "Expected SharedFunctionInfo with wrapped source code");
2715 return i::CodeSerializer::Serialize(i_isolate, shared);
2716}
2717
2719 ScriptOrigin* origin) {
2720 if (origin) {
2721 ScriptCompiler::Source script_source(source, *origin);
2722 return ScriptCompiler::Compile(context, &script_source);
2723 }
2724 ScriptCompiler::Source script_source(source);
2725 return ScriptCompiler::Compile(context, &script_source);
2726}
2727
2728// --- E x c e p t i o n s ---
2729
2731 : i_isolate_(reinterpret_cast<i::Isolate*>(v8_isolate)),
2732 next_(i_isolate_->try_catch_handler()),
2733 is_verbose_(false),
2734 can_continue_(true),
2735 capture_message_(true),
2736 rethrow_(false) {
2737 ResetInternal();
2738 // Special handling for simulators which have a separate JS stack.
2740 i::SimulatorStack::RegisterJSStackComparableAddress(i_isolate_));
2742}
2743
2744namespace {
2745
2746i::Tagged<i::Object> ToObject(void* object) {
2747 return i::Tagged<i::Object>(reinterpret_cast<i::Address>(object));
2748}
2749
2750} // namespace
2751
2753 if (HasCaught()) {
2754 if (rethrow_ || (V8_UNLIKELY(HasTerminated()) &&
2755 !i_isolate_->thread_local_top()->CallDepthIsZero())) {
2756 if (capture_message_) {
2757 // If an exception was caught and rethrow_ is indicated, the saved
2758 // message, script, and location need to be restored to Isolate TLS
2759 // for reuse. capture_message_ needs to be disabled so that Throw()
2760 // does not create a new message.
2761 i_isolate_->thread_local_top()->rethrowing_message_ = true;
2762 i_isolate_->set_pending_message(ToObject(message_obj_));
2763 }
2764 i_isolate_->UnregisterTryCatchHandler(this);
2765 i_isolate_->clear_internal_exception();
2766 i_isolate_->Throw(ToObject(exception_));
2767 return;
2768 }
2769 Reset();
2770 }
2771 i_isolate_->UnregisterTryCatchHandler(this);
2772 DCHECK_IMPLIES(rethrow_,
2773 !i_isolate_->thread_local_top()->rethrowing_message_);
2774}
2775
2776void* v8::TryCatch::operator new(size_t) { base::OS::Abort(); }
2777void* v8::TryCatch::operator new[](size_t) { base::OS::Abort(); }
2778void v8::TryCatch::operator delete(void*, size_t) { base::OS::Abort(); }
2779void v8::TryCatch::operator delete[](void*, size_t) { base::OS::Abort(); }
2780
2782 return !IsTheHole(ToObject(exception_), i_isolate_);
2783}
2784
2785bool v8::TryCatch::CanContinue() const { return can_continue_; }
2786
2788 return ToObject(exception_) ==
2789 i::ReadOnlyRoots(i_isolate_).termination_exception();
2790}
2791
2793 if (!HasCaught()) return v8::Local<v8::Value>();
2794 rethrow_ = true;
2795 return v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate_));
2796}
2797
2799 if (!HasCaught()) return v8::Local<Value>();
2800 if (HasTerminated()) {
2801 return v8::Utils::ToLocal(i_isolate_->factory()->null_value());
2802 }
2803 return v8::Utils::ToLocal(i::direct_handle(ToObject(exception_), i_isolate_));
2804}
2805
2807 Local<Value> exception) {
2808 auto i_exception = Utils::OpenDirectHandle(*exception);
2809 if (!IsJSObject(*i_exception)) return v8::Local<Value>();
2811 auto obj = i::Cast<i::JSObject>(i_exception);
2812 i::DirectHandle<i::String> name = i_isolate->factory()->stack_string();
2813 Maybe<bool> maybe = i::JSReceiver::HasProperty(i_isolate, obj, name);
2814 has_exception = maybe.IsNothing();
2816 if (!maybe.FromJust()) return v8::Local<Value>();
2818 has_exception = !ToLocal<Value>(
2819 i::JSReceiver::GetProperty(i_isolate, obj, name), &result);
2822}
2823
2825 if (!HasCaught()) return v8::Local<Value>();
2826 return StackTrace(context, Exception());
2827}
2828
2830 i::Tagged<i::Object> message = ToObject(message_obj_);
2831 DCHECK(IsJSMessageObject(message) || IsTheHole(message, i_isolate_));
2832 if (HasCaught() && !IsTheHole(message, i_isolate_)) {
2833 return v8::Utils::MessageToLocal(i::direct_handle(message, i_isolate_));
2834 } else {
2835 return v8::Local<v8::Message>();
2836 }
2837}
2838
2840 if (rethrow_) return;
2841 if (V8_UNLIKELY(i_isolate_->is_execution_terminating()) &&
2842 !i_isolate_->thread_local_top()->CallDepthIsZero()) {
2843 return;
2844 }
2845 i_isolate_->clear_internal_exception();
2846 i_isolate_->clear_pending_message();
2847 ResetInternal();
2848}
2849
2851 i::Tagged<i::Object> the_hole = i::ReadOnlyRoots(i_isolate_).the_hole_value();
2852 exception_ = reinterpret_cast<void*>(the_hole.ptr());
2853 message_obj_ = reinterpret_cast<void*>(the_hole.ptr());
2854}
2855
2856void v8::TryCatch::SetVerbose(bool value) { is_verbose_ = value; }
2857
2858bool v8::TryCatch::IsVerbose() const { return is_verbose_; }
2859
2860void v8::TryCatch::SetCaptureMessage(bool value) { capture_message_ = value; }
2861
2862// --- M e s s a g e ---
2863
2865 auto self = Utils::OpenDirectHandle(this);
2866 i::Isolate* i_isolate = self->GetIsolate();
2868 InternalEscapableScope scope(i_isolate);
2870 Utils::ToLocal(i::MessageHandler::GetMessage(i_isolate, self));
2871 return scope.Escape(result);
2872}
2873
2875 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
2876 return reinterpret_cast<Isolate*>(i_isolate);
2877}
2878
2880 auto self = Utils::OpenDirectHandle(this);
2881 i::Isolate* i_isolate = self->GetIsolate();
2883 i::DirectHandle<i::Script> script(self->script(), i_isolate);
2884 return GetScriptOriginForScript(i_isolate, script);
2885}
2886
2888 // TODO(cbruni, chromium:1244145): Remove checks once we allow arbitrary
2889 // host-defined options.
2890 if (host_defined_options_.IsEmpty()) return;
2891 Utils::ApiCheck(host_defined_options_->IsFixedArray(), "ScriptOrigin()",
2892 "Host-defined options has to be a PrimitiveArray");
2893 auto options =
2895 for (int i = 0; i < options->length(); i++) {
2896 Utils::ApiCheck(i::IsPrimitive(options->get(i)), "ScriptOrigin()",
2897 "PrimitiveArray can only contain primtive values");
2898 }
2899}
2900
2905
2907 auto self = Utils::OpenDirectHandle(this);
2908 i::Isolate* i_isolate = self->GetIsolate();
2910 InternalEscapableScope scope(i_isolate);
2911 i::DirectHandle<i::Object> stack_trace(self->stack_trace(), i_isolate);
2912 if (!IsStackTraceInfo(*stack_trace)) return {};
2913 return scope.Escape(
2914 Utils::StackTraceToLocal(i::Cast<i::StackTraceInfo>(stack_trace)));
2915}
2916
2918 auto self = Utils::OpenDirectHandle(this);
2919 i::Isolate* i_isolate = self->GetIsolate();
2921 HandleScope handle_scope(reinterpret_cast<Isolate*>(i_isolate));
2922 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
2923 return Just(self->GetLineNumber());
2924}
2925
2927 auto self = Utils::OpenDirectHandle(this);
2928 i::Isolate* i_isolate = self->GetIsolate();
2930 HandleScope handle_scope(reinterpret_cast<Isolate*>(i_isolate));
2931 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
2932 return self->GetStartPosition();
2933}
2934
2936 auto self = Utils::OpenDirectHandle(this);
2937 i::Isolate* i_isolate = self->GetIsolate();
2939 HandleScope handle_scope(reinterpret_cast<Isolate*>(i_isolate));
2940 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
2941 return self->GetEndPosition();
2942}
2943
2945 auto self = Utils::OpenDirectHandle(this);
2946 DCHECK_NO_SCRIPT_NO_EXCEPTION(self->GetIsolate());
2947 return self->error_level();
2948}
2949
2951 auto self = Utils::OpenDirectHandle(this);
2952 i::Isolate* i_isolate = self->GetIsolate();
2954 HandleScope handle_scope(reinterpret_cast<Isolate*>(i_isolate));
2955 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
2956 return self->GetColumnNumber();
2957}
2958
2960#if V8_ENABLE_WEBASSEMBLY
2961 auto self = Utils::OpenDirectHandle(this);
2962 i::Isolate* i_isolate = self->GetIsolate();
2964 HandleScope handle_scope(reinterpret_cast<Isolate*>(i_isolate));
2965 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
2966 int start_position = self->GetColumnNumber();
2967 if (start_position == -1) return Message::kNoWasmFunctionIndexInfo;
2968
2969 i::DirectHandle<i::Script> script(self->script(), i_isolate);
2970
2971 if (script->type() != i::Script::Type::kWasm) {
2973 }
2974
2975 auto debug_script = ToApiHandle<debug::Script>(script);
2976 return Local<debug::WasmScript>::Cast(debug_script)
2977 ->GetContainingFunction(start_position);
2978#else
2980#endif // V8_ENABLE_WEBASSEMBLY
2981}
2982
2986
2988 auto self = Utils::OpenDirectHandle(this);
2989 i::Isolate* i_isolate = self->GetIsolate();
2991 HandleScope handle_scope(reinterpret_cast<Isolate*>(i_isolate));
2992 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
2993 const int column_number = self->GetColumnNumber();
2994 if (column_number == -1) return -1;
2995 const int start = self->GetStartPosition();
2996 const int end = self->GetEndPosition();
2997 return column_number + (end - start);
2998}
2999
3001 return Just(GetEndColumn());
3002}
3003
3005 auto self = Utils::OpenDirectHandle(this);
3006 i::Isolate* i_isolate = self->GetIsolate();
3008 return self->script()->origin_options().IsSharedCrossOrigin();
3009}
3010
3011bool Message::IsOpaque() const {
3012 auto self = Utils::OpenDirectHandle(this);
3013 i::Isolate* i_isolate = self->GetIsolate();
3015 return self->script()->origin_options().IsOpaque();
3016}
3017
3019 auto self = Utils::OpenDirectHandle(this);
3020 i::Isolate* i_isolate = self->GetIsolate();
3022 InternalEscapableScope handle_scope(i_isolate);
3024 Utils::ToLocal(i::direct_handle(self->GetSource(), i_isolate)));
3025}
3026
3028 auto self = Utils::OpenDirectHandle(this);
3029 i::Isolate* i_isolate = self->GetIsolate();
3031 InternalEscapableScope handle_scope(i_isolate);
3032 i::JSMessageObject::EnsureSourcePositionsAvailable(i_isolate, self);
3033 RETURN_ESCAPED(Utils::ToLocal(self->GetSourceLine()));
3034}
3035
3037 Isolate* v8_isolate, std::ostream& out,
3038 PrintCurrentStackTraceFilterCallback should_include_frame_callback) {
3039 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3041 i_isolate->PrintCurrentStackTrace(out, should_include_frame_callback);
3042}
3043
3044// --- S t a c k T r a c e ---
3045
3047 auto self = Utils::OpenDirectHandle(this);
3048 return self->id();
3049}
3050
3052 uint32_t index) const {
3053 auto self = Utils::OpenDirectHandle(this);
3054 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3055 return Utils::StackFrameToLocal(
3056 i::direct_handle(self->get(index), i_isolate));
3057}
3058
3060 auto self = Utils::OpenDirectHandle(this);
3061 return self->length();
3062}
3063
3065 int frame_limit,
3066 StackTraceOptions options) {
3067 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3070 i_isolate->CaptureDetailedStackTrace(frame_limit, options);
3071 return Utils::StackTraceToLocal(stack_trace);
3072}
3073
3075 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3077 i::DirectHandle<i::String> name_or_source_url =
3078 i_isolate->CurrentScriptNameOrSourceURL();
3079 return Utils::ToLocal(name_or_source_url);
3080}
3081
3082// --- S t a c k F r a m e ---
3083
3085 auto self = Utils::OpenDirectHandle(this);
3086 i::Isolate* i_isolate = self->GetIsolate();
3087 i::DirectHandle<i::Script> script(self->script(), i_isolate);
3088 i::Script::PositionInfo info;
3089 CHECK(i::Script::GetPositionInfo(
3090 script, i::StackFrameInfo::GetSourcePosition(self), &info));
3091 if (script->HasSourceURLComment()) {
3092 info.line -= script->line_offset();
3093 if (info.line == 0) {
3094 info.column -= script->column_offset();
3095 }
3096 }
3097 return {info.line, info.column};
3098}
3099
3101 auto self = Utils::OpenHandle(this);
3102
3103 return i::StackFrameInfo::GetSourcePosition(self);
3104}
3105
3107 return Utils::OpenDirectHandle(this)->script()->id();
3108}
3109
3111 auto self = Utils::OpenDirectHandle(this);
3112 i::Isolate* i_isolate = self->GetIsolate();
3113 i::DirectHandle<i::Object> name(self->script()->name(), i_isolate);
3114 if (!IsString(*name)) return {};
3115 return Utils::ToLocal(i::Cast<i::String>(name));
3116}
3117
3119 auto self = Utils::OpenDirectHandle(this);
3120 i::Isolate* i_isolate = self->GetIsolate();
3121 i::DirectHandle<i::Object> name_or_source_url(
3122 self->script()->GetNameOrSourceURL(), i_isolate);
3123 if (!IsString(*name_or_source_url)) return {};
3124 return Utils::ToLocal(i::Cast<i::String>(name_or_source_url));
3125}
3126
3128 auto self = Utils::OpenDirectHandle(this);
3129 i::Isolate* i_isolate = self->GetIsolate();
3130 if (!self->script()->HasValidSource()) return {};
3131 i::DirectHandle<i::PrimitiveHeapObject> source(self->script()->source(),
3132 i_isolate);
3133 if (!IsString(*source)) return {};
3134 return Utils::ToLocal(i::Cast<i::String>(source));
3135}
3136
3138 auto self = Utils::OpenDirectHandle(this);
3139 i::Isolate* i_isolate = self->GetIsolate();
3140 i::DirectHandle<i::Object> source_mapping_url(
3141 self->script()->source_mapping_url(), i_isolate);
3142 if (!IsString(*source_mapping_url)) return {};
3143 return Utils::ToLocal(i::Cast<i::String>(source_mapping_url));
3144}
3145
3147 auto self = Utils::OpenDirectHandle(this);
3148 i::Isolate* i_isolate = self->GetIsolate();
3149 i::DirectHandle<i::String> name(self->function_name(), i_isolate);
3150 if (name->length() == 0) return {};
3151 return Utils::ToLocal(name);
3152}
3153
3155 auto self = Utils::OpenDirectHandle(this);
3156 return self->script()->compilation_type() ==
3157 i::Script::CompilationType::kEval;
3158}
3159
3161 return Utils::OpenDirectHandle(this)->is_constructor();
3162}
3163
3164bool StackFrame::IsWasm() const { return !IsUserJavaScript(); }
3165
3167 return Utils::OpenDirectHandle(this)->script()->IsUserJavaScript();
3168}
3169
3170// --- J S O N ---
3171
3173 Local<String> json_string) {
3174 PREPARE_FOR_EXECUTION(context, JSON, Parse);
3175 auto string = Utils::OpenHandle(*json_string);
3176 i::Handle<i::String> source = i::String::Flatten(i_isolate, string);
3177 i::Handle<i::Object> undefined = i_isolate->factory()->undefined_value();
3178 auto maybe =
3179 source->IsOneByteRepresentation()
3180 ? i::JsonParser<uint8_t>::Parse(i_isolate, source, undefined)
3181 : i::JsonParser<uint16_t>::Parse(i_isolate, source, undefined);
3183 has_exception = !ToLocal<Value>(maybe, &result);
3186}
3187
3189 Local<Value> json_object,
3190 Local<String> gap) {
3192 i::Handle<i::JSAny> object;
3193 if (!Utils::ApiCheck(
3194 i::TryCast<i::JSAny>(Utils::OpenHandle(*json_object), &object),
3195 "JSON::Stringify",
3196 "Invalid object, must be a JSON-serializable object.")) {
3197 return {};
3198 }
3199 i::Handle<i::Undefined> replacer = i_isolate->factory()->undefined_value();
3200 i::Handle<i::String> gap_string = gap.IsEmpty()
3201 ? i_isolate->factory()->empty_string()
3202 : Utils::OpenHandle(*gap);
3204 has_exception = !i::JsonStringify(i_isolate, object, replacer, gap_string)
3205 .ToHandle(&maybe);
3208 has_exception =
3209 !ToLocal<String>(i::Object::ToString(i_isolate, maybe), &result);
3212}
3213
3214// --- V a l u e S e r i a l i z a t i o n ---
3215
3217 : private_(std::move(other.private_)) {}
3218
3220
3222 SharedValueConveyor&& other) noexcept {
3223 private_ = std::move(other.private_);
3224 return *this;
3225}
3226
3228 : private_(std::make_unique<i::SharedObjectConveyorHandles>(
3229 reinterpret_cast<i::Isolate*>(v8_isolate))) {}
3230
3232 Local<Object> object) {
3233 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3235 i_isolate,
3236 NewError(i_isolate->error_function(), i::MessageTemplate::kDataCloneError,
3237 Utils::OpenDirectHandle(*object)),
3238 Nothing<bool>());
3239}
3240
3242 return false;
3243}
3244
3246 Local<Object> object) {
3247 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3248 auto js_object = i::Cast<i::JSObject>(Utils::OpenDirectHandle(*object));
3249 return Just<bool>(
3250 i::JSObject::GetEmbedderFieldCount(js_object->map(i_isolate)));
3251}
3252
3254 Isolate* v8_isolate, Local<SharedArrayBuffer> shared_array_buffer) {
3255 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3256 i_isolate->Throw(*i_isolate->factory()->NewError(
3257 i_isolate->error_function(), i::MessageTemplate::kDataCloneError,
3258 Utils::OpenDirectHandle(*shared_array_buffer)));
3259 return Nothing<uint32_t>();
3260}
3261
3266
3268 Isolate* v8_isolate, SharedValueConveyor&& conveyor) {
3269 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3270 i_isolate->Throw(*i_isolate->factory()->NewError(
3271 i_isolate->error_function(), i::MessageTemplate::kDataCloneError,
3272 i_isolate->factory()->NewStringFromAsciiChecked("shared value")));
3273 return false;
3274}
3275
3277 size_t size,
3278 size_t* actual_size) {
3279 *actual_size = size;
3280 return base::Realloc(old_buffer, size);
3281}
3282
3284 return base::Free(buffer);
3285}
3286
3293
3295 : ValueSerializer(v8_isolate, nullptr) {}
3296
3298 : private_(new PrivateData(reinterpret_cast<i::Isolate*>(v8_isolate),
3299 delegate)) {}
3300
3302
3304
3308
3310 Local<Value> value) {
3311 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3312 ENTER_V8(i_isolate, context, ValueSerializer, WriteValue, i::HandleScope);
3313 auto object = Utils::OpenHandle(*value);
3315 has_exception = result.IsNothing();
3317 return result;
3318}
3319
3320std::pair<uint8_t*, size_t> ValueSerializer::Release() {
3321 return private_->serializer.Release();
3322}
3323
3325 Local<ArrayBuffer> array_buffer) {
3327 transfer_id, Utils::OpenDirectHandle(*array_buffer));
3328}
3329
3330void ValueSerializer::WriteUint32(uint32_t value) {
3332}
3333
3334void ValueSerializer::WriteUint64(uint64_t value) {
3336}
3337
3340}
3341
3342void ValueSerializer::WriteRawBytes(const void* source, size_t length) {
3343 private_->serializer.WriteRawBytes(source, length);
3344}
3345
3347 Isolate* v8_isolate) {
3348 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3349 i_isolate->Throw(*i_isolate->factory()->NewError(
3350 i_isolate->error_function(),
3351 i::MessageTemplate::kDataCloneDeserializationError));
3352 return MaybeLocal<Object>();
3353}
3354
3356 Isolate* v8_isolate, uint32_t id) {
3357 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3358 i_isolate->Throw(*i_isolate->factory()->NewError(
3359 i_isolate->error_function(),
3360 i::MessageTemplate::kDataCloneDeserializationError));
3362}
3363
3366 uint32_t id) {
3367 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3368 i_isolate->Throw(*i_isolate->factory()->NewError(
3369 i_isolate->error_function(),
3370 i::MessageTemplate::kDataCloneDeserializationError));
3372}
3373
3375 Isolate* v8_isolate) {
3376 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3377 i_isolate->Throw(*i_isolate->factory()->NewError(
3378 i_isolate->error_function(),
3379 i::MessageTemplate::kDataCloneDeserializationError));
3380 return nullptr;
3381}
3382
3385 Delegate* delegate)
3386 : isolate(i_isolate), deserializer(i_isolate, data, delegate) {}
3389 bool supports_legacy_wire_format = false;
3390};
3391
3392ValueDeserializer::ValueDeserializer(Isolate* v8_isolate, const uint8_t* data,
3393 size_t size)
3394 : ValueDeserializer(v8_isolate, data, size, nullptr) {}
3395
3396ValueDeserializer::ValueDeserializer(Isolate* v8_isolate, const uint8_t* data,
3397 size_t size, Delegate* delegate) {
3398 private_ = new PrivateData(reinterpret_cast<i::Isolate*>(v8_isolate),
3399 base::Vector<const uint8_t>(data, size), delegate);
3400}
3401
3403
3405 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3406 ENTER_V8_NO_SCRIPT(i_isolate, context, ValueDeserializer, ReadHeader,
3408
3409 bool read_header = false;
3410 has_exception = !private_->deserializer.ReadHeader().To(&read_header);
3412 DCHECK(read_header);
3413
3414 static const uint32_t kMinimumNonLegacyVersion = 13;
3415 if (GetWireFormatVersion() < kMinimumNonLegacyVersion &&
3417 i_isolate->Throw(*i_isolate->factory()->NewError(
3418 i::MessageTemplate::kDataCloneDeserializationVersionError));
3419 has_exception = true;
3421 }
3422
3423 return Just(true);
3424}
3425
3427 bool supports_legacy_wire_format) {
3428 private_->supports_legacy_wire_format = supports_legacy_wire_format;
3429}
3430
3434
3449
3451 Local<ArrayBuffer> array_buffer) {
3453 transfer_id, Utils::OpenDirectHandle(*array_buffer));
3454}
3455
3457 uint32_t transfer_id, Local<SharedArrayBuffer> shared_array_buffer) {
3459 transfer_id, Utils::OpenDirectHandle(*shared_array_buffer));
3460}
3461
3462bool ValueDeserializer::ReadUint32(uint32_t* value) {
3463 return private_->deserializer.ReadUint32(value);
3464}
3465
3466bool ValueDeserializer::ReadUint64(uint64_t* value) {
3467 return private_->deserializer.ReadUint64(value);
3468}
3469
3471 return private_->deserializer.ReadDouble(value);
3472}
3473
3474bool ValueDeserializer::ReadRawBytes(size_t length, const void** data) {
3475 return private_->deserializer.ReadRawBytes(length, data);
3476}
3477
3478// --- D a t a ---
3479
3481 bool result = i::IsUndefined(*Utils::OpenDirectHandle(this));
3483 return result;
3484}
3485
3486bool Value::FullIsNull() const {
3489 return result;
3490}
3491
3492bool Value::FullIsTrue() const {
3493 auto object = *Utils::OpenDirectHandle(this);
3494 if (i::IsSmi(object)) return false;
3495 return i::IsTrue(object);
3496}
3497
3500 if (i::IsSmi(object)) return false;
3501 return i::IsFalse(object);
3502}
3503
3505 auto object = Utils::OpenDirectHandle(this);
3506 return i::IsPrimitive(*object) && !IsPrivateSymbol(*object);
3507}
3508
3509bool Value::IsFunction() const {
3510 return IsCallable(*Utils::OpenDirectHandle(this));
3511}
3512
3513bool Value::IsName() const { return i::IsName(*Utils::OpenDirectHandle(this)); }
3514
3516 bool result = i::IsString(*Utils::OpenDirectHandle(this));
3518 return result;
3519}
3520
3521bool Value::IsSymbol() const {
3522 return IsPublicSymbol(*Utils::OpenDirectHandle(this));
3523}
3524
3525bool Value::IsArray() const {
3526 return IsJSArray(*Utils::OpenDirectHandle(this));
3527}
3528
3530 auto obj = *Utils::OpenDirectHandle(this);
3531 if (!IsJSArrayBuffer(obj)) return false;
3532 return !i::Cast<i::JSArrayBuffer>(obj)->is_shared();
3533}
3534
3536 return IsJSArrayBufferView(*Utils::OpenDirectHandle(this));
3537}
3538
3540 return IsJSTypedArray(*Utils::OpenDirectHandle(this));
3541}
3542
3543#define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype) \
3544 bool Value::Is##Type##Array() const { \
3545 auto obj = *Utils::OpenDirectHandle(this); \
3546 return i::IsJSTypedArray(obj) && \
3547 i::Cast<i::JSTypedArray>(obj)->type() == i::kExternal##Type##Array; \
3548 }
3549
3551#undef VALUE_IS_TYPED_ARRAY
3552
3554 auto obj = *Utils::OpenDirectHandle(this);
3555 return i::IsJSTypedArray(obj) &&
3557 Utils::ApiCheck(i::v8_flags.js_float16array, "Value::IsFloat16Array",
3558 "Float16Array is not supported");
3559}
3560
3561bool Value::IsDataView() const {
3562 auto obj = *Utils::OpenDirectHandle(this);
3563 return IsJSDataView(obj) || IsJSRabGsabDataView(obj);
3564}
3565
3567 auto obj = *Utils::OpenDirectHandle(this);
3568 if (!IsJSArrayBuffer(obj)) return false;
3569 return i::Cast<i::JSArrayBuffer>(obj)->is_shared();
3570}
3571
3572bool Value::IsObject() const {
3573 return i::IsJSReceiver(*Utils::OpenDirectHandle(this));
3574}
3575
3576bool Value::IsNumber() const {
3577 return i::IsNumber(*Utils::OpenDirectHandle(this));
3578}
3579
3580bool Value::IsBigInt() const {
3581 return i::IsBigInt(*Utils::OpenDirectHandle(this));
3582}
3583
3584bool Value::IsProxy() const {
3585 return i::IsJSProxy(*Utils::OpenDirectHandle(this));
3586}
3587
3588#define VALUE_IS_SPECIFIC_TYPE(Type, Check) \
3589 bool Value::Is##Type() const { \
3590 return i::Is##Check(*Utils::OpenDirectHandle(this)); \
3591 }
3592
3593VALUE_IS_SPECIFIC_TYPE(ArgumentsObject, JSArgumentsObject)
3594VALUE_IS_SPECIFIC_TYPE(BigIntObject, BigIntWrapper)
3595VALUE_IS_SPECIFIC_TYPE(BooleanObject, BooleanWrapper)
3596VALUE_IS_SPECIFIC_TYPE(NumberObject, NumberWrapper)
3597VALUE_IS_SPECIFIC_TYPE(StringObject, StringWrapper)
3598VALUE_IS_SPECIFIC_TYPE(SymbolObject, SymbolWrapper)
3599VALUE_IS_SPECIFIC_TYPE(Date, JSDate)
3600VALUE_IS_SPECIFIC_TYPE(Map, JSMap)
3601VALUE_IS_SPECIFIC_TYPE(Set, JSSet)
3602#if V8_ENABLE_WEBASSEMBLY
3603VALUE_IS_SPECIFIC_TYPE(WasmMemoryMapDescriptor, WasmMemoryMapDescriptor)
3604VALUE_IS_SPECIFIC_TYPE(WasmMemoryObject, WasmMemoryObject)
3605VALUE_IS_SPECIFIC_TYPE(WasmModuleObject, WasmModuleObject)
3606VALUE_IS_SPECIFIC_TYPE(WasmNull, WasmNull)
3607#else
3608bool Value::IsWasmMemoryMapDescriptor() const { return false; }
3609bool Value::IsWasmMemoryObject() const { return false; }
3610bool Value::IsWasmModuleObject() const { return false; }
3611bool Value::IsWasmNull() const { return false; }
3612#endif // V8_ENABLE_WEBASSEMBLY
3613VALUE_IS_SPECIFIC_TYPE(WeakMap, JSWeakMap)
3614VALUE_IS_SPECIFIC_TYPE(WeakSet, JSWeakSet)
3615VALUE_IS_SPECIFIC_TYPE(WeakRef, JSWeakRef)
3616
3617#undef VALUE_IS_SPECIFIC_TYPE
3618
3619bool Value::IsBoolean() const {
3620 return i::IsBoolean(*Utils::OpenDirectHandle(this));
3621}
3622
3623bool Value::IsExternal() const {
3625 return IsJSExternalObject(obj);
3626}
3627
3628bool Value::IsInt32() const {
3630 if (i::IsSmi(obj)) return true;
3631 if (i::IsNumber(obj)) {
3632 return i::IsInt32Double(i::Object::NumberValue(i::Cast<i::Number>(obj)));
3633 }
3634 return false;
3635}
3636
3637bool Value::IsUint32() const {
3638 auto obj = *Utils::OpenDirectHandle(this);
3639 if (i::IsSmi(obj)) return i::Smi::ToInt(obj) >= 0;
3640 if (i::IsNumber(obj)) {
3641 double value = i::Object::NumberValue(i::Cast<i::Number>(obj));
3642 return !i::IsMinusZero(value) && value >= 0 && value <= i::kMaxUInt32 &&
3643 value == i::FastUI2D(i::FastD2UI(value));
3644 }
3645 return false;
3646}
3647
3649 return IsJSError(*Utils::OpenDirectHandle(this));
3650}
3651
3652bool Value::IsRegExp() const {
3653 return IsJSRegExp(*Utils::OpenDirectHandle(this));
3654}
3655
3657 auto obj = *Utils::OpenDirectHandle(this);
3658 if (!IsJSFunction(obj)) return false;
3659 auto func = i::Cast<i::JSFunction>(obj);
3660 return i::IsAsyncFunction(func->shared()->kind());
3661}
3662
3664 auto obj = *Utils::OpenDirectHandle(this);
3665 if (!IsJSFunction(obj)) return false;
3666 auto func = i::Cast<i::JSFunction>(obj);
3667 DCHECK_NO_SCRIPT_NO_EXCEPTION(func->GetIsolate());
3668 return i::IsGeneratorFunction(func->shared()->kind());
3669}
3670
3672 return IsJSGeneratorObject(*Utils::OpenDirectHandle(this));
3673}
3674
3676 return IsJSMapIterator(*Utils::OpenDirectHandle(this));
3677}
3678
3680 return IsJSSetIterator(*Utils::OpenDirectHandle(this));
3681}
3682
3683bool Value::IsPromise() const {
3684 return IsJSPromise(*Utils::OpenDirectHandle(this));
3685}
3686
3688 return IsJSModuleNamespace(*Utils::OpenDirectHandle(this));
3689}
3690
3692 auto obj = Utils::OpenDirectHandle(this);
3693 if (i::IsString(*obj)) return ToApiHandle<String>(obj);
3696 has_exception =
3697 !ToLocal<String>(i::Object::ToString(i_isolate, obj), &result);
3700}
3701
3704 i::Isolate* i_isolate;
3705 if (!context.IsEmpty()) {
3706 i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
3707 } else if (IsSmi(*obj) || !i::GetIsolateFromHeapObject(
3708 i::Cast<i::HeapObject>(*obj), &i_isolate)) {
3709 i_isolate = i::Isolate::Current();
3710 }
3711 if (i::IsString(*obj)) return ToApiHandle<String>(obj);
3713 return Utils::ToLocal(i::Object::NoSideEffectsToString(i_isolate, obj));
3714}
3715
3717 auto obj = Utils::OpenDirectHandle(this);
3718 if (i::IsJSReceiver(*obj)) return ToApiHandle<Object>(obj);
3721 has_exception =
3722 !ToLocal<Object>(i::Object::ToObject(i_isolate, obj), &result);
3725}
3726
3728 auto obj = Utils::OpenDirectHandle(this);
3729 if (i::IsBigInt(*obj)) return ToApiHandle<BigInt>(obj);
3732 has_exception =
3733 !ToLocal<BigInt>(i::BigInt::FromObject(i_isolate, obj), &result);
3736}
3737
3738bool Value::BooleanValue(Isolate* v8_isolate) const {
3739 return i::Object::BooleanValue(*Utils::OpenDirectHandle(this),
3740 reinterpret_cast<i::Isolate*>(v8_isolate));
3741}
3742
3744 auto obj = Utils::OpenDirectHandle(this);
3745 if (i::IsPrimitive(*obj)) return ToApiHandle<Primitive>(obj);
3748 has_exception =
3749 !ToLocal<Primitive>(i::Object::ToPrimitive(i_isolate, obj), &result);
3752}
3753
3755 auto obj = Utils::OpenDirectHandle(this);
3756 if (i::IsNumeric(*obj)) return ToApiHandle<Numeric>(obj);
3759 has_exception =
3760 !ToLocal<Numeric>(i::Object::ToNumeric(i_isolate, obj), &result);
3763}
3764
3766 auto i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
3768 return ToApiHandle<Boolean>(
3769 i_isolate->factory()->ToBoolean(BooleanValue(v8_isolate)));
3770}
3771
3773 auto obj = Utils::OpenDirectHandle(this);
3774 if (i::IsNumber(*obj)) return ToApiHandle<Number>(obj);
3777 has_exception =
3778 !ToLocal<Number>(i::Object::ToNumber(i_isolate, obj), &result);
3781}
3782
3784 auto obj = Utils::OpenDirectHandle(this);
3785 if (i::IsSmi(*obj)) return ToApiHandle<Integer>(obj);
3788 has_exception =
3789 !ToLocal<Integer>(i::Object::ToInteger(i_isolate, obj), &result);
3792}
3793
3795 auto obj = Utils::OpenDirectHandle(this);
3796 if (i::IsSmi(*obj)) return ToApiHandle<Int32>(obj);
3799 has_exception = !ToLocal<Int32>(i::Object::ToInt32(i_isolate, obj), &result);
3802}
3803
3805 auto obj = Utils::OpenDirectHandle(this);
3806 if (i::IsSmi(*obj)) return ToApiHandle<Uint32>(obj);
3809 has_exception =
3810 !ToLocal<Uint32>(i::Object::ToUint32(i_isolate, obj), &result);
3813}
3814
3818}
3819
3820namespace api_internal {
3824
3825 if (i::IsJSGlobalObject(holder)) {
3826 return i::Cast<i::JSGlobalObject>(holder)->global_proxy().ptr();
3827 }
3828 return holder_ptr;
3829}
3830} // namespace api_internal
3831
3832bool i::ShouldThrowOnError(i::Isolate* i_isolate) {
3833 return i::GetShouldThrow(i_isolate, Nothing<i::ShouldThrow>()) ==
3834 i::ShouldThrow::kThrowOnError;
3835}
3836
3837void i::Internals::CheckInitializedImpl(v8::Isolate* external_isolate) {
3838 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(external_isolate);
3839 Utils::ApiCheck(i_isolate != nullptr && !i_isolate->IsDead(),
3840 "v8::internal::Internals::CheckInitialized",
3841 "Isolate is not initialized or V8 has died");
3842}
3843
3845 Utils::ApiCheck(that->IsValue(), "v8::Value::Cast", "Data is not a Value");
3846}
3847
3849 Utils::ApiCheck(that->IsExternal(), "v8::External::Cast",
3850 "Value is not an External");
3851}
3852
3854 auto obj = Utils::OpenDirectHandle(that);
3855 Utils::ApiCheck(i::IsJSReceiver(*obj), "v8::Object::Cast",
3856 "Value is not an Object");
3857}
3858
3860 auto obj = Utils::OpenDirectHandle(that);
3861 Utils::ApiCheck(i::IsCallable(*obj), "v8::Function::Cast",
3862 "Value is not a Function");
3863}
3864
3866 auto obj = Utils::OpenDirectHandle(that);
3867 Utils::ApiCheck(i::IsBoolean(*obj), "v8::Boolean::Cast",
3868 "Value is not a Boolean");
3869}
3870
3872 auto obj = Utils::OpenDirectHandle(that);
3873 Utils::ApiCheck(i::IsName(*obj), "v8::Name::Cast", "Value is not a Name");
3874}
3875
3877 auto obj = Utils::OpenDirectHandle(that);
3878 Utils::ApiCheck(i::IsString(*obj), "v8::String::Cast",
3879 "Value is not a String");
3880}
3881
3883 auto obj = Utils::OpenDirectHandle(that);
3884 Utils::ApiCheck(i::IsSymbol(*obj), "v8::Symbol::Cast",
3885 "Value is not a Symbol");
3886}
3887
3889 auto obj = Utils::OpenDirectHandle(that);
3890 Utils::ApiCheck(IsSymbol(*obj) && i::Cast<i::Symbol>(obj)->is_private(),
3891 "v8::Private::Cast", "Value is not a Private");
3892}
3893
3895 auto obj = Utils::OpenDirectHandle(that);
3896 Utils::ApiCheck(i::IsFixedArray(*obj), "v8::FixedArray::Cast",
3897 "Value is not a FixedArray");
3898}
3899
3901 auto obj = Utils::OpenDirectHandle(that);
3902 Utils::ApiCheck(i::IsModuleRequest(*obj), "v8::ModuleRequest::Cast",
3903 "Value is not a ModuleRequest");
3904}
3905
3907 auto obj = Utils::OpenDirectHandle(that);
3908 Utils::ApiCheck(i::IsModule(*obj), "v8::Module::Cast",
3909 "Value is not a Module");
3910}
3911
3913 auto obj = Utils::OpenDirectHandle(that);
3914 Utils::ApiCheck(i::IsNumeric(*obj), "v8::Numeric::Cast()",
3915 "Value is not a Numeric");
3916}
3917
3919 auto obj = Utils::OpenDirectHandle(that);
3920 Utils::ApiCheck(i::IsNumber(*obj), "v8::Number::Cast()",
3921 "Value is not a Number");
3922}
3923
3925 auto obj = Utils::OpenDirectHandle(that);
3926 Utils::ApiCheck(i::IsNumber(*obj), "v8::Integer::Cast",
3927 "Value is not an Integer");
3928}
3929
3931 Utils::ApiCheck(Value::Cast(that)->IsInt32(), "v8::Int32::Cast",
3932 "Value is not a 32-bit signed integer");
3933}
3934
3936 Utils::ApiCheck(Value::Cast(that)->IsUint32(), "v8::Uint32::Cast",
3937 "Value is not a 32-bit unsigned integer");
3938}
3939
3941 Utils::ApiCheck(Value::Cast(that)->IsBigInt(), "v8::BigInt::Cast",
3942 "Value is not a BigInt");
3943}
3944
3946 auto obj = Utils::OpenDirectHandle(that);
3947 Utils::ApiCheck(i::IsContext(*obj), "v8::Context::Cast",
3948 "Value is not a Context");
3949}
3950
3952 auto obj = Utils::OpenDirectHandle(that);
3953 Utils::ApiCheck(i::IsJSArray(*obj), "v8::Array::Cast",
3954 "Value is not an Array");
3955}
3956
3958 auto obj = Utils::OpenDirectHandle(that);
3959 Utils::ApiCheck(i::IsJSMap(*obj), "v8::Map::Cast", "Value is not a Map");
3960}
3961
3963 auto obj = Utils::OpenDirectHandle(that);
3964 Utils::ApiCheck(i::IsJSSet(*obj), "v8_Set_Cast", "Value is not a Set");
3965}
3966
3968 Utils::ApiCheck(that->IsPromise(), "v8::Promise::Cast",
3969 "Value is not a Promise");
3970}
3971
3973 Utils::ApiCheck(that->IsPromise(), "v8::Promise::Resolver::Cast",
3974 "Value is not a Promise::Resolver");
3975}
3976
3978 Utils::ApiCheck(that->IsProxy(), "v8::Proxy::Cast", "Value is not a Proxy");
3979}
3980
3982 Utils::ApiCheck(that->IsWasmMemoryObject(), "v8::WasmMemoryObject::Cast",
3983 "Value is not a WasmMemoryObject");
3984}
3985
3987 Utils::ApiCheck(that->IsWasmMemoryMapDescriptor(),
3988 "v8::WasmMemoryMapDescriptor::Cast",
3989 "Value is not a WasmMemoryMapDescriptor");
3990}
3991
3993 Utils::ApiCheck(that->IsWasmModuleObject(), "v8::WasmModuleObject::Cast",
3994 "Value is not a WasmModuleObject");
3995}
3996
3998 auto i_this = reinterpret_cast<const i::BackingStore*>(this);
3999 i_this->~BackingStore(); // manually call internal destructor
4000}
4001
4003 return reinterpret_cast<const i::BackingStore*>(this)->buffer_start();
4004}
4005
4007 return reinterpret_cast<const i::BackingStore*>(this)->byte_length();
4008}
4009
4011 return reinterpret_cast<const i::BackingStore*>(this)->max_byte_length();
4012}
4013
4015 return reinterpret_cast<const i::BackingStore*>(this)->is_shared();
4016}
4017
4019 return reinterpret_cast<const i::BackingStore*>(this)->is_resizable_by_js();
4020}
4021
4022// static
4023void v8::BackingStore::EmptyDeleter(void* data, size_t length,
4024 void* deleter_data) {
4025 DCHECK_NULL(deleter_data);
4026}
4027
4028std::shared_ptr<v8::BackingStore> v8::ArrayBuffer::GetBackingStore() {
4029 auto self = Utils::OpenDirectHandle(this);
4030 std::shared_ptr<i::BackingStore> backing_store = self->GetBackingStore();
4031 if (!backing_store) {
4032 backing_store =
4033 i::BackingStore::EmptyBackingStore(i::SharedFlag::kNotShared);
4034 }
4035 std::shared_ptr<i::BackingStoreBase> bs_base = backing_store;
4036 return std::static_pointer_cast<v8::BackingStore>(bs_base);
4037}
4038
4040 return Utils::OpenDirectHandle(this)->backing_store();
4041}
4042
4044 return Utils::OpenDirectHandle(this)->is_resizable_by_js();
4045}
4046
4047std::shared_ptr<v8::BackingStore> v8::SharedArrayBuffer::GetBackingStore() {
4048 auto self = Utils::OpenDirectHandle(this);
4049 std::shared_ptr<i::BackingStore> backing_store = self->GetBackingStore();
4050 if (!backing_store) {
4051 backing_store = i::BackingStore::EmptyBackingStore(i::SharedFlag::kShared);
4052 }
4053 std::shared_ptr<i::BackingStoreBase> bs_base = backing_store;
4054 return std::static_pointer_cast<v8::BackingStore>(bs_base);
4055}
4056
4058 return Utils::OpenDirectHandle(this)->backing_store();
4059}
4060
4062 auto obj = *Utils::OpenDirectHandle(that);
4064 IsJSArrayBuffer(obj) && !i::Cast<i::JSArrayBuffer>(obj)->is_shared(),
4065 "v8::ArrayBuffer::Cast()", "Value is not an ArrayBuffer");
4066}
4067
4069 auto obj = *Utils::OpenDirectHandle(that);
4070 Utils::ApiCheck(i::IsJSArrayBufferView(obj), "v8::ArrayBufferView::Cast()",
4071 "Value is not an ArrayBufferView");
4072}
4073
4075 auto obj = *Utils::OpenDirectHandle(that);
4076 Utils::ApiCheck(i::IsJSTypedArray(obj), "v8::TypedArray::Cast()",
4077 "Value is not a TypedArray");
4078}
4079
4080#define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype) \
4081 void v8::Type##Array::CheckCast(Value* that) { \
4082 auto obj = *Utils::OpenDirectHandle(that); \
4083 Utils::ApiCheck( \
4084 i::IsJSTypedArray(obj) && i::Cast<i::JSTypedArray>(obj)->type() == \
4085 i::kExternal##Type##Array, \
4086 "v8::" #Type "Array::Cast()", "Value is not a " #Type "Array"); \
4087 }
4088
4090#undef CHECK_TYPED_ARRAY_CAST
4091
4093 Utils::ApiCheck(i::v8_flags.js_float16array, "v8::Float16Array::Cast",
4094 "Float16Array is not supported");
4095 auto obj = *Utils::OpenDirectHandle(that);
4097 i::IsJSTypedArray(obj) &&
4099 "v8::Float16Array::Cast()", "Value is not a Float16Array");
4100}
4101
4103 auto obj = *Utils::OpenDirectHandle(that);
4104 Utils::ApiCheck(i::IsJSDataView(obj) || IsJSRabGsabDataView(obj),
4105 "v8::DataView::Cast()", "Value is not a DataView");
4106}
4107
4109 auto obj = *Utils::OpenDirectHandle(that);
4111 IsJSArrayBuffer(obj) && i::Cast<i::JSArrayBuffer>(obj)->is_shared(),
4112 "v8::SharedArrayBuffer::Cast()", "Value is not a SharedArrayBuffer");
4113}
4114
4116 auto obj = *Utils::OpenDirectHandle(that);
4117 Utils::ApiCheck(i::IsJSDate(obj), "v8::Date::Cast()", "Value is not a Date");
4118}
4119
4121 auto obj = *Utils::OpenDirectHandle(that);
4122 Utils::ApiCheck(i::IsStringWrapper(obj), "v8::StringObject::Cast()",
4123 "Value is not a StringObject");
4124}
4125
4127 auto obj = *Utils::OpenDirectHandle(that);
4128 Utils::ApiCheck(i::IsSymbolWrapper(obj), "v8::SymbolObject::Cast()",
4129 "Value is not a SymbolObject");
4130}
4131
4133 auto obj = *Utils::OpenDirectHandle(that);
4134 Utils::ApiCheck(i::IsNumberWrapper(obj), "v8::NumberObject::Cast()",
4135 "Value is not a NumberObject");
4136}
4137
4139 auto obj = *Utils::OpenDirectHandle(that);
4140 Utils::ApiCheck(i::IsBigIntWrapper(obj), "v8::BigIntObject::Cast()",
4141 "Value is not a BigIntObject");
4142}
4143
4145 auto obj = *Utils::OpenDirectHandle(that);
4146 Utils::ApiCheck(i::IsBooleanWrapper(obj), "v8::BooleanObject::Cast()",
4147 "Value is not a BooleanObject");
4148}
4149
4151 auto obj = *Utils::OpenDirectHandle(that);
4152 Utils::ApiCheck(i::IsJSRegExp(obj), "v8::RegExp::Cast()",
4153 "Value is not a RegExp");
4154}
4155
4157 auto obj = Utils::OpenDirectHandle(this);
4158 if (i::IsNumber(*obj)) {
4159 return Just(i::Object::NumberValue(i::Cast<i::Number>(*obj)));
4160 }
4161 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4162 ENTER_V8(i_isolate, context, Value, NumberValue, i::HandleScope);
4164 has_exception = !i::Object::ToNumber(i_isolate, obj).ToHandle(&num);
4166 return Just(i::Object::NumberValue(*num));
4167}
4168
4170 auto obj = Utils::OpenDirectHandle(this);
4171 if (i::IsNumber(*obj)) {
4172 return Just(NumberToInt64(*obj));
4173 }
4174 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4175 ENTER_V8(i_isolate, context, Value, IntegerValue, i::HandleScope);
4177 has_exception = !i::Object::ToInteger(i_isolate, obj).ToHandle(&num);
4179 return Just(NumberToInt64(*num));
4180}
4181
4183 auto obj = Utils::OpenDirectHandle(this);
4184 if (i::IsNumber(*obj)) return Just(NumberToInt32(*obj));
4185 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4186 ENTER_V8(i_isolate, context, Value, Int32Value, i::HandleScope);
4188 has_exception = !i::Object::ToInt32(i_isolate, obj).ToHandle(&num);
4190 return Just(IsSmi(*num) ? i::Smi::ToInt(*num)
4191 : static_cast<int32_t>(
4192 i::Cast<i::HeapNumber>(*num)->value()));
4193}
4194
4196 auto obj = Utils::OpenDirectHandle(this);
4197 if (i::IsNumber(*obj)) return Just(NumberToUint32(*obj));
4198 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4199 ENTER_V8(i_isolate, context, Value, Uint32Value, i::HandleScope);
4201 has_exception = !i::Object::ToUint32(i_isolate, obj).ToHandle(&num);
4203 return Just(IsSmi(*num) ? static_cast<uint32_t>(i::Smi::ToInt(*num))
4204 : static_cast<uint32_t>(
4205 i::Cast<i::HeapNumber>(*num)->value()));
4206}
4207
4209 auto self = Utils::OpenDirectHandle(this);
4210 if (i::IsSmi(*self)) {
4211 if (i::Smi::ToInt(*self) >= 0) return Utils::Uint32ToLocal(self);
4212 return Local<Uint32>();
4213 }
4215 i::DirectHandle<i::Object> string_obj;
4216 has_exception = !i::Object::ToString(i_isolate, self).ToHandle(&string_obj);
4218 auto str = i::Cast<i::String>(string_obj);
4219 uint32_t index;
4220 if (str->AsArrayIndex(&index)) {
4222 if (index <= static_cast<uint32_t>(i::Smi::kMaxValue)) {
4223 value = direct_handle(i::Smi::FromInt(index), i_isolate);
4224 } else {
4225 value = i_isolate->factory()->NewNumber(index);
4226 }
4227 RETURN_ESCAPED(Utils::Uint32ToLocal(value));
4228 }
4229 return Local<Uint32>();
4230}
4231
4233 i::Isolate* i_isolate = Utils::OpenDirectHandle(*context)->GetIsolate();
4234 ENTER_V8(i_isolate, context, Value, Equals, i::HandleScope);
4235 auto self = Utils::OpenDirectHandle(this);
4236 auto other = Utils::OpenDirectHandle(*that);
4237 Maybe<bool> result = i::Object::Equals(i_isolate, self, other);
4238 has_exception = result.IsNothing();
4240 return result;
4241}
4242
4244 auto self = Utils::OpenDirectHandle(this);
4245 auto other = Utils::OpenDirectHandle(*that);
4246 return i::Object::StrictEquals(*self, *other);
4247}
4248
4250 auto self = Utils::OpenDirectHandle(this);
4251 auto other = Utils::OpenDirectHandle(*that);
4252 return i::Object::SameValue(*self, *other);
4253}
4254
4256 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(external_isolate);
4258 API_RCS_SCOPE(i_isolate, Value, TypeOf);
4259 return Utils::ToLocal(
4260 i::Object::TypeOf(i_isolate, Utils::OpenDirectHandle(this)));
4261}
4262
4264 v8::Local<v8::Object> object) {
4265 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4266 ENTER_V8(i_isolate, context, Value, InstanceOf, i::HandleScope);
4268 if (!Utils::ApiCheck(
4270 "Value::InstanceOf",
4271 "Invalid type, must be a JS primitive or object.")) {
4272 return Nothing<bool>();
4273 }
4274 auto right = Utils::OpenDirectHandle(*object);
4276 has_exception =
4277 !i::Object::InstanceOf(i_isolate, left, right).ToHandle(&result);
4279 return Just(i::IsTrue(*result, i_isolate));
4280}
4281
4282uint32_t Value::GetHash() {
4284
4285 auto self = Utils::OpenDirectHandle(this);
4286 i::Tagged<i::Object> hash = i::Object::GetHash(*self);
4287 if (IsSmi(hash)) return i::Cast<i::Smi>(hash).value();
4288
4290 auto i_isolate = obj->GetIsolate();
4292 return obj->GetOrCreateIdentityHash(i_isolate).value();
4293}
4294
4297 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4298 ENTER_V8(i_isolate, context, Object, Set, i::HandleScope);
4299 auto self = Utils::OpenDirectHandle(this);
4300 auto key_obj = Utils::OpenDirectHandle(*key);
4301 auto value_obj = Utils::OpenDirectHandle(*value);
4302 has_exception =
4303 i::Runtime::SetObjectProperty(i_isolate, self, key_obj, value_obj,
4304 i::StoreOrigin::kMaybeKeyed,
4305 Just(i::ShouldThrow::kDontThrow))
4306 .is_null();
4308 return Just(true);
4309}
4310
4314 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4315 ENTER_V8(i_isolate, context, Object, Set, i::HandleScope);
4316 auto self = Utils::OpenDirectHandle(this);
4317 auto key_obj = Utils::OpenDirectHandle(*key);
4318 auto value_obj = Utils::OpenDirectHandle(*value);
4320 if (!receiver.IsEmpty()) {
4321 receiver_obj = Utils::OpenDirectHandle(*receiver.ToLocalChecked());
4322 }
4323 has_exception =
4324 i::Runtime::SetObjectProperty(i_isolate, self, key_obj, value_obj,
4325 receiver_obj, i::StoreOrigin::kMaybeKeyed,
4326 Just(i::ShouldThrow::kDontThrow))
4327 .is_null();
4329 return Just(true);
4330}
4331
4333 v8::Local<Value> value) {
4334 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4335 ENTER_V8(i_isolate, context, Object, Set, i::HandleScope);
4336 auto self = Utils::OpenDirectHandle(this);
4337 auto value_obj = Utils::OpenHandle(*value);
4338 has_exception = i::Object::SetElement(i_isolate, self, index, value_obj,
4339 i::ShouldThrow::kDontThrow)
4340 .is_null();
4342 return Just(true);
4343}
4344
4347 v8::Local<Value> value) {
4348 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4349 auto self = Utils::OpenDirectHandle(this);
4350 auto key_obj = Utils::OpenDirectHandle(*key);
4351 auto value_obj = Utils::OpenDirectHandle(*value);
4352
4353 i::PropertyKey lookup_key(i_isolate, key_obj);
4354 if (i::IsJSObject(*self)) {
4355 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, CreateDataProperty,
4357 Maybe<bool> result = i::JSObject::CreateDataProperty(
4358 i_isolate, i::Cast<i::JSObject>(self), lookup_key, value_obj,
4360 has_exception = result.IsNothing();
4362 return result;
4363 }
4364 // JSProxy or WasmObject or other non-JSObject.
4365 ENTER_V8(i_isolate, context, Object, CreateDataProperty, i::HandleScope);
4366 Maybe<bool> result = i::JSReceiver::CreateDataProperty(
4367 i_isolate, self, lookup_key, value_obj, Just(i::kDontThrow));
4368 has_exception = result.IsNothing();
4370 return result;
4371}
4372
4374 uint32_t index,
4375 v8::Local<Value> value) {
4376 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4377 auto self = Utils::OpenDirectHandle(this);
4378 auto value_obj = Utils::OpenDirectHandle(*value);
4379
4380 i::PropertyKey lookup_key(i_isolate, index);
4381 if (i::IsJSObject(*self)) {
4382 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, CreateDataProperty,
4384 Maybe<bool> result = i::JSObject::CreateDataProperty(
4385 i_isolate, i::Cast<i::JSObject>(self), lookup_key, value_obj,
4387 has_exception = result.IsNothing();
4389 return result;
4390 }
4391 // JSProxy or WasmObject or other non-JSObject.
4392 ENTER_V8(i_isolate, context, Object, CreateDataProperty, i::HandleScope);
4393 Maybe<bool> result = i::JSReceiver::CreateDataProperty(
4394 i_isolate, self, lookup_key, value_obj, Just(i::kDontThrow));
4395 has_exception = result.IsNothing();
4397 return result;
4398}
4399
4404
4406
4407// DataDescriptor
4409 : private_(new PrivateData()) {
4411 Cast<i::JSAny>(Utils::OpenDirectHandle(*value, true)));
4412}
4413
4414// DataDescriptor with writable field
4416 bool writable)
4417 : private_(new PrivateData()) {
4419 Cast<i::JSAny>(Utils::OpenDirectHandle(*value, true)));
4421}
4422
4423// AccessorDescriptor
4426 : private_(new PrivateData()) {
4427 DCHECK(get.IsEmpty() || get->IsUndefined() || get->IsFunction());
4428 DCHECK(set.IsEmpty() || set->IsUndefined() || set->IsFunction());
4429 private_->desc.set_get(Cast<i::JSAny>(Utils::OpenDirectHandle(*get, true)));
4430 private_->desc.set_set(Cast<i::JSAny>(Utils::OpenDirectHandle(*set, true)));
4431}
4432
4434
4436 DCHECK(private_->desc.has_value());
4437 return Utils::ToLocal(private_->desc.value());
4438}
4439
4441 DCHECK(private_->desc.has_get());
4442 return Utils::ToLocal(private_->desc.get());
4443}
4444
4446 DCHECK(private_->desc.has_set());
4447 return Utils::ToLocal(private_->desc.set());
4448}
4449
4451 return private_->desc.has_value();
4452}
4454 return private_->desc.has_get();
4455}
4457 return private_->desc.has_set();
4458}
4459
4461 DCHECK(private_->desc.has_writable());
4462 return private_->desc.writable();
4463}
4464
4466 return private_->desc.has_writable();
4467}
4468
4470 private_->desc.set_enumerable(enumerable);
4471}
4472
4474 DCHECK(private_->desc.has_enumerable());
4475 return private_->desc.enumerable();
4476}
4477
4479 return private_->desc.has_enumerable();
4480}
4481
4483 private_->desc.set_configurable(configurable);
4484}
4485
4487 DCHECK(private_->desc.has_configurable());
4488 return private_->desc.configurable();
4489}
4490
4492 return private_->desc.has_configurable();
4493}
4494
4497 v8::Local<Value> value,
4498 v8::PropertyAttribute attributes) {
4499 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4500 auto self = Utils::OpenDirectHandle(this);
4501 auto key_obj = Utils::OpenDirectHandle(*key);
4502 auto value_obj = Utils::OpenDirectHandle(*value);
4503
4505 desc.set_writable(!(attributes & v8::ReadOnly));
4506 desc.set_enumerable(!(attributes & v8::DontEnum));
4507 desc.set_configurable(!(attributes & v8::DontDelete));
4508 desc.set_value(i::Cast<i::JSAny>(value_obj));
4509
4510 if (i::IsJSObject(*self)) {
4511 // If it's not a JSProxy, i::JSReceiver::DefineOwnProperty should never run
4512 // a script.
4513 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, DefineOwnProperty,
4515 Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4516 i_isolate, self, key_obj, &desc, Just(i::kDontThrow));
4517 has_exception = success.IsNothing();
4519 return success;
4520 }
4521 // JSProxy or WasmObject or other non-JSObject.
4522 ENTER_V8(i_isolate, context, Object, DefineOwnProperty, i::HandleScope);
4523 Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4524 i_isolate, self, key_obj, &desc, Just(i::kDontThrow));
4525 // Even though we said kDontThrow, there might be accessors that do throw.
4526 has_exception = success.IsNothing();
4528 return success;
4529}
4530
4533 PropertyDescriptor& descriptor) {
4534 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4535 ENTER_V8(i_isolate, context, Object, DefineOwnProperty, i::HandleScope);
4536 auto self = Utils::OpenDirectHandle(this);
4537 auto key_obj = Utils::OpenDirectHandle(*key);
4538
4539 Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4540 i_isolate, self, key_obj, &descriptor.get_private()->desc,
4542 has_exception = success.IsNothing();
4544 return success;
4545}
4546
4548 Local<Value> value) {
4549 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4550 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, SetPrivate, i::HandleScope);
4551 auto self = Utils::OpenDirectHandle(this);
4552 auto key_obj = Utils::OpenDirectHandle(reinterpret_cast<Name*>(*key));
4553 auto value_obj = Utils::OpenDirectHandle(*value);
4554 if (i::IsJSObject(*self)) {
4555 auto js_object = i::Cast<i::JSObject>(self);
4556 i::LookupIterator it(i_isolate, js_object, key_obj, js_object);
4557 has_exception = i::JSObject::DefineOwnPropertyIgnoreAttributes(
4558 &it, value_obj, i::DONT_ENUM)
4559 .is_null();
4561 return Just(true);
4562 }
4563 if (i::IsJSProxy(*self)) {
4565 desc.set_writable(true);
4566 desc.set_enumerable(false);
4567 desc.set_configurable(true);
4568 desc.set_value(i::Cast<i::JSAny>(value_obj));
4569 return i::JSProxy::SetPrivateSymbol(i_isolate, i::Cast<i::JSProxy>(self),
4570 i::Cast<i::Symbol>(key_obj), &desc,
4572 }
4573 // Wasm object, or other kind of special object not supported here.
4574 return Just(false);
4575}
4576
4578 Local<Value> key) {
4579 PREPARE_FOR_EXECUTION(context, Object, Get);
4580 auto self = Utils::OpenDirectHandle(this);
4581 auto key_obj = Utils::OpenDirectHandle(*key);
4583 has_exception = !i::Runtime::GetObjectProperty(i_isolate, self, key_obj)
4584 .ToHandle(&result);
4586 RETURN_ESCAPED(Utils::ToLocal(result));
4587}
4588
4591 PREPARE_FOR_EXECUTION(context, Object, Get);
4592 auto self = Utils::OpenDirectHandle(this);
4593 auto key_obj = Utils::OpenDirectHandle(*key);
4594 i::DirectHandle<i::JSReceiver> receiver_obj;
4595 if (!receiver.IsEmpty()) {
4596 receiver_obj = Utils::OpenDirectHandle(*receiver.ToLocalChecked());
4597 }
4599 has_exception =
4600 !i::Runtime::GetObjectProperty(i_isolate, self, key_obj, receiver_obj)
4601 .ToHandle(&result);
4603 RETURN_ESCAPED(Utils::ToLocal(result));
4604}
4605
4607 PREPARE_FOR_EXECUTION(context, Object, Get);
4608 auto self = Utils::OpenDirectHandle(this);
4610 has_exception =
4611 !i::JSReceiver::GetElement(i_isolate, self, index).ToHandle(&result);
4613 RETURN_ESCAPED(Utils::ToLocal(result));
4614}
4615
4618 return Get(context, key.UnsafeAs<Value>());
4619}
4620
4622 Local<Context> context, Local<Value> key) {
4623 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4624 ENTER_V8(i_isolate, context, Object, GetPropertyAttributes, i::HandleScope);
4625 auto self = Utils::OpenDirectHandle(this);
4626 auto key_obj = Utils::OpenDirectHandle(*key);
4627 if (!i::IsName(*key_obj)) {
4628 has_exception = !i::Object::ToString(i_isolate, key_obj).ToHandle(&key_obj);
4630 }
4631 auto key_name = i::Cast<i::Name>(key_obj);
4632 auto result = i::JSReceiver::GetPropertyAttributes(i_isolate, self, key_name);
4633 has_exception = result.IsNothing();
4635 if (result.FromJust() == i::ABSENT) {
4636 return Just(static_cast<PropertyAttribute>(i::NONE));
4637 }
4638 return Just(static_cast<PropertyAttribute>(result.FromJust()));
4639}
4640
4642 Local<Name> key) {
4643 PREPARE_FOR_EXECUTION(context, Object, GetOwnPropertyDescriptor);
4644 auto obj = Utils::OpenDirectHandle(this);
4645 auto key_name = Utils::OpenDirectHandle(*key);
4646
4648 Maybe<bool> found =
4649 i::JSReceiver::GetOwnPropertyDescriptor(i_isolate, obj, key_name, &desc);
4650 has_exception = found.IsNothing();
4652 if (!found.FromJust()) {
4653 return v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
4654 }
4655 RETURN_ESCAPED(Utils::ToLocal(desc.ToObject(i_isolate)));
4656}
4657
4658Local<Value> v8::Object::GetPrototype() {
4659 auto self = Utils::OpenDirectHandle(this);
4660 auto i_isolate = self->GetIsolate();
4661 i::PrototypeIterator iter(i_isolate, self);
4662 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
4663}
4664
4666 auto self = Utils::OpenDirectHandle(this);
4667 auto i_isolate = self->GetIsolate();
4668 i::PrototypeIterator iter(i_isolate, self);
4669 if (i::IsJSGlobalProxy(*self)) {
4670 // Skip hidden prototype (i.e. JSGlobalObject).
4671 iter.Advance();
4672 }
4673 DCHECK(!i::IsJSGlobalObject(*i::PrototypeIterator::GetCurrent(iter)));
4674 return Utils::ToLocal(i::PrototypeIterator::GetCurrent(iter));
4675}
4676
4677namespace {
4678
4679Maybe<bool> SetPrototypeImpl(v8::Object* this_, Local<Context> context,
4680 Local<Value> value, bool from_javascript) {
4681 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4682 auto self = Utils::OpenDirectHandle(this_);
4683 auto value_obj = Utils::OpenDirectHandle(*value);
4684 // TODO(333672197): turn this to DCHECK once it's no longer possible
4685 // to get JSGlobalObject via API.
4686 CHECK_IMPLIES(from_javascript, !i::IsJSGlobalObject(*value_obj));
4687 if (i::IsJSObject(*self)) {
4689 // TODO(333672197): turn this to DCHECK once it's no longer possible
4690 // to get JSGlobalObject via API.
4691 CHECK_IMPLIES(from_javascript, !i::IsJSGlobalObject(*self));
4692 auto result =
4693 i::JSObject::SetPrototype(i_isolate, i::Cast<i::JSObject>(self),
4694 value_obj, from_javascript, i::kDontThrow);
4695 if (!result.FromJust()) return Nothing<bool>();
4696 return Just(true);
4697 }
4698 if (i::IsJSProxy(*self)) {
4699 ENTER_V8(i_isolate, context, Object, SetPrototype, i::HandleScope);
4700 // We do not allow exceptions thrown while setting the prototype
4701 // to propagate outside.
4702 TryCatch try_catch(reinterpret_cast<v8::Isolate*>(i_isolate));
4703 auto result =
4704 i::JSProxy::SetPrototype(i_isolate, i::Cast<i::JSProxy>(self),
4705 value_obj, from_javascript, i::kThrowOnError);
4706 has_exception = result.IsNothing();
4708 return Just(true);
4709 }
4710 // Wasm object or other kind of special object not supported here.
4711 return Nothing<bool>();
4712}
4713
4714} // namespace
4715
4716Maybe<bool> v8::Object::SetPrototype(Local<Context> context,
4717 Local<Value> value) {
4718 static constexpr bool from_javascript = false;
4719 return SetPrototypeImpl(this, context, value, from_javascript);
4720}
4721
4723 Local<Value> value) {
4724 static constexpr bool from_javascript = true;
4725 return SetPrototypeImpl(this, context, value, from_javascript);
4726}
4727
4730 auto self = Utils::OpenDirectHandle(this);
4731 auto i_isolate = self->GetIsolate();
4732 i::PrototypeIterator iter(i_isolate, *self, i::kStartAtReceiver);
4735 if (!IsJSObject(iter.GetCurrent())) return Local<Object>();
4736 while (!tmpl_info->IsTemplateFor(iter.GetCurrent<i::JSObject>())) {
4737 iter.Advance();
4738 if (iter.IsAtEnd()) return Local<Object>();
4739 if (!IsJSObject(iter.GetCurrent())) return Local<Object>();
4740 }
4741 // IsTemplateFor() ensures that iter.GetCurrent() can't be a Proxy here.
4742 return Utils::ToLocal(
4743 i::direct_handle(iter.GetCurrent<i::JSObject>(), i_isolate));
4744}
4745
4752
4754 Local<Context> context, KeyCollectionMode mode,
4755 PropertyFilter property_filter, IndexFilter index_filter,
4756 KeyConversionMode key_conversion) {
4757 PREPARE_FOR_EXECUTION(context, Object, GetPropertyNames);
4758 auto self = Utils::OpenDirectHandle(this);
4760 i::KeyAccumulator accumulator(
4761 i_isolate, static_cast<i::KeyCollectionMode>(mode),
4762 static_cast<i::PropertyFilter>(property_filter));
4763 accumulator.set_skip_indices(index_filter == IndexFilter::kSkipIndices);
4764 has_exception = accumulator.CollectKeys(self, self).IsNothing();
4766 value =
4767 accumulator.GetKeys(static_cast<i::GetKeysConversion>(key_conversion));
4768 DCHECK(self->map()->EnumLength() == i::kInvalidEnumCacheSentinel ||
4769 self->map()->EnumLength() == 0 ||
4770 self->map()->instance_descriptors(i_isolate)->enum_cache()->keys() !=
4771 *value);
4772 auto result = i_isolate->factory()->NewJSArrayWithElements(value);
4773 RETURN_ESCAPED(Utils::ToLocal(result));
4774}
4775
4777 return GetOwnPropertyNames(
4778 context, static_cast<v8::PropertyFilter>(ONLY_ENUMERABLE | SKIP_SYMBOLS));
4779}
4780
4782 Local<Context> context, PropertyFilter filter,
4783 KeyConversionMode key_conversion) {
4784 return GetPropertyNames(context, KeyCollectionMode::kOwnOnly, filter,
4785 v8::IndexFilter::kIncludeIndices, key_conversion);
4786}
4787
4789 PREPARE_FOR_EXECUTION(context, Object, ObjectProtoToString);
4790 auto self = Utils::OpenDirectHandle(this);
4792 has_exception =
4793 !ToLocal<Value>(i::Execution::CallBuiltin(
4794 i_isolate, i_isolate->object_to_string(), self, {}),
4795 &result);
4798}
4799
4801 // TODO(v8:12547): Consider adding GetConstructorName(Local<Context>).
4802 auto self = Utils::OpenDirectHandle(this);
4803 i::Isolate* i_isolate;
4804 if (i::HeapLayout::InWritableSharedSpace(*self)) {
4805 i_isolate = i::Isolate::Current();
4806 } else {
4807 i_isolate = self->GetIsolate();
4808 }
4810 i::JSReceiver::GetConstructorName(i_isolate, self);
4811 return Utils::ToLocal(name);
4812}
4813
4815 IntegrityLevel level) {
4816 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4817 ENTER_V8(i_isolate, context, Object, SetIntegrityLevel, i::HandleScope);
4818 auto self = Utils::OpenDirectHandle(this);
4819 i::JSReceiver::IntegrityLevel i_level =
4821 Maybe<bool> result = i::JSReceiver::SetIntegrityLevel(
4822 i_isolate, self, i_level, i::kThrowOnError);
4823 has_exception = result.IsNothing();
4825 return result;
4826}
4827
4829 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4830 auto self = Utils::OpenDirectHandle(this);
4831 auto key_obj = Utils::OpenDirectHandle(*key);
4832 if (i::IsJSProxy(*self)) {
4833 ENTER_V8(i_isolate, context, Object, Delete, i::HandleScope);
4834 Maybe<bool> result = i::Runtime::DeleteObjectProperty(
4835 i_isolate, self, key_obj, i::LanguageMode::kSloppy);
4836 has_exception = result.IsNothing();
4838 return result;
4839 } else {
4840 // If it's not a JSProxy, i::Runtime::DeleteObjectProperty should never run
4841 // a script.
4842 DCHECK(i::IsJSObject(*self) || i::IsWasmObject(*self));
4843 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, Delete, i::HandleScope);
4844 Maybe<bool> result = i::Runtime::DeleteObjectProperty(
4845 i_isolate, self, key_obj, i::LanguageMode::kSloppy);
4846 has_exception = result.IsNothing();
4848 return result;
4849 }
4850}
4851
4854 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4855 // In case of private symbols, i::Runtime::DeleteObjectProperty does not run
4856 // any author script.
4857 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, Delete, i::HandleScope);
4858 auto self = Utils::OpenDirectHandle(this);
4859 auto key_obj = Utils::OpenDirectHandle(*key);
4860 Maybe<bool> result = i::Runtime::DeleteObjectProperty(
4861 i_isolate, self, key_obj, i::LanguageMode::kSloppy);
4862 has_exception = result.IsNothing();
4864 return result;
4865}
4866
4868 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4869 ENTER_V8(i_isolate, context, Object, Has, i::HandleScope);
4870 auto self = Utils::OpenDirectHandle(this);
4871 auto key_obj = Utils::OpenDirectHandle(*key);
4872 Maybe<bool> maybe = Nothing<bool>();
4873 // Check if the given key is an array index.
4874 uint32_t index = 0;
4875 if (i::Object::ToArrayIndex(*key_obj, &index)) {
4876 maybe = i::JSReceiver::HasElement(i_isolate, self, index);
4877 } else {
4878 // Convert the key to a name - possibly by calling back into JavaScript.
4880 if (i::Object::ToName(i_isolate, key_obj).ToHandle(&name)) {
4881 maybe = i::JSReceiver::HasProperty(i_isolate, self, name);
4882 }
4883 }
4884 has_exception = maybe.IsNothing();
4886 return maybe;
4887}
4888
4890 return HasOwnProperty(context, key.UnsafeAs<Name>());
4891}
4892
4894 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4895 ENTER_V8(i_isolate, context, Object, Delete, i::HandleScope);
4896 auto self = Utils::OpenDirectHandle(this);
4897 Maybe<bool> result = i::JSReceiver::DeleteElement(i_isolate, self, index);
4898 has_exception = result.IsNothing();
4900 return result;
4901}
4902
4904 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4905 ENTER_V8(i_isolate, context, Object, Has, i::HandleScope);
4906 auto self = Utils::OpenDirectHandle(this);
4907 auto maybe = i::JSReceiver::HasElement(i_isolate, self, index);
4908 has_exception = maybe.IsNothing();
4910 return maybe;
4911}
4912
4913template <typename Getter, typename Setter, typename Data>
4915 Local<Name> name, Getter getter,
4916 Setter setter, Data data,
4917 PropertyAttribute attributes,
4918 bool replace_on_access,
4919 SideEffectType getter_side_effect_type,
4920 SideEffectType setter_side_effect_type) {
4921 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4922 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, SetAccessor, i::HandleScope);
4923 if (!IsJSObject(*Utils::OpenDirectHandle(self))) return Just(false);
4924 auto obj = i::Cast<i::JSObject>(Utils::OpenHandle(self));
4925 i::DirectHandle<i::AccessorInfo> info = MakeAccessorInfo(
4926 i_isolate, name, getter, setter, data, replace_on_access);
4927 info->set_getter_side_effect_type(getter_side_effect_type);
4928 info->set_setter_side_effect_type(setter_side_effect_type);
4929 if (info.is_null()) return Nothing<bool>();
4930 bool fast = obj->HasFastProperties();
4932
4933 i::DirectHandle<i::Name> accessor_name(info->name(), i_isolate);
4934 i::PropertyAttributes attrs = static_cast<i::PropertyAttributes>(attributes);
4935 has_exception = !i::JSObject::SetAccessor(obj, accessor_name, info, attrs)
4936 .ToHandle(&result);
4938 if (i::IsUndefined(*result, i_isolate)) return Just(false);
4939 if (fast) {
4940 i::JSObject::MigrateSlowToFast(obj, 0, "APISetAccessor");
4941 }
4942 return Just(true);
4943}
4944
4947 PropertyAttribute attributes) {
4948 auto self = Utils::OpenDirectHandle(this);
4949 i::Isolate* i_isolate = self->GetIsolate();
4951 i::HandleScope scope(i_isolate);
4952 if (!IsJSObject(*self)) return;
4955 i::DirectHandle<i::JSAny> setter_i =
4957 if (setter_i.is_null()) setter_i = i_isolate->factory()->null_value();
4958
4960 desc.set_enumerable(!(attributes & v8::DontEnum));
4961 desc.set_configurable(!(attributes & v8::DontDelete));
4962 desc.set_get(getter_i);
4963 desc.set_set(setter_i);
4964
4965 auto name_i = v8::Utils::OpenDirectHandle(*name);
4966 // DefineOwnProperty might still throw if the receiver is a JSProxy and it
4967 // might fail if the receiver is non-extensible or already has this property
4968 // as non-configurable.
4969 Maybe<bool> success = i::JSReceiver::DefineOwnProperty(
4970 i_isolate, self, name_i, &desc, Just(i::kDontThrow));
4971 USE(success);
4972}
4973
4977 v8::Local<Value> data, PropertyAttribute attributes,
4978 SideEffectType getter_side_effect_type,
4979 SideEffectType setter_side_effect_type) {
4980 return ObjectSetAccessor(context, this, name, getter, setter, data,
4981 attributes, false, getter_side_effect_type,
4982 setter_side_effect_type);
4983}
4984
4988 PropertyAttribute attributes, SideEffectType getter_side_effect_type,
4989 SideEffectType setter_side_effect_type) {
4990 return ObjectSetAccessor(context, this, name, getter,
4991 static_cast<AccessorNameSetterCallback>(nullptr),
4992 data, attributes, true, getter_side_effect_type,
4993 setter_side_effect_type);
4994}
4995
4997 Local<Name> key) {
4998 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
4999 ENTER_V8(i_isolate, context, Object, HasOwnProperty, i::HandleScope);
5000 auto self = Utils::OpenDirectHandle(this);
5001 auto key_val = Utils::OpenDirectHandle(*key);
5002 auto result = i::JSReceiver::HasOwnProperty(i_isolate, self, key_val);
5003 has_exception = result.IsNothing();
5005 return result;
5006}
5007
5009 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5010 ENTER_V8(i_isolate, context, Object, HasOwnProperty, i::HandleScope);
5011 auto self = Utils::OpenDirectHandle(this);
5012 auto result = i::JSReceiver::HasOwnProperty(i_isolate, self, index);
5013 has_exception = result.IsNothing();
5015 return result;
5016}
5017
5019 Local<Name> key) {
5020 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5021 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, HasRealNamedProperty,
5023 auto self = Utils::OpenDirectHandle(this);
5024 if (!IsJSObject(*self)) return Just(false);
5025 auto key_val = Utils::OpenDirectHandle(*key);
5026 auto result = i::JSObject::HasRealNamedProperty(
5027 i_isolate, i::Cast<i::JSObject>(self), key_val);
5028 has_exception = result.IsNothing();
5030 return result;
5031}
5032
5034 uint32_t index) {
5035 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5036 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, HasRealIndexedProperty,
5038 auto self = Utils::OpenDirectHandle(this);
5039 if (!IsJSObject(*self)) return Just(false);
5040 auto result = i::JSObject::HasRealElementProperty(
5041 i_isolate, i::Cast<i::JSObject>(self), index);
5042 has_exception = result.IsNothing();
5044 return result;
5045}
5046
5048 Local<Name> key) {
5049 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5050 ENTER_V8_NO_SCRIPT(i_isolate, context, Object, HasRealNamedCallbackProperty,
5052 auto self = Utils::OpenDirectHandle(this);
5053 if (!IsJSObject(*self)) return Just(false);
5054 auto key_val = Utils::OpenDirectHandle(*key);
5055 auto result = i::JSObject::HasRealNamedCallbackProperty(
5056 i_isolate, i::Cast<i::JSObject>(self), key_val);
5057 has_exception = result.IsNothing();
5059 return result;
5060}
5061
5063 auto self = *Utils::OpenDirectHandle(this);
5064 if (!IsJSObject(*self)) return false;
5065 return i::Cast<i::JSObject>(self)->HasNamedInterceptor();
5066}
5067
5069 auto self = *Utils::OpenDirectHandle(this);
5070 if (!IsJSObject(*self)) return false;
5071 return i::Cast<i::JSObject>(self)->HasIndexedInterceptor();
5072}
5073
5075 Local<Context> context, Local<Name> key) {
5076 PREPARE_FOR_EXECUTION(context, Object, GetRealNamedPropertyInPrototypeChain);
5077 auto self = Utils::OpenDirectHandle(this);
5078 if (!IsJSObject(*self)) return MaybeLocal<Value>();
5079 auto key_obj = Utils::OpenDirectHandle(*key);
5080 i::PrototypeIterator iter(i_isolate, self);
5081 if (iter.IsAtEnd()) return MaybeLocal<Value>();
5083 i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
5084 i::PropertyKey lookup_key(i_isolate, key_obj);
5085 i::LookupIterator it(i_isolate, self, lookup_key, proto,
5086 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
5088 has_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
5090 if (!it.IsFound()) return MaybeLocal<Value>();
5092}
5093
5096 Local<Context> context, Local<Name> key) {
5097 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5098 ENTER_V8(i_isolate, context, Object,
5099 GetRealNamedPropertyAttributesInPrototypeChain, i::HandleScope);
5100 auto self = Utils::OpenDirectHandle(this);
5101 if (!IsJSObject(*self)) return Nothing<PropertyAttribute>();
5102 auto key_obj = Utils::OpenDirectHandle(*key);
5103 i::PrototypeIterator iter(i_isolate, self);
5104 if (iter.IsAtEnd()) return Nothing<PropertyAttribute>();
5106 i::PrototypeIterator::GetCurrent<i::JSReceiver>(iter);
5107 i::PropertyKey lookup_key(i_isolate, key_obj);
5108 i::LookupIterator it(i_isolate, self, lookup_key, proto,
5109 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
5111 i::JSReceiver::GetPropertyAttributes(&it);
5112 has_exception = result.IsNothing();
5114 if (!it.IsFound()) return Nothing<PropertyAttribute>();
5115 if (result.FromJust() == i::ABSENT) return Just(None);
5116 return Just(static_cast<PropertyAttribute>(result.FromJust()));
5117}
5118
5120 Local<Name> key) {
5121 PREPARE_FOR_EXECUTION(context, Object, GetRealNamedProperty);
5122 auto self = Utils::OpenDirectHandle(this);
5123 auto key_obj = Utils::OpenDirectHandle(*key);
5124 i::PropertyKey lookup_key(i_isolate, key_obj);
5125 i::LookupIterator it(i_isolate, self, lookup_key, self,
5126 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
5128 has_exception = !ToLocal<Value>(i::Object::GetProperty(&it), &result);
5130 if (!it.IsFound()) return MaybeLocal<Value>();
5132}
5133
5135 Local<Context> context, Local<Name> key) {
5136 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5137 ENTER_V8(i_isolate, context, Object, GetRealNamedPropertyAttributes,
5139 auto self = Utils::OpenDirectHandle(this);
5140 auto key_obj = Utils::OpenDirectHandle(*key);
5141 i::PropertyKey lookup_key(i_isolate, key_obj);
5142 i::LookupIterator it(i_isolate, self, lookup_key, self,
5143 i::LookupIterator::PROTOTYPE_CHAIN_SKIP_INTERCEPTOR);
5144 auto result = i::JSReceiver::GetPropertyAttributes(&it);
5145 has_exception = result.IsNothing();
5147 if (!it.IsFound()) return Nothing<PropertyAttribute>();
5148 if (result.FromJust() == i::ABSENT) {
5149 return Just(static_cast<PropertyAttribute>(i::NONE));
5150 }
5152 static_cast<PropertyAttribute>(result.FromJust()));
5153}
5154
5157 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5160 i_isolate->factory()->CopyJSObject(self);
5161 return Utils::ToLocal(result);
5162}
5163
5166 return Clone(reinterpret_cast<v8::Isolate*>(self->GetIsolate()));
5167}
5168
5169namespace {
5170V8_INLINE MaybeLocal<v8::Context> GetCreationContextImpl(
5171 i::DirectHandle<i::JSReceiver> object, i::Isolate* i_isolate) {
5173 if (object->GetCreationContext(i_isolate).ToHandle(&context)) {
5174 return Utils::ToLocal(context);
5175 }
5176 return MaybeLocal<v8::Context>();
5177}
5178} // namespace
5179
5181 auto self = Utils::OpenDirectHandle(this);
5182 auto i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5183 return GetCreationContextImpl(self, i_isolate);
5184}
5185
5187 auto self = Utils::OpenDirectHandle(this);
5188 return GetCreationContextImpl(self, i::Isolate::Current());
5189}
5190
5192 const PersistentBase<Object>& object) {
5193 return object.template value<Object>()->GetCreationContext(
5195}
5196
5197namespace {
5198V8_INLINE Local<v8::Context> GetCreationContextCheckedImpl(
5199 i::DirectHandle<i::JSReceiver> object, i::Isolate* i_isolate) {
5201 Utils::ApiCheck(object->GetCreationContext(i_isolate).ToHandle(&context),
5202 "v8::Object::GetCreationContextChecked",
5203 "No creation context available");
5204 return Utils::ToLocal(context);
5205}
5206} // namespace
5207
5209 auto self = Utils::OpenDirectHandle(this);
5210 auto i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5211 return GetCreationContextCheckedImpl(self, i_isolate);
5212}
5213
5215 auto self = Utils::OpenDirectHandle(this);
5216 return GetCreationContextCheckedImpl(self, i::Isolate::Current());
5217}
5218
5219namespace {
5220V8_INLINE void* GetAlignedPointerFromEmbedderDataInCreationContextImpl(
5222 i::IsolateForSandbox i_isolate_for_sandbox, int index) {
5223 const char* location =
5224 "v8::Object::GetAlignedPointerFromEmbedderDataInCreationContext()";
5225 auto maybe_context = object->GetCreationContext();
5226 if (!maybe_context.has_value()) return nullptr;
5227
5228 // The code below mostly mimics Context::GetAlignedPointerFromEmbedderData()
5229 // but it doesn't try to expand the EmbedderDataArray instance.
5231 i::Tagged<i::NativeContext> native_context = maybe_context.value();
5232
5233 // This macro requires a real Isolate while |i_isolate_for_sandbox| might be
5234 // nullptr if the V8 sandbox is not enabled.
5235 DCHECK_NO_SCRIPT_NO_EXCEPTION(native_context->GetIsolate());
5236
5237 // TODO(ishell): remove cast once embedder_data slot has a proper type.
5239 i::Cast<i::EmbedderDataArray>(native_context->embedder_data());
5240 if (V8_LIKELY(static_cast<unsigned>(index) <
5241 static_cast<unsigned>(data->length()))) {
5242 void* result;
5244 .ToAlignedPointer(i_isolate_for_sandbox, &result),
5245 location, "Pointer is not aligned");
5246 return result;
5247 }
5248 // Bad index, report an API error.
5249 Utils::ApiCheck(index >= 0, location, "Negative index");
5250 Utils::ApiCheck(index < i::EmbedderDataArray::kMaxLength, location,
5251 "Index too large");
5252 return nullptr;
5253}
5254} // namespace
5255
5257 v8::Isolate* isolate, int index) {
5258 auto self = Utils::OpenDirectHandle(this);
5259 auto i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5260 return GetAlignedPointerFromEmbedderDataInCreationContextImpl(self, i_isolate,
5261 index);
5262}
5263
5265 int index) {
5266 auto self = Utils::OpenDirectHandle(this);
5267 i::IsolateForSandbox isolate = GetIsolateForSandbox(*self);
5268 return GetAlignedPointerFromEmbedderDataInCreationContextImpl(self, isolate,
5269 index);
5270}
5271
5274 auto self = Utils::OpenDirectHandle(this);
5275 auto i_isolate = self->GetIsolate();
5277 return self->GetOrCreateIdentityHash(i_isolate).value();
5278}
5279
5281 return i::IsCallable(*Utils::OpenDirectHandle(this));
5282}
5283
5285 return i::IsConstructor(*Utils::OpenDirectHandle(this));
5286}
5287
5289 auto self = Utils::OpenDirectHandle(this);
5290 // This checks whether an object of a given instance type can serve as API
5291 // object. It does not check whether the JS object is wrapped via embedder
5292 // fields or Wrap()/Unwrap() API.
5293 return IsJSApiWrapperObject(*self);
5294}
5295
5297 auto self = Utils::OpenDirectHandle(this);
5298 return i::IsUndetectable(*self);
5299}
5300
5301namespace {
5302base::Vector<i::DirectHandle<i::Object>> PrepareArguments(int argc,
5303 Local<Value> argv[]) {
5304 static_assert(sizeof(v8::Local<v8::Value>) ==
5306 return {reinterpret_cast<i::DirectHandle<i::Object>*>(argv),
5307 static_cast<size_t>(argc)};
5308}
5309} // namespace
5310
5312 Local<Value> recv, int argc,
5313 Local<Value> argv[]) {
5314 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5315 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.Execute");
5317 i::TimerEventScope<i::TimerEventExecute> timer_scope(i_isolate);
5318 i::NestedTimedHistogramScope execute_timer(i_isolate->counters()->execute(),
5319 i_isolate);
5320 auto self = Utils::OpenDirectHandle(this);
5321 auto recv_obj = Utils::OpenDirectHandle(*recv);
5322 auto args = PrepareArguments(argc, argv);
5324 has_exception = !ToLocal<Value>(
5325 i::Execution::Call(i_isolate, self, recv_obj, args), &result);
5328}
5329
5331 Local<Value> argv[]) {
5332 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5333 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.Execute");
5334 ENTER_V8(i_isolate, context, Object, CallAsConstructor,
5336 i::TimerEventScope<i::TimerEventExecute> timer_scope(i_isolate);
5337 i::NestedTimedHistogramScope execute_timer(i_isolate->counters()->execute(),
5338 i_isolate);
5339 auto self = Utils::OpenDirectHandle(this);
5340 auto args = PrepareArguments(argc, argv);
5342 has_exception =
5343 !ToLocal<Value>(i::Execution::New(i_isolate, self, self, args), &result);
5346}
5347
5350 int length, ConstructorBehavior behavior,
5351 SideEffectType side_effect_type) {
5352 i::Isolate* i_isolate = Utils::OpenDirectHandle(*context)->GetIsolate();
5353 API_RCS_SCOPE(i_isolate, Function, New);
5355 auto templ =
5356 FunctionTemplateNew(i_isolate, callback, data, Local<Signature>(), length,
5357 behavior, true, Local<Private>(), side_effect_type);
5358 return Utils::ToLocal(templ)->GetFunction(context);
5359}
5360
5362 v8::Local<v8::Value> argv[]) const {
5363 return NewInstanceWithSideEffectType(context, argc, argv,
5365}
5366
5368 Local<Context> context, int argc, v8::Local<v8::Value> argv[],
5369 SideEffectType side_effect_type) const {
5370 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
5371 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.Execute");
5372 ENTER_V8(i_isolate, context, Function, NewInstance, InternalEscapableScope);
5373 i::TimerEventScope<i::TimerEventExecute> timer_scope(i_isolate);
5374 i::NestedTimedHistogramScope execute_timer(i_isolate->counters()->execute(),
5375 i_isolate);
5376 auto self = Utils::OpenDirectHandle(this);
5377 bool should_set_has_no_side_effect =
5378 side_effect_type == SideEffectType::kHasNoSideEffect &&
5379 i_isolate->should_check_side_effects();
5380 if (should_set_has_no_side_effect) {
5381 CHECK(IsJSFunction(*self) &&
5382 i::Cast<i::JSFunction>(*self)->shared()->IsApiFunction());
5384 i::Cast<i::JSFunction>(*self)->shared()->api_func_data();
5385 if (func_data->has_callback(i_isolate)) {
5386 if (func_data->has_side_effects()) {
5388 handle(func_data, i_isolate));
5389 }
5390 }
5391 }
5392 auto args = PrepareArguments(argc, argv);
5394 has_exception =
5395 !ToLocal<Object>(i::Execution::New(i_isolate, self, self, args), &result);
5398}
5399
5401 Local<Context> context,
5402 v8::Local<v8::Value> recv, int argc,
5403 v8::Local<v8::Value> argv[]) {
5404 auto i_isolate = reinterpret_cast<i::Isolate*>(isolate);
5405 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.Execute");
5406 ENTER_V8(i_isolate, context, Function, Call, InternalEscapableScope);
5407 i::TimerEventScope<i::TimerEventExecute> timer_scope(i_isolate);
5408 i::NestedTimedHistogramScope execute_timer(i_isolate->counters()->execute(),
5409 i_isolate);
5410 auto self = Utils::OpenDirectHandle(this);
5411 Utils::ApiCheck(!self.is_null(), "v8::Function::Call",
5412 "Function to be called is a null pointer");
5413 auto recv_obj = Utils::OpenDirectHandle(*recv);
5414 auto args = PrepareArguments(argc, argv);
5416 has_exception = !ToLocal<Value>(
5417 i::Execution::Call(i_isolate, self, recv_obj, args), &result);
5420}
5421
5423 v8::Local<v8::Value> recv, int argc,
5424 v8::Local<v8::Value> argv[]) {
5425 return Call(context->GetIsolate(), context, recv, argc, argv);
5426}
5427
5429 auto self = Utils::OpenDirectHandle(this);
5430 if (!IsJSFunction(*self)) return;
5431 auto func = i::Cast<i::JSFunction>(self);
5432 DCHECK_NO_SCRIPT_NO_EXCEPTION(func->GetIsolate());
5433 func->shared()->SetName(*Utils::OpenDirectHandle(*name));
5434}
5435
5437 auto self = Utils::OpenDirectHandle(this);
5438 i::Isolate* i_isolate = self->GetIsolate();
5439 if (i::IsJSBoundFunction(*self)) {
5440 auto func = i::Cast<i::JSBoundFunction>(self);
5443 i_isolate, name, i::JSBoundFunction::GetName(i_isolate, func),
5444 Local<Value>());
5445 return Utils::ToLocal(name);
5446 }
5447 if (i::IsJSFunction(*self)) {
5448 auto func = i::Cast<i::JSFunction>(self);
5449 return Utils::ToLocal(i::direct_handle(func->shared()->Name(), i_isolate));
5450 }
5451 return ToApiHandle<Primitive>(i_isolate->factory()->undefined_value());
5452}
5453
5455 auto self = Utils::OpenDirectHandle(this);
5456 if (!IsJSFunction(*self)) {
5458 self->GetIsolate()->factory()->undefined_value());
5459 }
5460 auto func = i::Cast<i::JSFunction>(self);
5461 i::Isolate* isolate = func->GetIsolate();
5462 return Utils::ToLocal(
5463 i::direct_handle(func->shared()->inferred_name(), isolate));
5464}
5465
5467 auto self = Utils::OpenDirectHandle(this);
5468 i::Isolate* i_isolate = self->GetIsolate();
5469 if (!IsJSFunction(*self)) {
5470 return ToApiHandle<Primitive>(i_isolate->factory()->undefined_value());
5471 }
5472 auto func = i::Cast<i::JSFunction>(self);
5473 i::DirectHandle<i::String> name = i::JSFunction::GetDebugName(func);
5474 return Utils::ToLocal(i::direct_handle(*name, i_isolate));
5475}
5476
5478 auto self = Utils::OpenDirectHandle(this);
5479 if (!IsJSFunction(*self)) return v8::ScriptOrigin(Local<Value>());
5480 auto func = i::Cast<i::JSFunction>(self);
5481 auto shared = func->shared();
5482 if (i::IsScript(shared->script())) {
5483 i::DirectHandle<i::Script> script(i::Cast<i::Script>(shared->script()),
5484 func->GetIsolate());
5485 return GetScriptOriginForScript(func->GetIsolate(), script);
5486 }
5488}
5489
5490const int Function::kLineOffsetNotFound = -1;
5491
5493 auto self = *Utils::OpenDirectHandle(this);
5494 if (!IsJSFunction(self)) {
5495 return kLineOffsetNotFound;
5496 }
5497 auto func = i::Cast<i::JSFunction>(self);
5498 auto shared = func->shared();
5499 if (i::IsScript(shared->script())) {
5500 i::DirectHandle<i::Script> script(i::Cast<i::Script>(shared->script()),
5501 func->GetIsolate());
5502 return i::Script::GetLineNumber(script, shared->StartPosition());
5503 }
5504 return kLineOffsetNotFound;
5505}
5506
5508 auto self = *Utils::OpenDirectHandle(this);
5509 if (!IsJSFunction(self)) {
5510 return kLineOffsetNotFound;
5511 }
5512 auto func = i::Cast<i::JSFunction>(self);
5513 auto shared = func->shared();
5514 if (i::IsScript(shared->script())) {
5515 i::DirectHandle<i::Script> script(i::Cast<i::Script>(shared->script()),
5516 func->GetIsolate());
5517 return i::Script::GetColumnNumber(script, shared->StartPosition());
5518 }
5519 return kLineOffsetNotFound;
5520}
5521
5523 auto self = *Utils::OpenDirectHandle(this);
5524 if (!IsJSFunction(self)) {
5525 return {-1, -1};
5526 }
5527 auto func = i::Cast<i::JSFunction>(self);
5528 auto shared = func->shared();
5529 if (i::IsScript(shared->script())) {
5530 i::DirectHandle<i::Script> script(i::Cast<i::Script>(shared->script()),
5531 func->GetIsolate());
5532 return {i::Script::GetLineNumber(script, shared->StartPosition()),
5533 i::Script::GetColumnNumber(script, shared->StartPosition())};
5534 }
5535 return {-1, -1};
5536}
5537
5539 auto self = *Utils::OpenDirectHandle(this);
5540 if (!IsJSFunction(self)) {
5541 return kLineOffsetNotFound;
5542 }
5543 auto func = i::Cast<i::JSFunction>(self);
5544 auto shared = func->shared();
5545 if (i::IsScript(shared->script())) {
5546 return shared->StartPosition();
5547 }
5548 return kLineOffsetNotFound;
5549}
5550
5552 auto self = *Utils::OpenDirectHandle(this);
5553 if (!IsJSFunction(self)) return v8::UnboundScript::kNoScriptId;
5554 auto func = i::Cast<i::JSFunction>(self);
5555 auto script = func->shared()->script();
5556 if (!IsScript(script)) return v8::UnboundScript::kNoScriptId;
5557 return i::Cast<i::Script>(script)->id();
5558}
5559
5561 auto self = Utils::OpenDirectHandle(this);
5562 if (i::IsJSBoundFunction(*self)) {
5563 auto bound_function = i::Cast<i::JSBoundFunction>(self);
5564 auto bound_target_function = i::direct_handle(
5565 bound_function->bound_target_function(), bound_function->GetIsolate());
5566 return Utils::CallableToLocal(bound_target_function);
5567 }
5568 return v8::Undefined(reinterpret_cast<v8::Isolate*>(self->GetIsolate()));
5569}
5570
5572 auto self = Utils::OpenDirectHandle(this);
5573 if (!IsJSFunction(*self)) return false;
5574 auto sfi = i::Cast<i::JSFunction>(*self)->shared();
5575 i::Isolate* i_isolate = self->GetIsolate();
5576 i::IsCompiledScope is_compiled_scope(sfi->is_compiled_scope(i_isolate));
5577 if (!is_compiled_scope.is_compiled() &&
5578 !i::Compiler::Compile(i_isolate, i::handle(sfi, i_isolate),
5579 i::Compiler::CLEAR_EXCEPTION, &is_compiled_scope)) {
5580 return false;
5581 }
5582 DCHECK(is_compiled_scope.is_compiled());
5583 // Since |sfi| can be GC'ed, we get it again.
5584 sfi = i::Cast<i::JSFunction>(*self)->shared();
5585 if (!sfi->HasBytecodeArray()) return false;
5586 i::Handle<i::BytecodeArray> bytecode_array(sfi->GetBytecodeArray(i_isolate),
5587 i_isolate);
5588 i::interpreter::BytecodeArrayIterator it(bytecode_array, 0);
5589 if (it.current_bytecode() != i::interpreter::Bytecode::kLdaUndefined) {
5590 return false;
5591 }
5592 it.Advance();
5593 DCHECK(!it.done());
5594 if (it.current_bytecode() != i::interpreter::Bytecode::kReturn) return false;
5595 it.Advance();
5596 DCHECK(it.done());
5597 return true;
5598}
5599
5601 PREPARE_FOR_EXECUTION(context, Function, FunctionProtoToString);
5602 auto self = Utils::OpenDirectHandle(this);
5604 has_exception =
5605 !ToLocal<Value>(i::Execution::CallBuiltin(
5606 i_isolate, i_isolate->function_to_string(), self, {}),
5607 &result);
5610}
5611
5613 return static_cast<int>(Utils::OpenDirectHandle(this)->EnsureHash());
5614}
5615
5616int String::Length() const {
5617 return static_cast<int>(Utils::OpenDirectHandle(this)->length());
5618}
5619
5620bool String::IsOneByte() const {
5621 return Utils::OpenDirectHandle(this)->IsOneByteRepresentation();
5622}
5623
5624// Helpers for ContainsOnlyOneByteHelper
5625template <size_t size>
5627template <>
5628struct OneByteMask<4> {
5629 static const uint32_t value = 0xFF00FF00;
5630};
5631template <>
5632struct OneByteMask<8> {
5633 static const uint64_t value = 0xFF00'FF00'FF00'FF00;
5634};
5635static const uintptr_t kOneByteMask = OneByteMask<sizeof(uintptr_t)>::value;
5636static const uintptr_t kAlignmentMask = sizeof(uintptr_t) - 1;
5637static inline bool Unaligned(const uint16_t* chars) {
5638 return reinterpret_cast<const uintptr_t>(chars) & kAlignmentMask;
5639}
5640
5641static inline const uint16_t* Align(const uint16_t* chars) {
5642 return reinterpret_cast<uint16_t*>(reinterpret_cast<uintptr_t>(chars) &
5643 ~kAlignmentMask);
5644}
5645
5647 public:
5651 delete;
5653 i::Tagged<i::ConsString> cons_string =
5654 i::String::VisitFlat(this, string, 0);
5655 if (cons_string.is_null()) return is_one_byte_;
5656 return CheckCons(cons_string);
5657 }
5658 void VisitOneByteString(const uint8_t* chars, int length) {
5659 // Nothing to do.
5660 }
5661 void VisitTwoByteString(const uint16_t* chars, int length) {
5662 // Accumulated bits.
5663 uintptr_t acc = 0;
5664 // Align to uintptr_t.
5665 const uint16_t* end = chars + length;
5666 while (Unaligned(chars) && chars != end) {
5667 acc |= *chars++;
5668 }
5669 // Read word aligned in blocks,
5670 // checking the return value at the end of each block.
5671 const uint16_t* aligned_end = Align(end);
5672 const int increment = sizeof(uintptr_t) / sizeof(uint16_t);
5673 const int inner_loops = 16;
5674 while (chars + inner_loops * increment < aligned_end) {
5675 for (int i = 0; i < inner_loops; i++) {
5676 acc |= *reinterpret_cast<const uintptr_t*>(chars);
5677 chars += increment;
5678 }
5679 // Check for early return.
5680 if ((acc & kOneByteMask) != 0) {
5681 is_one_byte_ = false;
5682 return;
5683 }
5684 }
5685 // Read the rest.
5686 while (chars != end) {
5687 acc |= *chars++;
5688 }
5689 // Check result.
5690 if ((acc & kOneByteMask) != 0) is_one_byte_ = false;
5691 }
5692
5693 private:
5695 while (true) {
5696 // Check left side if flat.
5697 i::Tagged<i::String> left = cons_string->first();
5698 i::Tagged<i::ConsString> left_as_cons =
5699 i::String::VisitFlat(this, left, 0);
5700 if (!is_one_byte_) return false;
5701 // Check right side if flat.
5702 i::Tagged<i::String> right = cons_string->second();
5703 i::Tagged<i::ConsString> right_as_cons =
5704 i::String::VisitFlat(this, right, 0);
5705 if (!is_one_byte_) return false;
5706 // Standard recurse/iterate trick.
5707 if (!left_as_cons.is_null() && !right_as_cons.is_null()) {
5708 if (left->length() < right->length()) {
5709 CheckCons(left_as_cons);
5710 cons_string = right_as_cons;
5711 } else {
5712 CheckCons(right_as_cons);
5713 cons_string = left_as_cons;
5714 }
5715 // Check fast return.
5716 if (!is_one_byte_) return false;
5717 continue;
5718 }
5719 // Descend left in place.
5720 if (!left_as_cons.is_null()) {
5721 cons_string = left_as_cons;
5722 continue;
5723 }
5724 // Descend right in place.
5725 if (!right_as_cons.is_null()) {
5726 cons_string = right_as_cons;
5727 continue;
5728 }
5729 // Terminate.
5730 break;
5731 }
5732 return is_one_byte_;
5733 }
5735};
5736
5738 auto str = Utils::OpenDirectHandle(this);
5739 if (str->IsOneByteRepresentation()) return true;
5741 return helper.Check(*str);
5742}
5743
5744int String::Utf8Length(Isolate* v8_isolate) const {
5745 auto str = Utils::OpenDirectHandle(this);
5746 str = i::String::Flatten(reinterpret_cast<i::Isolate*>(v8_isolate), str);
5747 int length = str->length();
5748 if (length == 0) return 0;
5750 i::String::FlatContent flat = str->GetFlatContent(no_gc);
5751 DCHECK(flat.IsFlat());
5752 int utf8_length = 0;
5753 if (flat.IsOneByte()) {
5754 for (uint8_t c : flat.ToOneByteVector()) {
5755 utf8_length += c >> 7;
5756 }
5757 utf8_length += length;
5758 } else {
5759 int last_character = unibrow::Utf16::kNoPreviousCharacter;
5760 for (uint16_t c : flat.ToUC16Vector()) {
5761 utf8_length += unibrow::Utf8::Length(c, last_character);
5762 last_character = c;
5763 }
5764 }
5765 return utf8_length;
5766}
5767
5768size_t String::Utf8LengthV2(Isolate* v8_isolate) const {
5769 auto str = Utils::OpenDirectHandle(this);
5770 return i::String::Utf8Length(reinterpret_cast<i::Isolate*>(v8_isolate), str);
5771}
5772
5773namespace {
5774// Writes the flat content of a string to a buffer. This is done in two phases.
5775// The first phase calculates a pessimistic estimate (writable_length) on how
5776// many code units can be safely written without exceeding the buffer capacity
5777// and without leaving at a lone surrogate. The estimated number of code units
5778// is then written out in one go, and the reported byte usage is used to
5779// correct the estimate. This is repeated until the estimate becomes <= 0 or
5780// all code units have been written out. The second phase writes out code
5781// units until the buffer capacity is reached, would be exceeded by the next
5782// unit, or all code units have been written out.
5783template <typename Char>
5784static int WriteUtf8Impl(base::Vector<const Char> string, char* write_start,
5785 int write_capacity, int options,
5786 int* utf16_chars_read_out) {
5787 bool write_null = !(options & v8::String::NO_NULL_TERMINATION);
5788 bool replace_invalid_utf8 = (options & v8::String::REPLACE_INVALID_UTF8);
5789 char* current_write = write_start;
5790 const Char* read_start = string.begin();
5791 int read_index = 0;
5792 int read_length = string.length();
5794 // Do a fast loop where there is no exit capacity check.
5795 // Need enough space to write everything but one character.
5797 static const int kMaxSizePerChar = sizeof(Char) == 1 ? 2 : 3;
5798 while (read_index < read_length) {
5799 int up_to = read_length;
5800 if (write_capacity != -1) {
5801 int remaining_capacity =
5802 write_capacity - static_cast<int>(current_write - write_start);
5803 int writable_length =
5804 (remaining_capacity - kMaxSizePerChar) / kMaxSizePerChar;
5805 // Need to drop into slow loop.
5806 if (writable_length <= 0) break;
5807 up_to = std::min(up_to, read_index + writable_length);
5808 }
5809 // Write the characters to the stream.
5810 if (sizeof(Char) == 1) {
5811 // Simply memcpy if we only have ASCII characters.
5812 uint8_t char_mask = 0;
5813 for (int i = read_index; i < up_to; i++) char_mask |= read_start[i];
5814 if ((char_mask & 0x80) == 0) {
5815 int copy_length = up_to - read_index;
5816 memcpy(current_write, read_start + read_index, copy_length);
5817 current_write += copy_length;
5818 read_index = up_to;
5819 } else {
5820 for (; read_index < up_to; read_index++) {
5821 current_write += unibrow::Utf8::EncodeOneByte(
5822 current_write, static_cast<uint8_t>(read_start[read_index]));
5823 DCHECK(write_capacity == -1 ||
5824 (current_write - write_start) <= write_capacity);
5825 }
5826 }
5827 } else {
5828 for (; read_index < up_to; read_index++) {
5829 uint16_t character = read_start[read_index];
5830 current_write += unibrow::Utf8::Encode(current_write, character,
5831 prev_char, replace_invalid_utf8);
5832 prev_char = character;
5833 DCHECK(write_capacity == -1 ||
5834 (current_write - write_start) <= write_capacity);
5835 }
5836 }
5837 }
5838 if (read_index < read_length) {
5839 DCHECK_NE(-1, write_capacity);
5840 // Aborted due to limited capacity. Check capacity on each iteration.
5841 int remaining_capacity =
5842 write_capacity - static_cast<int>(current_write - write_start);
5843 DCHECK_GE(remaining_capacity, 0);
5844 for (; read_index < read_length && remaining_capacity > 0; read_index++) {
5845 uint32_t character = read_start[read_index];
5846 int written = 0;
5847 // We can't use a local buffer here because Encode needs to modify
5848 // previous characters in the stream. We know, however, that
5849 // exactly one character will be advanced.
5850 if (unibrow::Utf16::IsSurrogatePair(prev_char, character)) {
5851 written = unibrow::Utf8::Encode(current_write, character, prev_char,
5852 replace_invalid_utf8);
5853 DCHECK_EQ(written, 1);
5854 } else {
5855 // Use a scratch buffer to check the required characters.
5856 char temp_buffer[unibrow::Utf8::kMaxEncodedSize];
5857 // Encoding a surrogate pair to Utf8 always takes 4 bytes.
5858 static const int kSurrogatePairEncodedSize =
5859 static_cast<int>(unibrow::Utf8::kMaxEncodedSize);
5860 // For REPLACE_INVALID_UTF8, catch the case where we cut off in the
5861 // middle of a surrogate pair. Abort before encoding the pair instead.
5862 if (replace_invalid_utf8 &&
5863 remaining_capacity < kSurrogatePairEncodedSize &&
5865 read_index + 1 < read_length &&
5866 unibrow::Utf16::IsTrailSurrogate(read_start[read_index + 1])) {
5867 write_null = false;
5868 break;
5869 }
5870 // Can't encode using prev_char as gcc has array bounds issues.
5871 written = unibrow::Utf8::Encode(temp_buffer, character,
5873 replace_invalid_utf8);
5874 if (written > remaining_capacity) {
5875 // Won't fit. Abort and do not null-terminate the result.
5876 write_null = false;
5877 break;
5878 }
5879 // Copy over the character from temp_buffer.
5880 for (int i = 0; i < written; i++) current_write[i] = temp_buffer[i];
5881 }
5882
5883 current_write += written;
5884 remaining_capacity -= written;
5885 prev_char = character;
5886 }
5887 }
5888
5889 // Write out number of utf16 characters written to the stream.
5890 if (utf16_chars_read_out != nullptr) *utf16_chars_read_out = read_index;
5891
5892 // Only null-terminate if there's space.
5893 if (write_null && (write_capacity == -1 ||
5894 (current_write - write_start) < write_capacity)) {
5895 *current_write++ = '\0';
5896 }
5897 return static_cast<int>(current_write - write_start);
5898}
5899} // anonymous namespace
5900
5901int String::WriteUtf8(Isolate* v8_isolate, char* buffer, int capacity,
5902 int* nchars_ref, int options) const {
5903 auto str = Utils::OpenDirectHandle(this);
5904 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
5905 API_RCS_SCOPE(i_isolate, String, WriteUtf8);
5907 str = i::String::Flatten(i_isolate, str);
5909 i::String::FlatContent content = str->GetFlatContent(no_gc);
5910 if (content.IsOneByte()) {
5911 return WriteUtf8Impl<uint8_t>(content.ToOneByteVector(), buffer, capacity,
5912 options, nchars_ref);
5913 } else {
5914 return WriteUtf8Impl<uint16_t>(content.ToUC16Vector(), buffer, capacity,
5915 options, nchars_ref);
5916 }
5917}
5918
5919template <typename CharType>
5920static inline int WriteHelper(i::Isolate* i_isolate, const String* string,
5921 CharType* buffer, int start, int length,
5922 int options) {
5923 API_RCS_SCOPE(i_isolate, String, Write);
5925 DCHECK(start >= 0 && length >= -1);
5926 auto str = Utils::OpenDirectHandle(string);
5927 int end = start + length;
5928 if ((length == -1) || (static_cast<uint32_t>(length) > str->length() - start))
5929 end = str->length();
5930 if (end < 0) return 0;
5931 int write_length = end - start;
5932 if (start < end) i::String::WriteToFlat(*str, buffer, start, write_length);
5933 if (!(options & String::NO_NULL_TERMINATION) &&
5934 (length == -1 || write_length < length)) {
5935 buffer[write_length] = '\0';
5936 }
5937 return write_length;
5938}
5939
5940int String::WriteOneByte(Isolate* v8_isolate, uint8_t* buffer, int start,
5941 int length, int options) const {
5942 return WriteHelper(reinterpret_cast<i::Isolate*>(v8_isolate), this, buffer,
5943 start, length, options);
5944}
5945
5946int String::Write(Isolate* v8_isolate, uint16_t* buffer, int start, int length,
5947 int options) const {
5948 return WriteHelper(reinterpret_cast<i::Isolate*>(v8_isolate), this, buffer,
5949 start, length, options);
5950}
5951
5952template <typename CharType>
5953static inline void WriteHelperV2(i::Isolate* i_isolate, const String* string,
5954 CharType* buffer, uint32_t offset,
5955 uint32_t length, int flags) {
5956 API_RCS_SCOPE(i_isolate, String, Write);
5958
5959 DCHECK_LE(length, string->Length());
5960 DCHECK_LE(offset, string->Length() - length);
5961
5962 auto str = Utils::OpenDirectHandle(string);
5963 i::String::WriteToFlat(*str, buffer, offset, length);
5965 buffer[length] = '\0';
5966 }
5967}
5968
5969void String::WriteV2(Isolate* v8_isolate, uint32_t offset, uint32_t length,
5970 uint16_t* buffer, int flags) const {
5971 WriteHelperV2(reinterpret_cast<i::Isolate*>(v8_isolate), this, buffer, offset,
5972 length, flags);
5973}
5974
5975void String::WriteOneByteV2(Isolate* v8_isolate, uint32_t offset,
5976 uint32_t length, uint8_t* buffer, int flags) const {
5977 DCHECK(IsOneByte());
5978 WriteHelperV2(reinterpret_cast<i::Isolate*>(v8_isolate), this, buffer, offset,
5979 length, flags);
5980}
5981
5982size_t String::WriteUtf8V2(Isolate* v8_isolate, char* buffer, size_t capacity,
5983 int flags,
5984 size_t* processed_characters_return) const {
5985 auto str = Utils::OpenDirectHandle(this);
5986 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
5987 API_RCS_SCOPE(i_isolate, String, WriteUtf8);
5989 i::String::Utf8EncodingFlags i_flags;
5991 i_flags |= i::String::Utf8EncodingFlag::kNullTerminate;
5992 }
5994 i_flags |= i::String::Utf8EncodingFlag::kReplaceInvalid;
5995 }
5996 return i::String::WriteUtf8(i_isolate, str, buffer, capacity, i_flags,
5997 processed_characters_return);
5998}
5999
6000namespace {
6001
6002bool HasExternalStringResource(i::Tagged<i::String> string) {
6003 return i::StringShape(string).IsExternal() ||
6004 string->HasExternalForwardingIndex(kAcquireLoad);
6005}
6006
6007v8::String::ExternalStringResourceBase* GetExternalResourceFromForwardingTable(
6008 i::Tagged<i::String> string, uint32_t raw_hash, bool* is_one_byte) {
6009 DCHECK(i::String::IsExternalForwardingIndex(raw_hash));
6010 const int index = i::String::ForwardingIndexValueBits::decode(raw_hash);
6011 // Note that with a shared heap the main and worker isolates all share the
6012 // same forwarding table.
6013 auto resource =
6014 i::Isolate::Current()->string_forwarding_table()->GetExternalResource(
6015 index, is_one_byte);
6016 DCHECK_NOT_NULL(resource);
6017 return resource;
6018}
6019
6020} // namespace
6021
6023 return HasExternalStringResource(*Utils::OpenDirectHandle(this));
6024}
6025
6027 auto str = Utils::OpenDirectHandle(this);
6028 if (i::StringShape(*str).IsExternalTwoByte()) return true;
6029 uint32_t raw_hash_field = str->raw_hash_field(kAcquireLoad);
6030 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6031 bool is_one_byte;
6032 GetExternalResourceFromForwardingTable(*str, raw_hash_field, &is_one_byte);
6033 return !is_one_byte;
6034 }
6035 return false;
6036}
6037
6039 auto str = Utils::OpenDirectHandle(this);
6040 if (i::StringShape(*str).IsExternalOneByte()) return true;
6041 uint32_t raw_hash_field = str->raw_hash_field(kAcquireLoad);
6042 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6043 bool is_one_byte;
6044 GetExternalResourceFromForwardingTable(*str, raw_hash_field, &is_one_byte);
6045 return is_one_byte;
6046 }
6047 return false;
6048}
6049
6051 auto* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
6052 auto str = Utils::OpenDirectHandle(this);
6053 return Utils::ToLocal(isolate->factory()->InternalizeString(str));
6054}
6055
6060 const v8::String::ExternalStringResource* expected;
6061
6062 if (i::IsThinString(str)) {
6063 str = i::Cast<i::ThinString>(str)->actual();
6064 }
6065
6066 if (i::StringShape(str).IsExternalTwoByte()) {
6067 const void* resource = i::Cast<i::ExternalTwoByteString>(str)->resource();
6068 expected = reinterpret_cast<const ExternalStringResource*>(resource);
6069 } else {
6070 uint32_t raw_hash_field = str->raw_hash_field(kAcquireLoad);
6071 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6072 bool is_one_byte;
6073 auto resource = GetExternalResourceFromForwardingTable(
6074 str, raw_hash_field, &is_one_byte);
6075 if (!is_one_byte) {
6076 expected = reinterpret_cast<const ExternalStringResource*>(resource);
6077 }
6078 } else {
6079 expected = nullptr;
6080 }
6081 }
6082 CHECK_EQ(expected, value);
6083}
6084
6086 v8::String::ExternalStringResourceBase* value, Encoding encoding) const {
6090 Encoding expectedEncoding;
6091
6092 if (i::IsThinString(str)) {
6093 str = i::Cast<i::ThinString>(str)->actual();
6094 }
6095
6096 if (i::StringShape(str).IsExternalOneByte()) {
6097 const void* resource = i::Cast<i::ExternalOneByteString>(str)->resource();
6098 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
6099 expectedEncoding = ONE_BYTE_ENCODING;
6100 } else if (i::StringShape(str).IsExternalTwoByte()) {
6101 const void* resource = i::Cast<i::ExternalTwoByteString>(str)->resource();
6102 expected = reinterpret_cast<const ExternalStringResourceBase*>(resource);
6103 expectedEncoding = TWO_BYTE_ENCODING;
6104 } else {
6105 uint32_t raw_hash_field = str->raw_hash_field(kAcquireLoad);
6106 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6107 bool is_one_byte;
6108 expected = GetExternalResourceFromForwardingTable(str, raw_hash_field,
6109 &is_one_byte);
6110 expectedEncoding = is_one_byte ? ONE_BYTE_ENCODING : TWO_BYTE_ENCODING;
6111 } else {
6112 expected = nullptr;
6113 expectedEncoding = str->IsOneByteRepresentation() ? ONE_BYTE_ENCODING
6114 : TWO_BYTE_ENCODING;
6115 }
6116 }
6117 CHECK_EQ(expected, value);
6118 CHECK_EQ(expectedEncoding, encoding);
6119}
6120
6124
6125 if (i::IsThinString(str)) {
6126 str = i::Cast<i::ThinString>(str)->actual();
6127 }
6128
6129 if (i::StringShape(str).IsExternalTwoByte()) {
6130 Isolate* isolate = i::Internals::GetIsolateForSandbox(str.ptr());
6131 i::Address value =
6132 i::Internals::ReadExternalPointerField<i::kExternalStringResourceTag>(
6133 isolate, str.ptr(), i::Internals::kStringResourceOffset);
6134 return reinterpret_cast<String::ExternalStringResource*>(value);
6135 } else {
6136 uint32_t raw_hash_field = str->raw_hash_field(kAcquireLoad);
6137 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6138 bool is_one_byte;
6139 auto resource = GetExternalResourceFromForwardingTable(
6140 str, raw_hash_field, &is_one_byte);
6141 if (!is_one_byte) {
6142 return reinterpret_cast<ExternalStringResource*>(resource);
6143 }
6144 }
6145 }
6146 return nullptr;
6147}
6148
6153
6155 DCHECK(IsCacheable() && cached_data_ != nullptr);
6156}
6157
6162
6164 DCHECK(IsCacheable() && cached_data_ != nullptr);
6165}
6166
6168 String::Encoding* encoding_out) const {
6170 ExternalStringResourceBase* resource = nullptr;
6172
6173 if (i::IsThinString(str)) {
6174 str = i::Cast<i::ThinString>(str)->actual();
6175 }
6176
6177 internal::Address string = str.ptr();
6178 int type = i::Internals::GetInstanceType(string) &
6179 i::Internals::kStringRepresentationAndEncodingMask;
6180 *encoding_out =
6181 static_cast<Encoding>(type & i::Internals::kStringEncodingMask);
6182 if (i::StringShape(str).IsExternalOneByte() ||
6184 Isolate* isolate = i::Internals::GetIsolateForSandbox(string);
6185 i::Address value =
6186 i::Internals::ReadExternalPointerField<i::kExternalStringResourceTag>(
6187 isolate, string, i::Internals::kStringResourceOffset);
6188 resource = reinterpret_cast<ExternalStringResourceBase*>(value);
6189 } else {
6190 uint32_t raw_hash_field = str->raw_hash_field();
6191 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6192 bool is_one_byte;
6193 resource = GetExternalResourceFromForwardingTable(str, raw_hash_field,
6194 &is_one_byte);
6195 *encoding_out = is_one_byte ? Encoding::ONE_BYTE_ENCODING
6197 }
6198 }
6199 return resource;
6200}
6201
6206 if (i::StringShape(str).IsExternalOneByte()) {
6207 return i::Cast<i::ExternalOneByteString>(str)->resource();
6208 } else if (i::IsThinString(str)) {
6209 str = i::Cast<i::ThinString>(str)->actual();
6210 if (i::StringShape(str).IsExternalOneByte()) {
6211 return i::Cast<i::ExternalOneByteString>(str)->resource();
6212 }
6213 }
6214 uint32_t raw_hash_field = str->raw_hash_field(kAcquireLoad);
6215 if (i::String::IsExternalForwardingIndex(raw_hash_field)) {
6216 bool is_one_byte;
6217 auto resource = GetExternalResourceFromForwardingTable(str, raw_hash_field,
6218 &is_one_byte);
6219 if (is_one_byte) {
6220 return reinterpret_cast<ExternalOneByteStringResource*>(resource);
6221 }
6222 }
6223 return nullptr;
6224}
6225
6227 auto sym = Utils::OpenDirectHandle(this);
6228 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
6229 return Utils::ToLocal(i::direct_handle(sym->description(), isolate));
6230}
6231
6233 const Symbol* sym = reinterpret_cast<const Symbol*>(this);
6234 auto i_sym = Utils::OpenDirectHandle(sym);
6235 // v8::Private symbols are created by API and are therefore writable, so we
6236 // can always recover an Isolate.
6237 i::Isolate* i_isolate = i::GetIsolateFromWritableObject(*i_sym);
6238 return sym->Description(reinterpret_cast<Isolate*>(i_isolate));
6239}
6240
6241double Number::Value() const {
6242 return i::Object::NumberValue(*Utils::OpenDirectHandle(this));
6243}
6244
6245bool Boolean::Value() const {
6246 return i::IsTrue(*Utils::OpenDirectHandle(this));
6247}
6248
6249int64_t Integer::Value() const {
6250 auto obj = *Utils::OpenDirectHandle(this);
6251 if (i::IsSmi(obj)) {
6252 return i::Smi::ToInt(obj);
6253 } else {
6254 return static_cast<int64_t>(i::Object::NumberValue(obj));
6255 }
6256}
6257
6258int32_t Int32::Value() const {
6259 auto obj = *Utils::OpenDirectHandle(this);
6260 if (i::IsSmi(obj)) {
6261 return i::Smi::ToInt(obj);
6262 } else {
6263 return static_cast<int32_t>(i::Object::NumberValue(obj));
6264 }
6265}
6266
6267uint32_t Uint32::Value() const {
6268 auto obj = *Utils::OpenDirectHandle(this);
6269 if (i::IsSmi(obj)) {
6270 return i::Smi::ToInt(obj);
6271 } else {
6272 return static_cast<uint32_t>(i::Object::NumberValue(obj));
6273 }
6274}
6275
6277 auto self = *Utils::OpenDirectHandle(this);
6278 if (!IsJSObject(self)) return 0;
6279 return i::Cast<i::JSObject>(self)->GetEmbedderFieldCount();
6280}
6281
6283 int index, const char* location) {
6284 return Utils::ApiCheck(
6285 IsJSObject(*obj) &&
6286 (index < i::Cast<i::JSObject>(*obj)->GetEmbedderFieldCount()),
6287 location, "Internal field out of bounds");
6288}
6289
6291 auto obj = Utils::OpenDirectHandle(this);
6292 const char* location = "v8::Object::GetInternalField()";
6293 if (!InternalFieldOK(obj, index, location)) return Local<Value>();
6294 i::Isolate* isolate = obj->GetIsolate();
6296 i::Cast<i::JSObject>(*obj)->GetEmbedderField(index), isolate));
6297}
6298
6300 auto obj = Utils::OpenDirectHandle(this);
6301 const char* location = "v8::Object::SetInternalField()";
6302 if (!InternalFieldOK(obj, index, location)) return;
6303 auto val = Utils::OpenDirectHandle(*value);
6304 i::Cast<i::JSObject>(obj)->SetEmbedderField(index, *val);
6305}
6306
6308 int index) {
6309 auto obj = Utils::OpenDirectHandle(this);
6310 const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
6311 if (!InternalFieldOK(obj, index, location)) return nullptr;
6312 void* result;
6315 .ToAlignedPointer(reinterpret_cast<i::Isolate*>(isolate), &result),
6316 location, "Unaligned pointer");
6317 return result;
6318}
6319
6321 auto obj = Utils::OpenDirectHandle(this);
6322 const char* location = "v8::Object::GetAlignedPointerFromInternalField()";
6323 if (!InternalFieldOK(obj, index, location)) return nullptr;
6324 void* result;
6326 .ToAlignedPointer(obj->GetIsolate(), &result),
6327 location, "Unaligned pointer");
6328 return result;
6329}
6330
6332 auto obj = Utils::OpenDirectHandle(this);
6333 const char* location = "v8::Object::SetAlignedPointerInInternalField()";
6334 if (!InternalFieldOK(obj, index, location)) return;
6335
6338 .store_aligned_pointer(obj->GetIsolate(), *obj, value),
6339 location, "Unaligned pointer");
6340 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
6341}
6342
6344 void* values[]) {
6345 auto obj = Utils::OpenDirectHandle(this);
6346 if (!IsJSObject(*obj)) return;
6348 const char* location = "v8::Object::SetAlignedPointerInInternalFields()";
6349 auto js_obj = i::Cast<i::JSObject>(*obj);
6350 int nof_embedder_fields = js_obj->GetEmbedderFieldCount();
6351 for (int i = 0; i < argc; i++) {
6352 int index = indices[i];
6353 if (!Utils::ApiCheck(index < nof_embedder_fields, location,
6354 "Internal field out of bounds")) {
6355 return;
6356 }
6357 void* value = values[i];
6359 .store_aligned_pointer(obj->GetIsolate(), *obj, value),
6360 location, "Unaligned pointer");
6361 DCHECK_EQ(value, GetAlignedPointerFromInternalField(index));
6362 }
6363}
6364
6365// static
6366void* v8::Object::Unwrap(v8::Isolate* isolate, i::Address wrapper_obj,
6367 CppHeapPointerTagRange tag_range) {
6368 DCHECK_LE(tag_range.lower_bound, tag_range.upper_bound);
6369 return i::JSApiWrapper(
6371 .GetCppHeapWrappable(reinterpret_cast<i::Isolate*>(isolate), tag_range);
6372}
6373
6374// static
6375void v8::Object::Wrap(v8::Isolate* isolate, i::Address wrapper_obj,
6376 CppHeapPointerTag tag, void* wrappable) {
6377 return i::JSApiWrapper(
6379 .SetCppHeapWrappable(reinterpret_cast<i::Isolate*>(isolate), wrappable,
6380 tag);
6381}
6382
6383// --- E n v i r o n m e n t ---
6384
6386 i::V8::InitializePlatform(platform);
6387}
6388
6389void v8::V8::DisposePlatform() { i::V8::DisposePlatform(); }
6390
6391bool v8::V8::Initialize(const int build_config) {
6392 const bool kEmbedderPointerCompression =
6393 (build_config & kPointerCompression) != 0;
6394 if (kEmbedderPointerCompression != COMPRESS_POINTERS_BOOL) {
6395 FATAL(
6396 "Embedder-vs-V8 build configuration mismatch. On embedder side "
6397 "pointer compression is %s while on V8 side it's %s.",
6398 kEmbedderPointerCompression ? "ENABLED" : "DISABLED",
6399 COMPRESS_POINTERS_BOOL ? "ENABLED" : "DISABLED");
6400 }
6401
6402 const int kEmbedderSmiValueSize = (build_config & k31BitSmis) ? 31 : 32;
6403 if (kEmbedderSmiValueSize != internal::kSmiValueSize) {
6404 FATAL(
6405 "Embedder-vs-V8 build configuration mismatch. On embedder side "
6406 "Smi value size is %d while on V8 side it's %d.",
6407 kEmbedderSmiValueSize, internal::kSmiValueSize);
6408 }
6409
6410 const bool kEmbedderSandbox = (build_config & kSandbox) != 0;
6411 if (kEmbedderSandbox != V8_ENABLE_SANDBOX_BOOL) {
6412 FATAL(
6413 "Embedder-vs-V8 build configuration mismatch. On embedder side "
6414 "sandbox is %s while on V8 side it's %s.",
6415 kEmbedderSandbox ? "ENABLED" : "DISABLED",
6416 V8_ENABLE_SANDBOX_BOOL ? "ENABLED" : "DISABLED");
6417 }
6418
6419 const bool kEmbedderTargetOsIsAndroid =
6420 (build_config & kTargetOsIsAndroid) != 0;
6421#ifdef V8_TARGET_OS_ANDROID
6422 const bool kV8TargetOsIsAndroid = true;
6423#else
6424 const bool kV8TargetOsIsAndroid = false;
6425#endif
6426 if (kEmbedderTargetOsIsAndroid != kV8TargetOsIsAndroid) {
6427 FATAL(
6428 "Embedder-vs-V8 build configuration mismatch. On embedder side "
6429 "target OS is %s while on V8 side it's %s.",
6430 kEmbedderTargetOsIsAndroid ? "Android" : "not Android",
6431 kV8TargetOsIsAndroid ? "Android" : "not Android");
6432 }
6433
6434 const bool kEmbedderEnableChecks = (build_config & kEnableChecks) != 0;
6435#ifdef V8_ENABLE_CHECKS
6436 const bool kV8EnableChecks = true;
6437#else
6438 const bool kV8EnableChecks = false;
6439#endif
6440 if (kEmbedderEnableChecks != kV8EnableChecks) {
6441 FATAL(
6442 "Embedder-vs-V8 build configuration mismatch. On embedder side "
6443 "V8_ENABLE_CHECKS is %s while on V8 side it's %s.",
6444 kEmbedderEnableChecks ? "ENABLED" : "DISABLED",
6445 kV8EnableChecks ? "ENABLED" : "DISABLED");
6446 }
6447
6448 i::V8::Initialize();
6449 if (!cppgc::IsInitialized()) {
6450 // cppgc::InitializeProcess() has to becalled after V8::Initialize().
6451 // V8::Initialize() triggers OS::Platform initialization code that is needed
6452 // by the default page allocator on Fuchsia to allocate memory correctly.
6453 cppgc::InitializeProcess(i::V8::GetCurrentPlatform()->GetPageAllocator());
6454 }
6455 return true;
6456}
6457
6458#if V8_OS_LINUX || V8_OS_DARWIN
6459bool TryHandleWebAssemblyTrapPosix(int sig_code, siginfo_t* info,
6460 void* context) {
6461#if V8_ENABLE_WEBASSEMBLY && V8_TRAP_HANDLER_SUPPORTED
6462 return i::trap_handler::TryHandleSignal(sig_code, info, context);
6463#else
6464 return false;
6465#endif
6466}
6467#endif
6468
6469#if V8_OS_WIN
6470bool TryHandleWebAssemblyTrapWindows(EXCEPTION_POINTERS* exception) {
6471#if V8_ENABLE_WEBASSEMBLY && V8_TRAP_HANDLER_SUPPORTED
6472 return i::trap_handler::TryHandleWasmTrap(exception);
6473#else
6474 return false;
6475#endif
6476}
6477#endif
6478
6479bool V8::EnableWebAssemblyTrapHandler(bool use_v8_signal_handler) {
6480#if V8_ENABLE_WEBASSEMBLY
6481 return v8::internal::trap_handler::EnableTrapHandler(use_v8_signal_handler);
6482#else
6483 return false;
6484#endif
6485}
6486
6487#if defined(V8_OS_WIN)
6488void V8::SetUnhandledExceptionCallback(
6489 UnhandledExceptionCallback unhandled_exception_callback) {
6490#if defined(V8_OS_WIN64)
6492 unhandled_exception_callback);
6493#else
6494 // Not implemented, port needed.
6495#endif // V8_OS_WIN64
6496}
6497#endif // V8_OS_WIN
6498
6500 v8::OOMErrorCallback oom_error_callback) {
6501 g_oom_error_callback = oom_error_callback;
6502}
6503
6507
6509 ReturnAddressLocationResolver return_address_resolver) {
6510 i::StackFrame::SetReturnAddressLocationResolver(return_address_resolver);
6511}
6512
6514 i::V8::Dispose();
6515 return true;
6516}
6517
6519 : read_only_space_size_(0),
6520 read_only_space_used_size_(0),
6521 read_only_space_physical_size_(0) {}
6522
6524 : total_heap_size_(0),
6525 total_heap_size_executable_(0),
6526 total_physical_size_(0),
6527 total_available_size_(0),
6528 used_heap_size_(0),
6529 heap_size_limit_(0),
6530 malloced_memory_(0),
6531 external_memory_(0),
6532 peak_malloced_memory_(0),
6533 does_zap_garbage_(false),
6534 number_of_native_contexts_(0),
6535 number_of_detached_contexts_(0) {}
6536
6538 : space_name_(nullptr),
6539 space_size_(0),
6540 space_used_size_(0),
6541 space_available_size_(0),
6542 physical_space_size_(0) {}
6543
6545 : object_type_(nullptr),
6546 object_sub_type_(nullptr),
6547 object_count_(0),
6548 object_size_(0) {}
6549
6551 : code_and_metadata_size_(0),
6552 bytecode_and_metadata_size_(0),
6553 external_script_source_size_(0),
6554 cpu_profiler_metadata_size_(0) {}
6555
6556bool v8::V8::InitializeICU(const char* icu_data_file) {
6557 return i::InitializeICU(icu_data_file);
6558}
6559
6560bool v8::V8::InitializeICUDefaultLocation(const char* exec_path,
6561 const char* icu_data_file) {
6562 return i::InitializeICUDefaultLocation(exec_path, icu_data_file);
6563}
6564
6565void v8::V8::InitializeExternalStartupData(const char* directory_path) {
6566 i::InitializeExternalStartupData(directory_path);
6567}
6568
6569// static
6570void v8::V8::InitializeExternalStartupDataFromFile(const char* snapshot_blob) {
6572}
6573
6574const char* v8::V8::GetVersion() { return i::Version::GetVersion(); }
6575
6576#ifdef V8_ENABLE_SANDBOX
6577VirtualAddressSpace* v8::V8::GetSandboxAddressSpace() {
6578 Utils::ApiCheck(i::Sandbox::current()->is_initialized(),
6579 "v8::V8::GetSandboxAddressSpace",
6580 "The sandbox must be initialized first");
6581 return i::Sandbox::current()->address_space();
6582}
6583
6584size_t v8::V8::GetSandboxSizeInBytes() {
6585 Utils::ApiCheck(i::Sandbox::current()->is_initialized(),
6586 "v8::V8::GetSandboxSizeInBytes",
6587 "The sandbox must be initialized first.");
6588 return i::Sandbox::current()->size();
6589}
6590
6591size_t v8::V8::GetSandboxReservationSizeInBytes() {
6592 Utils::ApiCheck(i::Sandbox::current()->is_initialized(),
6593 "v8::V8::GetSandboxReservationSizeInBytes",
6594 "The sandbox must be initialized first");
6595 return i::Sandbox::current()->reservation_size();
6596}
6597
6598bool v8::V8::IsSandboxConfiguredSecurely() {
6599 Utils::ApiCheck(i::Sandbox::current()->is_initialized(),
6600 "v8::V8::IsSandoxConfiguredSecurely",
6601 "The sandbox must be initialized first");
6602 // The sandbox is (only) configured insecurely if it is a partially reserved
6603 // sandbox, since in that case unrelated memory mappings may end up inside
6604 // the sandbox address space where they could be corrupted by an attacker.
6605 return !i::Sandbox::current()->is_partially_reserved();
6606}
6607#endif // V8_ENABLE_SANDBOX
6608
6610 i::ReadOnlyHeap::PopulateReadOnlySpaceStatistics(statistics);
6611}
6612
6613template <typename ObjectType>
6615
6616template <>
6617struct InvokeBootstrapper<i::NativeContext> {
6619 i::Isolate* i_isolate,
6620 i::MaybeDirectHandle<i::JSGlobalProxy> maybe_global_proxy,
6621 v8::Local<v8::ObjectTemplate> global_proxy_template,
6622 v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
6623 i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
6625 return i_isolate->bootstrapper()->CreateEnvironment(
6626 maybe_global_proxy, global_proxy_template, extensions,
6627 context_snapshot_index, embedder_fields_deserializer, microtask_queue);
6628 }
6629};
6630
6631template <>
6632struct InvokeBootstrapper<i::JSGlobalProxy> {
6634 i::Isolate* i_isolate,
6635 i::MaybeDirectHandle<i::JSGlobalProxy> maybe_global_proxy,
6636 v8::Local<v8::ObjectTemplate> global_proxy_template,
6637 v8::ExtensionConfiguration* extensions, size_t context_snapshot_index,
6638 i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
6640 USE(extensions);
6641 USE(context_snapshot_index);
6642 return i_isolate->bootstrapper()->NewRemoteContext(maybe_global_proxy,
6643 global_proxy_template);
6644 }
6645};
6646
6647template <typename ObjectType>
6649 i::Isolate* i_isolate, v8::ExtensionConfiguration* extensions,
6650 v8::MaybeLocal<ObjectTemplate> maybe_global_template,
6651 v8::MaybeLocal<Value> maybe_global_proxy, size_t context_snapshot_index,
6652 i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
6655
6656 {
6657 ENTER_V8_FOR_NEW_CONTEXT(i_isolate);
6658 v8::Local<ObjectTemplate> proxy_template;
6662 named_interceptor(i_isolate->factory()->undefined_value());
6664 indexed_interceptor(i_isolate->factory()->undefined_value());
6665
6666 if (!maybe_global_template.IsEmpty()) {
6667 v8::Local<v8::ObjectTemplate> global_template =
6668 maybe_global_template.ToLocalChecked();
6669 // Make sure that the global_template has a constructor.
6670 global_constructor = EnsureConstructor(i_isolate, *global_template);
6671
6672 // Create a fresh template for the global proxy object.
6673 proxy_template =
6674 ObjectTemplate::New(reinterpret_cast<v8::Isolate*>(i_isolate));
6675 proxy_constructor = EnsureConstructor(i_isolate, *proxy_template);
6676
6677 // Set the global template to be the prototype template of
6678 // global proxy template.
6679 i::FunctionTemplateInfo::SetPrototypeTemplate(
6680 i_isolate, proxy_constructor,
6681 Utils::OpenDirectHandle(*global_template));
6682
6683 proxy_template->SetInternalFieldCount(
6684 global_template->InternalFieldCount());
6685
6686 // Migrate security handlers from global_template to
6687 // proxy_template. Temporarily removing access check
6688 // information from the global template.
6689 if (!IsUndefined(global_constructor->GetAccessCheckInfo(), i_isolate)) {
6690 i::FunctionTemplateInfo::SetAccessCheckInfo(
6691 i_isolate, proxy_constructor,
6692 direct_handle(global_constructor->GetAccessCheckInfo(), i_isolate));
6693 proxy_constructor->set_needs_access_check(
6694 global_constructor->needs_access_check());
6695 global_constructor->set_needs_access_check(false);
6696 i::FunctionTemplateInfo::SetAccessCheckInfo(
6697 i_isolate, global_constructor,
6698 i_isolate->factory()->undefined_value());
6699 }
6700
6701 // Same for other interceptors. If the global constructor has
6702 // interceptors, we need to replace them temporarily with noop
6703 // interceptors, so the map is correctly marked as having interceptors,
6704 // but we don't invoke any.
6705 if (!IsUndefined(global_constructor->GetNamedPropertyHandler(),
6706 i_isolate)) {
6707 named_interceptor = direct_handle(
6708 global_constructor->GetNamedPropertyHandler(), i_isolate);
6709 i::FunctionTemplateInfo::SetNamedPropertyHandler(
6710 i_isolate, global_constructor,
6711 i_isolate->factory()->noop_interceptor_info());
6712 }
6713 if (!IsUndefined(global_constructor->GetIndexedPropertyHandler(),
6714 i_isolate)) {
6715 indexed_interceptor = direct_handle(
6716 global_constructor->GetIndexedPropertyHandler(), i_isolate);
6717 i::FunctionTemplateInfo::SetIndexedPropertyHandler(
6718 i_isolate, global_constructor,
6719 i_isolate->factory()->noop_interceptor_info());
6720 }
6721 }
6722
6724 if (!maybe_global_proxy.IsEmpty()) {
6725 maybe_proxy = i::Cast<i::JSGlobalProxy>(
6726 Utils::OpenDirectHandle(*maybe_global_proxy.ToLocalChecked()));
6727 }
6728 // Create the environment.
6730 result = invoke.Invoke(i_isolate, maybe_proxy, proxy_template, extensions,
6731 context_snapshot_index, embedder_fields_deserializer,
6733
6734 // Restore the access check info and interceptors on the global template.
6735 if (!maybe_global_template.IsEmpty()) {
6736 DCHECK(!global_constructor.is_null());
6737 DCHECK(!proxy_constructor.is_null());
6738 i::FunctionTemplateInfo::SetAccessCheckInfo(
6739 i_isolate, global_constructor,
6740 i::direct_handle(proxy_constructor->GetAccessCheckInfo(), i_isolate));
6741 global_constructor->set_needs_access_check(
6742 proxy_constructor->needs_access_check());
6743 i::FunctionTemplateInfo::SetNamedPropertyHandler(
6744 i_isolate, global_constructor, named_interceptor);
6745 i::FunctionTemplateInfo::SetIndexedPropertyHandler(
6746 i_isolate, global_constructor, indexed_interceptor);
6747 }
6748 }
6749 // Leave V8.
6750
6751 return result;
6752}
6753
6755 v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
6756 v8::MaybeLocal<ObjectTemplate> global_template,
6757 v8::MaybeLocal<Value> global_object, size_t context_snapshot_index,
6758 i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer,
6760 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(external_isolate);
6761 // TODO(jkummerow): This is for crbug.com/713699. Remove it if it doesn't
6762 // fail.
6763 // Sanity-check that the isolate is initialized and usable.
6764 CHECK(IsCode(i_isolate->builtins()->code(i::Builtin::kIllegal)));
6765
6766 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.NewContext");
6767 API_RCS_SCOPE(i_isolate, Context, New);
6768 i::HandleScope scope(i_isolate);
6769 ExtensionConfiguration no_extensions;
6770 if (extensions == nullptr) extensions = &no_extensions;
6772 i_isolate, extensions, global_template, global_object,
6773 context_snapshot_index, embedder_fields_deserializer, microtask_queue);
6774 if (env.is_null()) return Local<Context>();
6775 return Utils::ToLocal(scope.CloseAndEscape(env));
6776}
6777
6779 v8::Isolate* external_isolate, v8::ExtensionConfiguration* extensions,
6780 v8::MaybeLocal<ObjectTemplate> global_template,
6781 v8::MaybeLocal<Value> global_object,
6782 v8::DeserializeInternalFieldsCallback internal_fields_deserializer,
6784 v8::DeserializeContextDataCallback context_callback_deserializer,
6785 v8::DeserializeAPIWrapperCallback api_wrapper_deserializer) {
6786 return NewContext(
6787 external_isolate, extensions, global_template, global_object, 0,
6788 i::DeserializeEmbedderFieldsCallback(internal_fields_deserializer,
6789 context_callback_deserializer,
6790 api_wrapper_deserializer),
6792}
6793
6795 v8::Isolate* external_isolate, size_t context_snapshot_index,
6796 v8::DeserializeInternalFieldsCallback internal_fields_deserializer,
6797 v8::ExtensionConfiguration* extensions, MaybeLocal<Value> global_object,
6799 v8::DeserializeContextDataCallback context_callback_deserializer,
6800 v8::DeserializeAPIWrapperCallback api_wrapper_deserializer) {
6801 size_t index_including_default_context = context_snapshot_index + 1;
6802 if (!i::Snapshot::HasContextSnapshot(
6803 reinterpret_cast<i::Isolate*>(external_isolate),
6804 index_including_default_context)) {
6805 return MaybeLocal<Context>();
6806 }
6807 return NewContext(
6808 external_isolate, extensions, MaybeLocal<ObjectTemplate>(), global_object,
6809 index_including_default_context,
6810 i::DeserializeEmbedderFieldsCallback(internal_fields_deserializer,
6811 context_callback_deserializer,
6812 api_wrapper_deserializer),
6814}
6815
6817 v8::Isolate* external_isolate, v8::Local<ObjectTemplate> global_template,
6818 v8::MaybeLocal<v8::Value> global_object) {
6819 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(external_isolate);
6820 API_RCS_SCOPE(i_isolate, Context, NewRemoteContext);
6821 i::HandleScope scope(i_isolate);
6822 i::DirectHandle<i::FunctionTemplateInfo> global_constructor =
6823 EnsureConstructor(i_isolate, *global_template);
6824 Utils::ApiCheck(global_constructor->needs_access_check(),
6825 "v8::Context::NewRemoteContext",
6826 "Global template needs to have access checks enabled");
6827 i::DirectHandle<i::AccessCheckInfo> access_check_info(
6828 i::Cast<i::AccessCheckInfo>(global_constructor->GetAccessCheckInfo()),
6829 i_isolate);
6831 access_check_info->named_interceptor() != i::Tagged<i::Object>(),
6832 "v8::Context::NewRemoteContext",
6833 "Global template needs to have access check handlers");
6834 i::DirectHandle<i::JSObject> global_proxy =
6836 i_isolate, nullptr, global_template, global_object, 0,
6838 if (global_proxy.is_null()) {
6839 if (i_isolate->has_exception()) i_isolate->clear_exception();
6840 return MaybeLocal<Object>();
6841 }
6842 return Utils::ToLocal(scope.CloseAndEscape(global_proxy));
6843}
6844
6846 auto env = Utils::OpenDirectHandle(this);
6847 auto token_handle = Utils::OpenDirectHandle(*token);
6848 env->set_security_token(*token_handle);
6849}
6850
6852 auto env = Utils::OpenDirectHandle(this);
6853 env->set_security_token(env->global_object());
6854}
6855
6857 auto env = Utils::OpenDirectHandle(this);
6858 i::Isolate* i_isolate = env->GetIsolate();
6859 i::Tagged<i::Object> security_token = env->security_token();
6860 return Utils::ToLocal(i::direct_handle(security_token, i_isolate));
6861}
6862
6863namespace {
6864
6865bool MayContainObjectsToFreeze(i::InstanceType obj_type) {
6866 if (i::InstanceTypeChecker::IsString(obj_type)) return false;
6867 // SharedFunctionInfo is cross-context so it shouldn't be frozen.
6868 if (i::InstanceTypeChecker::IsSharedFunctionInfo(obj_type)) return false;
6869 // All TemplateInfo objects are cross-context so they shouldn't be frozen.
6870 if (i::InstanceTypeChecker::IsTemplateInfo(obj_type)) return false;
6871 return true;
6872}
6873
6874bool RequiresEmbedderSupportToFreeze(i::InstanceType obj_type) {
6875 DCHECK(i::InstanceTypeChecker::IsJSReceiver(obj_type));
6876
6877 return (i::InstanceTypeChecker::IsJSApiObject(obj_type) ||
6878 i::InstanceTypeChecker::IsJSExternalObject(obj_type) ||
6879 i::InstanceTypeChecker::IsJSAPIObjectWithEmbedderSlots(obj_type));
6880}
6881
6882bool IsJSReceiverSafeToFreeze(i::InstanceType obj_type) {
6883 DCHECK(i::InstanceTypeChecker::IsJSReceiver(obj_type));
6884
6885 switch (obj_type) {
6886 case i::JS_OBJECT_TYPE:
6887 case i::JS_GLOBAL_OBJECT_TYPE:
6888 case i::JS_GLOBAL_PROXY_TYPE:
6889 case i::JS_PRIMITIVE_WRAPPER_TYPE:
6890 case i::JS_FUNCTION_TYPE:
6891 /* Function types */
6892 case i::BIGINT64_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6893 case i::BIGUINT64_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6894 case i::FLOAT16_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6895 case i::FLOAT32_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6896 case i::FLOAT64_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6897 case i::INT16_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6898 case i::INT32_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6899 case i::INT8_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6900 case i::UINT16_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6901 case i::UINT32_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6902 case i::UINT8_CLAMPED_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6903 case i::UINT8_TYPED_ARRAY_CONSTRUCTOR_TYPE:
6904 case i::JS_ARRAY_CONSTRUCTOR_TYPE:
6905 case i::JS_PROMISE_CONSTRUCTOR_TYPE:
6906 case i::JS_REG_EXP_CONSTRUCTOR_TYPE:
6907 case i::JS_CLASS_CONSTRUCTOR_TYPE:
6908 /* Prototype Types */
6909 case i::JS_ARRAY_ITERATOR_PROTOTYPE_TYPE:
6910 case i::JS_ITERATOR_PROTOTYPE_TYPE:
6911 case i::JS_MAP_ITERATOR_PROTOTYPE_TYPE:
6912 case i::JS_OBJECT_PROTOTYPE_TYPE:
6913 case i::JS_PROMISE_PROTOTYPE_TYPE:
6914 case i::JS_REG_EXP_PROTOTYPE_TYPE:
6915 case i::JS_SET_ITERATOR_PROTOTYPE_TYPE:
6916 case i::JS_SET_PROTOTYPE_TYPE:
6917 case i::JS_STRING_ITERATOR_PROTOTYPE_TYPE:
6918 case i::JS_TYPED_ARRAY_PROTOTYPE_TYPE:
6919 /* */
6920 case i::JS_ARRAY_TYPE:
6921 return true;
6922#if V8_ENABLE_WEBASSEMBLY
6923 case i::WASM_ARRAY_TYPE:
6924 case i::WASM_STRUCT_TYPE:
6925 case i::WASM_TAG_OBJECT_TYPE:
6926#endif // V8_ENABLE_WEBASSEMBLY
6927 case i::JS_PROXY_TYPE:
6928 return true;
6929 // These types are known not to freeze.
6930 case i::JS_MAP_KEY_ITERATOR_TYPE:
6931 case i::JS_MAP_KEY_VALUE_ITERATOR_TYPE:
6932 case i::JS_MAP_VALUE_ITERATOR_TYPE:
6933 case i::JS_SET_KEY_VALUE_ITERATOR_TYPE:
6934 case i::JS_SET_VALUE_ITERATOR_TYPE:
6935 case i::JS_GENERATOR_OBJECT_TYPE:
6936 case i::JS_ASYNC_FUNCTION_OBJECT_TYPE:
6937 case i::JS_ASYNC_GENERATOR_OBJECT_TYPE:
6938 case i::JS_ARRAY_ITERATOR_TYPE: {
6939 return false;
6940 }
6941 default:
6942 // TODO(behamilton): Handle any types that fall through here.
6943 return false;
6944 }
6945}
6946
6947class ObjectVisitorDeepFreezer : i::ObjectVisitor {
6948 public:
6949 explicit ObjectVisitorDeepFreezer(i::Isolate* isolate,
6950 Context::DeepFreezeDelegate* delegate)
6951 : isolate_(isolate),
6952 delegate_(delegate),
6953 objects_to_freeze_(isolate),
6954 lazy_accessor_pairs_to_freeze_(isolate) {}
6955
6956 bool DeepFreeze(i::DirectHandle<i::Context> context) {
6957 bool success = VisitObject(i::Cast<i::HeapObject>(*context));
6958 if (success) {
6959 success = InstantiateAndVisitLazyAccessorPairs();
6960 }
6961 DCHECK_EQ(success, !error_.has_value());
6962 if (!success) {
6964 isolate_, NewTypeError(error_->msg_id, error_->name), false);
6965 }
6966 for (const auto& obj : objects_to_freeze_) {
6968 isolate_,
6969 i::JSReceiver::SetIntegrityLevel(isolate_, obj, i::FROZEN,
6971 false);
6972 }
6973 return true;
6974 }
6975
6976 void VisitPointers(i::Tagged<i::HeapObject> host, i::ObjectSlot start,
6977 i::ObjectSlot end) final {
6978 VisitPointersImpl(start, end);
6979 }
6980 void VisitPointers(i::Tagged<i::HeapObject> host, i::MaybeObjectSlot start,
6981 i::MaybeObjectSlot end) final {
6982 VisitPointersImpl(start, end);
6983 }
6984 void VisitMapPointer(i::Tagged<i::HeapObject> host) final {
6985 VisitPointer(host, host->map_slot());
6986 }
6987 void VisitInstructionStreamPointer(i::Tagged<i::Code> host,
6988 i::InstructionStreamSlot slot) final {}
6989 void VisitCustomWeakPointers(i::Tagged<i::HeapObject> host,
6991
6992 private:
6993 struct ErrorInfo {
6994 i::MessageTemplate msg_id;
6996 };
6997
6998 template <typename TSlot>
6999 void VisitPointersImpl(TSlot start, TSlot end) {
7000 for (TSlot current = start; current < end; ++current) {
7001 typename TSlot::TObject object = current.load(isolate_);
7002 i::Tagged<i::HeapObject> heap_object;
7003 if (object.GetHeapObjectIfStrong(&heap_object)) {
7004 if (!VisitObject(heap_object)) {
7005 return;
7006 }
7007 }
7008 }
7009 }
7010
7011 bool FreezeEmbedderObjectAndVisitChildren(i::DirectHandle<i::JSObject> obj) {
7012 DCHECK(delegate_);
7013 LocalVector<Object> children(reinterpret_cast<Isolate*>(isolate_));
7014 if (!delegate_->FreezeEmbedderObjectAndGetChildren(Utils::ToLocal(obj),
7015 children)) {
7016 return false;
7017 }
7018 for (auto child : children) {
7019 if (!VisitObject(
7021 return false;
7022 }
7023 }
7024 return true;
7025 }
7026
7028 DCHECK(!obj.is_null());
7029 if (error_.has_value()) {
7030 return false;
7031 }
7032
7034 i::InstanceType obj_type = obj->map()->instance_type();
7035
7036 // Skip common types that can't contain items to freeze.
7037 if (!MayContainObjectsToFreeze(obj_type)) {
7038 return true;
7039 }
7040
7041 if (!done_list_.insert(obj).second) {
7042 // If we couldn't insert (because it is already in the set) then we're
7043 // done.
7044 return true;
7045 }
7046
7047 if (i::InstanceTypeChecker::IsAccessorPair(obj_type)) {
7048 // For AccessorPairs we need to ensure that the functions they point to
7049 // have been instantiated into actual JavaScript objects that can be
7050 // frozen. If they haven't then we need to save them to instantiate
7051 // (and recurse) before freezing.
7053 if (i::IsFunctionTemplateInfo(accessor_pair->getter()) ||
7054 IsFunctionTemplateInfo(accessor_pair->setter())) {
7055 i::DirectHandle<i::AccessorPair> lazy_accessor_pair(accessor_pair,
7056 isolate_);
7057 lazy_accessor_pairs_to_freeze_.push_back(lazy_accessor_pair);
7058 }
7059 } else if (i::InstanceTypeChecker::IsContext(obj_type)) {
7060 // For contexts we need to ensure that all accessible locals are const.
7061 // If not they could be replaced to bypass freezing.
7062 i::Tagged<i::ScopeInfo> scope_info =
7063 i::Cast<i::Context>(obj)->scope_info();
7064 for (auto it : i::ScopeInfo::IterateLocalNames(scope_info, no_gc)) {
7066 scope_info->ContextLocalMode(it->index()))) {
7067 DCHECK(!error_.has_value());
7068 error_ = ErrorInfo{i::MessageTemplate::kCannotDeepFreezeValue,
7069 i::direct_handle(it->name(), isolate_)};
7070 return false;
7071 }
7072 }
7073 } else if (i::InstanceTypeChecker::IsJSReceiver(obj_type)) {
7075 isolate_);
7076 if (RequiresEmbedderSupportToFreeze(obj_type)) {
7077 auto js_obj = i::Cast<i::JSObject>(receiver);
7078
7079 // External objects don't have slots but still need to be processed by
7080 // the embedder.
7081 if (i::InstanceTypeChecker::IsJSExternalObject(obj_type) ||
7082 js_obj->GetEmbedderFieldCount() > 0) {
7083 if (!delegate_) {
7084 DCHECK(!error_.has_value());
7085 error_ =
7086 ErrorInfo{i::MessageTemplate::kCannotDeepFreezeObject,
7087 i::direct_handle(receiver->class_name(), isolate_)};
7088 return false;
7089 }
7090
7091 // Handle embedder specific types and any v8 children it wants to
7092 // freeze.
7093 if (!FreezeEmbedderObjectAndVisitChildren(js_obj)) {
7094 return false;
7095 }
7096 } else {
7097 DCHECK_EQ(js_obj->GetEmbedderFieldCount(), 0);
7098 }
7099 } else {
7101 i::InstanceTypeChecker::IsJSObject(obj_type),
7102 i::Cast<i::JSObject>(*receiver)->GetEmbedderFieldCount() == 0);
7103 if (!IsJSReceiverSafeToFreeze(obj_type)) {
7104 DCHECK(!error_.has_value());
7105 error_ =
7106 ErrorInfo{i::MessageTemplate::kCannotDeepFreezeObject,
7107 i::direct_handle(receiver->class_name(), isolate_)};
7108 return false;
7109 }
7110 }
7111
7112 // Save this to freeze after we are done. Freezing triggers garbage
7113 // collection which doesn't work well with this visitor pattern, so we
7114 // delay it until after.
7115 objects_to_freeze_.push_back(receiver);
7116
7117 } else {
7118 DCHECK(!i::InstanceTypeChecker::IsAccessorPair(obj_type));
7119 DCHECK(!i::InstanceTypeChecker::IsContext(obj_type));
7120 DCHECK(!i::InstanceTypeChecker::IsJSReceiver(obj_type));
7121 }
7122
7123 DCHECK(!error_.has_value());
7124 i::VisitObject(isolate_, obj, this);
7125 // Iterate sets error_ on failure. We should propagate errors.
7126 return !error_.has_value();
7127 }
7128
7129 bool InstantiateAndVisitLazyAccessorPairs() {
7131 isolate_->native_context();
7132
7133 i::DirectHandleVector<i::AccessorPair> lazy_accessor_pairs_to_freeze(
7134 isolate_);
7135 std::swap(lazy_accessor_pairs_to_freeze, lazy_accessor_pairs_to_freeze_);
7136
7137 for (const auto& accessor_pair : lazy_accessor_pairs_to_freeze) {
7138 i::AccessorPair::GetComponent(isolate_, native_context, accessor_pair,
7140 i::AccessorPair::GetComponent(isolate_, native_context, accessor_pair,
7142 VisitObject(*accessor_pair);
7143 }
7144 // Ensure no new lazy accessor pairs were discovered.
7145 CHECK_EQ(lazy_accessor_pairs_to_freeze_.size(), 0);
7146 return true;
7147 }
7148
7150 Context::DeepFreezeDelegate* delegate_;
7151 std::unordered_set<i::Tagged<i::Object>, i::Object::Hasher> done_list_;
7152 i::DirectHandleVector<i::JSReceiver> objects_to_freeze_;
7153 i::DirectHandleVector<i::AccessorPair> lazy_accessor_pairs_to_freeze_;
7154 std::optional<ErrorInfo> error_;
7155};
7156
7157} // namespace
7158
7160 auto env = Utils::OpenDirectHandle(this);
7161 i::Isolate* i_isolate = env->GetIsolate();
7162
7163 // TODO(behamilton): Incorporate compatibility improvements similar to NodeJS:
7164 // https://github.com/nodejs/node/blob/main/lib/internal/freeze_intrinsics.js
7165 // These need to be done before freezing.
7166
7167 Local<Context> context = Utils::ToLocal(env);
7168 ENTER_V8_NO_SCRIPT(i_isolate, context, Context, DeepFreeze, i::HandleScope);
7169 ObjectVisitorDeepFreezer vfreezer(i_isolate, delegate);
7170 has_exception = !vfreezer.DeepFreeze(env);
7171
7173 return JustVoid();
7174}
7175
7177 return reinterpret_cast<Isolate*>(
7178 Utils::OpenDirectHandle(this)->GetIsolate());
7179}
7180
7182 auto env = Utils::OpenDirectHandle(this);
7183 Utils::ApiCheck(i::IsNativeContext(*env), "v8::Context::GetMicrotaskQueue",
7184 "Must be called on a native context");
7185 return env->microtask_queue();
7186}
7187
7189 auto context = Utils::OpenDirectHandle(this);
7190 i::Isolate* i_isolate = context->GetIsolate();
7191 Utils::ApiCheck(i::IsNativeContext(*context),
7192 "v8::Context::SetMicrotaskQueue",
7193 "Must be called on a native context");
7195 Utils::ApiCheck(!context->microtask_queue()->IsRunningMicrotasks(),
7196 "v8::Context::SetMicrotaskQueue",
7197 "Must not be running microtasks");
7198 Utils::ApiCheck(context->microtask_queue()->GetMicrotasksScopeDepth() == 0,
7199 "v8::Context::SetMicrotaskQueue",
7200 "Must not have microtask scope pushed");
7201 Utils::ApiCheck(impl->EnteredContextCount() == 0,
7202 "v8::Context::SetMicrotaskQueue()",
7203 "Cannot set Microtask Queue with an entered context");
7204 context->set_microtask_queue(i_isolate,
7205 static_cast<const i::MicrotaskQueue*>(queue));
7206}
7207
7209 auto context = Utils::OpenDirectHandle(this);
7210 i::Isolate* i_isolate = context->GetIsolate();
7211 i::DirectHandle<i::JSGlobalProxy> global(context->global_proxy(), i_isolate);
7212 // TODO(chromium:324812): This should always return the global proxy
7213 // but can't presently as calls to GetPrototype will return the wrong result.
7214 if (global->IsDetachedFrom(context->global_object())) {
7215 i::DirectHandle<i::JSObject> result(context->global_object(), i_isolate);
7216 return Utils::ToLocal(result);
7217 }
7218 return Utils::ToLocal(i::Cast<i::JSObject>(global));
7219}
7220
7222 auto context = Utils::OpenDirectHandle(this);
7223 i::Isolate* i_isolate = context->GetIsolate();
7225 i_isolate->DetachGlobal(context);
7226}
7227
7229 auto context = Utils::OpenDirectHandle(this);
7230 i::Isolate* i_isolate = context->GetIsolate();
7231 return Utils::ToLocal(
7232 i::direct_handle(context->extras_binding_object(), i_isolate));
7233}
7234
7236 auto context = Utils::OpenDirectHandle(this);
7237 i::Isolate* i_isolate = context->GetIsolate();
7239 context->set_allow_code_gen_from_strings(
7240 i::ReadOnlyRoots(i_isolate).boolean_value(allow));
7241}
7242
7244 auto context = Utils::OpenDirectHandle(this);
7245 return !IsFalse(context->allow_code_gen_from_strings(),
7246 context->GetIsolate());
7247}
7248
7250 auto context = Utils::OpenDirectHandle(this);
7251 auto error_handle = Utils::OpenDirectHandle(*error);
7252 context->set_error_message_for_code_gen_from_strings(*error_handle);
7253}
7254
7256 auto context = Utils::OpenDirectHandle(this);
7257 auto error_handle = Utils::OpenDirectHandle(*error);
7258 context->set_error_message_for_wasm_code_gen(*error_handle);
7259}
7260
7263 auto context = Utils::OpenDirectHandle(this);
7264 i::Isolate* i_isolate = context->GetIsolate();
7265 if (callback == nullptr) {
7266 context->set_script_execution_callback(
7267 i::ReadOnlyRoots(i_isolate).undefined_value());
7268 } else {
7269 SET_FIELD_WRAPPED(i_isolate, context, set_script_execution_callback,
7271 }
7272}
7273
7275 Local<Function> before_hook,
7276 Local<Function> after_hook,
7277 Local<Function> resolve_hook) {
7278#ifdef V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS
7279 auto context = Utils::OpenDirectHandle(this);
7280 i::Isolate* i_isolate = context->GetIsolate();
7281
7282 auto undefined = i_isolate->factory()->undefined_value();
7283 i::DirectHandle<i::Object> init = undefined;
7284 i::DirectHandle<i::Object> before = undefined;
7285 i::DirectHandle<i::Object> after = undefined;
7286 i::DirectHandle<i::Object> resolve = undefined;
7287
7288 bool has_hook = false;
7289
7290 if (!init_hook.IsEmpty()) {
7291 init = Utils::OpenDirectHandle(*init_hook);
7292 has_hook = true;
7293 }
7294 if (!before_hook.IsEmpty()) {
7295 before = Utils::OpenDirectHandle(*before_hook);
7296 has_hook = true;
7297 }
7298 if (!after_hook.IsEmpty()) {
7299 after = Utils::OpenDirectHandle(*after_hook);
7300 has_hook = true;
7301 }
7302 if (!resolve_hook.IsEmpty()) {
7303 resolve = Utils::OpenDirectHandle(*resolve_hook);
7304 has_hook = true;
7305 }
7306
7307 i_isolate->SetHasContextPromiseHooks(has_hook);
7308
7309 context->native_context()->set_promise_hook_init_function(*init);
7310 context->native_context()->set_promise_hook_before_function(*before);
7311 context->native_context()->set_promise_hook_after_function(*after);
7312 context->native_context()->set_promise_hook_resolve_function(*resolve);
7313#else // V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS
7314 Utils::ApiCheck(false, "v8::Context::SetPromiseHook",
7315 "V8 was compiled without JavaScript Promise hooks");
7316#endif // V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS
7317}
7318
7321 i::Tagged<i::Object> i_object = *Utils::OpenDirectHandle(*object);
7322 if (!IsJSArray(i_object)) return false;
7323 return Utils::OpenDirectHandle(this)
7324 ->native_context()
7325 ->HasTemplateLiteralObject(i::Cast<i::JSArray>(i_object));
7326}
7327
7329 Isolate* v8_isolate, metrics::Recorder::ContextId id) {
7330 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7331 return i_isolate->GetContextFromRecorderContextId(id);
7332}
7333
7335 Local<Context> context) {
7336 auto i_context = Utils::OpenDirectHandle(*context);
7337 i::Isolate* i_isolate = i_context->GetIsolate();
7338 return i_isolate->GetOrRegisterRecorderContextId(
7339 direct_handle(i_context->native_context(), i_isolate));
7340}
7341
7343 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7344 return *i_isolate->GetCurrentLongTaskStats();
7345}
7346
7347namespace {
7348i::ValueHelper::InternalRepresentationType GetSerializedDataFromFixedArray(
7349 i::Isolate* i_isolate, i::Tagged<i::FixedArray> list, size_t index) {
7350 if (index < static_cast<size_t>(list->length())) {
7351 int int_index = static_cast<int>(index);
7352 i::Tagged<i::Object> object = list->get(int_index);
7353 if (!IsTheHole(object, i_isolate)) {
7354 list->set_the_hole(i_isolate, int_index);
7355 // Shrink the list so that the last element is not the hole (unless it's
7356 // the first element, because we don't want to end up with a non-canonical
7357 // empty FixedArray).
7358 int last = list->length() - 1;
7359 while (last >= 0 && list->is_the_hole(i_isolate, last)) last--;
7360 if (last != -1) list->RightTrim(i_isolate, last + 1);
7361 return i::Handle<i::Object>(object, i_isolate).repr();
7362 }
7363 }
7364 return i::ValueHelper::kEmpty;
7365}
7366} // anonymous namespace
7367
7368i::ValueHelper::InternalRepresentationType Context::GetDataFromSnapshotOnce(
7369 size_t index) {
7370 auto context = Utils::OpenDirectHandle(this);
7371 i::Isolate* i_isolate = context->GetIsolate();
7372 auto list = i::Cast<i::FixedArray>(context->serialized_objects());
7373 return GetSerializedDataFromFixedArray(i_isolate, list, index);
7374}
7375
7377 PREPARE_FOR_EXECUTION(context, ObjectTemplate, NewInstance);
7378 auto self = Utils::OpenDirectHandle(this);
7380 has_exception = !ToLocal<Object>(
7381 i::ApiNatives::InstantiateObject(i_isolate, self), &result);
7384}
7385
7387 auto obj = Utils::OpenDirectHandle(that);
7388 Utils::ApiCheck(i::IsObjectTemplateInfo(*obj), "v8::ObjectTemplate::Cast",
7389 "Value is not an ObjectTemplate");
7390}
7391
7393 auto obj = Utils::OpenDirectHandle(that);
7394 Utils::ApiCheck(i::IsDictionaryTemplateInfo(*obj),
7395 "v8::DictionaryTemplate::Cast",
7396 "Value is not an DictionaryTemplate");
7397}
7398
7400 auto obj = Utils::OpenDirectHandle(that);
7401 Utils::ApiCheck(i::IsFunctionTemplateInfo(*obj), "v8::FunctionTemplate::Cast",
7402 "Value is not a FunctionTemplate");
7403}
7404
7406 auto obj = Utils::OpenDirectHandle(that);
7407 Utils::ApiCheck(i::IsFunctionTemplateInfo(*obj), "v8::Signature::Cast",
7408 "Value is not a Signature");
7409}
7410
7412 PREPARE_FOR_EXECUTION(context, FunctionTemplate, GetFunction);
7413 auto self = Utils::OpenDirectHandle(this);
7415 has_exception =
7416 !ToLocal<Function>(i::ApiNatives::InstantiateFunction(
7417 i_isolate, i_isolate->native_context(), self),
7418 &result);
7421}
7422
7424 auto self = Utils::OpenDirectHandle(this);
7425 i::Isolate* i_isolate = self->GetIsolateChecked();
7426 API_RCS_SCOPE(i_isolate, FunctionTemplate, NewRemoteInstance);
7427 i::HandleScope scope(i_isolate);
7429 EnsureConstructor(i_isolate, *InstanceTemplate());
7430 Utils::ApiCheck(constructor->needs_access_check(),
7431 "v8::FunctionTemplate::NewRemoteInstance",
7432 "InstanceTemplate needs to have access checks enabled");
7433 i::DirectHandle<i::AccessCheckInfo> access_check_info(
7434 i::Cast<i::AccessCheckInfo>(constructor->GetAccessCheckInfo()),
7435 i_isolate);
7437 access_check_info->named_interceptor() != i::Tagged<i::Object>(),
7438 "v8::FunctionTemplate::NewRemoteInstance",
7439 "InstanceTemplate needs to have access check handlers");
7441 if (!i::ApiNatives::InstantiateRemoteObject(
7442 Utils::OpenDirectHandle(*InstanceTemplate()))
7443 .ToHandle(&object)) {
7444 return MaybeLocal<Object>();
7445 }
7446 return Utils::ToLocal(scope.CloseAndEscape(object));
7447}
7448
7450 auto self = Utils::OpenDirectHandle(this);
7451 auto obj = Utils::OpenDirectHandle(*value);
7452 if (i::IsJSObject(*obj) && self->IsTemplateFor(i::Cast<i::JSObject>(*obj))) {
7453 return true;
7454 }
7455 if (i::IsJSGlobalProxy(*obj)) {
7456 // If it's a global proxy, then test with the global object. Note that the
7457 // inner global object may not necessarily be a JSGlobalObject.
7458 auto jsobj = i::Cast<i::JSObject>(*obj);
7459 i::PrototypeIterator iter(jsobj->GetIsolate(), jsobj->map());
7460 // The global proxy should always have a prototype, as it is a bug to call
7461 // this on a detached JSGlobalProxy.
7462 DCHECK(!iter.IsAtEnd());
7463 return self->IsTemplateFor(iter.GetCurrent<i::JSObject>());
7464 }
7465 return false;
7466}
7467
7469 v8::Local<v8::Value> value) const {
7471 auto self = Utils::OpenDirectHandle(this);
7473 return self->IsLeafTemplateForApiObject(object);
7474}
7475
7477 auto self = Utils::OpenDirectHandle(this);
7478 i::Isolate* i_isolate = self->GetIsolateChecked();
7479 i::FunctionTemplateInfo::SealAndPrepareForPromotionToReadOnly(i_isolate,
7480 self);
7481}
7482
7483Local<External> v8::External::New(Isolate* v8_isolate, void* value) {
7484 static_assert(sizeof(value) == sizeof(i::Address));
7485 // Nullptr is not allowed here because serialization/deserialization of
7486 // nullptr external api references is not possible as nullptr is used as an
7487 // external_references table terminator, see v8::SnapshotCreator()
7488 // constructors.
7489 DCHECK_NOT_NULL(value);
7490 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7491 API_RCS_SCOPE(i_isolate, External, New);
7494 i_isolate->factory()->NewExternal(value);
7495 return Utils::ExternalToLocal(external);
7496}
7497
7498void* External::Value() const {
7501 ->value(isolate);
7502}
7503
7504// anonymous namespace for string creation helper functions
7505namespace {
7506
7507inline int StringLength(const char* string) {
7508 size_t len = strlen(string);
7509 CHECK_GE(i::kMaxInt, len);
7510 return static_cast<int>(len);
7511}
7512
7513inline int StringLength(const uint8_t* string) {
7514 return StringLength(reinterpret_cast<const char*>(string));
7515}
7516
7517inline int StringLength(const uint16_t* string) {
7518 size_t length = 0;
7519 while (string[length] != '\0') length++;
7520 CHECK_GE(i::kMaxInt, length);
7521 return static_cast<int>(length);
7522}
7523
7525inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
7526 NewStringType type,
7527 base::Vector<const char> string) {
7528 if (type == NewStringType::kInternalized) {
7529 return factory->InternalizeUtf8String(string);
7530 }
7531 return factory->NewStringFromUtf8(string);
7532}
7533
7535inline i::MaybeHandle<i::String> NewString(i::Factory* factory,
7536 NewStringType type,
7537 base::Vector<const uint8_t> string) {
7538 if (type == NewStringType::kInternalized) {
7539 return factory->InternalizeString(string);
7540 }
7541 return factory->NewStringFromOneByte(string);
7542}
7543
7545inline i::MaybeHandle<i::String> NewString(
7546 i::Factory* factory, NewStringType type,
7547 base::Vector<const uint16_t> string) {
7548 if (type == NewStringType::kInternalized) {
7549 return factory->InternalizeString(string);
7550 }
7551 return factory->NewStringFromTwoByte(string);
7552}
7553
7554static_assert(v8::String::kMaxLength == i::String::kMaxLength);
7555
7556} // anonymous namespace
7557
7558// TODO(dcarney): throw a context free exception.
7559#define NEW_STRING(v8_isolate, class_name, function_name, Char, data, type, \
7560 length) \
7561 MaybeLocal<String> result; \
7562 if (length == 0) { \
7563 result = String::Empty(v8_isolate); \
7564 } else if (length > 0 && \
7565 static_cast<uint32_t>(length) > i::String::kMaxLength) { \
7566 result = MaybeLocal<String>(); \
7567 } else { \
7568 i::Isolate* i_isolate = reinterpret_cast<internal::Isolate*>(v8_isolate); \
7569 ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate); \
7570 API_RCS_SCOPE(i_isolate, class_name, function_name); \
7571 if (length < 0) length = StringLength(data); \
7572 i::DirectHandle<i::String> handle_result = \
7573 NewString(i_isolate->factory(), type, \
7574 base::Vector<const Char>(data, length)) \
7575 .ToHandleChecked(); \
7576 result = Utils::ToLocal(handle_result); \
7577 }
7578
7580 const char* literal,
7581 NewStringType type, int length) {
7582 DCHECK_LE(length, i::String::kMaxLength);
7583 i::Isolate* i_isolate = reinterpret_cast<internal::Isolate*>(v8_isolate);
7585 API_RCS_SCOPE(i_isolate, String, NewFromUtf8Literal);
7586 i::DirectHandle<i::String> handle_result =
7587 NewString(i_isolate->factory(), type,
7589 .ToHandleChecked();
7590 return Utils::ToLocal(handle_result);
7591}
7592
7593MaybeLocal<String> String::NewFromUtf8(Isolate* v8_isolate, const char* data,
7594 NewStringType type, int length) {
7595 NEW_STRING(v8_isolate, String, NewFromUtf8, char, data, type, length);
7596 return result;
7597}
7598
7600 const uint8_t* data,
7601 NewStringType type, int length) {
7602 NEW_STRING(v8_isolate, String, NewFromOneByte, uint8_t, data, type, length);
7603 return result;
7604}
7605
7607 const uint16_t* data,
7608 NewStringType type, int length) {
7609 NEW_STRING(v8_isolate, String, NewFromTwoByte, uint16_t, data, type, length);
7610 return result;
7611}
7612
7614 Local<String> right) {
7615 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7616 auto left_string = Utils::OpenHandle(*left);
7618 API_RCS_SCOPE(i_isolate, String, Concat);
7619 auto right_string = Utils::OpenHandle(*right);
7620 // If we are steering towards a range error, do not wait for the error to be
7621 // thrown, and return the null handle instead.
7622 if (left_string->length() + right_string->length() > i::String::kMaxLength) {
7623 return Local<String>();
7624 }
7626 i_isolate->factory()
7627 ->NewConsString(left_string, right_string)
7628 .ToHandleChecked();
7629 return Utils::ToLocal(result);
7630}
7631
7633 Isolate* v8_isolate, v8::String::ExternalStringResource* resource) {
7634 CHECK(resource && resource->data());
7635 // TODO(dcarney): throw a context free exception.
7636 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
7637 return MaybeLocal<String>();
7638 }
7639 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7641 API_RCS_SCOPE(i_isolate, String, NewExternalTwoByte);
7642 if (resource->length() > 0) {
7644 i_isolate->factory()
7646 .ToHandleChecked();
7647 return Utils::ToLocal(string);
7648 } else {
7649 // The resource isn't going to be used, free it immediately.
7650 resource->Unaccount(v8_isolate);
7651 resource->Dispose();
7652 return Utils::ToLocal(i_isolate->factory()->empty_string());
7653 }
7654}
7655
7657 Isolate* v8_isolate, v8::String::ExternalOneByteStringResource* resource) {
7658 CHECK_NOT_NULL(resource);
7659 // TODO(dcarney): throw a context free exception.
7660 if (resource->length() > static_cast<size_t>(i::String::kMaxLength)) {
7661 return MaybeLocal<String>();
7662 }
7663 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7665 API_RCS_SCOPE(i_isolate, String, NewExternalOneByte);
7666 if (resource->length() == 0) {
7667 // The resource isn't going to be used, free it immediately.
7668 resource->Unaccount(v8_isolate);
7669 resource->Dispose();
7670 return Utils::ToLocal(i_isolate->factory()->empty_string());
7671 }
7672 CHECK_NOT_NULL(resource->data());
7674 i_isolate->factory()
7676 .ToHandleChecked();
7677 return Utils::ToLocal(string);
7678}
7679
7681 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i::Isolate::Current());
7682 return MakeExternal(isolate, resource);
7683}
7684
7688
7690
7691 if (i::IsThinString(obj)) {
7692 obj = i::Cast<i::ThinString>(obj)->actual();
7693 }
7694
7695 if (!obj->SupportsExternalization(Encoding::TWO_BYTE_ENCODING)) {
7696 return false;
7697 }
7698
7699 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7701
7702 CHECK(resource && resource->data());
7703
7704 bool result = obj->MakeExternal(i_isolate, resource);
7705 DCHECK_IMPLIES(result, HasExternalStringResource(obj));
7706 return result;
7707}
7708
7711 v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(i::Isolate::Current());
7712 return MakeExternal(isolate, resource);
7713}
7714
7718
7720
7721 if (i::IsThinString(obj)) {
7722 obj = i::Cast<i::ThinString>(obj)->actual();
7723 }
7724
7725 if (!obj->SupportsExternalization(Encoding::ONE_BYTE_ENCODING)) {
7726 return false;
7727 }
7728
7729 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
7731
7732 CHECK(resource && resource->data());
7733
7734 bool result = obj->MakeExternal(i_isolate, resource);
7735 DCHECK_IMPLIES(result, HasExternalStringResource(obj));
7736 return result;
7737}
7738
7741
7742 return obj->SupportsExternalization(encoding);
7743}
7744
7746 auto self = Utils::OpenDirectHandle(this);
7747 auto other = Utils::OpenDirectHandle(*that);
7748 return self->Equals(*other);
7749}
7750
7752 i::Isolate* i_isolate = Utils::OpenDirectHandle(this)->GetIsolate();
7753 return reinterpret_cast<Isolate*>(i_isolate);
7754}
7755
7757 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7758 API_RCS_SCOPE(i_isolate, Object, New);
7761 i_isolate->factory()->NewJSObject(i_isolate->object_function());
7762 return Utils::ToLocal(obj);
7763}
7764
7765namespace {
7766
7767// TODO(v8:7569): This is a workaround for the Handle vs MaybeHandle difference
7768// in the return types of the different Add functions:
7769// OrderedNameDictionary::Add returns MaybeHandle, NameDictionary::Add returns
7770// Handle.
7771template <typename T>
7772i::DirectHandle<T> ToHandle(i::Handle<T> h) {
7773 return h;
7774}
7775template <typename T>
7777 return h.ToHandleChecked();
7778}
7779
7780template <typename T>
7782 return h;
7783}
7784template <typename T>
7786 return h.ToHandleChecked();
7787}
7788
7789template <typename Dictionary>
7790void AddPropertiesAndElementsToObject(
7791 i::Isolate* i_isolate, i::DirectHandle<Dictionary>& properties,
7792 i::DirectHandle<i::FixedArrayBase>& elements, Local<Name>* names,
7793 Local<Value>* values, size_t length) {
7794 for (size_t i = 0; i < length; ++i) {
7795 auto name = Utils::OpenDirectHandle(*names[i]);
7796 auto value = Utils::OpenDirectHandle(*values[i]);
7797
7798 // See if the {name} is a valid array index, in which case we need to
7799 // add the {name}/{value} pair to the {elements}, otherwise they end
7800 // up in the {properties} backing store.
7801 uint32_t index;
7802 if (name->AsArrayIndex(&index)) {
7803 // If this is the first element, allocate a proper
7804 // dictionary elements backing store for {elements}.
7805 if (!IsNumberDictionary(*elements)) {
7806 elements =
7807 i::NumberDictionary::New(i_isolate, static_cast<int>(length));
7808 }
7809 elements = i::NumberDictionary::Set(
7810 i_isolate, i::Cast<i::NumberDictionary>(elements), index, value);
7811 } else {
7812 // Internalize the {name} first.
7813 name = i_isolate->factory()->InternalizeName(name);
7814 i::InternalIndex const entry = properties->FindEntry(i_isolate, name);
7815 if (entry.is_not_found()) {
7816 // Add the {name}/{value} pair as a new entry.
7817 properties = ToHandle(Dictionary::Add(
7818 i_isolate, properties, name, value, i::PropertyDetails::Empty()));
7819 } else {
7820 // Overwrite the {entry} with the {value}.
7821 properties->ValueAtPut(entry, *value);
7822 }
7823 }
7824 }
7825}
7826
7827} // namespace
7828
7830 Local<Value> prototype_or_null,
7831 Local<Name>* names, Local<Value>* values,
7832 size_t length) {
7833 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7835 if (!Utils::ApiCheck(
7836 i::TryCast(Utils::OpenDirectHandle(*prototype_or_null), &proto),
7837 "v8::Object::New", "prototype must be null or object")) {
7838 return Local<v8::Object>();
7839 }
7840 API_RCS_SCOPE(i_isolate, Object, New);
7842
7844 i_isolate->factory()->empty_fixed_array();
7845
7846 // We assume that this API is mostly used to create objects with named
7847 // properties, and so we default to creating a properties backing store
7848 // large enough to hold all of them, while we start with no elements
7849 // (see http://bit.ly/v8-fast-object-create-cpp for the motivation).
7852 i_isolate->factory()->NewSwissNameDictionary(static_cast<int>(length));
7853 AddPropertiesAndElementsToObject(i_isolate, properties, elements, names,
7854 values, length);
7857 proto, properties, elements);
7858 return Utils::ToLocal(obj);
7859 } else {
7861 i::NameDictionary::New(i_isolate, static_cast<int>(length));
7862 AddPropertiesAndElementsToObject(i_isolate, properties, elements, names,
7863 values, length);
7866 proto, properties, elements);
7867 return Utils::ToLocal(obj);
7868 }
7869}
7870
7872 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7873 API_RCS_SCOPE(i_isolate, NumberObject, New);
7875 i::DirectHandle<i::Object> number = i_isolate->factory()->NewNumber(value);
7877 i::Object::ToObject(i_isolate, number).ToHandleChecked();
7878 return Utils::ToLocal(obj);
7879}
7880
7882 auto obj = Utils::OpenDirectHandle(this);
7883 auto js_primitive_wrapper = i::Cast<i::JSPrimitiveWrapper>(obj);
7884 API_RCS_SCOPE(js_primitive_wrapper->GetIsolate(), NumberObject, NumberValue);
7885 return i::Object::NumberValue(
7886 i::Cast<i::Number>(js_primitive_wrapper->value()));
7887}
7888
7890 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7891 API_RCS_SCOPE(i_isolate, BigIntObject, New);
7893 i::DirectHandle<i::Object> bigint = i::BigInt::FromInt64(i_isolate, value);
7895 i::Object::ToObject(i_isolate, bigint).ToHandleChecked();
7896 return Utils::ToLocal(obj);
7897}
7898
7900 auto obj = Utils::OpenDirectHandle(this);
7901 auto js_primitive_wrapper = i::Cast<i::JSPrimitiveWrapper>(obj);
7902 i::Isolate* i_isolate = js_primitive_wrapper->GetIsolate();
7903 API_RCS_SCOPE(i_isolate, BigIntObject, BigIntValue);
7904 return Utils::ToLocal(i::direct_handle(
7905 i::Cast<i::BigInt>(js_primitive_wrapper->value()), i_isolate));
7906}
7907
7909 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7910 API_RCS_SCOPE(i_isolate, BooleanObject, New);
7912 i::DirectHandle<i::Object> boolean = i_isolate->factory()->ToBoolean(value);
7914 i::Object::ToObject(i_isolate, boolean).ToHandleChecked();
7915 return Utils::ToLocal(obj);
7916}
7917
7920 i::Tagged<i::JSPrimitiveWrapper> js_primitive_wrapper =
7922 i::Isolate* i_isolate = js_primitive_wrapper->GetIsolate();
7923 API_RCS_SCOPE(i_isolate, BooleanObject, BooleanValue);
7924 return i::IsTrue(js_primitive_wrapper->value(), i_isolate);
7925}
7926
7928 Local<String> value) {
7929 auto string = Utils::OpenDirectHandle(*value);
7930 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7931 API_RCS_SCOPE(i_isolate, StringObject, New);
7934 i::Object::ToObject(i_isolate, string).ToHandleChecked();
7935 return Utils::ToLocal(obj);
7936}
7937
7939 auto obj = Utils::OpenDirectHandle(this);
7940 auto js_primitive_wrapper = i::Cast<i::JSPrimitiveWrapper>(obj);
7941 i::Isolate* i_isolate = js_primitive_wrapper->GetIsolate();
7942 API_RCS_SCOPE(i_isolate, StringObject, StringValue);
7943 return Utils::ToLocal(i::direct_handle(
7944 i::Cast<i::String>(js_primitive_wrapper->value()), i_isolate));
7945}
7946
7948 Local<Symbol> value) {
7949 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
7950 API_RCS_SCOPE(i_isolate, SymbolObject, New);
7953 i::Object::ToObject(i_isolate, Utils::OpenDirectHandle(*value))
7954 .ToHandleChecked();
7955 return Utils::ToLocal(obj);
7956}
7957
7959 auto obj = Utils::OpenDirectHandle(this);
7960 auto js_primitive_wrapper = i::Cast<i::JSPrimitiveWrapper>(obj);
7961 i::Isolate* i_isolate = js_primitive_wrapper->GetIsolate();
7962 API_RCS_SCOPE(i_isolate, SymbolObject, SymbolValue);
7963 return Utils::ToLocal(i::direct_handle(
7964 i::Cast<i::Symbol>(js_primitive_wrapper->value()), i_isolate));
7965}
7966
7968 if (std::isnan(time)) {
7969 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
7970 time = std::numeric_limits<double>::quiet_NaN();
7971 }
7972 PREPARE_FOR_EXECUTION(context, Date, New);
7974 has_exception =
7975 !ToLocal<Value>(i::JSDate::New(i_isolate->date_function(),
7976 i_isolate->date_function(), time),
7977 &result);
7980}
7981
7983 PREPARE_FOR_EXECUTION(context, Date, Parse);
7984 auto string = Utils::OpenDirectHandle(*value);
7985 double time = ParseDateTimeString(i_isolate, string);
7986
7988 has_exception =
7989 !ToLocal<Value>(i::JSDate::New(i_isolate->date_function(),
7990 i_isolate->date_function(), time),
7991 &result);
7992
7995}
7996
7997double v8::Date::ValueOf() const {
7998 auto obj = Utils::OpenDirectHandle(this);
7999 auto jsdate = i::Cast<i::JSDate>(obj);
8000 return jsdate->value();
8001}
8002
8004 auto obj = Utils::OpenDirectHandle(this);
8005 auto jsdate = i::Cast<i::JSDate>(obj);
8006 i::Isolate* i_isolate = jsdate->GetIsolate();
8007 i::DateBuffer buffer =
8008 i::ToDateString(jsdate->value(), i_isolate->date_cache(),
8009 i::ToDateStringMode::kISODateAndTime);
8011 i_isolate->factory()
8013 .ToHandleChecked();
8014 return Utils::ToLocal(str);
8015}
8016
8018 auto obj = Utils::OpenDirectHandle(this);
8019 auto jsdate = i::Cast<i::JSDate>(obj);
8020 i::Isolate* i_isolate = jsdate->GetIsolate();
8021 i::DateBuffer buffer =
8022 i::ToDateString(jsdate->value(), i_isolate->date_cache(),
8023 i::ToDateStringMode::kUTCDateAndTime);
8025 i_isolate->factory()
8027 .ToHandleChecked();
8028 return Utils::ToLocal(str);
8029}
8030
8031// Assert that the static TimeZoneDetection cast in
8032// DateTimeConfigurationChangeNotification is valid.
8033#define TIME_ZONE_DETECTION_ASSERT_EQ(value) \
8034 static_assert( \
8035 static_cast<int>(v8::Isolate::TimeZoneDetection::value) == \
8036 static_cast<int>(base::TimezoneCache::TimeZoneDetection::value));
8039#undef TIME_ZONE_DETECTION_ASSERT_EQ
8040
8042 Local<String> pattern, Flags flags) {
8043 PREPARE_FOR_EXECUTION(context, RegExp, New);
8045 has_exception = !ToLocal<RegExp>(
8046 i::JSRegExp::New(i_isolate, Utils::OpenDirectHandle(*pattern),
8047 static_cast<i::JSRegExp::Flags>(flags)),
8048 &result);
8051}
8052
8054 Local<Context> context, Local<String> pattern, Flags flags,
8055 uint32_t backtrack_limit) {
8056 Utils::ApiCheck(i::Smi::IsValid(backtrack_limit),
8057 "v8::RegExp::NewWithBacktrackLimit",
8058 "backtrack_limit is too large or too small");
8059 Utils::ApiCheck(backtrack_limit != i::JSRegExp::kNoBacktrackLimit,
8060 "v8::RegExp::NewWithBacktrackLimit",
8061 "Must set backtrack_limit");
8062 PREPARE_FOR_EXECUTION(context, RegExp, New);
8064 has_exception = !ToLocal<RegExp>(
8065 i::JSRegExp::New(i_isolate, Utils::OpenDirectHandle(*pattern),
8066 static_cast<i::JSRegExp::Flags>(flags), backtrack_limit),
8067 &result);
8070}
8071
8073 auto obj = Utils::OpenDirectHandle(this);
8074 i::Isolate* i_isolate = obj->GetIsolate();
8075 return Utils::ToLocal(i::direct_handle(obj->EscapedPattern(), i_isolate));
8076}
8077
8078// Assert that the static flags cast in GetFlags is valid.
8079#define REGEXP_FLAG_ASSERT_EQ(flag) \
8080 static_assert(static_cast<int>(v8::RegExp::flag) == \
8081 static_cast<int>(i::JSRegExp::flag))
8091#undef REGEXP_FLAG_ASSERT_EQ
8092
8094 auto obj = Utils::OpenDirectHandle(this);
8095 return RegExp::Flags(static_cast<int>(obj->flags()));
8096}
8097
8099 Local<v8::String> subject) {
8100 PREPARE_FOR_EXECUTION(context, RegExp, Exec);
8101
8102 auto regexp = Utils::OpenHandle(this);
8103 auto subject_string = Utils::OpenDirectHandle(*subject);
8104
8105 // TODO(jgruber): RegExpUtils::RegExpExec was not written with efficiency in
8106 // mind. It fetches the 'exec' property and then calls it through JSEntry.
8107 // Unfortunately, this is currently the only full implementation of
8108 // RegExp.prototype.exec available in C++.
8110 has_exception = !ToLocal<Object>(
8111 i::RegExpUtils::RegExpExec(i_isolate, regexp, subject_string,
8112 i_isolate->factory()->undefined_value()),
8113 &result);
8114
8117}
8118
8119Local<v8::Array> v8::Array::New(Isolate* v8_isolate, int length) {
8120 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8121 API_RCS_SCOPE(i_isolate, Array, New);
8123 int real_length = length > 0 ? length : 0;
8125 i_isolate->factory()->NewJSArray(real_length);
8126 i::DirectHandle<i::Number> length_obj =
8127 i_isolate->factory()->NewNumberFromInt(real_length);
8128 obj->set_length(*length_obj);
8129 return Utils::ToLocal(obj);
8130}
8131
8133 size_t length) {
8134 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8135 i::Factory* factory = i_isolate->factory();
8136 API_RCS_SCOPE(i_isolate, Array, New);
8138 int len = static_cast<int>(length);
8139
8141 for (int i = 0; i < len; i++) {
8142 auto element = Utils::OpenDirectHandle(*elements[i]);
8143 result->set(i, *element);
8144 }
8145
8146 return Utils::ToLocal(
8148}
8149
8150// static
8152 Local<Context> context, size_t length,
8153 std::function<MaybeLocal<v8::Value>()> next_value_callback) {
8154 PREPARE_FOR_EXECUTION(context, Array, New);
8155 // We should never see an exception here as V8 will not create an
8156 // exception and the callback is invoked by the embedder where the exception
8157 // is already scheduled.
8158 USE(has_exception);
8159 i::Factory* factory = i_isolate->factory();
8160 const int len = static_cast<int>(length);
8161 i::DirectHandle<i::FixedArray> backing = factory->NewFixedArray(len);
8163 for (int i = 0; i < len; i++) {
8164 MaybeLocal<v8::Value> maybe_value = next_value_callback();
8165 // The embedder may signal to abort creation on exception via an empty
8166 // local.
8167 if (!maybe_value.ToLocal(&value)) {
8168 CHECK(i_isolate->has_exception());
8169 return {};
8170 }
8171 backing->set(i, *Utils::OpenDirectHandle(*value));
8172 }
8173 RETURN_ESCAPED(Utils::ToLocal(
8174 factory->NewJSArrayWithElements(backing, i::PACKED_ELEMENTS, len)));
8175}
8176
8177namespace internal {
8178
8180 Tagged<Number> length = array->length();
8181 if (IsSmi(length)) return Smi::ToInt(length);
8182 return static_cast<uint32_t>(Object::NumberValue(length));
8183}
8184
8185} // namespace internal
8186
8187uint32_t v8::Array::Length() const {
8189}
8190
8191namespace internal {
8192
8194 if (IsCustomElementsReceiverMap(array->map())) return false;
8195 if (array->GetElementsAccessor()->HasAccessors(*array)) return false;
8196 if (!JSObject::PrototypeHasNoElements(isolate, *array)) return false;
8197 return true;
8198}
8199
8201 kException = static_cast<int>(v8::Array::CallbackResult::kException),
8202 kBreak = static_cast<int>(v8::Array::CallbackResult::kBreak),
8203 kSlowPath,
8204 kFinished,
8205};
8206
8208 Isolate* isolate,
8210 void* callback_data) {
8211 // Instead of relying on callers to check condition, this function returns
8212 // {kSlowPath} for situations it can't handle.
8213 // Most code paths below don't allocate, and rely on {callback} not allocating
8214 // either, but this isn't enforced with {DisallowHeapAllocation} to allow
8215 // embedders to allocate error objects before terminating the iteration.
8216 // Since {callback} must not allocate anyway, we can get away with fake
8217 // handles, reducing per-element overhead.
8218 if (!CanUseFastIteration(isolate, array)) return FastIterateResult::kSlowPath;
8219 using Result = v8::Array::CallbackResult;
8220 DisallowJavascriptExecution no_js(isolate);
8221 uint32_t length = GetLength(*array);
8222 if (length == 0) return FastIterateResult::kFinished;
8223 switch (array->GetElementsKind()) {
8225 case PACKED_ELEMENTS:
8229 Tagged<FixedArray> elements = Cast<FixedArray>(array->elements());
8230 for (uint32_t i = 0; i < length; i++) {
8231 Tagged<Object> element = elements->get(static_cast<int>(i));
8232 // TODO(13270): When we switch to CSS, we can pass {element} to
8233 // the callback directly, without {fake_handle}.
8234 IndirectHandle<Object> fake_handle(
8235 reinterpret_cast<Address*>(&element));
8236 Result result = callback(i, Utils::ToLocal(fake_handle), callback_data);
8237 if (result != Result::kContinue) {
8238 return static_cast<FastIterateResult>(result);
8239 }
8240 DCHECK(CanUseFastIteration(isolate, array));
8241 }
8242 return FastIterateResult::kFinished;
8243 }
8244 case HOLEY_SMI_ELEMENTS:
8248 case HOLEY_ELEMENTS: {
8249 Tagged<FixedArray> elements = Cast<FixedArray>(array->elements());
8250 for (uint32_t i = 0; i < length; i++) {
8251 Tagged<Object> element = elements->get(static_cast<int>(i));
8252 // TODO(13270): When we switch to CSS, we can pass {element} to
8253 // the callback directly, without {fake_handle}.
8254 auto fake_handle =
8255 IsTheHole(element)
8256 ? isolate->factory()->undefined_value()
8257 : IndirectHandle<Object>(reinterpret_cast<Address*>(&element));
8258 Result result = callback(i, Utils::ToLocal(fake_handle), callback_data);
8259 if (result != Result::kContinue) {
8260 return static_cast<FastIterateResult>(result);
8261 }
8262 DCHECK(CanUseFastIteration(isolate, array));
8263 }
8264 return FastIterateResult::kFinished;
8265 }
8268 DCHECK_NE(length, 0); // Cast to FixedDoubleArray would be invalid.
8270 Cast<FixedDoubleArray>(array->elements()), isolate);
8271 FOR_WITH_HANDLE_SCOPE(isolate, uint32_t, i = 0, i, i < length, i++, {
8272 DirectHandle<Object> value =
8273 elements->is_the_hole(i)
8274 ? Handle<Object>(isolate->factory()->undefined_value())
8275 : isolate->factory()->NewNumber(elements->get_scalar(i));
8276 Result result = callback(i, Utils::ToLocal(value), callback_data);
8277 if (result != Result::kContinue) {
8278 return static_cast<FastIterateResult>(result);
8279 }
8280 DCHECK(CanUseFastIteration(isolate, array));
8281 });
8282 return FastIterateResult::kFinished;
8283 }
8284 case DICTIONARY_ELEMENTS: {
8286 Tagged<NumberDictionary> dict = array->element_dictionary();
8287 struct Entry {
8288 uint32_t index;
8289 InternalIndex entry;
8290 };
8291 std::vector<Entry> sorted;
8292 sorted.reserve(dict->NumberOfElements());
8293 ReadOnlyRoots roots(isolate);
8294 for (InternalIndex i : dict->IterateEntries()) {
8295 Tagged<Object> key = dict->KeyAt(isolate, i);
8296 if (!dict->IsKey(roots, key)) continue;
8297 uint32_t index =
8298 static_cast<uint32_t>(Object::NumberValue(Cast<Number>(key)));
8299 sorted.push_back({index, i});
8300 }
8301 std::sort(
8302 sorted.begin(), sorted.end(),
8303 [](const Entry& a, const Entry& b) { return a.index < b.index; });
8304 for (const Entry& entry : sorted) {
8305 Tagged<Object> value = dict->ValueAt(entry.entry);
8306 // TODO(13270): When we switch to CSS, we can pass {element} to
8307 // the callback directly, without {fake_handle}.
8308 IndirectHandle<Object> fake_handle(reinterpret_cast<Address*>(&value));
8309 Result result =
8310 callback(entry.index, Utils::ToLocal(fake_handle), callback_data);
8311 if (result != Result::kContinue) {
8312 return static_cast<FastIterateResult>(result);
8313 }
8314 SLOW_DCHECK(CanUseFastIteration(isolate, array));
8315 }
8316 return FastIterateResult::kFinished;
8317 }
8318 case NO_ELEMENTS:
8319 return FastIterateResult::kFinished;
8322 // Probably not worth implementing. Take the slow path.
8323 return FastIterateResult::kSlowPath;
8328#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype) case TYPE##_ELEMENTS:
8331#undef TYPED_ARRAY_CASE
8332 // These are never used by v8::Array instances.
8333 UNREACHABLE();
8334 }
8335 // The input value of the switch is untrusted, so even if it's exhaustive, it
8336 // can skip all cases and end up here, triggering UB since there's no return.
8337 SBXCHECK(false);
8338}
8339
8340} // namespace internal
8341
8344 void* callback_data) {
8345 auto array = Utils::OpenDirectHandle(this);
8346 i::Isolate* isolate = array->GetIsolate();
8347 i::FastIterateResult fast_result =
8348 i::FastIterateArray(array, isolate, callback, callback_data);
8349 if (fast_result == i::FastIterateResult::kException) return Nothing<void>();
8350 // Early breaks and completed iteration both return successfully.
8351 if (fast_result != i::FastIterateResult::kSlowPath) return JustVoid();
8352
8353 // Slow path: retrieving elements could have side effects.
8354 ENTER_V8(isolate, context, Array, Iterate, i::HandleScope);
8355 for (uint32_t i = 0; i < i::GetLength(*array); ++i) {
8357 has_exception =
8358 !i::JSReceiver::GetElement(isolate, array, i).ToHandle(&element);
8360 using Result = v8::Array::CallbackResult;
8361 Result result = callback(i, Utils::ToLocal(element), callback_data);
8362 if (result == Result::kException) return Nothing<void>();
8363 if (result == Result::kBreak) return JustVoid();
8364 }
8365 return JustVoid();
8366}
8367
8369#ifdef V8_ENABLE_DIRECT_HANDLE
8370 // An empty local suffices.
8371 : cached_map_()
8372#else
8373 // We need to reserve a handle that we can patch later.
8374 // We initialize it with something that cannot compare equal to any map.
8375 : cached_map_(v8::Number::New(isolate, 1))
8376#endif
8377{
8378}
8379
8382#ifdef V8_ENABLE_DIRECT_HANDLE
8383 if (IsSmi(obj)) {
8384 cached_map_ = Local<Data>();
8385 } else {
8387 cached_map_ = Local<Data>::FromAddress(map->ptr());
8388 }
8389#else
8390 i::Tagged<i::Object> map = i::Smi::zero();
8391 if (!IsSmi(obj)) map = i::Cast<i::HeapObject>(obj)->map();
8392 // Design overview: in the {TypecheckWitness} constructor, we create
8393 // a single handle for the witness value. Whenever {Update} is called, we
8394 // make this handle point at the fresh baseline/witness; the intention is
8395 // to allow having short-lived HandleScopes (e.g. in {FastIterateArray}
8396 // above) while a {TypecheckWitness} is alive: it therefore cannot hold
8397 // on to one of the short-lived handles.
8398 // Calling {OpenIndirectHandle} on the {cached_map_} only serves to
8399 // "reinterpret_cast" it to an {i::IndirectHandle} on which we can call
8400 // {PatchValue}.
8401 auto cache = Utils::OpenIndirectHandle(*cached_map_);
8402 cache.PatchValue(map);
8403#endif
8404}
8405
8407 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8408 API_RCS_SCOPE(i_isolate, Map, New);
8410 i::DirectHandle<i::JSMap> obj = i_isolate->factory()->NewJSMap();
8411 return Utils::ToLocal(obj);
8412}
8413
8414size_t v8::Map::Size() const {
8415 auto obj = Utils::OpenDirectHandle(this);
8416 return i::Cast<i::OrderedHashMap>(obj->table())->NumberOfElements();
8417}
8418
8420 auto self = Utils::OpenDirectHandle(this);
8421 i::Isolate* i_isolate = self->GetIsolate();
8422 API_RCS_SCOPE(i_isolate, Map, Clear);
8424 i::JSMap::Clear(i_isolate, self);
8425}
8426
8428 PREPARE_FOR_EXECUTION(context, Map, Get);
8429 auto self = Utils::OpenDirectHandle(this);
8432 has_exception =
8433 !ToLocal<Value>(i::Execution::CallBuiltin(i_isolate, i_isolate->map_get(),
8434 self, base::VectorOf(args)),
8435 &result);
8438}
8439
8441 Local<Value> value) {
8442 PREPARE_FOR_EXECUTION(context, Map, Set);
8443 auto self = Utils::OpenDirectHandle(this);
8446 Utils::OpenDirectHandle(*value)};
8447 has_exception = !i::Execution::CallBuiltin(i_isolate, i_isolate->map_set(),
8448 self, base::VectorOf(args))
8449 .ToHandle(&result);
8451 RETURN_ESCAPED(Local<Map>::Cast(Utils::ToLocal(result)));
8452}
8453
8455 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8456 ENTER_V8(i_isolate, context, Map, Has, i::HandleScope);
8457 auto self = Utils::OpenDirectHandle(this);
8460 has_exception = !i::Execution::CallBuiltin(i_isolate, i_isolate->map_has(),
8461 self, base::VectorOf(args))
8462 .ToHandle(&result);
8464 return Just(i::IsTrue(*result, i_isolate));
8465}
8466
8468 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8469 ENTER_V8(i_isolate, context, Map, Delete, i::HandleScope);
8470 auto self = Utils::OpenDirectHandle(this);
8473 has_exception = !i::Execution::CallBuiltin(i_isolate, i_isolate->map_delete(),
8474 self, base::VectorOf(args))
8475 .ToHandle(&result);
8477 return Just(i::IsTrue(*result, i_isolate));
8478}
8479
8480namespace {
8481
8482enum class MapAsArrayKind {
8483 kEntries = i::JS_MAP_KEY_VALUE_ITERATOR_TYPE,
8484 kKeys = i::JS_MAP_KEY_ITERATOR_TYPE,
8485 kValues = i::JS_MAP_VALUE_ITERATOR_TYPE
8486};
8487
8488enum class SetAsArrayKind {
8489 kEntries = i::JS_SET_KEY_VALUE_ITERATOR_TYPE,
8490 kValues = i::JS_SET_VALUE_ITERATOR_TYPE
8491};
8492
8493i::DirectHandle<i::JSArray> MapAsArray(i::Isolate* i_isolate,
8494 i::Tagged<i::Object> table_obj,
8495 int offset, MapAsArrayKind kind) {
8496 i::Factory* factory = i_isolate->factory();
8498 i::Cast<i::OrderedHashMap>(table_obj), i_isolate);
8499 const bool collect_keys =
8500 kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kKeys;
8501 const bool collect_values =
8502 kind == MapAsArrayKind::kEntries || kind == MapAsArrayKind::kValues;
8503 int capacity = table->UsedCapacity();
8504 int max_length =
8505 (capacity - offset) * ((collect_keys && collect_values) ? 2 : 1);
8507 int result_index = 0;
8508 {
8510 i::Tagged<i::Hole> hash_table_hole =
8511 i::ReadOnlyRoots(i_isolate).hash_table_hole_value();
8512 for (int i = offset; i < capacity; ++i) {
8513 i::InternalIndex entry(i);
8514 i::Tagged<i::Object> key = table->KeyAt(entry);
8515 if (key == hash_table_hole) continue;
8516 if (collect_keys) result->set(result_index++, key);
8517 if (collect_values) result->set(result_index++, table->ValueAt(entry));
8518 }
8519 }
8520 DCHECK_GE(max_length, result_index);
8521 if (result_index == 0) return factory->NewJSArray(0);
8522 result->RightTrim(i_isolate, result_index);
8524 result_index);
8525}
8526
8527} // namespace
8528
8530 auto obj = Utils::OpenDirectHandle(this);
8531 i::Isolate* i_isolate = obj->GetIsolate();
8532 API_RCS_SCOPE(i_isolate, Map, AsArray);
8534 return Utils::ToLocal(
8535 MapAsArray(i_isolate, obj->table(), 0, MapAsArrayKind::kEntries));
8536}
8537
8539 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8540 API_RCS_SCOPE(i_isolate, Set, New);
8542 i::DirectHandle<i::JSSet> obj = i_isolate->factory()->NewJSSet();
8543 return Utils::ToLocal(obj);
8544}
8545
8546size_t v8::Set::Size() const {
8547 auto obj = Utils::OpenDirectHandle(this);
8548 return i::Cast<i::OrderedHashSet>(obj->table())->NumberOfElements();
8549}
8550
8552 auto self = Utils::OpenDirectHandle(this);
8553 i::Isolate* i_isolate = self->GetIsolate();
8554 API_RCS_SCOPE(i_isolate, Set, Clear);
8556 i::JSSet::Clear(i_isolate, self);
8557}
8558
8560 PREPARE_FOR_EXECUTION(context, Set, Add);
8561 auto self = Utils::OpenDirectHandle(this);
8564 has_exception = !i::Execution::CallBuiltin(i_isolate, i_isolate->set_add(),
8565 self, base::VectorOf(args))
8566 .ToHandle(&result);
8568 RETURN_ESCAPED(Local<Set>::Cast(Utils::ToLocal(result)));
8569}
8570
8572 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8573 ENTER_V8(i_isolate, context, Set, Has, i::HandleScope);
8574 auto self = Utils::OpenDirectHandle(this);
8577 has_exception = !i::Execution::CallBuiltin(i_isolate, i_isolate->set_has(),
8578 self, base::VectorOf(args))
8579 .ToHandle(&result);
8581 return Just(i::IsTrue(*result, i_isolate));
8582}
8583
8585 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8586 ENTER_V8(i_isolate, context, Set, Delete, i::HandleScope);
8587 auto self = Utils::OpenDirectHandle(this);
8590 has_exception = !i::Execution::CallBuiltin(i_isolate, i_isolate->set_delete(),
8591 self, base::VectorOf(args))
8592 .ToHandle(&result);
8594 return Just(i::IsTrue(*result, i_isolate));
8595}
8596
8597namespace {
8598i::DirectHandle<i::JSArray> SetAsArray(i::Isolate* i_isolate,
8599 i::Tagged<i::Object> table_obj,
8600 int offset, SetAsArrayKind kind) {
8601 i::Factory* factory = i_isolate->factory();
8603 i::Cast<i::OrderedHashSet>(table_obj), i_isolate);
8604 // Elements skipped by |offset| may already be deleted.
8605 int capacity = table->UsedCapacity();
8606 const bool collect_key_values = kind == SetAsArrayKind::kEntries;
8607 int max_length = (capacity - offset) * (collect_key_values ? 2 : 1);
8608 if (max_length == 0) return factory->NewJSArray(0);
8610 int result_index = 0;
8611 {
8613 i::Tagged<i::Hole> hash_table_hole =
8614 i::ReadOnlyRoots(i_isolate).hash_table_hole_value();
8615 for (int i = offset; i < capacity; ++i) {
8616 i::InternalIndex entry(i);
8617 i::Tagged<i::Object> key = table->KeyAt(entry);
8618 if (key == hash_table_hole) continue;
8619 result->set(result_index++, key);
8620 if (collect_key_values) result->set(result_index++, key);
8621 }
8622 }
8623 DCHECK_GE(max_length, result_index);
8624 if (result_index == 0) return factory->NewJSArray(0);
8625 result->RightTrim(i_isolate, result_index);
8627 result_index);
8628}
8629} // namespace
8630
8632 auto obj = Utils::OpenDirectHandle(this);
8633 i::Isolate* i_isolate = obj->GetIsolate();
8634 API_RCS_SCOPE(i_isolate, Set, AsArray);
8636 return Utils::ToLocal(
8637 SetAsArray(i_isolate, obj->table(), 0, SetAsArrayKind::kValues));
8638}
8639
8641 PREPARE_FOR_EXECUTION(context, Promise_Resolver, New);
8643 has_exception = !ToLocal<Promise::Resolver>(
8644 i_isolate->factory()->NewJSPromise(), &result);
8645 // Also check if promise hooks set an exception.
8646 // TODO(clemensb): Should `Factory::NewJSPromise()` return a MaybeHandle
8647 // instead?
8648 has_exception |= i_isolate->has_exception();
8651}
8652
8654 auto promise = Utils::OpenDirectHandle(this);
8655 return Local<Promise>::Cast(Utils::ToLocal(promise));
8656}
8657
8659 Local<Value> value) {
8660 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8661 ENTER_V8(i_isolate, context, Promise_Resolver, Resolve, i::HandleScope);
8662 auto self = Utils::OpenDirectHandle(this);
8663 auto promise = i::Cast<i::JSPromise>(self);
8664
8665 if (promise->status() != Promise::kPending) {
8666 return Just(true);
8667 }
8668
8669 has_exception =
8670 i::JSPromise::Resolve(promise, Utils::OpenDirectHandle(*value)).is_null();
8672 return Just(true);
8673}
8674
8676 Local<Value> value) {
8677 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
8678 ENTER_V8(i_isolate, context, Promise_Resolver, Reject, i::HandleScope);
8679 auto self = Utils::OpenDirectHandle(this);
8680 auto promise = i::Cast<i::JSPromise>(self);
8681
8682 if (promise->status() != Promise::kPending) {
8683 return Just(true);
8684 }
8685
8686 has_exception =
8687 i::JSPromise::Reject(promise, Utils::OpenDirectHandle(*value)).is_null();
8689 return Just(true);
8690}
8691
8693 Local<Function> handler) {
8694 PREPARE_FOR_EXECUTION(context, Promise, Catch);
8695 auto self = Utils::OpenDirectHandle(this);
8696 i::DirectHandle<i::Object> args[] = {i_isolate->factory()->undefined_value(),
8697 Utils::OpenDirectHandle(*handler)};
8699 // Do not call the built-in Promise.prototype.catch!
8700 // v8::Promise should not call out to a monkeypatched Promise.prototype.then
8701 // as the implementation of Promise.prototype.catch does.
8702 has_exception =
8703 !i::Execution::CallBuiltin(i_isolate, i_isolate->promise_then(), self,
8705 .ToHandle(&result);
8707 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
8708}
8709
8711 Local<Function> handler) {
8712 PREPARE_FOR_EXECUTION(context, Promise, Then);
8713 auto self = Utils::OpenDirectHandle(this);
8716 has_exception =
8717 !i::Execution::CallBuiltin(i_isolate, i_isolate->promise_then(), self,
8719 .ToHandle(&result);
8721 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
8722}
8723
8725 Local<Function> on_fulfilled,
8726 Local<Function> on_rejected) {
8727 PREPARE_FOR_EXECUTION(context, Promise, Then);
8728 auto self = Utils::OpenDirectHandle(this);
8730 Utils::OpenDirectHandle(*on_rejected)};
8732 has_exception =
8733 !i::Execution::CallBuiltin(i_isolate, i_isolate->promise_then(), self,
8735 .ToHandle(&result);
8737 RETURN_ESCAPED(Local<Promise>::Cast(Utils::ToLocal(result)));
8738}
8739
8742 i::Isolate* i_isolate = promise->GetIsolate();
8743 API_RCS_SCOPE(i_isolate, Promise, HasRejectHandler);
8745 if (!IsJSPromise(promise)) return false;
8746 return i::Cast<i::JSPromise>(promise)->has_handler();
8747}
8748
8750 auto promise = Utils::OpenDirectHandle(this);
8751 i::Isolate* i_isolate = promise->GetIsolate();
8752 API_RCS_SCOPE(i_isolate, Promise, Result);
8753 auto js_promise = i::Cast<i::JSPromise>(promise);
8754 Utils::ApiCheck(js_promise->status() != kPending, "v8_Promise_Result",
8755 "Promise is still pending");
8756 return Utils::ToLocal(i::direct_handle(js_promise->result(), i_isolate));
8757}
8758
8760 auto promise = Utils::OpenDirectHandle(this);
8761 API_RCS_SCOPE(promise->GetIsolate(), Promise, Status);
8762 auto js_promise = i::Cast<i::JSPromise>(promise);
8763 return static_cast<PromiseState>(js_promise->status());
8764}
8765
8767 Utils::OpenDirectHandle(this)->set_has_handler(true);
8768}
8769
8771 Utils::OpenDirectHandle(this)->set_is_silent(true);
8772}
8773
8775 auto self = Utils::OpenDirectHandle(this);
8776 i::Isolate* i_isolate = self->GetIsolate();
8777 return Utils::ToLocal(i::direct_handle(self->target(), i_isolate));
8778}
8779
8781 auto self = Utils::OpenDirectHandle(this);
8782 i::Isolate* i_isolate = self->GetIsolate();
8783 return Utils::ToLocal(i::direct_handle(self->handler(), i_isolate));
8784}
8785
8786bool Proxy::IsRevoked() const {
8787 return Utils::OpenDirectHandle(this)->IsRevoked();
8788}
8789
8791 auto self = Utils::OpenDirectHandle(this);
8792 i::JSProxy::Revoke(self);
8793}
8794
8796 Local<Object> local_handler) {
8797 PREPARE_FOR_EXECUTION(context, Proxy, New);
8798 auto target = Utils::OpenDirectHandle(*local_target);
8799 auto handler = Utils::OpenDirectHandle(*local_handler);
8801 has_exception =
8802 !ToLocal<Proxy>(i::JSProxy::New(i_isolate, target, handler), &result);
8805}
8806
8808 std::shared_ptr<internal::wasm::NativeModule> native_module,
8809 const char* source_url, size_t url_length)
8810 : native_module_(std::move(native_module)),
8811 source_url_(source_url, url_length) {
8813}
8814
8816#if V8_ENABLE_WEBASSEMBLY
8817 TRACE_EVENT0("v8.wasm", "wasm.SerializeModule");
8818 i::wasm::WasmSerializer wasm_serializer(native_module_.get());
8819 size_t buffer_size = wasm_serializer.GetSerializedNativeModuleSize();
8820 std::unique_ptr<uint8_t[]> buffer(new uint8_t[buffer_size]);
8821 if (!wasm_serializer.SerializeNativeModule({buffer.get(), buffer_size}))
8822 return {};
8823 return {std::move(buffer), buffer_size};
8824#else
8825 UNREACHABLE();
8826#endif // V8_ENABLE_WEBASSEMBLY
8827}
8828
8830#if V8_ENABLE_WEBASSEMBLY
8831 base::Vector<const uint8_t> bytes_vec = native_module_->wire_bytes();
8832 return {bytes_vec.begin(), bytes_vec.size()};
8833#else
8834 UNREACHABLE();
8835#endif // V8_ENABLE_WEBASSEMBLY
8836}
8837
8839#if V8_ENABLE_WEBASSEMBLY
8840 auto obj = Utils::OpenDirectHandle(this);
8841 i::Isolate* i_isolate = obj->GetIsolate();
8842 return Utils::ToLocal(i::direct_handle(obj->array_buffer(), i_isolate));
8843#else
8844 UNREACHABLE();
8845#endif // V8_ENABLE_WEBASSEMBLY
8846}
8847
8849#if V8_ENABLE_WEBASSEMBLY
8851 auto url = i::direct_handle(i::Cast<i::String>(obj->script()->name()),
8852 obj->GetIsolate());
8853 size_t length;
8854 std::unique_ptr<char[]> cstring = url->ToCString(&length);
8855 return CompiledWasmModule(std::move(obj->shared_native_module()),
8856 cstring.get(), length);
8857#else
8858 UNREACHABLE();
8859#endif // V8_ENABLE_WEBASSEMBLY
8860}
8861
8863 Isolate* v8_isolate, const CompiledWasmModule& compiled_module) {
8864#if V8_ENABLE_WEBASSEMBLY
8865 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8867 i::wasm::GetWasmEngine()->ImportNativeModule(
8868 i_isolate, compiled_module.native_module_,
8869 base::VectorOf(compiled_module.source_url()));
8870 return Utils::ToLocal(module_object);
8871#else
8872 UNREACHABLE();
8873#endif // V8_ENABLE_WEBASSEMBLY
8874}
8875
8877 Isolate* v8_isolate, MemorySpan<const uint8_t> wire_bytes) {
8878#if V8_ENABLE_WEBASSEMBLY
8880 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8881 if (!i::wasm::IsWasmCodegenAllowed(i_isolate, i_isolate->native_context())) {
8883 }
8885 {
8886 i::wasm::ErrorThrower thrower(i_isolate, "WasmModuleObject::Compile()");
8887 auto enabled_features =
8888 i::wasm::WasmEnabledFeatures::FromIsolate(i_isolate);
8889 // TODO(14179): Provide an API method that supports compile options.
8890 maybe_compiled = i::wasm::GetWasmEngine()->SyncCompile(
8891 i_isolate, enabled_features, i::wasm::CompileTimeImports{}, &thrower,
8892 std::move(bytes));
8893 }
8894 CHECK_EQ(maybe_compiled.is_null(), i_isolate->has_exception());
8895 if (maybe_compiled.is_null()) {
8897 }
8898 return Utils::ToLocal(maybe_compiled.ToHandleChecked());
8899#else
8900 Utils::ApiCheck(false, "WasmModuleObject::Compile",
8901 "WebAssembly support is not enabled");
8902 UNREACHABLE();
8903#endif // V8_ENABLE_WEBASSEMBLY
8904}
8905
8906// static
8909#if V8_ENABLE_WEBASSEMBLY
8910 CHECK(i::v8_flags.experimental_wasm_memory_control);
8911 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
8913 i::WasmMemoryMapDescriptor::NewFromFileDescriptor(i_isolate, fd);
8914 return Utils::ToLocal(result);
8915#else
8916 Utils::ApiCheck(false, "WasmMemoryMapDescriptor::New",
8917 "WebAssembly support is not enabled");
8918 UNREACHABLE();
8919#endif
8920}
8921
8922// static
8924#ifdef V8_ENABLE_SANDBOX
8925 return new ArrayBufferAllocator(i::IsolateGroup::GetDefault());
8926#else
8927 return new ArrayBufferAllocator();
8928#endif
8929}
8930
8931#if defined(V8_COMPRESS_POINTERS) && \
8932 !defined(V8_COMPRESS_POINTERS_IN_SHARED_CAGE)
8934 const IsolateGroup& group) {
8935#ifdef V8_ENABLE_SANDBOX
8936 return new ArrayBufferAllocator(group.isolate_group_);
8937#else
8938 return new ArrayBufferAllocator();
8939#endif
8940}
8941#endif // defined(V8_COMPRESS_POINTERS) &&
8942 // !defined(V8_COMPRESS_POINTERS_IN_SHARED_CAGE)
8943
8945 return Utils::OpenDirectHandle(this)->is_detachable();
8946}
8947
8949 return Utils::OpenDirectHandle(this)->was_detached();
8950}
8951
8952namespace {
8953std::shared_ptr<i::BackingStore> ToInternal(
8954 std::shared_ptr<i::BackingStoreBase> backing_store) {
8955 return std::static_pointer_cast<i::BackingStore>(backing_store);
8956}
8957} // namespace
8958
8960 auto obj = Utils::OpenDirectHandle(this);
8961 i::Isolate* i_isolate = obj->GetIsolate();
8962 Utils::ApiCheck(obj->is_detachable(), "v8::ArrayBuffer::Detach",
8963 "Only detachable ArrayBuffers can be detached");
8964 Local<Context> context =
8965 reinterpret_cast<v8::Isolate*>(i_isolate)->GetCurrentContext();
8966 // TODO(verwaest): Remove this case after forcing the embedder to enter the
8967 // context.
8968 if (context.IsEmpty()) {
8970 if (key.IsEmpty()) {
8971 i::JSArrayBuffer::Detach(obj).Check();
8972 } else {
8973 auto i_key = Utils::OpenDirectHandle(*key);
8974 constexpr bool kForceForWasmMemory = false;
8975 i::JSArrayBuffer::Detach(obj, kForceForWasmMemory, i_key).Check();
8976 }
8977 return Just(true);
8978 }
8979 ENTER_V8_NO_SCRIPT(i_isolate, context, ArrayBuffer, Detach, i::HandleScope);
8980 if (!key.IsEmpty()) {
8981 auto i_key = Utils::OpenDirectHandle(*key);
8982 constexpr bool kForceForWasmMemory = false;
8983 has_exception =
8984 i::JSArrayBuffer::Detach(obj, kForceForWasmMemory, i_key).IsNothing();
8985 } else {
8986 has_exception = i::JSArrayBuffer::Detach(obj).IsNothing();
8987 }
8989 return Just(true);
8990}
8991
8992void v8::ArrayBuffer::Detach() { Detach(Local<Value>()).Check(); }
8993
8995 auto obj = Utils::OpenDirectHandle(this);
8996 auto i_key = Utils::OpenDirectHandle(*key);
8997 obj->set_detach_key(*i_key);
8998}
8999
9001 return Utils::OpenDirectHandle(this)->GetByteLength();
9002}
9003
9005 return Utils::OpenDirectHandle(this)->max_byte_length();
9006}
9007
9008namespace {
9009i::InitializedFlag GetInitializedFlag(
9010 BackingStoreInitializationMode initialization_mode) {
9011 switch (initialization_mode) {
9013 return i::InitializedFlag::kUninitialized;
9015 return i::InitializedFlag::kZeroInitialized;
9016 }
9017 UNREACHABLE();
9018}
9019} // namespace
9020
9022 Isolate* isolate, size_t byte_length,
9023 BackingStoreInitializationMode initialization_mode) {
9024 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
9025 API_RCS_SCOPE(i_isolate, ArrayBuffer, MaybeNew);
9026 size_t max = i_isolate->array_buffer_allocator()->MaxAllocationSize();
9028 if (byte_length > max) {
9029 return {};
9030 }
9034 byte_length, GetInitializedFlag(initialization_mode));
9035
9037 if (!result.ToHandle(&array_buffer)) {
9038 return {};
9039 }
9040
9041 return Utils::ToLocal(array_buffer);
9042}
9043
9045 Isolate* v8_isolate, size_t byte_length,
9046 BackingStoreInitializationMode initialization_mode) {
9047 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9048 API_RCS_SCOPE(i_isolate, ArrayBuffer, New);
9052 byte_length, GetInitializedFlag(initialization_mode));
9053
9055 if (!result.ToHandle(&array_buffer)) {
9056 i::V8::FatalProcessOutOfMemory(i_isolate, "v8::ArrayBuffer::New");
9057 }
9058
9059 return Utils::ToLocal(array_buffer);
9060}
9061
9063 Isolate* v8_isolate, std::shared_ptr<BackingStore> backing_store) {
9064 CHECK_IMPLIES(backing_store->ByteLength() != 0,
9065 backing_store->Data() != nullptr);
9066 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9067 API_RCS_SCOPE(i_isolate, ArrayBuffer, New);
9069 std::shared_ptr<i::BackingStore> i_backing_store(
9070 ToInternal(std::move(backing_store)));
9072 !i_backing_store->is_shared(), "v8_ArrayBuffer_New",
9073 "Cannot construct ArrayBuffer with a BackingStore of SharedArrayBuffer");
9075 i_isolate->factory()->NewJSArrayBuffer(std::move(i_backing_store));
9076 return Utils::ToLocal(obj);
9077}
9078
9079std::unique_ptr<v8::BackingStore> v8::ArrayBuffer::NewBackingStore(
9080 Isolate* v8_isolate, size_t byte_length,
9081 BackingStoreInitializationMode initialization_mode,
9082 BackingStoreOnFailureMode on_failure) {
9083 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9084 API_RCS_SCOPE(i_isolate, ArrayBuffer, NewBackingStore);
9085 if (on_failure == BackingStoreOnFailureMode::kOutOfMemory) {
9086 CHECK_LE(byte_length, i::JSArrayBuffer::kMaxByteLength);
9087 } else if (byte_length > i::JSArrayBuffer::kMaxByteLength) {
9089 return {};
9090 }
9092 std::unique_ptr<i::BackingStoreBase> backing_store =
9093 i::BackingStore::Allocate(i_isolate, byte_length,
9094 i::SharedFlag::kNotShared,
9095 GetInitializedFlag(initialization_mode));
9096 if (!backing_store) {
9097 if (on_failure == BackingStoreOnFailureMode::kOutOfMemory) {
9098 i::V8::FatalProcessOutOfMemory(i_isolate,
9099 "v8::ArrayBuffer::NewBackingStore");
9100 } else {
9102 return {};
9103 }
9104 }
9105 return std::unique_ptr<v8::BackingStore>(
9106 static_cast<v8::BackingStore*>(backing_store.release()));
9107}
9108
9109std::unique_ptr<v8::BackingStore> v8::ArrayBuffer::NewBackingStore(
9110 void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
9111 void* deleter_data) {
9112 CHECK_LE(byte_length, i::JSArrayBuffer::kMaxByteLength);
9113#ifdef V8_ENABLE_SANDBOX
9114 Utils::ApiCheck(!data || i::Sandbox::current()->Contains(data),
9115 "v8_ArrayBuffer_NewBackingStore",
9116 "When the V8 Sandbox is enabled, ArrayBuffer backing stores "
9117 "must be allocated inside the sandbox address space. Please "
9118 "use an appropriate ArrayBuffer::Allocator to allocate these "
9119 "buffers, or disable the sandbox.");
9120#endif // V8_ENABLE_SANDBOX
9121
9122 std::unique_ptr<i::BackingStoreBase> backing_store =
9123 i::BackingStore::WrapAllocation(data, byte_length, deleter, deleter_data,
9124 i::SharedFlag::kNotShared);
9125 return std::unique_ptr<v8::BackingStore>(
9126 static_cast<v8::BackingStore*>(backing_store.release()));
9127}
9128
9129// static
9130std::unique_ptr<BackingStore> v8::ArrayBuffer::NewResizableBackingStore(
9131 size_t byte_length, size_t max_byte_length) {
9132 Utils::ApiCheck(byte_length <= max_byte_length,
9133 "v8::ArrayBuffer::NewResizableBackingStore",
9134 "Cannot construct resizable ArrayBuffer, byte_length must be "
9135 "<= max_byte_length");
9137 byte_length <= i::JSArrayBuffer::kMaxByteLength,
9138 "v8::ArrayBuffer::NewResizableBackingStore",
9139 "Cannot construct resizable ArrayBuffer, requested length is too big");
9140
9141 size_t page_size, initial_pages, max_pages;
9142 if (i::JSArrayBuffer::GetResizableBackingStorePageConfiguration(
9143 nullptr, byte_length, max_byte_length, i::kDontThrow, &page_size,
9144 &initial_pages, &max_pages)
9145 .IsNothing()) {
9146 i::V8::FatalProcessOutOfMemory(nullptr,
9147 "v8::ArrayBuffer::NewResizableBackingStore");
9148 }
9149 std::unique_ptr<i::BackingStoreBase> backing_store =
9150 i::BackingStore::TryAllocateAndPartiallyCommitMemory(
9151 nullptr, byte_length, max_byte_length, page_size, initial_pages,
9152 max_pages, i::WasmMemoryFlag::kNotWasm, i::SharedFlag::kNotShared);
9153 if (!backing_store) {
9154 i::V8::FatalProcessOutOfMemory(nullptr,
9155 "v8::ArrayBuffer::NewResizableBackingStore");
9156 }
9157 return std::unique_ptr<v8::BackingStore>(
9158 static_cast<v8::BackingStore*>(backing_store.release()));
9159}
9160
9162 auto obj = Utils::OpenDirectHandle(this);
9163 i::Isolate* i_isolate = obj->GetIsolate();
9164 if (i::IsJSDataView(*obj)) {
9166 i_isolate);
9167 DCHECK(IsJSArrayBuffer(data_view->buffer()));
9168 return Utils::ToLocal(i::direct_handle(
9169 i::Cast<i::JSArrayBuffer>(data_view->buffer()), i_isolate));
9170 } else if (i::IsJSRabGsabDataView(*obj)) {
9172 i::Cast<i::JSRabGsabDataView>(*obj), i_isolate);
9173 DCHECK(IsJSArrayBuffer(data_view->buffer()));
9174 return Utils::ToLocal(i::direct_handle(
9175 i::Cast<i::JSArrayBuffer>(data_view->buffer()), i_isolate));
9176 } else {
9177 DCHECK(IsJSTypedArray(*obj));
9178 return Utils::ToLocal(i::Cast<i::JSTypedArray>(*obj)->GetBuffer());
9179 }
9180}
9181
9182size_t v8::ArrayBufferView::CopyContents(void* dest, size_t byte_length) {
9183 auto self = Utils::OpenDirectHandle(this);
9184 size_t bytes_to_copy = std::min(byte_length, self->byte_length());
9185 if (bytes_to_copy) {
9187 const char* source;
9188 if (i::IsJSTypedArray(*self)) {
9190 source = reinterpret_cast<char*>(array->DataPtr());
9191 } else {
9192 DCHECK(i::IsJSDataView(*self) || i::IsJSRabGsabDataView(*self));
9195 source = reinterpret_cast<char*>(data_view->data_pointer());
9196 }
9197 memcpy(dest, source, bytes_to_copy);
9198 }
9199 return bytes_to_copy;
9200}
9201
9203 v8::MemorySpan<uint8_t> storage) {
9205 auto self = Utils::OpenDirectHandle(this);
9206 if (self->WasDetached()) {
9207 return {};
9208 }
9209 if (internal::IsJSTypedArray(*self)) {
9211 if (typed_array->is_on_heap()) {
9212 // The provided storage does not have enough capacity for the content of
9213 // the TypedArray.
9214 size_t bytes_to_copy = self->byte_length();
9215 CHECK_LE(bytes_to_copy, storage.size());
9216 const uint8_t* source =
9217 reinterpret_cast<uint8_t*>(typed_array->DataPtr());
9218 memcpy(reinterpret_cast<void*>(storage.data()), source, bytes_to_copy);
9219 return {storage.data(), bytes_to_copy};
9220 }
9221 // The TypedArray already has off-heap storage, just return a view on it.
9222 return {reinterpret_cast<uint8_t*>(typed_array->DataPtr()),
9223 typed_array->GetByteLength()};
9224 }
9225 if (i::IsJSDataView(*self)) {
9227 return {reinterpret_cast<uint8_t*>(data_view->data_pointer()),
9228 data_view->byte_length()};
9229 }
9230 // Other types of ArrayBufferView always have an off-heap storage.
9231 DCHECK(i::IsJSRabGsabDataView(*self));
9234 return {reinterpret_cast<uint8_t*>(data_view->data_pointer()),
9235 data_view->GetByteLength()};
9236}
9237
9239 auto self = Utils::OpenDirectHandle(this);
9240 if (!IsJSTypedArray(*self)) return true;
9241 auto typed_array = i::Cast<i::JSTypedArray>(self);
9242 return !typed_array->is_on_heap();
9243}
9244
9246 auto obj = Utils::OpenDirectHandle(this);
9247 return obj->WasDetached() ? 0 : obj->byte_offset();
9248}
9249
9253 if (obj->WasDetached()) {
9254 return 0;
9255 }
9256 if (i::IsJSTypedArray(obj)) {
9257 return i::Cast<i::JSTypedArray>(obj)->GetByteLength();
9258 }
9259 if (i::IsJSDataView(obj)) {
9260 return i::Cast<i::JSDataView>(obj)->byte_length();
9261 }
9262 return i::Cast<i::JSRabGsabDataView>(obj)->GetByteLength();
9263}
9264
9268 return obj->WasDetached() ? 0 : obj->GetLength();
9269}
9270
9271static_assert(v8::TypedArray::kMaxByteLength == i::JSTypedArray::kMaxByteLength,
9272 "v8::TypedArray::kMaxByteLength must match "
9273 "i::JSTypedArray::kMaxByteLength");
9274
9275#define TYPED_ARRAY_NEW(Type, type, TYPE, ctype) \
9276 Local<Type##Array> Type##Array::New(Local<ArrayBuffer> array_buffer, \
9277 size_t byte_offset, size_t length) { \
9278 i::Isolate* i_isolate = \
9279 Utils::OpenDirectHandle(*array_buffer)->GetIsolate(); \
9280 API_RCS_SCOPE(i_isolate, Type##Array, New); \
9281 ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate); \
9282 if (!Utils::ApiCheck(length <= kMaxLength, \
9283 "v8::" #Type \
9284 "Array::New(Local<ArrayBuffer>, size_t, size_t)", \
9285 "length exceeds max allowed value")) { \
9286 return Local<Type##Array>(); \
9287 } \
9288 auto buffer = Utils::OpenDirectHandle(*array_buffer); \
9289 i::DirectHandle<i::JSTypedArray> obj = \
9290 i_isolate->factory()->NewJSTypedArray(i::kExternal##Type##Array, \
9291 buffer, byte_offset, length); \
9292 return Utils::ToLocal##Type##Array(obj); \
9293 } \
9294 Local<Type##Array> Type##Array::New( \
9295 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset, \
9296 size_t length) { \
9297 i::Isolate* i_isolate = \
9298 Utils::OpenDirectHandle(*shared_array_buffer)->GetIsolate(); \
9299 API_RCS_SCOPE(i_isolate, Type##Array, New); \
9300 ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate); \
9301 if (!Utils::ApiCheck( \
9302 length <= kMaxLength, \
9303 "v8::" #Type \
9304 "Array::New(Local<SharedArrayBuffer>, size_t, size_t)", \
9305 "length exceeds max allowed value")) { \
9306 return Local<Type##Array>(); \
9307 } \
9308 auto buffer = Utils::OpenDirectHandle(*shared_array_buffer); \
9309 i::DirectHandle<i::JSTypedArray> obj = \
9310 i_isolate->factory()->NewJSTypedArray(i::kExternal##Type##Array, \
9311 buffer, byte_offset, length); \
9312 return Utils::ToLocal##Type##Array(obj); \
9313 }
9314
9316#undef TYPED_ARRAY_NEW
9317
9319 size_t byte_offset, size_t length) {
9320 Utils::ApiCheck(i::v8_flags.js_float16array, "v8::Float16Array::New",
9321 "Float16Array is not supported");
9322 i::Isolate* i_isolate = Utils::OpenDirectHandle(*array_buffer)->GetIsolate();
9323 API_RCS_SCOPE(i_isolate, Float16Array, New);
9325 if (!Utils::ApiCheck(
9326 length <= kMaxLength,
9327 "v8::Float16Array::New(Local<ArrayBuffer>, size_t, size_t)",
9328 "length exceeds max allowed value")) {
9329 return Local<Float16Array>();
9330 }
9331 auto buffer = Utils::OpenDirectHandle(*array_buffer);
9333 i::kExternalFloat16Array, buffer, byte_offset, length);
9334 return Utils::ToLocalFloat16Array(obj);
9335}
9337 Local<SharedArrayBuffer> shared_array_buffer, size_t byte_offset,
9338 size_t length) {
9339 Utils::ApiCheck(i::v8_flags.js_float16array, "v8::Float16Array::New",
9340 "Float16Array is not supported");
9341 i::Isolate* i_isolate =
9342 Utils::OpenDirectHandle(*shared_array_buffer)->GetIsolate();
9343 API_RCS_SCOPE(i_isolate, Float16Array, New);
9345 if (!Utils::ApiCheck(
9346 length <= kMaxLength,
9347 "v8::Float16Array::New(Local<SharedArrayBuffer>, size_t, size_t)",
9348 "length exceeds max allowed value")) {
9349 return Local<Float16Array>();
9350 }
9351 auto buffer = Utils::OpenDirectHandle(*shared_array_buffer);
9353 i::kExternalFloat16Array, buffer, byte_offset, length);
9354 return Utils::ToLocalFloat16Array(obj);
9355}
9356
9357// TODO(v8:11111): Support creating length tracking DataViews via the API.
9359 size_t byte_offset, size_t byte_length) {
9360 auto buffer = Utils::OpenDirectHandle(*array_buffer);
9361 i::Isolate* i_isolate = buffer->GetIsolate();
9362 API_RCS_SCOPE(i_isolate, DataView, New);
9364 auto obj = i::Cast<i::JSDataView>(
9365 i_isolate->factory()->NewJSDataViewOrRabGsabDataView(buffer, byte_offset,
9366 byte_length));
9367 return Utils::ToLocal(obj);
9368}
9369
9371 size_t byte_offset, size_t byte_length) {
9372 auto buffer = Utils::OpenDirectHandle(*shared_array_buffer);
9373 i::Isolate* i_isolate = buffer->GetIsolate();
9374 API_RCS_SCOPE(i_isolate, DataView, New);
9376 auto obj = i::Cast<i::JSDataView>(
9377 i_isolate->factory()->NewJSDataViewOrRabGsabDataView(buffer, byte_offset,
9378 byte_length));
9379 return Utils::ToLocal(obj);
9380}
9381
9383 return Utils::OpenDirectHandle(this)->GetByteLength();
9384}
9385
9387 return Utils::OpenDirectHandle(this)->max_byte_length();
9388}
9389
9391 Isolate* v8_isolate, size_t byte_length,
9392 BackingStoreInitializationMode initialization_mode) {
9393 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9394 API_RCS_SCOPE(i_isolate, SharedArrayBuffer, New);
9396
9397 std::unique_ptr<i::BackingStore> backing_store =
9398 i::BackingStore::Allocate(i_isolate, byte_length, i::SharedFlag::kShared,
9399 GetInitializedFlag(initialization_mode));
9400
9401 if (!backing_store) {
9402 i::V8::FatalProcessOutOfMemory(i_isolate, "v8::SharedArrayBuffer::New");
9403 }
9404
9406 i_isolate->factory()->NewJSSharedArrayBuffer(std::move(backing_store));
9407 return Utils::ToLocalShared(obj);
9408}
9409
9411 Isolate* v8_isolate, size_t byte_length,
9412 BackingStoreInitializationMode initialization_mode) {
9413 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9414 API_RCS_SCOPE(i_isolate, SharedArrayBuffer, New);
9416
9417 std::unique_ptr<i::BackingStore> backing_store =
9418 i::BackingStore::Allocate(i_isolate, byte_length, i::SharedFlag::kShared,
9419 GetInitializedFlag(initialization_mode));
9420
9421 if (!backing_store) return {};
9422
9424 i_isolate->factory()->NewJSSharedArrayBuffer(std::move(backing_store));
9425 return Utils::ToLocalShared(obj);
9426}
9427
9429 Isolate* v8_isolate, std::shared_ptr<BackingStore> backing_store) {
9430 CHECK_IMPLIES(backing_store->ByteLength() != 0,
9431 backing_store->Data() != nullptr);
9432 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9433 API_RCS_SCOPE(i_isolate, SharedArrayBuffer, New);
9435 std::shared_ptr<i::BackingStore> i_backing_store(ToInternal(backing_store));
9437 i_backing_store->is_shared(), "v8::SharedArrayBuffer::New",
9438 "Cannot construct SharedArrayBuffer with BackingStore of ArrayBuffer");
9440 i_isolate->factory()->NewJSSharedArrayBuffer(std::move(i_backing_store));
9441 return Utils::ToLocalShared(obj);
9442}
9443
9444std::unique_ptr<v8::BackingStore> v8::SharedArrayBuffer::NewBackingStore(
9445 Isolate* v8_isolate, size_t byte_length,
9446 BackingStoreInitializationMode initialization_mode,
9447 BackingStoreOnFailureMode on_failure) {
9448 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9449 API_RCS_SCOPE(i_isolate, SharedArrayBuffer, NewBackingStore);
9450 if (on_failure == BackingStoreOnFailureMode::kOutOfMemory) {
9452 byte_length <= i::JSArrayBuffer::kMaxByteLength,
9453 "v8::SharedArrayBuffer::NewBackingStore",
9454 "Cannot construct SharedArrayBuffer, requested length is too big");
9455 } else {
9457 if (byte_length > i::JSArrayBuffer::kMaxByteLength) return {};
9458 }
9460 std::unique_ptr<i::BackingStoreBase> backing_store =
9461 i::BackingStore::Allocate(i_isolate, byte_length, i::SharedFlag::kShared,
9462 GetInitializedFlag(initialization_mode));
9463 if (!backing_store) {
9464 if (on_failure == BackingStoreOnFailureMode::kOutOfMemory) {
9465 i::V8::FatalProcessOutOfMemory(i_isolate,
9466 "v8::SharedArrayBuffer::NewBackingStore");
9467 } else {
9469 return {};
9470 }
9471 }
9472 return std::unique_ptr<v8::BackingStore>(
9473 static_cast<v8::BackingStore*>(backing_store.release()));
9474}
9475
9476std::unique_ptr<v8::BackingStore> v8::SharedArrayBuffer::NewBackingStore(
9477 void* data, size_t byte_length, v8::BackingStore::DeleterCallback deleter,
9478 void* deleter_data) {
9479 CHECK_LE(byte_length, i::JSArrayBuffer::kMaxByteLength);
9480 std::unique_ptr<i::BackingStoreBase> backing_store =
9481 i::BackingStore::WrapAllocation(data, byte_length, deleter, deleter_data,
9482 i::SharedFlag::kShared);
9483 return std::unique_ptr<v8::BackingStore>(
9484 static_cast<v8::BackingStore*>(backing_store.release()));
9485}
9486
9488 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9489 API_RCS_SCOPE(i_isolate, Symbol, New);
9492 if (!name.IsEmpty()) result->set_description(*Utils::OpenDirectHandle(*name));
9493 return Utils::ToLocal(result);
9494}
9495
9497 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9499 auto i_name = Utils::OpenHandle(*name);
9500 return Utils::ToLocal(
9501 i_isolate->SymbolFor(i::RootIndex::kPublicSymbolTable, i_name, false));
9502}
9503
9505 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9507 auto i_name = Utils::OpenHandle(*name);
9508 return Utils::ToLocal(
9509 i_isolate->SymbolFor(i::RootIndex::kApiSymbolTable, i_name, false));
9510}
9511
9512#define WELL_KNOWN_SYMBOLS(V) \
9513 V(AsyncIterator, async_iterator) \
9514 V(HasInstance, has_instance) \
9515 V(IsConcatSpreadable, is_concat_spreadable) \
9516 V(Iterator, iterator) \
9517 V(Match, match) \
9518 V(Replace, replace) \
9519 V(Search, search) \
9520 V(Split, split) \
9521 V(ToPrimitive, to_primitive) \
9522 V(ToStringTag, to_string_tag) \
9523 V(Unscopables, unscopables) \
9524 V(Dispose, dispose) \
9525 V(AsyncDispose, async_dispose)
9526
9527#define SYMBOL_GETTER(Name, name) \
9528 Local<Symbol> v8::Symbol::Get##Name(Isolate* v8_isolate) { \
9529 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate); \
9530 return Utils::ToLocal(i_isolate->factory()->name##_symbol()); \
9531 }
9532
9534
9535#undef SYMBOL_GETTER
9536#undef WELL_KNOWN_SYMBOLS
9537
9539 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9540 API_RCS_SCOPE(i_isolate, Private, New);
9542 i::DirectHandle<i::Symbol> symbol = i_isolate->factory()->NewPrivateSymbol();
9543 if (!name.IsEmpty()) symbol->set_description(*Utils::OpenDirectHandle(*name));
9544 Local<Symbol> result = Utils::ToLocal(symbol);
9545 return result.UnsafeAs<Private>();
9546}
9547
9549 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9551 auto i_name = Utils::OpenHandle(*name);
9552 Local<Symbol> result = Utils::ToLocal(
9553 i_isolate->SymbolFor(i::RootIndex::kApiPrivateSymbolTable, i_name, true));
9554 return result.UnsafeAs<Private>();
9555}
9556
9557Local<Number> v8::Number::New(Isolate* v8_isolate, double value) {
9558 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9560 if (std::isnan(value)) {
9561 // Introduce only canonical NaN value into the VM, to avoid signaling NaNs.
9562 value = std::numeric_limits<double>::quiet_NaN();
9563 }
9564 i::DirectHandle<i::Object> result = i_isolate->factory()->NewNumber(value);
9565 return Utils::NumberToLocal(result);
9566}
9567
9568Local<Integer> v8::Integer::New(Isolate* v8_isolate, int32_t value) {
9569 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9571 if (i::Smi::IsValid(value)) {
9572 return Utils::IntegerToLocal(
9573 i::DirectHandle<i::Object>(i::Smi::FromInt(value), i_isolate));
9574 }
9575 i::DirectHandle<i::Object> result = i_isolate->factory()->NewNumber(value);
9576 return Utils::IntegerToLocal(result);
9577}
9578
9580 uint32_t value) {
9581 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9583 bool fits_into_int32_t = (value & (1 << 31)) == 0;
9584 if (fits_into_int32_t) {
9585 return Integer::New(v8_isolate, static_cast<int32_t>(value));
9586 }
9587 i::DirectHandle<i::Object> result = i_isolate->factory()->NewNumber(value);
9588 return Utils::IntegerToLocal(result);
9589}
9590
9591Local<BigInt> v8::BigInt::New(Isolate* v8_isolate, int64_t value) {
9592 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9594 i::DirectHandle<i::BigInt> result = i::BigInt::FromInt64(i_isolate, value);
9595 return Utils::ToLocal(result);
9596}
9597
9599 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9601 i::DirectHandle<i::BigInt> result = i::BigInt::FromUint64(i_isolate, value);
9602 return Utils::ToLocal(result);
9603}
9604
9606 int sign_bit, int word_count,
9607 const uint64_t* words) {
9608 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
9609 ENTER_V8_NO_SCRIPT(i_isolate, context, BigInt, NewFromWords,
9612 i::BigInt::FromWords64(i_isolate, sign_bit, word_count, words);
9613 has_exception = result.is_null();
9615 RETURN_ESCAPED(Utils::ToLocal(result.ToHandleChecked()));
9616}
9617
9618uint64_t v8::BigInt::Uint64Value(bool* lossless) const {
9619 return Utils::OpenDirectHandle(this)->AsUint64(lossless);
9620}
9621
9622int64_t v8::BigInt::Int64Value(bool* lossless) const {
9623 return Utils::OpenDirectHandle(this)->AsInt64(lossless);
9624}
9625
9627 return Utils::OpenDirectHandle(this)->Words64Count();
9628}
9629
9630void BigInt::ToWordsArray(int* sign_bit, int* word_count,
9631 uint64_t* words) const {
9632 // TODO(saelo): consider migrating the public API to also use uint32_t or
9633 // size_t for length and count values.
9634 uint32_t unsigned_word_count = *word_count;
9635 Utils::OpenDirectHandle(this)->ToWordsArray64(sign_bit, &unsigned_word_count,
9636 words);
9637 *word_count = base::checked_cast<int>(unsigned_word_count);
9638}
9639
9641 int64_t change_in_bytes) {
9642 // Try to check for unreasonably large or small values from the embedder.
9643 static constexpr int64_t kMaxReasonableBytes = int64_t(1) << 60;
9644 static constexpr int64_t kMinReasonableBytes = -kMaxReasonableBytes;
9645 static_assert(kMaxReasonableBytes >= i::JSArrayBuffer::kMaxByteLength);
9646 CHECK(kMinReasonableBytes <= change_in_bytes &&
9647 change_in_bytes < kMaxReasonableBytes);
9648
9649 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9650 const uint64_t amount =
9651 i_isolate->heap()->UpdateExternalMemory(change_in_bytes);
9652
9653 if (change_in_bytes <= 0) {
9654 return amount;
9655 }
9656
9657 if (amount > i_isolate->heap()->external_memory_limit_for_interrupt()) {
9659 }
9660 return amount;
9661}
9662
9664 i::Heap* heap = reinterpret_cast<i::Isolate*>(this)->heap();
9665 if (heap->gc_state() != i::Heap::NOT_IN_GC) return;
9666 heap->HandleExternalMemoryInterrupt();
9667}
9668
9670 : isolate_group_(isolate_group) {
9672}
9673
9675 : isolate_group_(other.isolate_group_) {
9677}
9678
9680 if (this != &other && isolate_group_ != other.isolate_group_) {
9682 isolate_group_ = other.isolate_group_;
9684 }
9685 return *this;
9686}
9687
9689 if (isolate_group_) {
9691#ifdef DEBUG
9692 isolate_group_ = nullptr;
9693#endif
9694 }
9695}
9696
9697// static
9699 return IsolateGroup(i::IsolateGroup::AcquireDefault());
9700}
9701
9702// static
9704 return i::IsolateGroup::CanCreateNewGroups();
9705}
9706
9707// static
9709 return IsolateGroup(i::IsolateGroup::New());
9710}
9711
9713 isolate_group_ = other.isolate_group_;
9714 other.isolate_group_ = nullptr;
9715}
9716
9718 if (this == &other) {
9719 return *this;
9720 }
9721
9722 if (isolate_group_) {
9723 isolate_group_->Release();
9724 }
9725 isolate_group_ = other.isolate_group_;
9726 other.isolate_group_ = nullptr;
9727 return *this;
9728}
9729
9731 i::HeapProfiler* heap_profiler =
9732 reinterpret_cast<i::Isolate*>(this)->heap()->heap_profiler();
9733 return reinterpret_cast<HeapProfiler*>(heap_profiler);
9734}
9735
9736void Isolate::SetIdle(bool is_idle) {
9737 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9738 i_isolate->SetIdle(is_idle);
9739}
9740
9742 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9743 return i_isolate->array_buffer_allocator();
9744}
9745
9747 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9748 return !i_isolate->context().is_null();
9749}
9750
9752 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9753 i_isolate->ClearKeptObjects();
9754}
9755
9757 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9758 i::Tagged<i::Context> context = i_isolate->context();
9759 if (context.is_null()) return Local<Context>();
9760 i::Tagged<i::NativeContext> native_context = context->native_context();
9761 return Utils::ToLocal(i::direct_handle(native_context, i_isolate));
9762}
9763
9764// TODO(ishell): rename back to GetEnteredContext().
9766 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9769 if (last.is_null()) return Local<Context>();
9770 return Utils::ToLocal(last);
9771}
9772
9774 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9776 return Utils::ToLocal(context);
9777}
9778
9780 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9782 if (!i_isolate->CurrentReferrerScript().ToHandle(&script)) {
9783 return MaybeLocal<v8::Data>();
9784 }
9785 return ToApiHandle<Data>(
9786 i::direct_handle(script->host_defined_options(), i_isolate));
9787}
9788
9792
9794 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9795 ENTER_V8_BASIC(i_isolate);
9796 i_isolate->clear_internal_exception();
9797 // If we're passed an empty handle, we throw an undefined exception
9798 // to deal more gracefully with out of memory situations.
9799 if (value.IsEmpty()) {
9800 i_isolate->Throw(i::ReadOnlyRoots(i_isolate).undefined_value());
9801 } else {
9802 i_isolate->Throw(*Utils::OpenDirectHandle(*value));
9803 }
9804 return v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
9805}
9806
9808 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9809 if (i_isolate->has_exception()) {
9810 return true;
9811 }
9812 v8::TryCatch* try_catch_handler =
9814 return try_catch_handler && try_catch_handler->HasCaught();
9815}
9816
9818 GCType gc_type) {
9819 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9820 i_isolate->heap()->AddGCPrologueCallback(callback, gc_type, data);
9821}
9822
9824 void* data) {
9825 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9826 i_isolate->heap()->RemoveGCPrologueCallback(callback, data);
9827}
9828
9830 GCType gc_type) {
9831 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9832 i_isolate->heap()->AddGCEpilogueCallback(callback, gc_type, data);
9833}
9834
9836 void* data) {
9837 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9838 i_isolate->heap()->RemoveGCEpilogueCallback(callback, data);
9839}
9840
9841static void CallGCCallbackWithoutData(Isolate* v8_isolate, GCType type,
9842 GCCallbackFlags flags, void* data) {
9843 reinterpret_cast<Isolate::GCCallback>(data)(v8_isolate, type, flags);
9844}
9845
9847 void* data = reinterpret_cast<void*>(callback);
9849}
9850
9852 void* data = reinterpret_cast<void*>(callback);
9854}
9855
9857 void* data = reinterpret_cast<void*>(callback);
9859}
9860
9862 void* data = reinterpret_cast<void*>(callback);
9864}
9865
9867 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9868 i_isolate->heap()->SetEmbedderRootsHandler(handler);
9869}
9870
9872 const i::Isolate* i_isolate = reinterpret_cast<const i::Isolate*>(this);
9873 return i_isolate->heap()->cpp_heap();
9874}
9875
9878 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9880}
9881
9887
9889 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9890 i_isolate->stack_guard()->RequestTerminateExecution();
9891}
9892
9894 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9895 return i_isolate->is_execution_terminating();
9896}
9897
9899 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9900 i_isolate->stack_guard()->ClearTerminateExecution();
9901 i_isolate->CancelTerminateExecution();
9902}
9903
9905 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9906 i_isolate->RequestInterrupt(callback, data);
9907}
9908
9910#if V8_ENABLE_WEBASSEMBLY
9911 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
9912 return i::wasm::GetWasmEngine()->HasRunningCompileJob(i_isolate);
9913#else
9914 return false;
9915#endif // V8_ENABLE_WEBASSEMBLY
9916}
9917
9919 Utils::ApiCheck(i::v8_flags.expose_gc,
9920 "v8::Isolate::RequestGarbageCollectionForTesting",
9921 "Must use --expose-gc");
9922 // The embedder must have entered the isolate (via `Isolate::Scope`) such that
9923 // the GC can get the "current" isolate from TLS.
9925
9926 if (type == kMinorGarbageCollection) {
9927 reinterpret_cast<i::Isolate*>(this)->heap()->CollectGarbage(
9928 i::NEW_SPACE, i::GarbageCollectionReason::kTesting,
9930 } else {
9932 reinterpret_cast<i::Isolate*>(this)->heap()->PreciseCollectAllGarbage(
9933 i::GCFlag::kNoFlags, i::GarbageCollectionReason::kTesting,
9935 }
9936}
9937
9939 StackState stack_state) {
9940 std::optional<i::EmbedderStackStateScope> stack_scope;
9941 if (type == kFullGarbageCollection) {
9942 stack_scope.emplace(reinterpret_cast<i::Isolate*>(this)->heap(),
9943 i::EmbedderStackStateOrigin::kExplicitInvocation,
9944 stack_state);
9945 }
9947}
9948
9950 i::Isolate* i_isolate = i::Isolate::Current();
9951 return reinterpret_cast<Isolate*>(i_isolate);
9952}
9953
9955 i::Isolate* i_isolate = i::Isolate::TryGetCurrent();
9956 return reinterpret_cast<Isolate*>(i_isolate);
9957}
9958
9960 return reinterpret_cast<const i::Isolate*>(this)->IsCurrent();
9961}
9962
9963// static
9967
9968// static
9970 i::IsolateGroup* isolate_group = group.isolate_group_->Acquire();
9971 return reinterpret_cast<Isolate*>(i::Isolate::New(isolate_group));
9972}
9973
9975 const i::Isolate* i_isolate = reinterpret_cast<const i::Isolate*>(this);
9976 return IsolateGroup(i_isolate->isolate_group()->Acquire());
9977}
9978
9980
9982
9983// static
9984// This is separate so that tests can provide a different |isolate|.
9986 const v8::Isolate::CreateParams& params) {
9987 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
9988 TRACE_EVENT_CALL_STATS_SCOPED(i_isolate, "v8", "V8.IsolateInitialize");
9989 if (auto allocator = params.array_buffer_allocator_shared) {
9990 CHECK(params.array_buffer_allocator == nullptr ||
9991 params.array_buffer_allocator == allocator.get());
9992 i_isolate->set_array_buffer_allocator(allocator.get());
9993 i_isolate->set_array_buffer_allocator_shared(std::move(allocator));
9994 } else {
9995 CHECK_NOT_NULL(params.array_buffer_allocator);
9996 i_isolate->set_array_buffer_allocator(params.array_buffer_allocator);
9997 }
9998 if (params.snapshot_blob != nullptr) {
9999 i_isolate->set_snapshot_blob(params.snapshot_blob);
10000 } else {
10001 i_isolate->set_snapshot_blob(i::Snapshot::DefaultSnapshotBlob());
10002 }
10003
10004 if (params.fatal_error_callback) {
10005 v8_isolate->SetFatalErrorHandler(params.fatal_error_callback);
10006 }
10007
10008#if __clang__
10009#pragma clang diagnostic push
10010#pragma clang diagnostic ignored "-Wdeprecated-declarations"
10011#endif
10012 if (params.oom_error_callback) {
10013 v8_isolate->SetOOMErrorHandler(params.oom_error_callback);
10014 }
10015#if __clang__
10016#pragma clang diagnostic pop
10017#endif
10018
10019 if (params.counter_lookup_callback) {
10020 v8_isolate->SetCounterFunction(params.counter_lookup_callback);
10021 }
10022
10023 if (params.create_histogram_callback) {
10024 v8_isolate->SetCreateHistogramFunction(params.create_histogram_callback);
10025 }
10026
10027 if (params.add_histogram_sample_callback) {
10029 params.add_histogram_sample_callback);
10030 }
10031
10032 i_isolate->set_api_external_references(params.external_references);
10033 i_isolate->set_allow_atomics_wait(params.allow_atomics_wait);
10034
10035 CppHeap* cpp_heap = params.cpp_heap;
10036 if (!cpp_heap) {
10037 cpp_heap =
10038 CppHeap::Create(i::V8::GetCurrentPlatform(), CppHeapCreateParams{{}})
10039 .release();
10040 }
10041
10042 i_isolate->heap()->ConfigureHeap(params.constraints, cpp_heap);
10043 if (params.constraints.stack_limit() != nullptr) {
10044 uintptr_t limit =
10045 reinterpret_cast<uintptr_t>(params.constraints.stack_limit());
10046 i_isolate->stack_guard()->SetStackLimit(limit);
10047 i_isolate->set_stack_size(base::Stack::GetStackStart() - limit);
10048 }
10049
10050 // TODO(v8:2487): Once we got rid of Isolate::Current(), we can remove this.
10051 Isolate::Scope isolate_scope(v8_isolate);
10052 if (i_isolate->snapshot_blob() == nullptr) {
10053 FATAL(
10054 "V8 snapshot blob was not set during initialization. This can mean "
10055 "that the snapshot blob file is corrupted or missing.");
10056 }
10057 if (!i::Snapshot::Initialize(i_isolate)) {
10058 // If snapshot data was provided and we failed to deserialize it must
10059 // have been corrupted.
10060 FATAL(
10061 "Failed to deserialize the V8 snapshot blob. This can mean that the "
10062 "snapshot blob file is corrupted or missing.");
10063 }
10064
10065 {
10066 // Set up code event handlers. Needs to be after i::Snapshot::Initialize
10067 // because that is where we add the isolate to WasmEngine.
10068 auto code_event_handler = params.code_event_handler;
10069 if (code_event_handler) {
10071 code_event_handler);
10072 }
10073 }
10074
10075 i_isolate->set_embedder_wrapper_type_index(
10076 params.embedder_wrapper_type_index);
10077 i_isolate->set_embedder_wrapper_object_index(
10078 params.embedder_wrapper_object_index);
10079
10080 if (!i::V8::GetCurrentPlatform()
10081 ->GetForegroundTaskRunner(v8_isolate)
10082 ->NonNestableTasksEnabled()) {
10083 FATAL(
10084 "The current platform's foreground task runner does not have "
10085 "non-nestable tasks enabled. The embedder must provide one.");
10086 }
10087}
10088
10090 return Isolate::New(IsolateGroup::GetDefault(), params);
10091}
10092
10094 const Isolate::CreateParams& params) {
10095 Isolate* v8_isolate = Allocate(group);
10096 Initialize(v8_isolate, params);
10097 return v8_isolate;
10098}
10099
10101 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10102 if (!Utils::ApiCheck(!i_isolate->IsInUse(), "v8::Isolate::Dispose()",
10103 "Disposing the isolate that is entered by a thread")) {
10104 return;
10105 }
10106 i::Isolate::Delete(i_isolate);
10107}
10108
10110 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10111 i_isolate->DumpAndResetStats();
10112}
10113
10115 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10117}
10118
10120 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10121 i_isolate->Enter();
10122}
10123
10125 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10126 i_isolate->Exit();
10127}
10128
10134
10140
10146
10152
10158
10163
10165 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10166 int stack_trace_limit = 0;
10167 if (!i_isolate->GetStackTraceLimit(i_isolate, &stack_trace_limit)) {
10168 return i::v8_flags.stack_trace_limit;
10169 }
10170 return stack_trace_limit;
10171}
10172
10174 Isolate* v8_isolate,
10176 : v8_isolate_(v8_isolate), on_failure_(on_failure) {
10177 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
10178 switch (on_failure_) {
10179 case CRASH_ON_FAILURE:
10180 i::DisallowJavascriptExecution::Open(i_isolate, &was_execution_allowed_);
10181 break;
10182 case THROW_ON_FAILURE:
10183 i::ThrowOnJavascriptExecution::Open(i_isolate, &was_execution_allowed_);
10184 break;
10185 case DUMP_ON_FAILURE:
10186 i::DumpOnJavascriptExecution::Open(i_isolate, &was_execution_allowed_);
10187 break;
10188 }
10189}
10190
10192 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate_);
10193 switch (on_failure_) {
10194 case CRASH_ON_FAILURE:
10195 i::DisallowJavascriptExecution::Close(i_isolate, was_execution_allowed_);
10196 break;
10197 case THROW_ON_FAILURE:
10198 i::ThrowOnJavascriptExecution::Close(i_isolate, was_execution_allowed_);
10199 break;
10200 case DUMP_ON_FAILURE:
10201 i::DumpOnJavascriptExecution::Close(i_isolate, was_execution_allowed_);
10202 break;
10203 }
10204}
10205
10207 Isolate* v8_isolate)
10208 : v8_isolate_(v8_isolate) {
10209 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
10210 i::AllowJavascriptExecution::Open(i_isolate, &was_execution_allowed_assert_);
10211 i::NoThrowOnJavascriptExecution::Open(i_isolate,
10213 i::NoDumpOnJavascriptExecution::Open(i_isolate, &was_execution_allowed_dump_);
10214}
10215
10217 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate_);
10218 i::AllowJavascriptExecution::Close(i_isolate, was_execution_allowed_assert_);
10219 i::NoThrowOnJavascriptExecution::Close(i_isolate,
10220 was_execution_allowed_throws_);
10221 i::NoDumpOnJavascriptExecution::Close(i_isolate, was_execution_allowed_dump_);
10222}
10223
10226 : i_isolate_(reinterpret_cast<i::Isolate*>(v8_isolate)),
10227 microtask_queue_(microtask_queue
10228 ? static_cast<i::MicrotaskQueue*>(microtask_queue)
10229 : i_isolate_->default_microtask_queue()) {
10230 i_isolate_->thread_local_top()->IncrementCallDepth<true>(this);
10232}
10233
10235 microtask_queue_->DecrementMicrotasksSuppressions();
10236 i_isolate_->thread_local_top()->DecrementCallDepth(this);
10237}
10238
10239i::ValueHelper::InternalRepresentationType Isolate::GetDataFromSnapshotOnce(
10240 size_t index) {
10241 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10242 auto list = i::Cast<i::FixedArray>(i_isolate->heap()->serialized_objects());
10243 return GetSerializedDataFromFixedArray(i_isolate, list, index);
10244}
10245
10247 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10248#ifdef V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
10250 i_isolate->isolate_data()->continuation_preserved_embedder_data(),
10251 i_isolate));
10252#else // V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
10253 return v8::Undefined(reinterpret_cast<v8::Isolate*>(i_isolate));
10254#endif // V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
10255}
10256
10258#ifdef V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
10259 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10260 if (data.IsEmpty())
10261 data = v8::Undefined(reinterpret_cast<v8::Isolate*>(this));
10262 i_isolate->isolate_data()->set_continuation_preserved_embedder_data(
10263 *Utils::OpenDirectHandle(*data));
10264#endif // V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
10265}
10266
10268 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10269 i::Heap* heap = i_isolate->heap();
10270
10271 heap->FreeMainThreadLinearAllocationAreas();
10272
10273 // The order of acquiring memory statistics is important here. We query in
10274 // this order because of concurrent allocation: 1) used memory 2) committed
10275 // physical memory 3) committed memory. Therefore the condition used <=
10276 // committed physical <= committed should hold.
10277 heap_statistics->used_global_handles_size_ = heap->UsedGlobalHandlesSize();
10278 heap_statistics->total_global_handles_size_ = heap->TotalGlobalHandlesSize();
10279 DCHECK_LE(heap_statistics->used_global_handles_size_,
10280 heap_statistics->total_global_handles_size_);
10281
10282 heap_statistics->used_heap_size_ = heap->SizeOfObjects();
10283 heap_statistics->total_physical_size_ = heap->CommittedPhysicalMemory();
10284 heap_statistics->total_heap_size_ = heap->CommittedMemory();
10285
10286 heap_statistics->total_available_size_ = heap->Available();
10287
10288 // TODO(dinfuehr): Right now used <= committed physical does not hold. Fix
10289 // this and add DCHECK.
10290 DCHECK_LE(heap_statistics->used_heap_size_,
10291 heap_statistics->total_heap_size_);
10292
10293 heap_statistics->total_heap_size_executable_ =
10294 heap->CommittedMemoryExecutable();
10295 heap_statistics->heap_size_limit_ = heap->MaxReserved();
10296 // TODO(7424): There is no public API for the {WasmEngine} yet. Once such an
10297 // API becomes available we should report the malloced memory separately. For
10298 // now we just add the values, thereby over-approximating the peak slightly.
10299 heap_statistics->malloced_memory_ =
10300 i_isolate->allocator()->GetCurrentMemoryUsage() +
10301 i_isolate->string_table()->GetCurrentMemoryUsage();
10302 // On 32-bit systems backing_store_bytes() might overflow size_t temporarily
10303 // due to concurrent array buffer sweeping.
10304 heap_statistics->external_memory_ =
10305 i_isolate->heap()->backing_store_bytes() < SIZE_MAX
10306 ? static_cast<size_t>(i_isolate->heap()->backing_store_bytes())
10307 : SIZE_MAX;
10308 heap_statistics->peak_malloced_memory_ =
10309 i_isolate->allocator()->GetMaxMemoryUsage();
10310 heap_statistics->number_of_native_contexts_ = heap->NumberOfNativeContexts();
10311 heap_statistics->number_of_detached_contexts_ =
10312 heap->NumberOfDetachedContexts();
10313 heap_statistics->does_zap_garbage_ = i::heap::ShouldZapGarbage();
10314
10315#if V8_ENABLE_WEBASSEMBLY
10316 heap_statistics->malloced_memory_ +=
10317 i::wasm::GetWasmEngine()->allocator()->GetCurrentMemoryUsage();
10318 heap_statistics->peak_malloced_memory_ +=
10319 i::wasm::GetWasmEngine()->allocator()->GetMaxMemoryUsage();
10320#endif // V8_ENABLE_WEBASSEMBLY
10321}
10322
10324 return i::LAST_SPACE - i::FIRST_SPACE + 1;
10325}
10326
10328 size_t index) {
10329 if (!space_statistics) return false;
10330 if (!i::Heap::IsValidAllocationSpace(static_cast<i::AllocationSpace>(index)))
10331 return false;
10332
10333 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10334 i::Heap* heap = i_isolate->heap();
10335
10336 heap->FreeMainThreadLinearAllocationAreas();
10337
10338 i::AllocationSpace allocation_space = static_cast<i::AllocationSpace>(index);
10339 space_statistics->space_name_ = i::ToString(allocation_space);
10340
10341 if (allocation_space == i::RO_SPACE) {
10342 // RO_SPACE memory is shared across all isolates and accounted for
10343 // elsewhere.
10344 space_statistics->space_size_ = 0;
10345 space_statistics->space_used_size_ = 0;
10346 space_statistics->space_available_size_ = 0;
10347 space_statistics->physical_space_size_ = 0;
10348 } else {
10349 i::Space* space = heap->space(static_cast<int>(index));
10350 space_statistics->space_size_ = space ? space->CommittedMemory() : 0;
10351 space_statistics->space_used_size_ = space ? space->SizeOfObjects() : 0;
10352 space_statistics->space_available_size_ = space ? space->Available() : 0;
10353 space_statistics->physical_space_size_ =
10354 space ? space->CommittedPhysicalMemory() : 0;
10355 }
10356 return true;
10357}
10358
10360 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10361 i::Heap* heap = i_isolate->heap();
10362 return heap->NumberOfTrackedHeapObjectTypes();
10363}
10364
10366 HeapObjectStatistics* object_statistics, size_t type_index) {
10367 if (!object_statistics) return false;
10368 if (V8_LIKELY(!i::TracingFlags::is_gc_stats_enabled())) return false;
10369
10370 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10371 i::Heap* heap = i_isolate->heap();
10372 if (type_index >= heap->NumberOfTrackedHeapObjectTypes()) return false;
10373
10374 const char* object_type;
10375 const char* object_sub_type;
10376 size_t object_count = heap->ObjectCountAtLastGC(type_index);
10377 size_t object_size = heap->ObjectSizeAtLastGC(type_index);
10378 if (!heap->GetObjectTypeName(type_index, &object_type, &object_sub_type)) {
10379 // There should be no objects counted when the type is unknown.
10380 DCHECK_EQ(object_count, 0U);
10381 DCHECK_EQ(object_size, 0U);
10382 return false;
10383 }
10384
10385 object_statistics->object_type_ = object_type;
10386 object_statistics->object_sub_type_ = object_sub_type;
10387 object_statistics->object_count_ = object_count;
10388 object_statistics->object_size_ = object_size;
10389 return true;
10390}
10391
10393 HeapCodeStatistics* code_statistics) {
10394 if (!code_statistics) return false;
10395
10396 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10397 i_isolate->heap()->CollectCodeStatistics();
10398
10399 code_statistics->code_and_metadata_size_ =
10400 i_isolate->code_and_metadata_size();
10401 code_statistics->bytecode_and_metadata_size_ =
10402 i_isolate->bytecode_and_metadata_size();
10403 code_statistics->external_script_source_size_ =
10404 i_isolate->external_script_source_size();
10405 code_statistics->cpu_profiler_metadata_size_ =
10406 i::CpuProfiler::GetAllProfilersMemorySize(i_isolate);
10407
10408 return true;
10409}
10410
10411bool Isolate::MeasureMemory(std::unique_ptr<MeasureMemoryDelegate> delegate,
10412 MeasureMemoryExecution execution) {
10413 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10414 return i_isolate->heap()->MeasureMemory(std::move(delegate), execution);
10415}
10416
10417std::unique_ptr<MeasureMemoryDelegate> MeasureMemoryDelegate::Default(
10418 Isolate* v8_isolate, Local<Context> context,
10419 Local<Promise::Resolver> promise_resolver, MeasureMemoryMode mode) {
10420 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
10421 return i_isolate->heap()->CreateDefaultMeasureMemoryDelegate(
10422 context, promise_resolver, mode);
10423}
10424
10425void Isolate::GetStackSample(const RegisterState& state, void** frames,
10426 size_t frames_limit, SampleInfo* sample_info) {
10427 RegisterState regs = state;
10428 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10429 if (i::TickSample::GetStackSample(i_isolate, &regs,
10430 i::TickSample::kSkipCEntryFrame, frames,
10431 frames_limit, sample_info)) {
10432 return;
10433 }
10434 sample_info->frames_count = 0;
10435 sample_info->vm_state = OTHER;
10436 sample_info->external_callback_entry = nullptr;
10437}
10438
10440 int64_t change_in_bytes) {
10441 return AdjustAmountOfExternalAllocatedMemoryImpl(change_in_bytes);
10442}
10443
10445 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10446 i_isolate->set_event_logger(that);
10447}
10448
10450 if (callback == nullptr) return;
10451 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10453}
10454
10457 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10459}
10460
10462 if (callback == nullptr) return;
10463 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10465}
10466
10468 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10470}
10471
10473 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10474 i_isolate->SetPromiseHook(hook);
10475}
10476
10478 if (callback == nullptr) return;
10479 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10481}
10482
10485 if (callback == nullptr) return;
10486 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10488}
10489
10492 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10493 i_isolate->default_microtask_queue()->PerformCheckpoint(this);
10494}
10495
10497 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10498 auto function = Utils::OpenDirectHandle(*v8_function);
10499 i::DirectHandle<i::NativeContext> handler_context;
10500 if (!i::JSReceiver::GetContextForMicrotask(function).ToHandle(
10501 &handler_context))
10502 handler_context = i_isolate->native_context();
10503 MicrotaskQueue* microtask_queue = handler_context->microtask_queue();
10504 if (microtask_queue) microtask_queue->EnqueueMicrotask(this, v8_function);
10505}
10506
10508 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10509 i_isolate->default_microtask_queue()->EnqueueMicrotask(this, callback, data);
10510}
10511
10513 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10514 i_isolate->default_microtask_queue()->set_microtasks_policy(policy);
10515}
10516
10518 i::Isolate* i_isolate =
10519 reinterpret_cast<i::Isolate*>(const_cast<Isolate*>(this));
10520 return i_isolate->default_microtask_queue()->microtasks_policy();
10521}
10522
10526 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10527 i_isolate->default_microtask_queue()->AddMicrotasksCompletedCallback(callback,
10528 data);
10529}
10530
10533 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10534 i_isolate->default_microtask_queue()->RemoveMicrotasksCompletedCallback(
10535 callback, data);
10536}
10537
10541
10543 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10544 i_isolate->counters()->ResetCounterFunction(callback);
10545}
10546
10548 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10550}
10551
10554 reinterpret_cast<i::Isolate*>(this)
10555 ->counters()
10556 ->SetAddHistogramSampleFunction(callback);
10557}
10558
10560 const std::shared_ptr<metrics::Recorder>& metrics_recorder) {
10561 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10562 i_isolate->metrics_recorder()->SetEmbedderRecorder(i_isolate,
10563 metrics_recorder);
10564}
10565
10567 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10568 i_isolate->SetAddCrashKeyCallback(callback);
10569}
10570
10572 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10573 {
10574 i::NestedTimedHistogramScope idle_notification_scope(
10575 i_isolate->counters()->gc_low_memory_notification());
10576 TRACE_EVENT0("v8", "V8.GCLowMemoryNotification");
10577 i_isolate->heap()->CollectAllAvailableGarbage(
10578 i::GarbageCollectionReason::kLowMemoryNotification);
10579 }
10580}
10581
10582int Isolate::ContextDisposedNotification(bool dependant_context) {
10583 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10584 if (V8_UNLIKELY(i::v8_flags.trace_context_disposal)) {
10585 i_isolate->PrintWithTimestamp("[context-disposal] Disposing %s context\n",
10586 dependant_context ? "nested" : "top-level");
10587 }
10588#if V8_ENABLE_WEBASSEMBLY
10589 if (!dependant_context) {
10590 if (!i_isolate->context().is_null()) {
10591 // We left the current context, we can abort all WebAssembly compilations
10592 // of that context.
10593 // A handle scope for the native context.
10594 i::HandleScope handle_scope(i_isolate);
10595 i::wasm::GetWasmEngine()->DeleteCompileJobsOnContext(
10596 i_isolate->native_context());
10597 }
10598 }
10599#endif // V8_ENABLE_WEBASSEMBLY
10600 i_isolate->AbortConcurrentOptimization(i::BlockingBehavior::kDontBlock);
10601 return i_isolate->heap()->NotifyContextDisposed(dependant_context);
10602}
10603
10605 // TODO(mlippautz): Replace implementation with the old version of
10606 // ContextDisposedNotification() that still has a return parameter.
10610}
10611
10613 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10614 return i_isolate->SetPriority(Priority::kUserBlocking);
10615}
10616
10618 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10619 return i_isolate->SetPriority(Priority::kBestEffort);
10620}
10621
10623 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10624 return i_isolate->SetPriority(priority);
10625}
10626
10628 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10629 bool on_isolate_thread =
10630 i_isolate->was_locker_ever_used()
10631 ? i_isolate->thread_manager()->IsLockedByCurrentThread()
10632 : i::ThreadId::Current() == i_isolate->thread_id();
10633 i_isolate->heap()->MemoryPressureNotification(level, on_isolate_thread);
10634}
10635
10636void Isolate::SetBatterySaverMode(bool battery_saver_mode_enabled) {
10637 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10638 i_isolate->set_battery_saver_mode_enabled(battery_saver_mode_enabled);
10639}
10640
10641void Isolate::SetMemorySaverMode(bool memory_saver_mode_enabled) {
10642 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10643 i_isolate->set_memory_saver_mode_enabled(memory_saver_mode_enabled);
10644}
10645
10647 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10648 i_isolate->AbortConcurrentOptimization(i::BlockingBehavior::kBlock);
10649 i_isolate->ClearSerializerData();
10650 i_isolate->compilation_cache()->Clear();
10651}
10652
10653void Isolate::SetIsLoading(bool is_loading) {
10654 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10655 i_isolate->SetIsLoading(is_loading);
10656}
10657
10658void Isolate::Freeze(bool is_frozen) {
10659 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10660 i_isolate->Freeze(is_frozen);
10661}
10662
10664 // No-op.
10665}
10666
10668 // No-op.
10669}
10670
10672
10674 JitCodeEventHandler event_handler) {
10675 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10676 // Ensure that logging is initialized for our isolate.
10677 i_isolate->InitializeLoggingAndCounters();
10678 i_isolate->v8_file_logger()->SetCodeEventHandler(options, event_handler);
10679}
10680
10681void Isolate::SetStackLimit(uintptr_t stack_limit) {
10682 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10683 CHECK(stack_limit);
10684 i_isolate->stack_guard()->SetStackLimit(stack_limit);
10685 i_isolate->set_stack_size(base::Stack::GetStackStart() - stack_limit);
10686}
10687
10688void Isolate::GetCodeRange(void** start, size_t* length_in_bytes) {
10689 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10690 const base::AddressRegion& code_region = i_isolate->heap()->code_region();
10691 *start = reinterpret_cast<void*>(code_region.begin());
10692 *length_in_bytes = code_region.size();
10693}
10694
10696 size_t* length_in_bytes) {
10697 // Note, we should return the embedded code rande from the .text section here.
10698 i::EmbeddedData d = i::EmbeddedData::FromBlob();
10699 *start = reinterpret_cast<const void*>(d.code());
10700 *length_in_bytes = d.code_size();
10701}
10702
10704 JSEntryStubs entry_stubs;
10705
10706 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10707 std::array<std::pair<i::Builtin, JSEntryStub*>, 3> stubs = {
10708 {{i::Builtin::kJSEntry, &entry_stubs.js_entry_stub},
10709 {i::Builtin::kJSConstructEntry, &entry_stubs.js_construct_entry_stub},
10710 {i::Builtin::kJSRunMicrotasksEntry,
10711 &entry_stubs.js_run_microtasks_entry_stub}}};
10712 for (auto& pair : stubs) {
10713 i::Tagged<i::Code> js_entry = i_isolate->builtins()->code(pair.first);
10714 pair.second->code.start =
10715 reinterpret_cast<const void*>(js_entry->instruction_start());
10716 pair.second->code.length_in_bytes = js_entry->instruction_size();
10717 }
10718
10719 return entry_stubs;
10720}
10721
10722size_t Isolate::CopyCodePages(size_t capacity, MemoryRange* code_pages_out) {
10723#if !defined(V8_TARGET_ARCH_64_BIT) && !defined(V8_TARGET_ARCH_ARM)
10724 // Not implemented on other platforms.
10725 UNREACHABLE();
10726#else
10727
10728 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10729 std::vector<MemoryRange>* code_pages = i_isolate->GetCodePages();
10730
10731 DCHECK_NOT_NULL(code_pages);
10732
10733 // Copy as many elements into the output vector as we can. If the
10734 // caller-provided buffer is not big enough, we fill it, and the caller can
10735 // provide a bigger one next time. We do it this way because allocation is not
10736 // allowed in signal handlers.
10737 size_t limit = std::min(capacity, code_pages->size());
10738 for (size_t i = 0; i < limit; i++) {
10739 code_pages_out[i] = code_pages->at(i);
10740 }
10741 return code_pages->size();
10742#endif
10743}
10744
10745#define CALLBACK_SETTER(ExternalName, Type, InternalName) \
10746 void Isolate::Set##ExternalName(Type callback) { \
10747 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this); \
10748 i_isolate->set_##InternalName(callback); \
10749 }
10750
10751CALLBACK_SETTER(FatalErrorHandler, FatalErrorCallback, exception_behavior)
10752CALLBACK_SETTER(OOMErrorHandler, OOMErrorCallback, oom_behavior)
10755 modify_code_gen_callback)
10757 AllowWasmCodeGenerationCallback, allow_wasm_code_gen_callback)
10758
10759CALLBACK_SETTER(WasmModuleCallback, ExtensionCallback, wasm_module_callback)
10760CALLBACK_SETTER(WasmInstanceCallback, ExtensionCallback, wasm_instance_callback)
10761
10763 wasm_streaming_callback)
10764
10767 wasm_async_resolve_promise_callback)
10768
10770 wasm_load_source_map_callback)
10771
10774 wasm_imported_strings_enabled_callback)
10775
10777 wasm_jspi_enabled_callback)
10778
10781 sharedarraybuffer_constructor_enabled_callback)
10782
10783// TODO(42203853): Remove this after the deprecated API is removed. Right now,
10784// the embedder can still set the callback, but it's never called.
10787 compile_hints_magic_enabled_callback)
10788
10791 is_js_api_wrapper_native_error_callback)
10792
10794 v8::HandleScope handle_scope(this);
10795 v8::Context::Scope context_scope(context);
10796 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10797 if (i_isolate->is_execution_terminating()) return;
10799 if (i_isolate->has_exception()) return;
10800#if V8_ENABLE_WEBASSEMBLY
10801 i::WasmJs::InstallConditionalFeatures(i_isolate,
10802 Utils::OpenDirectHandle(*context));
10803#endif // V8_ENABLE_WEBASSEMBLY
10804}
10805
10807 void* data) {
10808 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10809 i_isolate->heap()->AddNearHeapLimitCallback(callback, data);
10810}
10811
10813 size_t heap_limit) {
10814 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10815 i_isolate->heap()->RemoveNearHeapLimitCallback(callback, heap_limit);
10816}
10817
10819 DCHECK_GT(threshold_percent, 0.0);
10820 DCHECK_LT(threshold_percent, 1.0);
10821 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10822 i_isolate->heap()->AutomaticallyRestoreInitialHeapLimit(threshold_percent);
10823}
10824
10826 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10827 return i_isolate->IsDead();
10828}
10829
10833
10835 int message_levels,
10836 Local<Value> data) {
10837 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10839 i::HandleScope scope(i_isolate);
10841 i_isolate->factory()->message_listeners();
10843 i_isolate->factory()->NewFixedArray(3);
10846 FUNCTION_ADDR(that));
10847 listener->set(0, *foreign);
10848 listener->set(1, data.IsEmpty()
10849 ? i::ReadOnlyRoots(i_isolate).undefined_value()
10850 : *Utils::OpenDirectHandle(*data));
10851 listener->set(2, i::Smi::FromInt(message_levels));
10852 list = i::ArrayList::Add(i_isolate, list, listener);
10853 i_isolate->heap()->SetMessageListeners(*list);
10854 return true;
10855}
10856
10858 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10860 i::HandleScope scope(i_isolate);
10862 i::Tagged<i::ArrayList> listeners = i_isolate->heap()->message_listeners();
10863 for (int i = 0; i < listeners->length(); i++) {
10864 if (i::IsUndefined(listeners->get(i), i_isolate)) {
10865 continue; // skip deleted ones
10866 }
10867 i::Tagged<i::FixedArray> listener =
10868 i::Cast<i::FixedArray>(listeners->get(i));
10869 i::Tagged<i::Foreign> callback_obj = i::Cast<i::Foreign>(listener->get(0));
10870 if (callback_obj->foreign_address<internal::kMessageListenerTag>() ==
10871 FUNCTION_ADDR(that)) {
10872 listeners->set(i, i::ReadOnlyRoots(i_isolate).undefined_value());
10873 }
10874 }
10875}
10876
10879 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10881}
10882
10884 bool capture, int frame_limit, StackTrace::StackTraceOptions options) {
10885 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10886 i_isolate->SetCaptureStackTraceForUncaughtExceptions(capture, frame_limit,
10887 options);
10888}
10889
10891 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10892 return i_isolate->IsInUse();
10893}
10894
10896 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10897 i_isolate->set_allow_atomics_wait(allow);
10898}
10899
10901 TimeZoneDetection time_zone_detection) {
10902 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10905 i_isolate->date_cache()->ResetDateCache(
10906 static_cast<base::TimezoneCache::TimeZoneDetection>(time_zone_detection));
10907#ifdef V8_INTL_SUPPORT
10908 i_isolate->clear_cached_icu_object(
10909 i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormat);
10910 i_isolate->clear_cached_icu_object(
10911 i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForTime);
10912 i_isolate->clear_cached_icu_object(
10913 i::Isolate::ICUObjectCacheType::kDefaultSimpleDateFormatForDate);
10914#endif // V8_INTL_SUPPORT
10915}
10916
10918 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10921
10922#ifdef V8_INTL_SUPPORT
10923 i_isolate->ResetDefaultLocale();
10924#endif // V8_INTL_SUPPORT
10925}
10926
10928 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10930
10931#ifdef V8_INTL_SUPPORT
10932 return i_isolate->DefaultLocale();
10933#else
10934 return std::string();
10935#endif
10936}
10937
10939 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10940 return HashSeed(i_isolate);
10941}
10942
10943#if defined(V8_ENABLE_ETW_STACK_WALKING)
10944void Isolate::SetFilterETWSessionByURLCallback(
10945 FilterETWSessionByURLCallback callback) {
10946 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10947 i_isolate->SetFilterETWSessionByURLCallback(callback);
10948}
10949
10950void Isolate::SetFilterETWSessionByURL2Callback(
10951 FilterETWSessionByURL2Callback callback) {
10952 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(this);
10953 i_isolate->SetFilterETWSessionByURL2Callback(callback);
10954}
10955#endif // V8_ENABLE_ETW_STACK_WALKING
10956
10957bool v8::Object::IsCodeLike(v8::Isolate* v8_isolate) const {
10958 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
10959 API_RCS_SCOPE(i_isolate, Object, IsCodeLike);
10961 i::HandleScope scope(i_isolate);
10962 return Utils::OpenDirectHandle(this)->IsCodeLike(i_isolate);
10963}
10964
10965// static
10966std::unique_ptr<MicrotaskQueue> MicrotaskQueue::New(Isolate* v8_isolate,
10967 MicrotasksPolicy policy) {
10968 auto microtask_queue =
10969 i::MicrotaskQueue::New(reinterpret_cast<i::Isolate*>(v8_isolate));
10970 microtask_queue->set_microtasks_policy(policy);
10971 std::unique_ptr<MicrotaskQueue> ret(std::move(microtask_queue));
10972 return ret;
10973}
10974
10977 : MicrotasksScope(v8_context->GetIsolate(), v8_context->GetMicrotaskQueue(),
10978 type) {}
10979
10983 : i_isolate_(reinterpret_cast<i::Isolate*>(v8_isolate)),
10984 microtask_queue_(microtask_queue
10985 ? static_cast<i::MicrotaskQueue*>(microtask_queue)
10986 : i_isolate_->default_microtask_queue()),
10987 run_(type == MicrotasksScope::kRunMicrotasks) {
10989#ifdef DEBUG
10990 if (!run_) microtask_queue_->IncrementDebugMicrotasksScopeDepth();
10991#endif
10992}
10993
10995 if (run_) {
11000 reinterpret_cast<Isolate*>(i_isolate_));
11003 }
11004 }
11005#ifdef DEBUG
11006 if (!run_) microtask_queue_->DecrementDebugMicrotasksScopeDepth();
11007#endif
11008}
11009
11010// static
11012 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11013 auto* microtask_queue = i_isolate->default_microtask_queue();
11014 microtask_queue->PerformCheckpoint(v8_isolate);
11015}
11016
11017// static
11019 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11020 auto* microtask_queue = i_isolate->default_microtask_queue();
11021 return microtask_queue->GetMicrotasksScopeDepth();
11022}
11023
11024// static
11026 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11027 auto* microtask_queue = i_isolate->default_microtask_queue();
11028 return microtask_queue->IsRunningMicrotasks();
11029}
11030
11032 WriteOptions options)
11033 : str_(nullptr), length_(0) {
11034 if (obj.IsEmpty()) return;
11035 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11036 Local<Context> context = v8_isolate->GetCurrentContext();
11037 ENTER_V8_BASIC(i_isolate);
11038 i::HandleScope scope(i_isolate);
11039 TryCatch try_catch(v8_isolate);
11040 Local<String> str;
11041 if (!obj->ToString(context).ToLocal(&str)) return;
11042 length_ = str->Utf8LengthV2(v8_isolate);
11045 if (options & REPLACE_INVALID_UTF8)
11047 str->WriteUtf8V2(v8_isolate, str_, length_ + 1, flags);
11048}
11049
11051
11053 : str_(nullptr), length_(0) {
11054 if (obj.IsEmpty()) return;
11055 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11056 i::HandleScope scope(i_isolate);
11057 Local<Context> context = v8_isolate->GetCurrentContext();
11058 ENTER_V8_BASIC(i_isolate);
11059 TryCatch try_catch(v8_isolate);
11060 Local<String> str;
11061 if (!obj->ToString(context).ToLocal(&str)) return;
11062 length_ = str->Length();
11064 str->WriteV2(v8_isolate, 0, length_, str_,
11066}
11067
11069
11072 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11073 i::HandleScope scope(i_isolate);
11075 i::DirectHandle<i::String> i_flat_str = i::String::Flatten(i_isolate, i_str);
11076
11077 flat_str_ = Utils::ToLocal(i_flat_str);
11078
11080 new (no_gc_debug_scope_) i::DisallowGarbageCollectionInRelease();
11081 i::String::FlatContent flat_content = i_flat_str->GetFlatContent(*no_gc);
11082 DCHECK(flat_content.IsFlat());
11083 is_one_byte_ = flat_content.IsOneByte();
11084 length_ = flat_content.length();
11085 if (is_one_byte_) {
11086 data8_ = flat_content.ToOneByteVector().data();
11087 } else {
11088 data16_ = flat_content.ToUC16Vector().data();
11089 }
11090}
11091
11094 DisallowGarbageCollectionInRelease* no_gc =
11095 reinterpret_cast<DisallowGarbageCollectionInRelease*>(no_gc_debug_scope_);
11096 no_gc->~DisallowGarbageCollectionInRelease();
11097}
11098
11099void String::ValueView::CheckOneByte(bool is_one_byte) const {
11100 if (is_one_byte) {
11101 Utils::ApiCheck(is_one_byte_, "v8::String::ValueView::data8",
11102 "Called the one-byte accessor on a two-byte string view.");
11103 } else {
11104 Utils::ApiCheck(!is_one_byte_, "v8::String::ValueView::data16",
11105 "Called the two-byte accessor on a one-byte string view.");
11106 }
11107}
11108
11109#define DEFINE_ERROR(NAME, name) \
11110 Local<Value> Exception::NAME(v8::Local<v8::String> raw_message, \
11111 v8::Local<v8::Value> raw_options) { \
11112 i::Isolate* i_isolate = i::Isolate::Current(); \
11113 API_RCS_SCOPE(i_isolate, NAME, New); \
11114 ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate); \
11115 i::Tagged<i::Object> error; \
11116 { \
11117 i::HandleScope scope(i_isolate); \
11118 i::DirectHandle<i::Object> options; \
11119 if (!raw_options.IsEmpty()) { \
11120 options = Utils::OpenDirectHandle(*raw_options); \
11121 } \
11122 auto message = Utils::OpenDirectHandle(*raw_message); \
11123 i::DirectHandle<i::JSFunction> constructor = \
11124 i_isolate->name##_function(); \
11125 error = *i_isolate->factory()->NewError(constructor, message, options); \
11126 } \
11127 return Utils::ToLocal(i::direct_handle(error, i_isolate)); \
11128 }
11129
11130DEFINE_ERROR(RangeError, range_error)
11131DEFINE_ERROR(ReferenceError, reference_error)
11132DEFINE_ERROR(SyntaxError, syntax_error)
11133DEFINE_ERROR(TypeError, type_error)
11134DEFINE_ERROR(WasmCompileError, wasm_compile_error)
11135DEFINE_ERROR(WasmLinkError, wasm_link_error)
11136DEFINE_ERROR(WasmRuntimeError, wasm_runtime_error)
11137DEFINE_ERROR(WasmSuspendError, wasm_suspend_error)
11138DEFINE_ERROR(Error, error)
11139
11140#undef DEFINE_ERROR
11141
11143 Local<Value> exception) {
11144 auto obj = Utils::OpenHandle(*exception);
11145 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(v8_isolate);
11147 i::HandleScope scope(i_isolate);
11148 return Utils::MessageToLocal(
11149 scope.CloseAndEscape(i_isolate->CreateMessage(obj, nullptr)));
11150}
11151
11153 auto obj = Utils::OpenDirectHandle(*exception);
11154 if (!IsJSObject(*obj)) return {};
11155 auto js_obj = i::Cast<i::JSObject>(obj);
11156 i::Isolate* i_isolate = js_obj->GetIsolate();
11158 auto stack_trace = i_isolate->GetDetailedStackTrace(js_obj);
11159 return Utils::StackTraceToLocal(stack_trace);
11160}
11161
11163 Local<Object> object) {
11164 auto i_isolate = reinterpret_cast<i::Isolate*>(context->GetIsolate());
11165 ENTER_V8_NO_SCRIPT(i_isolate, context, Exception, CaptureStackTrace,
11167 auto obj = Utils::OpenHandle(*object);
11168 if (!IsJSObject(*obj)) return Just(false);
11169
11170 auto js_obj = i::Cast<i::JSObject>(obj);
11171
11172 i::FrameSkipMode mode = i::FrameSkipMode::SKIP_FIRST;
11173
11174 auto result = i::ErrorUtils::CaptureStackTrace(i_isolate, js_obj, mode, {});
11175
11177 has_exception = !result.ToHandle(&handle);
11179 return Just(true);
11180}
11181
11183 auto object = Utils::OpenDirectHandle(this);
11184 i::Isolate* i_isolate = object->GetIsolate();
11185 if (i_isolate->is_execution_terminating()) return {};
11186 if (IsMap()) {
11187 *is_key_value = true;
11188 return Map::Cast(this)->AsArray();
11189 }
11190 if (IsSet()) {
11191 *is_key_value = false;
11192 return Set::Cast(this)->AsArray();
11193 }
11194
11195 Isolate* v8_isolate = reinterpret_cast<Isolate*>(i_isolate);
11197 if (i::IsJSWeakCollection(*object)) {
11198 *is_key_value = IsJSWeakMap(*object);
11199 return Utils::ToLocal(i::JSWeakCollection::GetEntries(
11200 i::Cast<i::JSWeakCollection>(object), 0));
11201 }
11202 if (i::IsJSMapIterator(*object)) {
11203 auto it = i::Cast<i::JSMapIterator>(object);
11204 MapAsArrayKind const kind =
11205 static_cast<MapAsArrayKind>(it->map()->instance_type());
11206 *is_key_value = kind == MapAsArrayKind::kEntries;
11207 if (!it->HasMore()) return v8::Array::New(v8_isolate);
11208 return Utils::ToLocal(
11209 MapAsArray(i_isolate, it->table(), i::Smi::ToInt(it->index()), kind));
11210 }
11211 if (i::IsJSSetIterator(*object)) {
11212 auto it = i::Cast<i::JSSetIterator>(object);
11213 SetAsArrayKind const kind =
11214 static_cast<SetAsArrayKind>(it->map()->instance_type());
11215 *is_key_value = kind == SetAsArrayKind::kEntries;
11216 if (!it->HasMore()) return v8::Array::New(v8_isolate);
11217 return Utils::ToLocal(
11218 SetAsArray(i_isolate, it->table(), i::Smi::ToInt(it->index()), kind));
11219 }
11221}
11222
11224 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11225 i::Isolate* i_isolate = node->isolate();
11226 const i::CodeEntry* entry = node->entry();
11228 i_isolate->factory()->InternalizeUtf8String(entry->name());
11229 return ToApiHandle<String>(name);
11230}
11231
11233 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11234 return node->entry()->name();
11235}
11236
11238 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11239 const i::CodeEntry* entry = node->entry();
11240 return entry->script_id();
11241}
11242
11244 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11245 i::Isolate* i_isolate = node->isolate();
11247 node->entry()->resource_name()));
11248}
11249
11251 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11252 return node->entry()->resource_name();
11253}
11254
11256 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11257 return node->entry()->is_shared_cross_origin();
11258}
11259
11261 return reinterpret_cast<const i::ProfileNode*>(this)->line_number();
11262}
11263
11265 return reinterpret_cast<const i::ProfileNode*>(this)
11266 ->entry()
11267 ->column_number();
11268}
11269
11271 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11272 return node->GetHitLineCount();
11273}
11274
11276 unsigned int length) const {
11277 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11278 return node->GetLineTicks(entries, length);
11279}
11280
11282 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11283 return node->entry()->bailout_reason();
11284}
11285
11287 return reinterpret_cast<const i::ProfileNode*>(this)->self_ticks();
11288}
11289
11291 return reinterpret_cast<const i::ProfileNode*>(this)->id();
11292}
11293
11295 return reinterpret_cast<const i::ProfileNode*>(this)->source_type();
11296}
11297
11299 return static_cast<int>(
11300 reinterpret_cast<const i::ProfileNode*>(this)->children()->size());
11301}
11302
11304 const i::ProfileNode* child =
11305 reinterpret_cast<const i::ProfileNode*>(this)->children()->at(index);
11306 return reinterpret_cast<const CpuProfileNode*>(child);
11307}
11308
11310 const i::ProfileNode* parent =
11311 reinterpret_cast<const i::ProfileNode*>(this)->parent();
11312 return reinterpret_cast<const CpuProfileNode*>(parent);
11313}
11314
11315const std::vector<CpuProfileDeoptInfo>& CpuProfileNode::GetDeoptInfos() const {
11316 const i::ProfileNode* node = reinterpret_cast<const i::ProfileNode*>(this);
11317 return node->deopt_infos();
11318}
11319
11321 i::CpuProfile* profile = reinterpret_cast<i::CpuProfile*>(this);
11322 i::CpuProfiler* profiler = profile->cpu_profiler();
11323 DCHECK_NOT_NULL(profiler);
11324 profiler->DeleteProfile(profile);
11325}
11326
11328 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11329 i::Isolate* i_isolate = profile->top_down()->isolate();
11330 return ToApiHandle<String>(
11331 i_isolate->factory()->InternalizeUtf8String(profile->title()));
11332}
11333
11335 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11336 return reinterpret_cast<const CpuProfileNode*>(profile->top_down()->root());
11337}
11338
11339const CpuProfileNode* CpuProfile::GetSample(int index) const {
11340 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11341 return reinterpret_cast<const CpuProfileNode*>(profile->sample(index).node);
11342}
11343
11346
11347int64_t CpuProfile::GetSampleTimestamp(int index) const {
11348 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11349 return profile->sample(index).timestamp.since_origin().InMicroseconds();
11350}
11351
11353 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11354 return profile->sample(index).state_tag;
11355}
11356
11358 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11359 return profile->sample(index).embedder_state_tag;
11360}
11361
11363 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11364 return profile->start_time().since_origin().InMicroseconds();
11365}
11366
11367int64_t CpuProfile::GetEndTime() const {
11368 const i::CpuProfile* profile = reinterpret_cast<const i::CpuProfile*>(this);
11369 return profile->end_time().since_origin().InMicroseconds();
11370}
11371
11372static i::CpuProfile* ToInternal(const CpuProfile* profile) {
11373 return const_cast<i::CpuProfile*>(
11374 reinterpret_cast<const i::CpuProfile*>(profile));
11375}
11376
11378 CpuProfile::SerializationFormat format) const {
11379 Utils::ApiCheck(format == kJSON, "v8::CpuProfile::Serialize",
11380 "Unknown serialization format");
11381 Utils::ApiCheck(stream->GetChunkSize() > 0, "v8::CpuProfile::Serialize",
11382 "Invalid stream chunk size");
11383 i::CpuProfileJSONSerializer serializer(ToInternal(this));
11384 serializer.Serialize(stream);
11385}
11386
11388 return reinterpret_cast<const i::CpuProfile*>(this)->samples_count();
11389}
11390
11392 CpuProfilingNamingMode naming_mode,
11393 CpuProfilingLoggingMode logging_mode) {
11394 return reinterpret_cast<CpuProfiler*>(new i::CpuProfiler(
11395 reinterpret_cast<i::Isolate*>(v8_isolate), naming_mode, logging_mode));
11396}
11397
11399 unsigned max_samples,
11400 int sampling_interval_us,
11401 MaybeLocal<Context> filter_context)
11402 : mode_(mode),
11403 max_samples_(max_samples),
11404 sampling_interval_us_(sampling_interval_us) {
11405 if (!filter_context.IsEmpty()) {
11406 Local<Context> local_filter_context = filter_context.ToLocalChecked();
11407 filter_context_.Reset(local_filter_context->GetIsolate(),
11408 local_filter_context);
11409 filter_context_.SetWeak();
11410 }
11411}
11412
11414 return reinterpret_cast<void*>(
11416 ->native_context()
11417 .address());
11418}
11419
11420void CpuProfiler::Dispose() { delete reinterpret_cast<i::CpuProfiler*>(this); }
11421
11422// static
11423// |trace_id| is an optional identifier stored in the sample record used
11424// to associate the sample with a trace event.
11426 const std::optional<uint64_t> trace_id) {
11427 i::CpuProfiler::CollectSample(reinterpret_cast<i::Isolate*>(v8_isolate),
11428 trace_id);
11429}
11430
11432 DCHECK_GE(us, 0);
11433 return reinterpret_cast<i::CpuProfiler*>(this)->set_sampling_interval(
11435}
11436
11437void CpuProfiler::SetUsePreciseSampling(bool use_precise_sampling) {
11438 reinterpret_cast<i::CpuProfiler*>(this)->set_use_precise_sampling(
11439 use_precise_sampling);
11440}
11441
11443 CpuProfilingOptions options,
11444 std::unique_ptr<DiscardedSamplesDelegate> delegate) {
11445 return reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
11446 std::move(options), std::move(delegate));
11447}
11448
11450 Local<String> title, CpuProfilingOptions options,
11451 std::unique_ptr<DiscardedSamplesDelegate> delegate) {
11452 return reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
11453 *Utils::OpenDirectHandle(*title), std::move(options),
11454 std::move(delegate));
11455}
11456
11458 bool record_samples) {
11461 record_samples ? CpuProfilingOptions::kNoSampleLimit : 0);
11462 return reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
11463 *Utils::OpenDirectHandle(*title), std::move(options));
11464}
11465
11467 CpuProfilingMode mode,
11468 bool record_samples,
11469 unsigned max_samples) {
11470 CpuProfilingOptions options(mode, record_samples ? max_samples : 0);
11471 return reinterpret_cast<i::CpuProfiler*>(this)->StartProfiling(
11472 *Utils::OpenDirectHandle(*title), std::move(options));
11473}
11474
11476 Local<String> title, CpuProfilingOptions options,
11477 std::unique_ptr<DiscardedSamplesDelegate> delegate) {
11478 return Start(title, std::move(options), std::move(delegate)).status;
11479}
11480
11482 bool record_samples) {
11483 return Start(title, record_samples).status;
11484}
11485
11487 CpuProfilingMode mode,
11488 bool record_samples,
11489 unsigned max_samples) {
11490 return Start(title, mode, record_samples, max_samples).status;
11491}
11492
11494 return reinterpret_cast<CpuProfile*>(
11495 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(
11496 *Utils::OpenDirectHandle(*title)));
11497}
11498
11500 return reinterpret_cast<CpuProfile*>(
11501 reinterpret_cast<i::CpuProfiler*>(this)->StopProfiling(id));
11502}
11503
11505 reinterpret_cast<i::Isolate*>(v8_isolate)
11506 ->SetDetailedSourcePositionsForProfiling(true);
11507}
11508
11510 return reinterpret_cast<i::CodeEvent*>(this)->code_start_address;
11511}
11512
11514 return reinterpret_cast<i::CodeEvent*>(this)->code_size;
11515}
11516
11518 return ToApiHandle<String>(
11519 reinterpret_cast<i::CodeEvent*>(this)->function_name);
11520}
11521
11523 return ToApiHandle<String>(
11524 reinterpret_cast<i::CodeEvent*>(this)->script_name);
11525}
11526
11528 return reinterpret_cast<i::CodeEvent*>(this)->script_line;
11529}
11530
11532 return reinterpret_cast<i::CodeEvent*>(this)->script_column;
11533}
11534
11536 return reinterpret_cast<i::CodeEvent*>(this)->code_type;
11537}
11538
11540 return reinterpret_cast<i::CodeEvent*>(this)->comment;
11541}
11542
11544 return reinterpret_cast<i::CodeEvent*>(this)->previous_code_start_address;
11545}
11546
11548 switch (code_event_type) {
11549 case kUnknownType:
11550 return "Unknown";
11551#define V(Name) \
11552 case k##Name##Type: \
11553 return #Name;
11555#undef V
11556 }
11557 // The execution should never pass here
11558 UNREACHABLE();
11559}
11560
11563 reinterpret_cast<i::Isolate*>(v8_isolate));
11564}
11565
11569
11572 ->StartListening(this);
11573}
11574
11577 ->StopListening();
11578}
11579
11581 return const_cast<i::HeapGraphEdge*>(
11582 reinterpret_cast<const i::HeapGraphEdge*>(edge));
11583}
11584
11586 return static_cast<HeapGraphEdge::Type>(ToInternal(this)->type());
11587}
11588
11590 i::HeapGraphEdge* edge = ToInternal(this);
11591 i::Isolate* i_isolate = edge->isolate();
11592 switch (edge->type()) {
11593 case i::HeapGraphEdge::kContextVariable:
11594 case i::HeapGraphEdge::kInternal:
11595 case i::HeapGraphEdge::kProperty:
11596 case i::HeapGraphEdge::kShortcut:
11597 case i::HeapGraphEdge::kWeak:
11598 return ToApiHandle<String>(
11599 i_isolate->factory()->InternalizeUtf8String(edge->name()));
11600 case i::HeapGraphEdge::kElement:
11601 case i::HeapGraphEdge::kHidden:
11602 return ToApiHandle<Number>(
11603 i_isolate->factory()->NewNumberFromInt(edge->index()));
11604 default:
11605 UNREACHABLE();
11606 }
11607}
11608
11610 const i::HeapEntry* from = ToInternal(this)->from();
11611 return reinterpret_cast<const HeapGraphNode*>(from);
11612}
11613
11615 const i::HeapEntry* to = ToInternal(this)->to();
11616 return reinterpret_cast<const HeapGraphNode*>(to);
11617}
11618
11620 return const_cast<i::HeapEntry*>(
11621 reinterpret_cast<const i::HeapEntry*>(entry));
11622}
11623
11625 return static_cast<HeapGraphNode::Type>(ToInternal(this)->type());
11626}
11627
11629 i::Isolate* i_isolate = ToInternal(this)->isolate();
11630 return ToApiHandle<String>(
11631 i_isolate->factory()->InternalizeUtf8String(ToInternal(this)->name()));
11632}
11633
11635
11637 return ToInternal(this)->self_size();
11638}
11639
11641 return ToInternal(this)->children_count();
11642}
11643
11645 return reinterpret_cast<const HeapGraphEdge*>(ToInternal(this)->child(index));
11646}
11647
11648static i::HeapSnapshot* ToInternal(const HeapSnapshot* snapshot) {
11649 return const_cast<i::HeapSnapshot*>(
11650 reinterpret_cast<const i::HeapSnapshot*>(snapshot));
11651}
11652
11654 i::Isolate* i_isolate = ToInternal(this)->profiler()->isolate();
11655 if (i_isolate->heap()->heap_profiler()->GetSnapshotsCount() > 1 ||
11656 i_isolate->heap()->heap_profiler()->IsTakingSnapshot()) {
11657 ToInternal(this)->Delete();
11658 } else {
11659 // If this is the last snapshot, clean up all accessory data as well.
11660 i_isolate->heap()->heap_profiler()->DeleteAllSnapshots();
11661 }
11662}
11663
11665 return reinterpret_cast<const HeapGraphNode*>(ToInternal(this)->root());
11666}
11667
11669 return reinterpret_cast<const HeapGraphNode*>(
11670 ToInternal(this)->GetEntryById(id));
11671}
11672
11674 return static_cast<int>(ToInternal(this)->entries().size());
11675}
11676
11677const HeapGraphNode* HeapSnapshot::GetNode(int index) const {
11678 return reinterpret_cast<const HeapGraphNode*>(
11679 &ToInternal(this)->entries().at(index));
11680}
11681
11683 return ToInternal(this)->max_snapshot_js_object_id();
11684}
11685
11687 HeapSnapshot::SerializationFormat format) const {
11688 Utils::ApiCheck(format == kJSON, "v8::HeapSnapshot::Serialize",
11689 "Unknown serialization format");
11690 Utils::ApiCheck(stream->GetChunkSize() > 0, "v8::HeapSnapshot::Serialize",
11691 "Invalid stream chunk size");
11692 i::HeapSnapshotJSONSerializer serializer(ToInternal(this));
11693 serializer.Serialize(stream);
11694}
11695
11696// static
11699
11701 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotsCount();
11702}
11703
11705 QueryObjectPredicate* predicate,
11706 std::vector<Global<Object>>* objects) {
11707 i::Isolate* isolate = reinterpret_cast<i::Isolate*>(v8_context->GetIsolate());
11708 i::HeapProfiler* profiler = reinterpret_cast<i::HeapProfiler*>(this);
11709 DCHECK_EQ(isolate, profiler->isolate());
11711 profiler->QueryObjects(Utils::OpenDirectHandle(*v8_context), predicate,
11712 objects);
11713}
11714
11716 return reinterpret_cast<const HeapSnapshot*>(
11717 reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshot(index));
11718}
11719
11721 auto obj = Utils::OpenDirectHandle(*value);
11722 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(obj);
11723}
11724
11726 return reinterpret_cast<i::HeapProfiler*>(this)->GetSnapshotObjectId(value);
11727}
11728
11731 reinterpret_cast<i::HeapProfiler*>(this)->FindHeapObjectById(id);
11732 if (obj.is_null()) return Local<Value>();
11733 return Utils::ToLocal(obj);
11734}
11735
11737 reinterpret_cast<i::HeapProfiler*>(this)->ClearHeapObjectMap();
11738}
11739
11741 const HeapSnapshotOptions& options) {
11742 return reinterpret_cast<const HeapSnapshot*>(
11743 reinterpret_cast<i::HeapProfiler*>(this)->TakeSnapshot(options));
11744}
11745
11747 ObjectNameResolver* resolver,
11748 bool hide_internals,
11749 bool capture_numeric_value) {
11751 options.control = control;
11752 options.global_object_name_resolver = resolver;
11753 options.snapshot_mode = hide_internals ? HeapSnapshotMode::kRegular
11755 options.numerics_mode = capture_numeric_value
11758 return TakeHeapSnapshot(options);
11759}
11760
11761std::vector<v8::Local<v8::Value>> HeapProfiler::GetDetachedJSWrapperObjects() {
11762 return reinterpret_cast<i::HeapProfiler*>(this)
11764}
11765
11766void HeapProfiler::StartTrackingHeapObjects(bool track_allocations) {
11767 reinterpret_cast<i::HeapProfiler*>(this)->StartHeapObjectsTracking(
11768 track_allocations);
11769}
11770
11772 reinterpret_cast<i::HeapProfiler*>(this)->StopHeapObjectsTracking();
11773}
11774
11776 int64_t* timestamp_us) {
11777 i::HeapProfiler* heap_profiler = reinterpret_cast<i::HeapProfiler*>(this);
11778 return heap_profiler->PushHeapObjectsStats(stream, timestamp_us);
11779}
11780
11781bool HeapProfiler::StartSamplingHeapProfiler(uint64_t sample_interval,
11782 int stack_depth,
11783 SamplingFlags flags) {
11784 return reinterpret_cast<i::HeapProfiler*>(this)->StartSamplingHeapProfiler(
11785 sample_interval, stack_depth, flags);
11786}
11787
11789 reinterpret_cast<i::HeapProfiler*>(this)->StopSamplingHeapProfiler();
11790}
11791
11795
11797 reinterpret_cast<i::HeapProfiler*>(this)->DeleteAllSnapshots();
11798}
11799
11801 const v8::Local<v8::Data>& data) {
11802 CHECK(data->IsValue());
11803 return V8Node(data.As<v8::Value>());
11804}
11805
11807 BuildEmbedderGraphCallback callback, void* data) {
11808 reinterpret_cast<i::HeapProfiler*>(this)->AddBuildEmbedderGraphCallback(
11809 callback, data);
11810}
11811
11813 BuildEmbedderGraphCallback callback, void* data) {
11814 reinterpret_cast<i::HeapProfiler*>(this)->RemoveBuildEmbedderGraphCallback(
11815 callback, data);
11816}
11817
11819 void* data) {
11820 reinterpret_cast<i::HeapProfiler*>(this)->SetGetDetachednessCallback(callback,
11821 data);
11822}
11823
11825 return reinterpret_cast<i::HeapProfiler*>(this)->IsTakingSnapshot();
11826}
11827
11828const char* HeapProfiler::CopyNameForHeapSnapshot(const char* name) {
11829 return reinterpret_cast<i::HeapProfiler*>(this)->CopyNameForHeapSnapshot(
11830 name);
11831}
11832
11834 Local<v8::Context> context,
11835 EmbedderStateTag tag)
11836 : embedder_state_(new internal::EmbedderState(v8_isolate, context, tag)) {}
11837
11838// std::unique_ptr's destructor is not compatible with Forward declared
11839// EmbedderState class.
11840// Default destructor must be defined in implementation file.
11842
11844#ifdef V8_HOST_ARCH_64_BIT
11845 if (IsEmpty()) return;
11846
11848 *reinterpret_cast<uint64_t*>(slot()));
11849#endif // V8_HOST_ARCH_64_BIT
11850}
11851
11852CFunction::CFunction(const void* address, const CFunctionInfo* type_info)
11853 : address_(address), type_info_(type_info) {
11856}
11857
11859 unsigned int arg_count, const CTypeInfo* arg_info,
11861 : return_info_(return_info),
11862 repr_(repr),
11863 arg_count_(arg_count),
11864 arg_info_(arg_info) {
11867 if (arg_count_ > 0) {
11868 for (unsigned int i = 0; i < arg_count_ - 1; ++i) {
11870 }
11871 }
11872}
11873
11874const CTypeInfo& CFunctionInfo::ArgumentInfo(unsigned int index) const {
11875 DCHECK_LT(index, ArgumentCount());
11876 return arg_info_[index];
11877}
11878
11879namespace api_internal {
11881 v8::Isolate* isolate, v8::Local<v8::Data> raw_target) {
11882 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
11884 if (i::IsFunctionTemplateInfo(*target)) {
11886 i::Cast<i::FunctionTemplateInfo>(*target)->callback_data(kAcquireLoad),
11887 i_isolate);
11888 return Utils::ToLocal(data);
11889
11890 } else if (i::IsJSFunction(*target)) {
11892 auto shared = target_func->shared();
11893 if (shared->IsApiFunction()) {
11895 shared->api_func_data()->callback_data(kAcquireLoad), i_isolate);
11896 return Utils::ToLocal(data);
11897 }
11898 }
11899 Utils::ApiCheck(false, "api_internal::GetFunctionTemplateData",
11900 "Target function is not an Api function");
11901 UNREACHABLE();
11902}
11903} // namespace api_internal
11904
11906 : pc(nullptr), sp(nullptr), fp(nullptr), lr(nullptr) {}
11908
11909RegisterState::RegisterState(const RegisterState& other) { *this = other; }
11910
11912 if (&other != this) {
11913 pc = other.pc;
11914 sp = other.sp;
11915 fp = other.fp;
11916 lr = other.lr;
11917 if (other.callee_saved) {
11918 // Make a deep copy if {other.callee_saved} is non-null.
11919 callee_saved =
11920 std::make_unique<CalleeSavedRegisters>(*(other.callee_saved));
11921 } else {
11922 // Otherwise, set {callee_saved} to null to match {other}.
11923 callee_saved.reset();
11924 }
11925 }
11926 return *this;
11927}
11928
11929#if !V8_ENABLE_WEBASSEMBLY
11930// If WebAssembly is disabled, we still need to provide an implementation of the
11931// WasmStreaming API. Since {WasmStreaming::Unpack} will always fail, all
11932// methods are unreachable.
11933
11935
11936WasmStreaming::WasmStreaming(std::unique_ptr<WasmStreamingImpl>) {
11937 UNREACHABLE();
11938}
11939
11941
11942void WasmStreaming::OnBytesReceived(const uint8_t* bytes, size_t size) {
11943 UNREACHABLE();
11944}
11945
11946void WasmStreaming::Finish(bool can_use_compiled_module) { UNREACHABLE(); }
11947
11949
11950bool WasmStreaming::SetCompiledModuleBytes(const uint8_t* bytes, size_t size) {
11951 UNREACHABLE();
11952}
11953
11958
11959void WasmStreaming::SetUrl(const char* url, size_t length) { UNREACHABLE(); }
11960
11961// static
11962std::shared_ptr<WasmStreaming> WasmStreaming::Unpack(Isolate* v8_isolate,
11963 Local<Value> value) {
11964 FATAL("WebAssembly is disabled");
11965}
11966#endif // !V8_ENABLE_WEBASSEMBLY
11967
11968namespace internal {
11969
11971 offsetof(HandleScopeImplementer, entered_contexts_);
11972
11974
11978 MemCopy(storage, this, sizeof(*this));
11979
11981 current->Initialize();
11982
11983 return storage + ArchiveSpacePerThread();
11984}
11985
11989
11991 MemCopy(this, storage, sizeof(*this));
11993 return storage + ArchiveSpacePerThread();
11994}
11995
11997#ifdef DEBUG
11998 bool found_block_before_persistent = false;
11999#endif
12000 // Iterate over all handles in the blocks except for the last.
12001 for (int i = static_cast<int>(blocks()->size()) - 2; i >= 0; --i) {
12002 Address* block = blocks()->at(i);
12003 // Cast possibly-unrelated pointers to plain Address before comparing them
12004 // to avoid undefined behavior.
12005 if (HasPersistentScope() &&
12006 (reinterpret_cast<Address>(
12008 reinterpret_cast<Address>(&block[kHandleBlockSize])) &&
12009 (reinterpret_cast<Address>(
12011 reinterpret_cast<Address>(block))) {
12013 Root::kHandleScope, nullptr, FullObjectSlot(block),
12015 DCHECK(!found_block_before_persistent);
12016#ifdef DEBUG
12017 found_block_before_persistent = true;
12018#endif
12019 } else {
12020 v->VisitRootPointers(Root::kHandleScope, nullptr, FullObjectSlot(block),
12022 }
12023 }
12024
12026 last_handle_before_persistent_block_.value() != nullptr,
12027 found_block_before_persistent);
12028
12029 // Iterate over live handles in the last block (if any).
12030 if (!blocks()->empty()) {
12031 v->VisitRootPointers(Root::kHandleScope, nullptr,
12032 FullObjectSlot(blocks()->back()),
12034 }
12035
12036 saved_contexts_.shrink_to_fit();
12037 if (!saved_contexts_.empty()) {
12039 v->VisitRootPointers(Root::kHandleScope, nullptr, start,
12040 start + static_cast<int>(saved_contexts_.size()));
12041 }
12042 entered_contexts_.shrink_to_fit();
12043 if (!entered_contexts_.empty()) {
12045 v->VisitRootPointers(Root::kHandleScope, nullptr, start,
12046 start + static_cast<int>(entered_contexts_.size()));
12047 }
12048}
12049
12055
12057 HandleScopeImplementer* scope_implementer =
12058 reinterpret_cast<HandleScopeImplementer*>(storage);
12059 scope_implementer->IterateThis(v);
12060 return storage + ArchiveSpacePerThread();
12061}
12062
12063std::unique_ptr<PersistentHandles> HandleScopeImplementer::DetachPersistent(
12064 Address* first_block) {
12065 std::unique_ptr<PersistentHandles> ph(new PersistentHandles(isolate()));
12067 DCHECK_NOT_NULL(first_block);
12068
12069 Address* block_start;
12070 do {
12071 block_start = blocks_.back();
12072 ph->blocks_.push_back(blocks_.back());
12073#if DEBUG
12074 ph->ordered_blocks_.insert(blocks_.back());
12075#endif
12076 blocks_.pop_back();
12077 } while (block_start != first_block);
12078
12079 // ph->blocks_ now contains the blocks installed on the HandleScope stack
12080 // since BeginPersistentScope was called, but in reverse order.
12081
12082 // Switch first and last blocks, such that the last block is the one
12083 // that is potentially half full.
12084 DCHECK(!ph->blocks_.empty());
12085 std::swap(ph->blocks_.front(), ph->blocks_.back());
12086
12087 ph->block_next_ = isolate()->handle_scope_data()->next;
12088 block_start = ph->blocks_.back();
12089 ph->block_limit_ = block_start + kHandleBlockSize;
12090
12092 last_handle_before_persistent_block_.value() == nullptr);
12094 return ph;
12095}
12096
12098 v8::Local<v8::Name> property,
12100 // Leaving JavaScript.
12101 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
12102 RCS_SCOPE(i_isolate, RuntimeCallCounterId::kAccessorGetterCallback);
12103
12105 {
12106 Address arg = i_isolate->isolate_data()->api_callback_thunk_argument();
12107 // Currently we don't call InterceptorInfo callbacks via CallApiGetter.
12108 DCHECK(IsAccessorInfo(Tagged<Object>(arg)));
12109 Tagged<AccessorInfo> accessor_info =
12111 getter = reinterpret_cast<v8::AccessorNameGetterCallback>(
12112 accessor_info->getter(i_isolate));
12113
12114 if (V8_UNLIKELY(i_isolate->should_check_side_effects())) {
12115 i::DirectHandle<Object> receiver_check_unsupported;
12116
12117 if (!i_isolate->debug()->PerformSideEffectCheckForAccessor(
12118 direct_handle(accessor_info, i_isolate),
12119 receiver_check_unsupported, ACCESSOR_GETTER)) {
12120 return;
12121 }
12122 }
12123 }
12124 ExternalCallbackScope call_scope(i_isolate, FUNCTION_ADDR(getter),
12126 getter(property, info);
12127}
12128
12129namespace {
12130
12131inline Tagged<FunctionTemplateInfo> GetTargetFunctionTemplateInfo(
12134 CHECK(IsFunctionTemplateInfo(target));
12135 return Cast<FunctionTemplateInfo>(target);
12136}
12137
12138inline void InvokeFunctionCallback(
12140 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
12141 RCS_SCOPE(i_isolate, RuntimeCallCounterId::kFunctionCallback);
12142
12143 Tagged<FunctionTemplateInfo> fti = GetTargetFunctionTemplateInfo(info);
12145 reinterpret_cast<v8::FunctionCallback>(fti->callback(i_isolate));
12146 switch (mode) {
12148 if (V8_UNLIKELY(i_isolate->should_check_side_effects())) {
12149 if (!i_isolate->debug()->PerformSideEffectCheckForCallback(
12150 handle(fti, i_isolate))) {
12151 // Failed side effect check.
12152 return;
12153 }
12154 if (DEBUG_BOOL) {
12155 // Clear raw pointer to ensure it's not accidentally used after
12156 // potential GC in PerformSideEffectCheckForCallback.
12157 fti = {};
12158 }
12159 }
12160 break;
12161 }
12163 // CallFunction builtin should deoptimize an optimized function when
12164 // side effects checking is enabled, so we don't have to handle side
12165 // effects checking in the optimized version of the builtin.
12166 DCHECK(!i_isolate->should_check_side_effects());
12167 break;
12169 // This mode doesn't call InvokeFunctionCallback.
12170 UNREACHABLE();
12171 }
12172
12173 ExternalCallbackScope call_scope(i_isolate, FUNCTION_ADDR(callback),
12174 info.IsConstructCall()
12177 &info);
12178 callback(info);
12179}
12180} // namespace
12181
12184 InvokeFunctionCallback(info, CallApiCallbackMode::kGeneric);
12185}
12186
12189 InvokeFunctionCallback(info, CallApiCallbackMode::kOptimized);
12190}
12191
12194 DirectHandle<JSFinalizationRegistry> finalization_registry) {
12195 i::Isolate* i_isolate = finalization_registry->native_context()->GetIsolate();
12196 RCS_SCOPE(i_isolate,
12197 RuntimeCallCounterId::kFinalizationRegistryCleanupFromTask);
12198 // Do not use ENTER_V8 because this is always called from a running
12199 // FinalizationRegistryCleanupTask within V8 and we should not log it as an
12200 // API call. This method is implemented here to avoid duplication of the
12201 // exception handling and microtask running logic in CallDepthScope.
12202 if (i_isolate->is_execution_terminating()) return;
12203 Local<v8::Context> api_context = Utils::ToLocal(native_context);
12204 CallDepthScope<true> call_depth_scope(i_isolate, api_context);
12205 VMState<OTHER> state(i_isolate);
12206 JSFinalizationRegistry::Cleanup(i_isolate, finalization_registry);
12207}
12208
12209template <>
12211int32_t ConvertDouble(double d) {
12212 return internal::DoubleToInt32(d);
12213}
12214
12215template <>
12217uint32_t ConvertDouble(double d) {
12218 return internal::DoubleToUint32(d);
12219}
12220
12221template <>
12223float ConvertDouble(double d) {
12224 return internal::DoubleToFloat32(d);
12225}
12226
12227template <>
12229double ConvertDouble(double d) {
12230 return d;
12231}
12232
12233template <>
12235int64_t ConvertDouble(double d) {
12237}
12238
12239template <>
12241uint64_t ConvertDouble(double d) {
12243}
12244
12245template <>
12248 // Implements https://tc39.es/ecma262/#sec-toboolean.
12249 return !std::isnan(d) && d != 0;
12250}
12251
12252// Undefine macros for jumbo build.
12253#undef SET_FIELD_WRAPPED
12254#undef NEW_STRING
12255#undef CALLBACK_SETTER
12256
12257template <typename T>
12259 CHECK_GE(info.Length(), 0);
12260 // Theortically args-length is unlimited, practically we run out of stack
12261 // space. This should guard against accidentally used raw pointers.
12262 CHECK_LE(info.Length(), 0xFFFFF);
12263 if (info.Length() > 0) {
12264 CHECK(info[0]->IsValue());
12265 CHECK(info[info.Length() - 1]->IsValue());
12266 }
12267 auto* i_isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
12268 CHECK_EQ(i_isolate, Isolate::Current());
12269 CHECK(!i_isolate->GetIncumbentContext().is_null());
12270 CHECK(info.This()->IsObject());
12271 CHECK(!info.Data().IsEmpty());
12272 CHECK(info.GetReturnValue().Get()->IsValue());
12273 return true;
12274}
12275
12276template <typename T>
12278 auto* i_isolate = reinterpret_cast<i::Isolate*>(info.GetIsolate());
12279 CHECK_EQ(i_isolate, Isolate::Current());
12280 CHECK(info.This()->IsValue());
12281 CHECK(info.HolderV2()->IsObject());
12282 CHECK(!i::IsJSGlobalObject(*Utils::OpenDirectHandle(*info.HolderV2())));
12283 // Allow usages of v8::PropertyCallbackInfo<T>::Holder() for now.
12284 // TODO(https://crbug.com/333672197): remove.
12286 CHECK(info.Holder()->IsObject());
12287 CHECK_IMPLIES(info.Holder() != info.HolderV2(),
12288 i::IsJSGlobalObject(*Utils::OpenDirectHandle(*info.Holder())));
12290 i::Tagged<i::Object> key = i::PropertyCallbackArguments::GetPropertyKey(info);
12291 CHECK(i::IsSmi(key) || i::IsName(key));
12292 CHECK(info.Data()->IsValue());
12293 USE(info.ShouldThrowOnError());
12294 if (!std::is_same_v<T, void>) {
12295 CHECK(info.GetReturnValue().Get()->IsValue());
12296 }
12297 return true;
12298}
12299
12300template <>
12304
12305template <>
12306bool V8_EXPORT
12310
12311template <>
12312bool V8_EXPORT
12316
12317template <>
12318bool V8_EXPORT
12322
12323template <>
12324bool V8_EXPORT
12328
12329template <>
12330bool V8_EXPORT
12334
12335template <>
12339
12340} // namespace internal
12341
12343#ifdef V8_ENABLE_MEMORY_ACCOUNTING_CHECKS
12344 DCHECK_EQ(amount_of_external_memory_, 0U);
12345#endif
12346}
12347
12349 ExternalMemoryAccounter&& other) {
12350#if V8_ENABLE_MEMORY_ACCOUNTING_CHECKS
12351 amount_of_external_memory_ =
12352 std::exchange(other.amount_of_external_memory_, 0U);
12353 isolate_ = std::exchange(other.isolate_, nullptr);
12354#endif
12355}
12356
12358 ExternalMemoryAccounter&& other) {
12359#if V8_ENABLE_MEMORY_ACCOUNTING_CHECKS
12360 if (this == &other) {
12361 return *this;
12362 }
12363 DCHECK_EQ(amount_of_external_memory_, 0U);
12364 amount_of_external_memory_ =
12365 std::exchange(other.amount_of_external_memory_, 0U);
12366 isolate_ = std::exchange(other.isolate_, nullptr);
12367#endif
12368 return *this;
12369}
12370
12371void ExternalMemoryAccounter::Increase(Isolate* isolate, size_t size) {
12372#ifdef V8_ENABLE_MEMORY_ACCOUNTING_CHECKS
12373 DCHECK(isolate == isolate_ || isolate_ == nullptr);
12374 isolate_ = isolate;
12375 amount_of_external_memory_ += size;
12376#endif
12377 isolate->AdjustAmountOfExternalAllocatedMemoryImpl(
12378 static_cast<int64_t>(size));
12379}
12380
12381void ExternalMemoryAccounter::Update(Isolate* isolate, int64_t delta) {
12382#ifdef V8_ENABLE_MEMORY_ACCOUNTING_CHECKS
12383 DCHECK(isolate == isolate_ || isolate_ == nullptr);
12384 DCHECK_GE(static_cast<int64_t>(amount_of_external_memory_), -delta);
12385 isolate_ = isolate;
12386 amount_of_external_memory_ += delta;
12387#endif
12388 isolate->AdjustAmountOfExternalAllocatedMemoryImpl(delta);
12389}
12390
12391void ExternalMemoryAccounter::Decrease(Isolate* isolate, size_t size) {
12393 if (size == 0) {
12394 return;
12395 }
12396#ifdef V8_ENABLE_MEMORY_ACCOUNTING_CHECKS
12397 DCHECK_EQ(isolate, isolate_);
12398 DCHECK_GE(amount_of_external_memory_, size);
12399 amount_of_external_memory_ -= size;
12400#endif
12401 i::Isolate* i_isolate = reinterpret_cast<i::Isolate*>(isolate);
12402 i_isolate->heap()->UpdateExternalMemory(-static_cast<int64_t>(size));
12403}
12404
12405int64_t
12407 const Isolate* isolate) {
12408 const i::Isolate* i_isolate = reinterpret_cast<const i::Isolate*>(isolate);
12409 return i_isolate->heap()->external_memory();
12410}
12411
12412template <>
12414TryToCopyAndConvertArrayToCppBuffer<CTypeInfoBuilder<int32_t>::Build().GetId(),
12415 int32_t>(Local<Array> src, int32_t* dst,
12416 uint32_t max_length) {
12418 CTypeInfo(CTypeInfo::Type::kInt32).GetId(), int32_t>(src, dst,
12419 max_length);
12420}
12421
12422template <>
12424TryToCopyAndConvertArrayToCppBuffer<CTypeInfoBuilder<uint32_t>::Build().GetId(),
12425 uint32_t>(Local<Array> src, uint32_t* dst,
12426 uint32_t max_length) {
12428 CTypeInfo(CTypeInfo::Type::kUint32).GetId(), uint32_t>(src, dst,
12429 max_length);
12430}
12431
12432template <>
12434TryToCopyAndConvertArrayToCppBuffer<CTypeInfoBuilder<float>::Build().GetId(),
12435 float>(Local<Array> src, float* dst,
12436 uint32_t max_length) {
12438 CTypeInfo(CTypeInfo::Type::kFloat32).GetId(), float>(src, dst,
12439 max_length);
12440}
12441
12442template <>
12444TryToCopyAndConvertArrayToCppBuffer<CTypeInfoBuilder<double>::Build().GetId(),
12445 double>(Local<Array> src, double* dst,
12446 uint32_t max_length) {
12448 CTypeInfo(CTypeInfo::Type::kFloat64).GetId(), double>(src, dst,
12449 max_length);
12450}
12451
12452} // namespace v8
12453
12454#ifdef ENABLE_SLOW_DCHECKS
12455EXPORT_CONTEXTUAL_VARIABLE(v8::internal::StackAllocatedCheck)
12456#endif
12457
#define INTERCEPTOR_INFO_CALLBACK_LIST(V)
#define PREPARE_FOR_EXECUTION(context, class_name, function_name)
Definition api-macros.h:59
#define RETURN_ON_FAILED_EXECUTION_PRIMITIVE(T)
Definition api-macros.h:109
#define RETURN_ON_FAILED_EXECUTION(T)
Definition api-macros.h:106
#define DCHECK_NO_SCRIPT_NO_EXCEPTION(i_isolate)
Definition api-macros.h:97
#define ENTER_V8_FOR_NEW_CONTEXT(i_isolate)
Definition api-macros.h:102
#define ENTER_V8_BASIC(i_isolate)
Definition api-macros.h:36
#define ENTER_V8_NO_SCRIPT_NO_EXCEPTION(i_isolate)
Definition api-macros.h:99
#define API_RCS_SCOPE(i_isolate, class_name, function_name)
Definition api-macros.h:32
#define ENTER_V8_NO_SCRIPT(i_isolate, context, class_name, function_name, HandleScopeClass)
Definition api-macros.h:92
#define RETURN_ESCAPED(value)
Definition api-macros.h:112
#define ENTER_V8(i_isolate, context, class_name, function_name, HandleScopeClass)
Definition api-macros.h:65
Isolate * isolate_
#define DEFINE_ERROR(NAME, name)
Definition api.cc:11109
#define TYPED_ARRAY_CASE(Type, type, TYPE, ctype)
#define VALUE_IS_SPECIFIC_TYPE(Type, Check)
Definition api.cc:3588
#define SET_FIELD_WRAPPED(i_isolate, obj, setter, cdata, tag)
Definition api.cc:1209
#define SYMBOL_GETTER(Name, name)
Definition api.cc:9527
#define V(Name)
#define CALLBACK_SETTER(ExternalName, Type, InternalName)
Definition api.cc:10745
#define WELL_KNOWN_SYMBOLS(V)
Definition api.cc:9512
#define CHECK_TYPED_ARRAY_CAST(Type, typeName, TYPE, ctype)
Definition api.cc:4080
#define TIME_ZONE_DETECTION_ASSERT_EQ(value)
Definition api.cc:8033
#define VALUE_IS_TYPED_ARRAY(Type, typeName, TYPE, ctype)
Definition api.cc:3543
#define NEW_STRING(v8_isolate, class_name, function_name, Char, data, type, length)
Definition api.cc:7559
#define SET_CALLBACK_FIELD(Name, name)
#define TYPED_ARRAY_NEW(Type, type, TYPE, ctype)
Definition api.cc:9275
#define REGEXP_FLAG_ASSERT_EQ(flag)
Definition api.cc:8079
RegisterAllocator * allocator_
uint8_t data_[MAX_STACK_LENGTH]
const char * name
Definition builtins.cc:39
union v8::internal::@341::BuiltinMetadata::KindSpecificData data
Builtins::Kind kind
Definition builtins.cc:40
PropertyT * setter
PropertyT * getter
#define SBXCHECK(condition)
Definition check.h:61
#define SLOW_DCHECK(condition)
Definition checks.h:21
static bool IsOnStack(const void *slot)
Definition stack.cc:24
static const int kNoPreviousCharacter
Definition unicode.h:102
static const int kMaxExtraUtf8BytesForOneUtf16CodeUnit
Definition unicode.h:122
static bool IsSurrogatePair(int lead, int trail)
Definition unicode.h:103
static bool IsTrailSurrogate(int code)
Definition unicode.h:109
static bool IsLeadSurrogate(int code)
Definition unicode.h:106
static unsigned Length(uchar chr, int previous)
static const unsigned kMaxEncodedSize
Definition unicode.h:178
static unsigned EncodeOneByte(char *out, uint8_t c)
static unsigned Encode(char *out, uchar c, int previous, bool replace_invalid=false)
Local< ArrayBuffer > Buffer()
Definition api.cc:9161
size_t ByteOffset()
Definition api.cc:9245
v8::MemorySpan< uint8_t > GetContents(v8::MemorySpan< uint8_t > storage)
Definition api.cc:9202
size_t ByteLength()
Definition api.cc:9250
size_t CopyContents(void *dest, size_t byte_length)
Definition api.cc:9182
bool HasBuffer() const
Definition api.cc:9238
static void CheckCast(Value *obj)
Definition api.cc:4068
static Allocator * NewDefaultAllocator()
Definition api.cc:8923
virtual size_t MaxAllocationSize() const
size_t MaxByteLength() const
Definition api.cc:9004
static MaybeLocal< ArrayBuffer > MaybeNew(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized)
Definition api.cc:9021
static std::unique_ptr< BackingStore > NewResizableBackingStore(size_t byte_length, size_t max_byte_length)
Definition api.cc:9130
static Local< ArrayBuffer > New(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized)
Definition api.cc:9044
static std::unique_ptr< BackingStore > NewBackingStore(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized, BackingStoreOnFailureMode on_failure=BackingStoreOnFailureMode::kOutOfMemory)
Definition api.cc:9079
V8_WARN_UNUSED_RESULT Maybe< bool > Detach(v8::Local< v8::Value > key)
Definition api.cc:8959
void SetDetachKey(v8::Local< v8::Value > key)
Definition api.cc:8994
bool IsDetachable() const
Definition api.cc:8944
bool WasDetached() const
Definition api.cc:8948
bool IsResizableByUserJavaScript() const
Definition api.cc:4043
void * Data() const
Definition api.cc:4039
std::shared_ptr< BackingStore > GetBackingStore()
Definition api.cc:4028
static constexpr size_t kMaxByteLength
static void CheckCast(Value *obj)
Definition api.cc:4061
size_t ByteLength() const
Definition api.cc:9000
CallbackResult(*)(uint32_t index, Local< Value > element, void *data) IterationCallback
static Local< Array > New(Isolate *isolate, int length=0)
Definition api.cc:8119
uint32_t Length() const
Definition api.cc:8187
Maybe< void > Iterate(Local< Context > context, IterationCallback callback, void *callback_data)
Definition api.cc:8342
static void CheckCast(Value *obj)
Definition api.cc:3951
void(*)(void *data, size_t length, void *deleter_data) DeleterCallback
size_t MaxByteLength() const
Definition api.cc:4010
bool IsShared() const
Definition api.cc:4014
size_t ByteLength() const
Definition api.cc:4006
bool IsResizableByUserJavaScript() const
Definition api.cc:4018
static void EmptyDeleter(void *data, size_t length, void *deleter_data)
Definition api.cc:4023
void * Data() const
Definition api.cc:4002
Local< BigInt > ValueOf() const
Definition api.cc:7899
static void CheckCast(Value *obj)
Definition api.cc:4138
static Local< Value > New(Isolate *isolate, int64_t value)
Definition api.cc:7889
uint64_t Uint64Value(bool *lossless=nullptr) const
Definition api.cc:9618
static void CheckCast(v8::Data *that)
Definition api.cc:3940
static Local< BigInt > New(Isolate *isolate, int64_t value)
Definition api.cc:9591
int64_t Int64Value(bool *lossless=nullptr) const
Definition api.cc:9622
static Local< BigInt > NewFromUnsigned(Isolate *isolate, uint64_t value)
Definition api.cc:9598
int WordCount() const
Definition api.cc:9626
static MaybeLocal< BigInt > NewFromWords(Local< Context > context, int sign_bit, int word_count, const uint64_t *words)
Definition api.cc:9605
void ToWordsArray(int *sign_bit, int *word_count, uint64_t *words) const
Definition api.cc:9630
static void CheckCast(Value *obj)
Definition api.cc:4144
static Local< Value > New(Isolate *isolate, bool value)
Definition api.cc:7908
bool ValueOf() const
Definition api.cc:7918
bool Value() const
Definition api.cc:6245
static void CheckCast(v8::Data *that)
Definition api.cc:3865
const CTypeInfo * arg_info_
const CTypeInfo & ArgumentInfo(unsigned int index) const
Definition api.cc:11874
const unsigned int arg_count_
unsigned int ArgumentCount() const
CFunctionInfo(const CTypeInfo &return_info, unsigned int arg_count, const CTypeInfo *arg_info, Int64Representation repr=Int64Representation::kNumber)
Definition api.cc:11858
constexpr CFunction()
const void * GetAddress() const
const CFunctionInfo * GetTypeInfo() const
const void * address_
const CFunctionInfo * type_info_
static constexpr Type kCallbackOptionsType
constexpr Identifier GetId() const
virtual ~CodeEventHandler()
Definition api.cc:11566
CodeEventType GetCodeType()
Definition api.cc:11535
uintptr_t GetCodeStartAddress()
Definition api.cc:11509
Local< String > GetFunctionName()
Definition api.cc:11517
static const char * GetCodeEventTypeName(CodeEventType code_event_type)
Definition api.cc:11547
uintptr_t GetPreviousCodeStartAddress()
Definition api.cc:11543
const char * GetComment()
Definition api.cc:11539
Local< String > GetScriptName()
Definition api.cc:11522
size_t GetCodeSize()
Definition api.cc:11513
int GetScriptColumn()
Definition api.cc:11531
int GetScriptLine()
Definition api.cc:11527
std::vector< int > GetCompileHints(Isolate *isolate) const
Definition api.cc:2013
const std::shared_ptr< internal::wasm::NativeModule > native_module_
Definition v8-wasm.h:65
OwnedBuffer Serialize()
Definition api.cc:8815
CompiledWasmModule(std::shared_ptr< internal::wasm::NativeModule >, const char *source_url, size_t url_length)
Definition api.cc:8807
MemorySpan< const uint8_t > GetWireBytesRef()
Definition api.cc:8829
const std::string & source_url() const
Definition v8-wasm.h:56
ContainsOnlyOneByteHelper & operator=(const ContainsOnlyOneByteHelper &)=delete
void VisitOneByteString(const uint8_t *chars, int length)
Definition api.cc:5658
ContainsOnlyOneByteHelper(const ContainsOnlyOneByteHelper &)=delete
void VisitTwoByteString(const uint16_t *chars, int length)
Definition api.cc:5661
bool CheckCons(i::Tagged< i::ConsString > cons_string)
Definition api.cc:5694
bool Check(i::Tagged< i::String > string)
Definition api.cc:5652
BackupIncumbentScope(Local< Context > backup_incumbent_context)
Definition api.cc:842
const BackupIncumbentScope * prev_
Definition v8-context.h:417
Local< Context > backup_incumbent_context_
Definition v8-context.h:415
static Local< Context > New(Isolate *isolate, ExtensionConfiguration *extensions=nullptr, MaybeLocal< ObjectTemplate > global_template=MaybeLocal< ObjectTemplate >(), MaybeLocal< Value > global_object=MaybeLocal< Value >(), DeserializeInternalFieldsCallback internal_fields_deserializer=DeserializeInternalFieldsCallback(), MicrotaskQueue *microtask_queue=nullptr, DeserializeContextDataCallback context_data_deserializer=DeserializeContextDataCallback(), DeserializeAPIWrapperCallback api_wrapper_deserializer=DeserializeAPIWrapperCallback())
Definition api.cc:6778
void SetErrorMessageForWasmCodeGeneration(Local< String > message)
Definition api.cc:7255
void SetEmbedderData(int index, Local< Value > value)
Definition api.cc:916
void SetPromiseHooks(Local< Function > init_hook, Local< Function > before_hook, Local< Function > after_hook, Local< Function > resolve_hook)
Definition api.cc:7274
void SetSecurityToken(Local< Value > token)
Definition api.cc:6845
MicrotaskQueue * GetMicrotaskQueue()
Definition api.cc:7181
void Exit()
Definition api.cc:829
static void CheckCast(Data *obj)
Definition api.cc:3945
bool IsCodeGenerationFromStringsAllowed() const
Definition api.cc:7243
V8_INLINE void * GetAlignedPointerFromEmbedderData(Isolate *isolate, int index)
Definition v8-context.h:462
void SetAlignedPointerInEmbedderData(int index, void *value)
Definition api.cc:941
void * SlowGetAlignedPointerFromEmbedderData(int index)
Definition api.cc:927
void(*)(Isolate *isolate, Local< Context > context) AbortScriptExecutionCallback
Definition v8-context.h:363
Local< Value > SlowGetEmbedderData(int index)
Definition api.cc:906
void Enter()
Definition api.cc:818
void SetAbortScriptExecution(AbortScriptExecutionCallback callback)
Definition api.cc:7261
Maybe< void > DeepFreeze(DeepFreezeDelegate *delegate=nullptr)
Definition api.cc:7159
bool HasTemplateLiteralObject(Local< Value > object)
Definition api.cc:7319
void AllowCodeGenerationFromStrings(bool allow)
Definition api.cc:7235
Local< Value > GetSecurityToken()
Definition api.cc:6856
void DetachGlobal()
Definition api.cc:7221
void SetErrorMessageForCodeGenerationFromStrings(Local< String > message)
Definition api.cc:7249
Isolate * GetIsolate()
Definition api.cc:7176
V8_INLINE MaybeLocal< T > GetDataFromSnapshotOnce(size_t index)
uint32_t GetNumberOfEmbedderDataFields()
Definition api.cc:895
V8_INLINE Local< Value > GetEmbedderData(int index)
Definition v8-context.h:438
void SetMicrotaskQueue(MicrotaskQueue *queue)
Definition api.cc:7188
Local< Object > GetExtrasBindingObject()
Definition api.cc:7228
Local< Object > Global()
Definition api.cc:7208
void UseDefaultSecurityToken()
Definition api.cc:6851
static MaybeLocal< Object > NewRemoteContext(Isolate *isolate, Local< ObjectTemplate > global_template, MaybeLocal< Value > global_object=MaybeLocal< Value >())
Definition api.cc:6816
static MaybeLocal< Context > FromSnapshot(Isolate *isolate, size_t context_snapshot_index, DeserializeInternalFieldsCallback internal_fields_deserializer=DeserializeInternalFieldsCallback(), ExtensionConfiguration *extensions=nullptr, MaybeLocal< Value > global_object=MaybeLocal< Value >(), MicrotaskQueue *microtask_queue=nullptr, DeserializeContextDataCallback context_data_deserializer=DeserializeContextDataCallback(), DeserializeAPIWrapperCallback api_wrapper_deserializer=DeserializeAPIWrapperCallback())
Definition api.cc:6794
static std::unique_ptr< CppHeap > Create(v8::Platform *platform, const CppHeapCreateParams &params)
Definition cpp-heap.cc:103
const CpuProfileNode * GetChild(int index) const
Definition api.cc:11303
bool GetLineTicks(LineTick *entries, unsigned int length) const
Definition api.cc:11275
const CpuProfileNode * GetParent() const
Definition api.cc:11309
unsigned GetHitCount() const
Definition api.cc:11286
unsigned int GetHitLineCount() const
Definition api.cc:11270
int GetLineNumber() const
Definition api.cc:11260
unsigned GetNodeId() const
Definition api.cc:11290
const char * GetScriptResourceNameStr() const
Definition api.cc:11250
const char * GetFunctionNameStr() const
Definition api.cc:11232
static const int kNoColumnNumberInfo
const std::vector< CpuProfileDeoptInfo > & GetDeoptInfos() const
Definition api.cc:11315
int GetColumnNumber() const
Definition api.cc:11264
Local< String > GetFunctionName() const
Definition api.cc:11223
Local< String > GetScriptResourceName() const
Definition api.cc:11243
static const int kNoLineNumberInfo
const char * GetBailoutReason() const
Definition api.cc:11281
int GetScriptId() const
Definition api.cc:11237
SourceType GetSourceType() const
Definition api.cc:11294
bool IsScriptSharedCrossOrigin() const
Definition api.cc:11255
int GetChildrenCount() const
Definition api.cc:11298
const CpuProfileNode * GetTopDownRoot() const
Definition api.cc:11334
int GetSamplesCount() const
Definition api.cc:11387
StateTag GetSampleState(int index) const
Definition api.cc:11352
Local< String > GetTitle() const
Definition api.cc:11327
int64_t GetEndTime() const
Definition api.cc:11367
void Delete()
Definition api.cc:11320
const CpuProfileNode * GetSample(int index) const
Definition api.cc:11339
int64_t GetSampleTimestamp(int index) const
Definition api.cc:11347
int64_t GetStartTime() const
Definition api.cc:11362
EmbedderStateTag GetSampleEmbedderState(int index) const
Definition api.cc:11357
void Serialize(OutputStream *stream, SerializationFormat format=kJSON) const
Definition api.cc:11377
CpuProfilingResult Start(CpuProfilingOptions options, std::unique_ptr< DiscardedSamplesDelegate > delegate=nullptr)
Definition api.cc:11442
CpuProfilingStatus StartProfiling(Local< String > title, CpuProfilingOptions options, std::unique_ptr< DiscardedSamplesDelegate > delegate=nullptr)
Definition api.cc:11475
void SetUsePreciseSampling(bool)
Definition api.cc:11437
static CpuProfiler * New(Isolate *isolate, CpuProfilingNamingMode=kDebugNaming, CpuProfilingLoggingMode=kLazyLogging)
Definition api.cc:11391
static void CollectSample(Isolate *isolate, const std::optional< uint64_t > trace_id=std::nullopt)
Definition api.cc:11425
CpuProfile * StopProfiling(Local< String > title)
Definition api.cc:11493
void Dispose()
Definition api.cc:11420
void SetSamplingInterval(int us)
Definition api.cc:11431
static void UseDetailedSourcePositionsForProfiling(Isolate *isolate)
Definition api.cc:11504
CpuProfile * Stop(ProfilerId id)
Definition api.cc:11499
Global< Context > filter_context_
void * raw_filter_context() const
Definition api.cc:11413
static const unsigned kNoSampleLimit
CpuProfilingOptions(CpuProfilingMode mode=kLeafNodeLineNumbers, unsigned max_samples=kNoSampleLimit, int sampling_interval_us=0, MaybeLocal< Context > filter_context=MaybeLocal< Context >())
Definition api.cc:11398
static void CheckCast(Value *obj)
Definition api.cc:4102
static Local< DataView > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
Definition api.cc:9358
bool IsPrivate() const
Definition api.cc:802
bool IsModuleRequest() const
Definition api.cc:782
bool IsModule() const
Definition api.cc:778
bool IsContext() const
Definition api.cc:814
bool IsValue() const
Definition api.cc:790
Data()=delete
bool IsFunctionTemplate() const
Definition api.cc:810
bool IsFixedArray() const
Definition api.cc:786
bool IsObjectTemplate() const
Definition api.cc:806
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > New(Local< Context > context, double time)
Definition api.cc:7967
v8::Local< v8::String > ToISOString() const
Definition api.cc:8003
v8::Local< v8::String > ToUTCString() const
Definition api.cc:8017
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > Parse(Local< Context > context, Local< String > date_string)
Definition api.cc:7982
double ValueOf() const
Definition api.cc:7997
static void CheckCast(Value *obj)
Definition api.cc:4115
static void CheckCast(Data *that)
Definition api.cc:7392
static Local< DictionaryTemplate > New(Isolate *isolate, MemorySpan< const std::string_view > names)
Definition api.cc:1710
V8_WARN_UNUSED_RESULT Local< Object > NewInstance(Local< Context > context, MemorySpan< MaybeLocal< Value > > property_values)
Definition api.cc:1718
virtual Node * V8Node(const v8::Local< v8::Value > &value)=0
EmbedderStateScope(Isolate *isolate, Local< v8::Context > context, EmbedderStateTag tag)
Definition api.cc:11833
internal::Address * EscapeSlot(internal::Address *escape_value)
Definition api.cc:753
EscapableHandleScopeBase(Isolate *isolate)
Definition api.cc:746
internal::Address * escape_slot_
static Local< Message > CreateMessage(Isolate *isolate, Local< Value > exception)
Definition api.cc:11142
static Maybe< bool > CaptureStackTrace(Local< Context > context, Local< Object > object)
Definition api.cc:11162
static Local< StackTrace > GetStackTrace(Local< Value > exception)
Definition api.cc:11152
static Local< Value > Error(Local< String > message, Local< Value > options={})
String::ExternalOneByteStringResource * source_
size_t source_length_
Extension(const char *name, const char *source=nullptr, int dep_count=0, const char **deps=nullptr, int source_length=-1)
Definition api.cc:490
void Decrease(Isolate *isolate, size_t size)
Definition api.cc:12391
void Update(Isolate *isolate, int64_t delta)
Definition api.cc:12381
static int64_t GetTotalAmountOfExternalAllocatedMemoryForTesting(const Isolate *isolate)
Definition api.cc:12406
ExternalMemoryAccounter & operator=(ExternalMemoryAccounter &&)
Definition api.cc:12357
void Increase(Isolate *isolate, size_t size)
Definition api.cc:12371
void * Value() const
Definition api.cc:7498
static Local< External > New(Isolate *isolate, void *value)
Definition api.cc:7483
static void CheckCast(v8::Value *obj)
Definition api.cc:3848
int Length() const
Definition api.cc:2080
static void CheckCast(Data *obj)
Definition api.cc:3894
Local< Data > Get(Local< Context > context, int i) const
Definition api.cc:2084
static constexpr size_t kMaxLength
static void CheckCast(Value *obj)
Definition api.cc:4092
static Local< Float16Array > New(Local< ArrayBuffer > array_buffer, size_t byte_offset, size_t length)
Definition api.cc:9318
void SetExceptionContext(ExceptionContext context)
Definition api.cc:1342
Local< ObjectTemplate > PrototypeTemplate()
Definition api.cc:1014
V8_WARN_UNUSED_RESULT MaybeLocal< Function > GetFunction(Local< Context > context)
Definition api.cc:7411
void SetCallHandler(FunctionCallback callback, Local< Value > data=Local< Value >(), SideEffectType side_effect_type=SideEffectType::kHasSideEffect, const MemorySpan< const CFunction > &c_function_overloads={})
Definition api.cc:1216
static Local< FunctionTemplate > NewWithCache(Isolate *isolate, FunctionCallback callback, Local< Private > cache_property, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
Definition api.cc:1191
static Local< FunctionTemplate > New(Isolate *isolate, FunctionCallback callback=nullptr, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect, const CFunction *c_function=nullptr, uint16_t instance_type=0, uint16_t allowed_receiver_instance_type_range_start=0, uint16_t allowed_receiver_instance_type_range_end=0)
Definition api.cc:1101
void SetClassName(Local< String > name)
Definition api.cc:1326
void RemovePrototype()
Definition api.cc:1366
void SetLength(int length)
Definition api.cc:1318
void SetAcceptAnyReceiver(bool value)
Definition api.cc:1350
static Local< FunctionTemplate > NewWithCFunctionOverloads(Isolate *isolate, FunctionCallback callback=nullptr, Local< Value > data=Local< Value >(), Local< Signature > signature=Local< Signature >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect, const MemorySpan< const CFunction > &c_function_overloads={})
Definition api.cc:1158
void SealAndPrepareForPromotionToReadOnly()
Definition api.cc:7476
bool HasInstance(Local< Value > object)
Definition api.cc:7449
void ReadOnlyPrototype()
Definition api.cc:1358
bool IsLeafTemplateForApiObject(v8::Local< v8::Value > value) const
Definition api.cc:7468
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewRemoteInstance()
Definition api.cc:7423
static void CheckCast(Data *that)
Definition api.cc:7399
void SetPrototypeProviderTemplate(Local< FunctionTemplate > prototype_provider)
Definition api.cc:1032
void Inherit(Local< FunctionTemplate > parent)
Definition api.cc:1089
void SetInterfaceName(Local< String > name)
Definition api.cc:1334
Local< ObjectTemplate > InstanceTemplate()
Definition api.cc:1297
Local< Value > GetName() const
Definition api.cc:5436
V8_WARN_UNUSED_RESULT bool Experimental_IsNopFunction() const
Definition api.cc:5571
static MaybeLocal< Function > New(Local< Context > context, FunctionCallback callback, Local< Value > data=Local< Value >(), int length=0, ConstructorBehavior behavior=ConstructorBehavior::kAllow, SideEffectType side_effect_type=SideEffectType::kHasSideEffect)
Definition api.cc:5348
Local< Value > GetInferredName() const
Definition api.cc:5454
int ScriptId() const
Definition api.cc:5551
V8_WARN_UNUSED_RESULT MaybeLocal< String > FunctionProtoToString(Local< Context > context)
Definition api.cc:5600
int GetScriptLineNumber() const
Definition api.cc:5492
ScriptOrigin GetScriptOrigin() const
Definition api.cc:5477
int GetScriptColumnNumber() const
Definition api.cc:5507
static void CheckCast(Value *obj)
Definition api.cc:3859
void SetName(Local< String > name)
Definition api.cc:5428
Local< Value > GetBoundFunction() const
Definition api.cc:5560
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Call(v8::Isolate *isolate, Local< Context > context, Local< Value > recv, int argc, Local< Value > argv[])
Definition api.cc:5400
Location GetScriptLocation() const
Definition api.cc:5522
static const int kLineOffsetNotFound
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstance(Local< Context > context, int argc, Local< Value > argv[]) const
Definition api.cc:5361
Local< Value > GetDebugName() const
Definition api.cc:5466
int GetScriptStartPosition() const
Definition api.cc:5538
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstanceWithSideEffectType(Local< Context > context, int argc, Local< Value > argv[], SideEffectType side_effect_type=SideEffectType::kHasSideEffect) const
Definition api.cc:5367
V8_INLINE Isolate * GetIsolate() const
internal::Address * prev_next_
void Initialize(Isolate *isolate)
Definition api.cc:694
internal::Isolate * i_isolate_
static int NumberOfHandles(Isolate *isolate)
Definition api.cc:728
V8_INLINE HandleScope()=default
internal::Address * prev_limit_
static internal::Address * CreateHandleForCurrentIsolate(internal::Address value)
static internal::Address * CreateHandle(internal::Isolate *i_isolate, internal::Address value)
const HeapGraphNode * GetToNode() const
Definition api.cc:11614
const HeapGraphNode * GetFromNode() const
Definition api.cc:11609
Type GetType() const
Definition api.cc:11585
Local< Value > GetName() const
Definition api.cc:11589
Local< String > GetName() const
Definition api.cc:11628
SnapshotObjectId GetId() const
Definition api.cc:11634
Type GetType() const
Definition api.cc:11624
const HeapGraphEdge * GetChild(int index) const
Definition api.cc:11644
size_t GetShallowSize() const
Definition api.cc:11636
int GetChildrenCount() const
Definition api.cc:11640
void StartTrackingHeapObjects(bool track_allocations=false)
Definition api.cc:11766
void SetGetDetachednessCallback(GetDetachednessCallback callback, void *data)
Definition api.cc:11818
EmbedderGraph::Node::Detachedness(*)( v8::Isolate *isolate, const v8::Local< v8::Value > &v8_value, uint16_t class_id, void *data) GetDetachednessCallback
int GetSnapshotCount()
Definition api.cc:11700
bool IsTakingSnapshot()
Definition api.cc:11824
Local< Value > FindObjectById(SnapshotObjectId id)
Definition api.cc:11729
AllocationProfile * GetAllocationProfile()
Definition api.cc:11792
void RemoveBuildEmbedderGraphCallback(BuildEmbedderGraphCallback callback, void *data)
Definition api.cc:11812
static const SnapshotObjectId kUnknownObjectId
void AddBuildEmbedderGraphCallback(BuildEmbedderGraphCallback callback, void *data)
Definition api.cc:11806
std::vector< v8::Local< v8::Value > > GetDetachedJSWrapperObjects()
Definition api.cc:11761
void DeleteAllHeapSnapshots()
Definition api.cc:11796
bool StartSamplingHeapProfiler(uint64_t sample_interval=512 *1024, int stack_depth=16, SamplingFlags flags=kSamplingNoFlags)
Definition api.cc:11781
const char * CopyNameForHeapSnapshot(const char *name)
Definition api.cc:11828
void ClearObjectIds()
Definition api.cc:11736
void QueryObjects(v8::Local< v8::Context > context, QueryObjectPredicate *predicate, std::vector< v8::Global< v8::Object > > *objects)
Definition api.cc:11704
SnapshotObjectId GetObjectId(Local< Value > value)
Definition api.cc:11720
void StopSamplingHeapProfiler()
Definition api.cc:11788
const HeapSnapshot * TakeHeapSnapshot(const HeapSnapshotOptions &options=HeapSnapshotOptions())
Definition api.cc:11740
const HeapSnapshot * GetHeapSnapshot(int index)
Definition api.cc:11715
SnapshotObjectId GetHeapStats(OutputStream *stream, int64_t *timestamp_us=nullptr)
Definition api.cc:11775
void StopTrackingHeapObjects()
Definition api.cc:11771
const HeapGraphNode * GetNodeById(SnapshotObjectId id) const
Definition api.cc:11668
int GetNodesCount() const
Definition api.cc:11673
const HeapGraphNode * GetRoot() const
Definition api.cc:11664
SnapshotObjectId GetMaxSnapshotJSObjectId() const
Definition api.cc:11682
const HeapGraphNode * GetNode(int index) const
Definition api.cc:11677
void Serialize(OutputStream *stream, SerializationFormat format=kJSON) const
Definition api.cc:11686
void Delete()
Definition api.cc:11653
size_t total_heap_size_executable_
size_t number_of_detached_contexts_
size_t total_global_handles_size_
size_t used_global_handles_size_
size_t number_of_native_contexts_
int32_t Value() const
Definition api.cc:6258
static void CheckCast(v8::Data *that)
Definition api.cc:3930
static void CheckCast(v8::Data *that)
Definition api.cc:3924
static Local< Integer > New(Isolate *isolate, int32_t value)
Definition api.cc:9568
int64_t Value() const
Definition api.cc:6249
static Local< Integer > NewFromUnsigned(Isolate *isolate, uint32_t value)
Definition api.cc:9579
V8_INLINE Local< T > Escape(Local< T > value)
Definition api-inl.h:246
internal::IsolateGroup * isolate_group_
Definition v8-isolate.h:263
static bool CanCreateNewGroups()
Definition api.cc:9703
static IsolateGroup Create()
Definition api.cc:9708
static IsolateGroup GetDefault()
Definition api.cc:9698
IsolateGroup(IsolateGroup &&other)
Definition api.cc:9712
IsolateGroup & operator=(IsolateGroup &&other)
Definition api.cc:9717
AllowJavascriptExecutionScope(Isolate *isolate)
Definition api.cc:10206
DisallowJavascriptExecutionScope(Isolate *isolate, OnFailure on_failure)
Definition api.cc:10173
SuppressMicrotaskExecutionScope(Isolate *isolate, MicrotaskQueue *microtask_queue=nullptr)
Definition api.cc:10224
internal::MicrotaskQueue *const microtask_queue_
Definition v8-isolate.h:445
void RemoveMessageListeners(MessageCallback that)
Definition api.cc:10857
int GetStackTraceLimit()
Definition api.cc:10164
void RemoveGCEpilogueCallback(GCCallback callback)
Definition api.cc:9861
void SetCaptureStackTraceForUncaughtExceptions(bool capture, int frame_limit=10, StackTrace::StackTraceOptions options=StackTrace::kOverview)
Definition api.cc:10883
bool GetHeapCodeAndMetadataStatistics(HeapCodeStatistics *object_statistics)
Definition api.cc:10392
HeapProfiler * GetHeapProfiler()
Definition api.cc:9730
void SetFatalErrorHandler(FatalErrorCallback that)
bool MeasureMemory(std::unique_ptr< MeasureMemoryDelegate > delegate, MeasureMemoryExecution execution=MeasureMemoryExecution::kDefault)
Definition api.cc:10411
void IsolateInBackgroundNotification()
Definition api.cc:10617
size_t NumberOfTrackedHeapObjectTypes()
Definition api.cc:10359
void Dispose()
Definition api.cc:10100
void LocaleConfigurationChangeNotification()
Definition api.cc:10917
bool AddMessageListener(MessageCallback that, Local< Value > data=Local< Value >())
Definition api.cc:10830
void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback)
Definition api.cc:10449
static Isolate * Allocate()
Definition api.cc:9964
void RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback, void *data=nullptr)
Definition api.cc:10531
void(*)(std::unique_ptr< CppHeap >) ReleaseCppHeapCallback
bool GetHeapSpaceStatistics(HeapSpaceStatistics *space_statistics, size_t index)
Definition api.cc:10327
void SetEventLogger(LogEventCallback that)
Definition api.cc:10444
void SetExceptionPropagationCallback(ExceptionPropagationCallback callback)
Definition api.cc:10483
void RemoveNearHeapLimitCallback(NearHeapLimitCallback callback, size_t heap_limit)
Definition api.cc:10812
void ClearKeptObjects()
Definition api.cc:9751
V8_INLINE MaybeLocal< T > GetDataFromSnapshotOnce(size_t index)
CppHeap * GetCppHeap() const
Definition api.cc:9871
size_t(*)() GetExternallyAllocatedMemoryInBytesCallback
void SetAddCrashKeyCallback(AddCrashKeyCallback)
Definition api.cc:10566
void GetCodeRange(void **start, size_t *length_in_bytes)
Definition api.cc:10688
void RemoveCallCompletedCallback(CallCompletedCallback callback)
Definition api.cc:10467
size_t CopyCodePages(size_t capacity, MemoryRange *code_pages_out)
Definition api.cc:10722
int ContextDisposedNotification(bool dependant_context=true)
Definition api.cc:10582
bool HasPendingException()
Definition api.cc:9807
void RequestGarbageCollectionForTesting(GarbageCollectionType type)
Definition api.cc:9918
void SetMemorySaverMode(bool memory_saver_mode_enabled)
Definition api.cc:10641
@ kFullGarbageCollection
Definition v8-isolate.h:456
@ kMinorGarbageCollection
Definition v8-isolate.h:457
bool IsDead()
Definition api.cc:10825
void DumpAndResetStats()
Definition api.cc:10109
void SetHostImportModuleDynamicallyCallback(HostImportModuleDynamicallyCallback callback)
Definition api.cc:10135
void Exit()
Definition api.cc:10124
bool GetHeapObjectStatisticsAtLastGC(HeapObjectStatistics *object_statistics, size_t type_index)
Definition api.cc:10365
void HandleExternalMemoryInterrupt()
Definition api.cc:9663
void SetMicrotasksPolicy(MicrotasksPolicy policy)
Definition api.cc:10512
Local< Context > GetIncumbentContext()
Definition api.cc:9773
bool AddMessageListenerWithErrorLevel(MessageCallback that, int message_levels, Local< Value > data=Local< Value >())
Definition api.cc:10834
void SetPromiseRejectCallback(PromiseRejectCallback callback)
Definition api.cc:10477
void SetPromiseHook(PromiseHook hook)
Definition api.cc:10472
void GetEmbeddedCodeRange(const void **start, size_t *length_in_bytes)
Definition api.cc:10695
void SetJitCodeEventHandler(JitCodeEventOptions options, JitCodeEventHandler event_handler)
Definition api.cc:10673
void IncreaseHeapLimitForDebugging()
Definition api.cc:10663
void CancelTerminateExecution()
Definition api.cc:9898
void InstallConditionalFeatures(Local< Context > context)
Definition api.cc:10793
void SetOOMErrorHandler(OOMErrorCallback that)
void SetHostCreateShadowRealmContextCallback(HostCreateShadowRealmContextCallback callback)
Definition api.cc:10153
bool IsCurrent() const
Definition api.cc:9959
void EnqueueMicrotask(Local< Function > microtask)
Definition api.cc:10496
void SetIsLoading(bool is_loading)
Definition api.cc:10653
void AddGCPrologueCallback(GCCallback callback, GCType gc_type_filter=kGCTypeAll)
Definition api.cc:9846
void RemoveGCPrologueCallback(GCCallback callback)
Definition api.cc:9851
void SetPriority(Priority priority)
Definition api.cc:10622
void SetBatterySaverMode(bool battery_saver_mode_enabled)
Definition api.cc:10636
void DateTimeConfigurationChangeNotification(TimeZoneDetection time_zone_detection=TimeZoneDetection::kSkip)
Definition api.cc:10900
bool IsHeapLimitIncreasedForDebugging()
Definition api.cc:10671
void AddCallCompletedCallback(CallCompletedCallback callback)
Definition api.cc:10461
void GetStackSample(const RegisterState &state, void **frames, size_t frames_limit, SampleInfo *sample_info)
Definition api.cc:10425
void SetEmbedderRootsHandler(EmbedderRootsHandler *handler)
Definition api.cc:9866
void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback)
Definition api.cc:10455
bool IsInUse()
Definition api.cc:10890
void RequestInterrupt(InterruptCallback callback, void *data)
Definition api.cc:9904
uint64_t GetHashSeed()
Definition api.cc:10938
void SetIdle(bool is_idle)
Definition api.cc:9736
std::string GetDefaultLocale()
Definition api.cc:10927
void PerformMicrotaskCheckpoint()
Definition api.cc:10490
int64_t AdjustAmountOfExternalAllocatedMemoryImpl(int64_t change_in_bytes)
Definition api.cc:9640
void SetAllowAtomicsWait(bool allow)
Definition api.cc:10895
static Isolate * TryGetCurrent()
Definition api.cc:9954
Local< Value > ThrowError(const char(&message)[N])
void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback)
Definition api.cc:10159
int64_t AdjustAmountOfExternalAllocatedMemory(int64_t change_in_bytes)
Definition api.cc:10439
void LowMemoryNotification()
Definition api.cc:10571
Local< Context > GetEnteredOrMicrotaskContext()
Definition api.cc:9765
void SetCounterFunction(CounterLookupCallback)
Definition api.cc:10542
MicrotasksPolicy GetMicrotasksPolicy() const
Definition api.cc:10517
void SetFailedAccessCheckCallbackFunction(FailedAccessCheckCallback)
Definition api.cc:10877
static Isolate * New(const CreateParams &params)
Definition api.cc:10089
void RestoreOriginalHeapLimit()
Definition api.cc:10667
void(*)(Isolate *isolate, GCType type, GCCallbackFlags flags, void *data) GCCallbackWithData
void AddGCEpilogueCallback(GCCallback callback, GCType gc_type_filter=kGCTypeAll)
Definition api.cc:9856
bool HasPendingBackgroundTasks()
Definition api.cc:9909
void DiscardThreadSpecificMetadata()
Definition api.cc:10114
bool(*)(Isolate *) AbortOnUncaughtExceptionCallback
Definition v8-isolate.h:756
void AddMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback, void *data=nullptr)
Definition api.cc:10523
void TerminateExecution()
Definition api.cc:9888
static void Initialize(Isolate *isolate, const CreateParams &params)
Definition api.cc:9985
void AutomaticallyRestoreInitialHeapLimit(double threshold_percent=0.5)
Definition api.cc:10818
Local< Value > ThrowException(Local< Value > exception)
Definition api.cc:9793
void SetHostInitializeImportMetaObjectCallback(HostInitializeImportMetaObjectCallback callback)
Definition api.cc:10147
void SetUseCounterCallback(UseCounterCallback callback)
Definition api.cc:10538
Local< Value > GetContinuationPreservedEmbedderData()
Definition api.cc:10246
size_t NumberOfHeapSpaces()
Definition api.cc:10323
void GetHeapStatistics(HeapStatistics *heap_statistics)
Definition api.cc:10267
void SetStackLimit(uintptr_t stack_limit)
Definition api.cc:10681
void SetContinuationPreservedEmbedderData(Local< Value > data)
Definition api.cc:10257
void(*)(Isolate *isolate, GCType type, GCCallbackFlags flags) GCCallback
void SetMetricsRecorder(const std::shared_ptr< metrics::Recorder > &metrics_recorder)
Definition api.cc:10559
void MemoryPressureNotification(MemoryPressureLevel level)
Definition api.cc:10627
void SetAddHistogramSampleFunction(AddHistogramSampleCallback)
Definition api.cc:10552
void AddNearHeapLimitCallback(NearHeapLimitCallback callback, void *data)
Definition api.cc:10806
IsolateGroup GetGroup() const
Definition api.cc:9974
void SetGetExternallyAllocatedMemoryInBytesCallback(GetExternallyAllocatedMemoryInBytesCallback callback)
Definition api.cc:9882
void Enter()
Definition api.cc:10119
JSEntryStubs GetJSEntryStubs()
Definition api.cc:10703
bool IsExecutionTerminating()
Definition api.cc:9893
ArrayBuffer::Allocator * GetArrayBufferAllocator()
Definition api.cc:9741
Local< Context > GetCurrentContext()
Definition api.cc:9756
void SetReleaseCppHeapCallbackForTesting(ReleaseCppHeapCallback callback)
Definition api.cc:9876
void IsolateInForegroundNotification()
Definition api.cc:10612
bool InContext()
Definition api.cc:9746
void SetAbortOnUncaughtExceptionCallback(AbortOnUncaughtExceptionCallback callback)
Definition api.cc:10129
void ClearCachesForTesting()
Definition api.cc:10646
void SetHostImportModuleWithPhaseDynamicallyCallback(HostImportModuleWithPhaseDynamicallyCallback callback)
Definition api.cc:10141
void(*)(Isolate *isolate, UseCounterFeature feature) UseCounterCallback
Definition v8-isolate.h:669
void SetCreateHistogramFunction(CreateHistogramCallback)
Definition api.cc:10547
static Isolate * GetCurrent()
Definition api.cc:9949
void Freeze(bool is_frozen)
Definition api.cc:10658
MaybeLocal< Data > GetCurrentHostDefinedOptions()
Definition api.cc:9779
static V8_WARN_UNUSED_RESULT MaybeLocal< String > Stringify(Local< Context > context, Local< Value > json_object, Local< String > gap=Local< String >())
Definition api.cc:3188
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > Parse(Local< Context > context, Local< String > json_string)
Definition api.cc:3172
static V8_INLINE Local< T > Cast(Local< S > that)
void Clear()
Definition api.cc:8419
Local< Array > AsArray() const
Definition api.cc:8529
static void CheckCast(Value *obj)
Definition api.cc:3957
static V8_INLINE Map * Cast(Value *value)
static Local< Map > New(Isolate *isolate)
Definition api.cc:8406
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, Local< Value > key)
Definition api.cc:8467
size_t Size() const
Definition api.cc:8414
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Get(Local< Context > context, Local< Value > key)
Definition api.cc:8427
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
Definition api.cc:8454
V8_WARN_UNUSED_RESULT MaybeLocal< Map > Set(Local< Context > context, Local< Value > key, Local< Value > value)
Definition api.cc:8440
V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local< S > *out) const
V8_INLINE Local< T > ToLocalChecked()
V8_INLINE bool IsEmpty() const
V8_INLINE T FromJust() const &
Definition v8-maybe.h:64
V8_INLINE bool IsNothing() const
Definition v8-maybe.h:35
static std::unique_ptr< MeasureMemoryDelegate > Default(Isolate *isolate, Local< Context > context, Local< Promise::Resolver > promise_resolver, MeasureMemoryMode mode)
Definition api.cc:10417
constexpr T * data() const
constexpr bool empty() const
constexpr size_t size() const
Local< StackTrace > GetStackTrace() const
Definition api.cc:2906
ScriptOrigin GetScriptOrigin() const
Definition api.cc:2879
int GetStartColumn() const
Definition api.cc:2950
V8_WARN_UNUSED_RESULT MaybeLocal< String > GetSourceLine(Local< Context > context) const
Definition api.cc:3027
Local< String > Get() const
Definition api.cc:2864
Isolate * GetIsolate() const
Definition api.cc:2874
bool IsSharedCrossOrigin() const
Definition api.cc:3004
int GetWasmFunctionIndex() const
Definition api.cc:2959
static void PrintCurrentStackTrace(Isolate *isolate, std::ostream &out, PrintCurrentStackTraceFilterCallback should_include_frame_callback=nullptr)
Definition api.cc:3036
int GetStartPosition() const
Definition api.cc:2926
int ErrorLevel() const
Definition api.cc:2944
int GetEndPosition() const
Definition api.cc:2935
V8_WARN_UNUSED_RESULT Maybe< int > GetLineNumber(Local< Context > context) const
Definition api.cc:2917
static const int kNoWasmFunctionIndexInfo
Definition v8-message.h:201
Local< Value > GetScriptResourceName() const
Definition api.cc:2901
V8_WARN_UNUSED_RESULT MaybeLocal< String > GetSource(Local< Context > context) const
Definition api.cc:3018
bool IsOpaque() const
Definition api.cc:3011
int GetEndColumn() const
Definition api.cc:2987
static std::unique_ptr< MicrotaskQueue > New(Isolate *isolate, MicrotasksPolicy policy=MicrotasksPolicy::kAuto)
Definition api.cc:10966
static bool IsRunningMicrotasks(Isolate *isolate)
Definition api.cc:11025
MicrotasksScope(Local< Context > context, Type type)
Definition api.cc:10975
static int GetCurrentDepth(Isolate *isolate)
Definition api.cc:11018
static void PerformCheckpoint(Isolate *isolate)
Definition api.cc:11011
internal::MicrotaskQueue *const microtask_queue_
internal::Isolate *const i_isolate_
Local< FixedArray > GetImportAttributes() const
Definition api.cc:2106
Local< String > GetSpecifier() const
Definition api.cc:2091
ModuleImportPhase GetPhase() const
Definition api.cc:2097
static void CheckCast(Data *obj)
Definition api.cc:3900
int GetSourceOffset() const
Definition api.cc:2102
Location SourceOffsetToLocation(int offset) const
Definition api.cc:2159
static void CheckCast(Data *obj)
Definition api.cc:3906
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Evaluate(Local< Context > context)
Definition api.cc:2251
Local< Value > GetModuleNamespace()
Definition api.cc:2174
V8_WARN_UNUSED_RESULT Maybe< bool > SetSyntheticModuleExport(Isolate *isolate, Local< String > export_name, Local< Value > export_value)
Definition api.cc:2291
static Local< Module > CreateSyntheticModule(Isolate *isolate, Local< String > module_name, const MemorySpan< const Local< String > > &export_names, SyntheticModuleEvaluationSteps evaluation_steps)
Definition api.cc:2271
Local< FixedArray > GetModuleRequests() const
Definition api.cc:2144
bool IsGraphAsync() const
Definition api.cc:2211
bool HasTopLevelAwait() const
Definition api.cc:2205
int ScriptId() const
Definition api.cc:2197
bool IsSyntheticModule() const
Definition api.cc:2227
Local< Value > GetException() const
Definition api.cc:2135
std::pair< LocalVector< Module >, LocalVector< Message > > GetStalledTopLevelAwaitMessages(Isolate *isolate)
Definition api.cc:2313
int GetIdentityHash() const
Definition api.cc:2233
Local< UnboundModuleScript > GetUnboundModuleScript()
Definition api.cc:2186
Status GetStatus() const
Definition api.cc:2113
V8_WARN_UNUSED_RESULT Maybe< bool > InstantiateModule(Local< Context > context, ResolveModuleCallback module_callback, ResolveSourceCallback source_callback=nullptr)
Definition api.cc:2239
bool IsSourceTextModule() const
Definition api.cc:2221
static void CheckCast(Data *that)
Definition api.cc:3871
int GetIdentityHash()
Definition api.cc:5612
static void CheckCast(Value *obj)
Definition api.cc:4132
double ValueOf() const
Definition api.cc:7881
static Local< Value > New(Isolate *isolate, double value)
Definition api.cc:7871
static Local< Number > New(Isolate *isolate, double value)
Definition api.cc:9557
static void CheckCast(v8::Data *that)
Definition api.cc:3918
double Value() const
Definition api.cc:6241
static void CheckCast(v8::Data *that)
Definition api.cc:3912
static Local< ObjectTemplate > New(Isolate *isolate, Local< FunctionTemplate > constructor=Local< FunctionTemplate >())
Definition api.cc:1376
void SetCallAsFunctionHandler(FunctionCallback callback, Local< Value > data=Local< Value >())
Definition api.cc:1647
V8_WARN_UNUSED_RESULT MaybeLocal< Object > NewInstance(Local< Context > context)
Definition api.cc:7376
bool IsCodeLike() const
Definition api.cc:1699
void SetCodeLike()
Definition api.cc:1703
int InternalFieldCount() const
Definition api.cc:1667
void SetHandler(const NamedPropertyHandlerConfiguration &configuration)
Definition api.cc:1550
void SetAccessCheckCallback(AccessCheckCallback callback, Local< Value > data=Local< Value >())
Definition api.cc:1567
void MarkAsUndetectable()
Definition api.cc:1558
bool IsImmutableProto() const
Definition api.cc:1688
static void CheckCast(Data *that)
Definition api.cc:7386
void SetInternalFieldCount(int value)
Definition api.cc:1671
void SetAccessCheckCallbackAndHandler(AccessCheckCallback callback, const NamedPropertyHandlerConfiguration &named_handler, const IndexedPropertyHandlerConfiguration &indexed_handler, Local< Value > data=Local< Value >())
Definition api.cc:1593
void SetImmutableProto()
Definition api.cc:1692
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetRealNamedPropertyAttributesInPrototypeChain(Local< Context > context, Local< Name > key)
Definition api.cc:5095
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetPropertyAttributes(Local< Context > context, Local< Value > key)
Definition api.cc:4621
void * SlowGetAlignedPointerFromInternalField(int index)
Definition api.cc:6320
void SetAlignedPointerInInternalField(int index, void *value)
Definition api.cc:6331
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetOwnPropertyDescriptor(Local< Context > context, Local< Name > key)
Definition api.cc:4641
bool HasNamedLookupInterceptor() const
Definition api.cc:5062
Maybe< bool > SetPrivate(Local< Context > context, Local< Private > key, Local< Value > value)
Definition api.cc:4547
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealNamedProperty(Local< Context > context, Local< Name > key)
Definition api.cc:5018
V8_WARN_UNUSED_RESULT MaybeLocal< Array > GetPropertyNames(Local< Context > context)
Definition api.cc:4746
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetRealNamedProperty(Local< Context > context, Local< Name > key)
Definition api.cc:5119
V8_WARN_UNUSED_RESULT Maybe< bool > DefineProperty(Local< Context > context, Local< Name > key, PropertyDescriptor &descriptor)
Definition api.cc:4531
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, Local< Value > key)
Definition api.cc:4828
static Local< Object > New(Isolate *isolate)
Definition api.cc:7756
bool IsConstructor() const
Definition api.cc:5284
bool IsUndetectable() const
Definition api.cc:5296
V8_WARN_UNUSED_RESULT MaybeLocal< Value > CallAsFunction(Local< Context > context, Local< Value > recv, int argc, Local< Value > argv[])
Definition api.cc:5311
V8_WARN_UNUSED_RESULT Maybe< bool > DefineOwnProperty(Local< Context > context, Local< Name > key, Local< Value > value, PropertyAttribute attributes=None)
Definition api.cc:4495
V8_WARN_UNUSED_RESULT Maybe< bool > SetNativeDataProperty(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attributes=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition api.cc:4974
void * GetAlignedPointerFromEmbedderDataInCreationContext(v8::Isolate *isolate, int index)
Definition api.cc:5256
Local< Data > SlowGetInternalField(int index)
Definition api.cc:6290
V8_WARN_UNUSED_RESULT MaybeLocal< Value > GetRealNamedPropertyInPrototypeChain(Local< Context > context, Local< Name > key)
Definition api.cc:5074
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
Definition api.cc:4867
V8_WARN_UNUSED_RESULT MaybeLocal< Array > GetOwnPropertyNames(Local< Context > context)
Definition api.cc:4776
bool IsCodeLike(Isolate *isolate) const
Definition api.cc:10957
V8_WARN_UNUSED_RESULT Maybe< bool > Set(Local< Context > context, Local< Value > key, Local< Value > value)
Definition api.cc:4295
V8_WARN_UNUSED_RESULT MaybeLocal< Value > CallAsConstructor(Local< Context > context, int argc, Local< Value > argv[])
Definition api.cc:5330
Local< Object > Clone()
Definition api.cc:5164
MaybeLocal< Value > GetPrivate(Local< Context > context, Local< Private > key)
Definition api.cc:4616
V8_WARN_UNUSED_RESULT Maybe< bool > SetPrototypeV2(Local< Context > context, Local< Value > prototype)
Definition api.cc:4722
static V8_INLINE void Wrap(v8::Isolate *isolate, const v8::Local< v8::Object > &wrapper, void *wrappable)
void SetAccessorProperty(Local< Name > name, Local< Function > getter, Local< Function > setter=Local< Function >(), PropertyAttribute attributes=None)
Definition api.cc:4945
V8_WARN_UNUSED_RESULT Maybe< bool > CreateDataProperty(Local< Context > context, Local< Name > key, Local< Value > value)
Definition api.cc:4345
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealIndexedProperty(Local< Context > context, uint32_t index)
Definition api.cc:5033
Isolate * GetIsolate()
Definition api.cc:7751
V8_WARN_UNUSED_RESULT MaybeLocal< String > ObjectProtoToString(Local< Context > context)
Definition api.cc:4788
MaybeLocal< Array > PreviewEntries(bool *is_key_value)
Definition api.cc:11182
V8_WARN_UNUSED_RESULT Maybe< bool > SetLazyDataProperty(Local< Context > context, Local< Name > name, AccessorNameGetterCallback getter, Local< Value > data=Local< Value >(), PropertyAttribute attributes=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition api.cc:4985
bool IsApiWrapper() const
Definition api.cc:5288
Maybe< bool > SetIntegrityLevel(Local< Context > context, IntegrityLevel level)
Definition api.cc:4814
int InternalFieldCount() const
Definition api.cc:6276
Local< Value > GetPrototypeV2()
Definition api.cc:4665
V8_WARN_UNUSED_RESULT Maybe< PropertyAttribute > GetRealNamedPropertyAttributes(Local< Context > context, Local< Name > key)
Definition api.cc:5134
static V8_INLINE T * Unwrap(v8::Isolate *isolate, const v8::Local< v8::Object > &wrapper)
Maybe< bool > HasPrivate(Local< Context > context, Local< Private > key)
Definition api.cc:4889
Local< Object > FindInstanceInPrototypeChain(Local< FunctionTemplate > tmpl)
Definition api.cc:4728
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Get(Local< Context > context, Local< Value > key)
Definition api.cc:4577
int GetIdentityHash()
Definition api.cc:5272
Local< Context > GetCreationContextChecked()
Definition api.cc:5214
void SetInternalField(int index, Local< Data > data)
Definition api.cc:6299
MaybeLocal< Context > GetCreationContext()
Definition api.cc:5186
V8_WARN_UNUSED_RESULT Maybe< bool > HasOwnProperty(Local< Context > context, Local< Name > key)
Definition api.cc:4996
bool IsCallable() const
Definition api.cc:5280
Maybe< bool > DeletePrivate(Local< Context > context, Local< Private > key)
Definition api.cc:4852
Local< String > GetConstructorName()
Definition api.cc:4800
static void CheckCast(Value *obj)
Definition api.cc:3853
void SetAlignedPointerInInternalFields(int argc, int indices[], void *values[])
Definition api.cc:6343
V8_WARN_UNUSED_RESULT Maybe< bool > HasRealNamedCallbackProperty(Local< Context > context, Local< Name > key)
Definition api.cc:5047
bool HasIndexedLookupInterceptor() const
Definition api.cc:5068
virtual int GetChunkSize()
Local< Primitive > Get(Isolate *isolate, int index)
Definition api.cc:2061
static Local< PrimitiveArray > New(Isolate *isolate, int length)
Definition api.cc:2035
int Length() const
Definition api.cc:2045
static void CheckCast(Data *obj)
Definition api.cc:2072
void Set(Isolate *isolate, int index, Local< Primitive > item)
Definition api.cc:2049
static void CheckCast(Data *that)
Definition api.cc:3888
static Local< Private > ForApi(Isolate *isolate, Local< String > name)
Definition api.cc:9548
Local< Value > Name() const
Definition api.cc:6232
static Local< Private > New(Isolate *isolate, Local< String > name=Local< String >())
Definition api.cc:9538
static V8_WARN_UNUSED_RESULT MaybeLocal< Resolver > New(Local< Context > context)
Definition api.cc:8640
V8_WARN_UNUSED_RESULT Maybe< bool > Resolve(Local< Context > context, Local< Value > value)
Definition api.cc:8658
Local< Promise > GetPromise()
Definition api.cc:8653
static void CheckCast(Value *obj)
Definition api.cc:3972
V8_WARN_UNUSED_RESULT Maybe< bool > Reject(Local< Context > context, Local< Value > value)
Definition api.cc:8675
bool HasHandler() const
Definition api.cc:8740
PromiseState State()
Definition api.cc:8759
void MarkAsHandled()
Definition api.cc:8766
Local< Value > Result()
Definition api.cc:8749
void MarkAsSilent()
Definition api.cc:8770
V8_WARN_UNUSED_RESULT MaybeLocal< Promise > Catch(Local< Context > context, Local< Function > handler)
Definition api.cc:8692
static void CheckCast(Value *obj)
Definition api.cc:3967
V8_WARN_UNUSED_RESULT MaybeLocal< Promise > Then(Local< Context > context, Local< Function > handler)
Definition api.cc:8710
void set_enumerable(bool enumerable)
Definition api.cc:4469
bool has_writable() const
Definition api.cc:4465
bool has_value() const
Definition api.cc:4450
Local< Value > get() const
Definition api.cc:4440
bool writable() const
Definition api.cc:4460
PrivateData * private_
Definition v8-object.h:133
bool has_enumerable() const
Definition api.cc:4478
PrivateData * get_private() const
Definition v8-object.h:127
bool has_get() const
Definition api.cc:4453
bool enumerable() const
Definition api.cc:4473
Local< Value > value() const
Definition api.cc:4435
void set_configurable(bool configurable)
Definition api.cc:4482
bool has_set() const
Definition api.cc:4456
bool has_configurable() const
Definition api.cc:4491
Local< Value > set() const
Definition api.cc:4445
bool configurable() const
Definition api.cc:4486
static MaybeLocal< Proxy > New(Local< Context > context, Local< Object > local_target, Local< Object > local_handler)
Definition api.cc:8795
void Revoke()
Definition api.cc:8790
static void CheckCast(Value *obj)
Definition api.cc:3977
Local< Value > GetHandler()
Definition api.cc:8780
Local< Value > GetTarget()
Definition api.cc:8774
bool IsRevoked() const
Definition api.cc:8786
V8_WARN_UNUSED_RESULT MaybeLocal< Object > Exec(Local< Context > context, Local< String > subject)
Definition api.cc:8098
Flags GetFlags() const
Definition api.cc:8093
Local< String > GetSource() const
Definition api.cc:8072
static V8_WARN_UNUSED_RESULT MaybeLocal< RegExp > New(Local< Context > context, Local< String > pattern, Flags flags)
Definition api.cc:8041
static V8_WARN_UNUSED_RESULT MaybeLocal< RegExp > NewWithBacktrackLimit(Local< Context > context, Local< String > pattern, Flags flags, uint32_t backtrack_limit)
Definition api.cc:8053
static void CheckCast(Value *obj)
Definition api.cc:4150
Extension * extension() const
Definition api.h:82
static void Register(std::unique_ptr< Extension >)
Definition api.cc:452
static void UnregisterAll()
Definition api.cc:460
RegisteredExtension(Extension *)
RegisteredExtension * next() const
Definition api.h:83
RegisteredExtension * next_
Definition api.h:90
static RegisteredExtension * first_extension_
Definition api.h:91
void set_code_range_size_in_bytes(size_t limit)
Definition v8-isolate.h:115
void set_initial_old_generation_size_in_bytes(size_t initial_size)
Definition v8-isolate.h:146
void ConfigureDefaultsFromHeapSize(size_t initial_heap_size_in_bytes, size_t maximum_heap_size_in_bytes)
Definition api.cc:503
void set_initial_young_generation_size_in_bytes(size_t initial_size)
Definition v8-isolate.h:153
void set_max_young_generation_size_in_bytes(size_t limit)
Definition v8-isolate.h:139
void ConfigureDefaults(uint64_t physical_memory, uint64_t virtual_memory_limit)
Definition api.cc:529
void set_max_old_generation_size_in_bytes(size_t limit)
Definition v8-isolate.h:127
ConsumeCodeCacheTask(std::unique_ptr< internal::BackgroundDeserializeTask > impl)
Definition api.cc:2558
void SourceTextAvailable(Isolate *isolate, Local< String > source_text, const ScriptOrigin &origin)
Definition api.cc:2566
internal::ScriptStreamingData * impl() const
Definition v8-script.h:590
CompilationDetails & compilation_details()
Definition v8-script.h:596
StreamedSource(std::unique_ptr< ExternalSourceStream > source_stream, Encoding encoding)
Definition api.cc:1758
static CachedData * CreateCodeCacheForFunction(Local< Function > function)
Definition api.cc:2703
static CachedData * CreateCodeCache(Local< UnboundScript > unbound_script)
Definition api.cc:2673
static V8_WARN_UNUSED_RESULT MaybeLocal< Module > CompileModule(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition api.cc:2454
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition api.cc:2438
static bool CompileOptionsIsValid(CompileOptions compile_options)
Definition v8-script.h:683
static V8_WARN_UNUSED_RESULT MaybeLocal< Function > CompileFunction(Local< Context > context, Source *source, size_t arguments_count=0, Local< String > arguments[]=nullptr, size_t context_extension_count=0, Local< Object > context_extensions[]=nullptr, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition api.cc:2473
static V8_WARN_UNUSED_RESULT MaybeLocal< UnboundScript > CompileUnboundScript(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
Definition api.cc:2428
static ConsumeCodeCacheTask * StartConsumingCodeCache(Isolate *isolate, std::unique_ptr< CachedData > source)
Definition api.cc:2594
static ConsumeCodeCacheTask * StartConsumingCodeCacheOnBackground(Isolate *isolate, std::unique_ptr< CachedData > source)
Definition api.cc:2605
static V8_WARN_UNUSED_RESULT MaybeLocal< UnboundScript > CompileUnboundInternal(Isolate *isolate, Source *source, CompileOptions options, NoCacheReason no_cache_reason)
Definition api.cc:2366
static uint32_t CachedDataVersionTag()
Definition api.cc:2668
static ScriptStreamingTask * StartStreaming(Isolate *isolate, StreamedSource *source, ScriptType type=ScriptType::kClassic, CompileOptions options=kNoCompileOptions, CompileHintCallback compile_hint_callback=nullptr, void *compile_hint_callback_data=nullptr)
Definition api.cc:2540
Local< Value > GetResourceName()
Definition api.cc:1946
Local< Data > HostDefinedOptions()
Definition api.cc:1953
V8_INLINE int LineOffset() const
Definition v8-message.h:210
void VerifyHostDefinedOptions() const
Definition api.cc:2887
V8_INLINE int ColumnOffset() const
Definition v8-message.h:212
V8_INLINE ScriptOriginOptions Options() const
Definition v8-message.h:91
Local< Data > host_defined_options_
Definition v8-message.h:101
V8_INLINE Local< Value > ResourceName() const
Definition v8-message.h:204
V8_INLINE Local< Value > SourceMapUrl() const
Definition v8-message.h:216
V8_INLINE Local< Data > GetHostDefinedOptions() const
Definition v8-message.h:206
Local< CompileHintsCollector > GetCompileHintsCollector() const
Definition api.cc:2002
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Run(Local< Context > context)
Definition api.cc:1902
Local< UnboundScript > GetUnboundScript()
Definition api.cc:1961
std::vector< int > GetProducedCompileHints() const
Definition api.cc:1979
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Local< String > source, ScriptOrigin *origin=nullptr)
Definition api.cc:2718
Local< Value > GetResourceName()
Definition api.cc:1969
internal::Isolate *const i_isolate_
SealHandleScope(Isolate *isolate)
Definition api.cc:761
internal::Address * prev_limit_
static void CheckCast(Value *obj)
Definition api.cc:3962
static Local< Set > New(Isolate *isolate)
Definition api.cc:8538
void Clear()
Definition api.cc:8551
V8_WARN_UNUSED_RESULT Maybe< bool > Delete(Local< Context > context, Local< Value > key)
Definition api.cc:8584
Local< Array > AsArray() const
Definition api.cc:8631
static V8_INLINE Set * Cast(Value *value)
V8_WARN_UNUSED_RESULT Maybe< bool > Has(Local< Context > context, Local< Value > key)
Definition api.cc:8571
size_t Size() const
Definition api.cc:8546
V8_WARN_UNUSED_RESULT MaybeLocal< Set > Add(Local< Context > context, Local< Value > key)
Definition api.cc:8559
std::shared_ptr< BackingStore > GetBackingStore()
Definition api.cc:4047
void * Data() const
Definition api.cc:4057
static MaybeLocal< SharedArrayBuffer > MaybeNew(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized)
Definition api.cc:9410
static std::unique_ptr< BackingStore > NewBackingStore(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized, BackingStoreOnFailureMode on_failure=BackingStoreOnFailureMode::kOutOfMemory)
Definition api.cc:9444
size_t ByteLength() const
Definition api.cc:9382
size_t MaxByteLength() const
Definition api.cc:9386
static void CheckCast(Value *obj)
Definition api.cc:4108
static Local< SharedArrayBuffer > New(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized)
Definition api.cc:9390
SharedValueConveyor & operator=(SharedValueConveyor &&) noexcept
Definition api.cc:3221
SharedValueConveyor(SharedValueConveyor &&) noexcept
Definition api.cc:3216
static void CheckCast(Data *that)
Definition api.cc:7405
static Local< Signature > New(Isolate *isolate, Local< FunctionTemplate > receiver=Local< FunctionTemplate >())
Definition api.cc:1204
Isolate * GetIsolate()
Definition api.cc:376
size_t AddContext(Local< Context > context, SerializeInternalFieldsCallback internal_fields_serializer=SerializeInternalFieldsCallback(), SerializeContextDataCallback context_data_serializer=SerializeContextDataCallback(), SerializeAPIWrapperCallback api_wrapper_serializer=SerializeAPIWrapperCallback())
Definition api.cc:392
V8_INLINE size_t AddData(Local< Context > context, Local< T > object)
void SetDefaultContext(Local< Context > context, SerializeInternalFieldsCallback internal_fields_serializer=SerializeInternalFieldsCallback(), SerializeContextDataCallback context_data_serializer=SerializeContextDataCallback(), SerializeAPIWrapperCallback api_wrapper_serializer=SerializeAPIWrapperCallback())
Definition api.cc:380
StartupData CreateBlob(FunctionCodeHandling function_code_handling)
Definition api.cc:412
internal::SnapshotCreatorImpl * impl_
SnapshotCreator(Isolate *isolate, const intptr_t *external_references=nullptr, const StartupData *existing_blob=nullptr, bool owns_isolate=true)
Definition api.cc:351
int GetSourcePosition() const
Definition api.cc:3100
bool IsUserJavaScript() const
Definition api.cc:3166
Local< String > GetScriptName() const
Definition api.cc:3110
Local< String > GetScriptNameOrSourceURL() const
Definition api.cc:3118
Location GetLocation() const
Definition api.cc:3084
Local< String > GetScriptSourceMappingURL() const
Definition api.cc:3137
bool IsConstructor() const
Definition api.cc:3160
bool IsEval() const
Definition api.cc:3154
Local< String > GetFunctionName() const
Definition api.cc:3146
int GetScriptId() const
Definition api.cc:3106
Local< String > GetScriptSource() const
Definition api.cc:3127
bool IsWasm() const
Definition api.cc:3164
Local< StackFrame > GetFrame(Isolate *isolate, uint32_t index) const
Definition api.cc:3051
static Local< String > CurrentScriptNameOrSourceURL(Isolate *isolate)
Definition api.cc:3074
static Local< StackTrace > CurrentStackTrace(Isolate *isolate, int frame_limit, StackTraceOptions options=kDetailed)
Definition api.cc:3064
int GetFrameCount() const
Definition api.cc:3059
int GetID() const
Definition api.cc:3046
bool CanBeRehashed() const
Definition api.cc:417
bool IsValid() const
Definition api.cc:422
Local< String > ValueOf() const
Definition api.cc:7938
static Local< Value > New(Isolate *isolate, Local< String > value)
Definition api.cc:7927
static void CheckCast(Value *obj)
Definition api.cc:4120
virtual const char * data() const =0
virtual void Unaccount(Isolate *isolate)
void CheckCachedDataInvariants() const
Definition api.cc:6154
virtual const uint16_t * data() const =0
virtual size_t length() const =0
Utf8Value(Isolate *isolate, Local< v8::Value > obj, WriteOptions options=REPLACE_INVALID_UTF8)
Definition api.cc:11031
void CheckOneByte(bool is_one_byte) const
Definition api.cc:11099
ValueView(Isolate *isolate, Local< v8::String > str)
Definition api.cc:11070
Local< v8::Value > obj
Value(const Value &)=delete
Definition api.cc:11052
static void CheckCast(v8::Data *that)
Definition api.cc:3876
size_t Utf8LengthV2(Isolate *isolate) const
Definition api.cc:5768
bool IsExternalTwoByte() const
Definition api.cc:6026
bool IsExternal() const
Definition api.cc:6022
ExternalStringResource * GetExternalStringResourceSlow() const
Definition api.cc:6121
bool IsExternalOneByte() const
Definition api.cc:6038
bool ContainsOnlyOneByte() const
Definition api.cc:5737
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewExternalTwoByte(Isolate *isolate, ExternalStringResource *resource)
Definition api.cc:7632
void WriteOneByteV2(Isolate *isolate, uint32_t offset, uint32_t length, uint8_t *buffer, int flags=WriteFlags::kNone) const
Definition api.cc:5975
bool StringEquals(Local< String > str) const
Definition api.cc:7745
bool MakeExternal(ExternalStringResource *resource)
Definition api.cc:7680
int WriteOneByte(Isolate *isolate, uint8_t *buffer, int start=0, int length=-1, int options=NO_OPTIONS) const
Definition api.cc:5940
static V8_WARN_UNUSED_RESULT Local< String > NewFromUtf8Literal(Isolate *isolate, const char(&literal)[N], NewStringType type=NewStringType::kNormal)
static constexpr int kMaxLength
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromUtf8(Isolate *isolate, const char *data, NewStringType type=NewStringType::kNormal, int length=-1)
Definition api.cc:7593
void WriteV2(Isolate *isolate, uint32_t offset, uint32_t length, uint16_t *buffer, int flags=WriteFlags::kNone) const
Definition api.cc:5969
int Write(Isolate *isolate, uint16_t *buffer, int start=0, int length=-1, int options=NO_OPTIONS) const
Definition api.cc:5946
ExternalStringResourceBase * GetExternalStringResourceBaseSlow(String::Encoding *encoding_out) const
Definition api.cc:6167
int WriteUtf8(Isolate *isolate, char *buffer, int length=-1, int *nchars_ref=nullptr, int options=NO_OPTIONS) const
Definition api.cc:5901
static Local< String > Concat(Isolate *isolate, Local< String > left, Local< String > right)
Definition api.cc:7613
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewExternalOneByte(Isolate *isolate, ExternalOneByteStringResource *resource)
Definition api.cc:7656
size_t WriteUtf8V2(Isolate *isolate, char *buffer, size_t capacity, int flags=WriteFlags::kNone, size_t *processed_characters_return=nullptr) const
Definition api.cc:5982
bool IsOneByte() const
Definition api.cc:5620
Local< String > InternalizeString(Isolate *isolate)
Definition api.cc:6050
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromTwoByte(Isolate *isolate, const uint16_t *data, NewStringType type=NewStringType::kNormal, int length=-1)
Definition api.cc:7606
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromOneByte(Isolate *isolate, const uint8_t *data, NewStringType type=NewStringType::kNormal, int length=-1)
Definition api.cc:7599
bool CanMakeExternal(Encoding encoding) const
Definition api.cc:7739
const ExternalOneByteStringResource * GetExternalOneByteStringResource() const
Definition api.cc:6203
void VerifyExternalStringResource(ExternalStringResource *val) const
Definition api.cc:6056
void VerifyExternalStringResourceBase(ExternalStringResourceBase *v, Encoding encoding) const
Definition api.cc:6085
int Utf8Length(Isolate *isolate) const
Definition api.cc:5744
int Length() const
Definition api.cc:5616
static Local< Value > New(Isolate *isolate, Local< Symbol > value)
Definition api.cc:7947
static void CheckCast(Value *obj)
Definition api.cc:4126
Local< Symbol > ValueOf() const
Definition api.cc:7958
static Local< Symbol > New(Isolate *isolate, Local< String > description=Local< String >())
Definition api.cc:9487
static Local< Symbol > For(Isolate *isolate, Local< String > description)
Definition api.cc:9496
static Local< Symbol > ForApi(Isolate *isolate, Local< String > description)
Definition api.cc:9504
static void CheckCast(Data *that)
Definition api.cc:3882
Local< Value > Description(Isolate *isolate) const
Definition api.cc:6226
void SetNativeDataProperty(Local< Name > name, AccessorNameGetterCallback getter, AccessorNameSetterCallback setter=nullptr, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition api.cc:1433
void Set(Local< Name > name, Local< Data > value, PropertyAttribute attributes=None)
Definition api.cc:954
void SetPrivate(Local< Private > name, Local< Data > value, PropertyAttribute attributes=None)
Definition api.cc:978
void SetAccessorProperty(Local< Name > name, Local< FunctionTemplate > getter=Local< FunctionTemplate >(), Local< FunctionTemplate > setter=Local< FunctionTemplate >(), PropertyAttribute attribute=None)
Definition api.cc:983
void SetLazyDataProperty(Local< Name > name, AccessorNameGetterCallback getter, Local< Value > data=Local< Value >(), PropertyAttribute attribute=None, SideEffectType getter_side_effect_type=SideEffectType::kHasSideEffect, SideEffectType setter_side_effect_type=SideEffectType::kHasSideEffect)
Definition api.cc:1444
void SetIntrinsicDataProperty(Local< Name > name, Intrinsic intrinsic, PropertyAttribute attribute=None)
Definition api.cc:1455
V8_EXPORT void CheckValue() const
Definition api.cc:11843
void SetVerbose(bool value)
Definition api.cc:2856
Local< v8::Message > Message() const
Definition api.cc:2829
bool HasTerminated() const
Definition api.cc:2787
void Reset()
Definition api.cc:2839
void SetCaptureMessage(bool value)
Definition api.cc:2860
Local< Value > Exception() const
Definition api.cc:2798
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > StackTrace(Local< Context > context, Local< Value > exception)
Definition api.cc:2806
TryCatch(Isolate *isolate)
Definition api.cc:2730
internal::Address js_stack_comparable_address_
bool IsVerbose() const
Definition api.cc:2858
Local< Value > ReThrow()
Definition api.cc:2792
bool HasCaught() const
Definition api.cc:2781
internal::Isolate * i_isolate_
void ResetInternal()
Definition api.cc:2850
bool CanContinue() const
Definition api.cc:2785
void Update(Local< Value > baseline)
Definition api.cc:8380
TypecheckWitness(Isolate *isolate)
Definition api.cc:8368
static void CheckCast(Value *obj)
Definition api.cc:4074
static constexpr size_t kMaxByteLength
size_t Length()
Definition api.cc:9265
static void CheckCast(v8::Data *that)
Definition api.cc:3935
uint32_t Value() const
Definition api.cc:6267
Local< Value > GetSourceURL()
Definition api.cc:1869
Local< Value > GetSourceMappingURL()
Definition api.cc:1885
static const int kNoScriptId
Definition v8-script.h:91
int GetColumnNumber(int code_pos=0)
Definition api.cc:1803
Local< Value > GetSourceMappingURL()
Definition api.cc:1852
Local< Value > GetScriptName()
Definition api.cc:1820
int GetLineNumber(int code_pos=0)
Definition api.cc:1786
Local< Value > GetSourceURL()
Definition api.cc:1836
int GetId() const
Definition api.cc:1777
Local< Script > BindToCurrentContext()
Definition api.cc:1764
static v8::internal::Handle< To > OpenHandle(v8::Local< From > handle)
Definition api.h:274
static v8::internal::DirectHandle< To > OpenDirectHandle(v8::Local< From > handle)
Definition api.h:279
static v8::internal::Handle< v8::internal::Object > OpenPersistent(const v8::PersistentBase< T > &persistent)
Definition api.h:262
static void ReportOOMFailure(v8::internal::Isolate *isolate, const char *location, const OOMDetails &details)
Definition api.cc:272
static V8_INLINE bool ApiCheck(bool condition, const char *location, const char *message)
Definition api.h:214
V8_NOINLINE static V8_PRESERVE_MOST void ReportApiFailure(const char *location, const char *message)
Definition api.cc:256
static void DisposePlatform()
Definition api.cc:6389
static void SetFatalMemoryErrorCallback(OOMErrorCallback callback)
Definition api.cc:6499
static void SetReturnAddressLocationResolver(ReturnAddressLocationResolver return_address_resolver)
Definition api.cc:6508
static bool InitializeICU(const char *icu_data_file=nullptr)
Definition api.cc:6556
static const char * GetVersion()
Definition api.cc:6574
static void GetSharedMemoryStatistics(SharedMemoryStatistics *statistics)
Definition api.cc:6609
static void InitializeExternalStartupDataFromFile(const char *snapshot_blob)
Definition api.cc:6570
static void InitializePlatform(Platform *platform)
Definition api.cc:6385
static void InitializeExternalStartupData(const char *directory_path)
Definition api.cc:6565
static bool InitializeICUDefaultLocation(const char *exec_path, const char *icu_data_file=nullptr)
Definition api.cc:6560
static void SetSnapshotDataBlob(StartupData *startup_blob)
Definition api.cc:295
static void SetFlagsFromCommandLine(int *argc, char **argv, bool remove_flags)
Definition api.cc:440
static V8_INLINE bool Initialize()
static void SetEntropySource(EntropySource source)
Definition api.cc:6504
static void SetFatalErrorHandler(V8FatalErrorCallback that)
Definition api.cc:428
static void SetFlagsFromString(const char *str)
Definition api.cc:432
static void SetDcheckErrorHandler(DcheckErrorCallback that)
Definition api.cc:424
static bool Dispose()
Definition api.cc:6513
static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler)
Definition api.cc:6479
virtual MaybeLocal< WasmModuleObject > GetWasmModuleFromId(Isolate *isolate, uint32_t transfer_id)
Definition api.cc:3355
virtual MaybeLocal< Object > ReadHostObject(Isolate *isolate)
Definition api.cc:3346
virtual const SharedValueConveyor * GetSharedValueConveyor(Isolate *isolate)
Definition api.cc:3374
virtual MaybeLocal< SharedArrayBuffer > GetSharedArrayBufferFromId(Isolate *isolate, uint32_t clone_id)
Definition api.cc:3365
V8_WARN_UNUSED_RESULT bool ReadUint64(uint64_t *value)
Definition api.cc:3466
void SetSupportsLegacyWireFormat(bool supports_legacy_wire_format)
Definition api.cc:3426
void TransferSharedArrayBuffer(uint32_t id, Local< SharedArrayBuffer > shared_array_buffer)
Definition api.cc:3456
V8_WARN_UNUSED_RESULT bool ReadDouble(double *value)
Definition api.cc:3470
V8_WARN_UNUSED_RESULT bool ReadUint32(uint32_t *value)
Definition api.cc:3462
void TransferArrayBuffer(uint32_t transfer_id, Local< ArrayBuffer > array_buffer)
Definition api.cc:3450
ValueDeserializer(Isolate *isolate, const uint8_t *data, size_t size)
Definition api.cc:3392
V8_WARN_UNUSED_RESULT Maybe< bool > ReadHeader(Local< Context > context)
Definition api.cc:3404
V8_WARN_UNUSED_RESULT MaybeLocal< Value > ReadValue(Local< Context > context)
Definition api.cc:3435
uint32_t GetWireFormatVersion() const
Definition api.cc:3431
V8_WARN_UNUSED_RESULT bool ReadRawBytes(size_t length, const void **data)
Definition api.cc:3474
virtual Maybe< uint32_t > GetWasmModuleTransferId(Isolate *isolate, Local< WasmModuleObject > module)
Definition api.cc:3262
virtual bool AdoptSharedValueConveyor(Isolate *isolate, SharedValueConveyor &&conveyor)
Definition api.cc:3267
virtual Maybe< bool > IsHostObject(Isolate *isolate, Local< Object > object)
Definition api.cc:3245
virtual void FreeBufferMemory(void *buffer)
Definition api.cc:3283
virtual Maybe< bool > WriteHostObject(Isolate *isolate, Local< Object > object)
Definition api.cc:3231
virtual Maybe< uint32_t > GetSharedArrayBufferId(Isolate *isolate, Local< SharedArrayBuffer > shared_array_buffer)
Definition api.cc:3253
virtual bool HasCustomHostObject(Isolate *isolate)
Definition api.cc:3241
virtual void * ReallocateBufferMemory(void *old_buffer, size_t size, size_t *actual_size)
Definition api.cc:3276
void TransferArrayBuffer(uint32_t transfer_id, Local< ArrayBuffer > array_buffer)
Definition api.cc:3324
void WriteUint64(uint64_t value)
Definition api.cc:3334
void WriteDouble(double value)
Definition api.cc:3338
ValueSerializer(Isolate *isolate)
Definition api.cc:3294
V8_WARN_UNUSED_RESULT std::pair< uint8_t *, size_t > Release()
Definition api.cc:3320
void WriteUint32(uint32_t value)
Definition api.cc:3330
V8_WARN_UNUSED_RESULT Maybe< bool > WriteValue(Local< Context > context, Local< Value > value)
Definition api.cc:3309
void WriteHeader()
Definition api.cc:3303
void WriteRawBytes(const void *source, size_t length)
Definition api.cc:3342
void SetTreatArrayBufferViewsAsHostObjects(bool mode)
Definition api.cc:3305
V8_WARN_UNUSED_RESULT MaybeLocal< String > ToDetailString(Local< Context > context) const
Definition api.cc:3702
bool BooleanValue(Isolate *isolate) const
Definition api.cc:3738
bool IsRegExp() const
Definition api.cc:3652
bool IsTypedArray() const
Definition api.cc:3539
V8_WARN_UNUSED_RESULT Maybe< int32_t > Int32Value(Local< Context > context) const
Definition api.cc:4182
bool IsSymbol() const
Definition api.cc:3521
bool IsSet() const
bool IsBigInt() const
Definition api.cc:3580
bool IsName() const
Definition api.cc:3513
bool IsSharedArrayBuffer() const
Definition api.cc:3566
Local< String > TypeOf(Isolate *)
Definition api.cc:4255
V8_WARN_UNUSED_RESULT MaybeLocal< Int32 > ToInt32(Local< Context > context) const
Definition api.cc:3794
V8_WARN_UNUSED_RESULT Maybe< double > NumberValue(Local< Context > context) const
Definition api.cc:4156
V8_WARN_UNUSED_RESULT MaybeLocal< Numeric > ToNumeric(Local< Context > context) const
Definition api.cc:3754
V8_WARN_UNUSED_RESULT MaybeLocal< BigInt > ToBigInt(Local< Context > context) const
Definition api.cc:3727
bool IsPrimitive() const
Definition api.cc:3504
bool FullIsUndefined() const
Definition api.cc:3480
bool IsProxy() const
Definition api.cc:3584
bool IsArray() const
Definition api.cc:3525
bool IsPromise() const
Definition api.cc:3683
V8_INLINE bool QuickIsUndefined() const
Definition v8-value.h:552
Local< Boolean > ToBoolean(Isolate *isolate) const
Definition api.cc:3765
bool FullIsTrue() const
Definition api.cc:3492
bool IsArrayBuffer() const
Definition api.cc:3529
uint32_t GetHash()
Definition api.cc:4282
bool IsNumber() const
Definition api.cc:3576
bool IsObject() const
Definition api.cc:3572
V8_WARN_UNUSED_RESULT MaybeLocal< Uint32 > ToArrayIndex(Local< Context > context) const
Definition api.cc:4208
bool IsMapIterator() const
Definition api.cc:3675
bool IsBoolean() const
Definition api.cc:3619
bool SameValue(Local< Value > that) const
Definition api.cc:4249
bool IsNativeError() const
Definition api.cc:3648
bool IsMap() const
V8_WARN_UNUSED_RESULT Maybe< int64_t > IntegerValue(Local< Context > context) const
Definition api.cc:4169
bool FullIsFalse() const
Definition api.cc:3498
bool IsExternal() const
Definition api.cc:3623
bool IsSetIterator() const
Definition api.cc:3679
V8_INLINE bool QuickIsString() const
Definition v8-value.h:650
bool FullIsString() const
Definition api.cc:3515
V8_WARN_UNUSED_RESULT MaybeLocal< String > ToString(Local< Context > context) const
Definition api.cc:3691
static V8_INLINE Value * Cast(T *value)
Definition v8-value.h:467
bool IsModuleNamespaceObject() const
Definition api.cc:3687
V8_WARN_UNUSED_RESULT Maybe< uint32_t > Uint32Value(Local< Context > context) const
Definition api.cc:4195
bool IsWasmMemoryObject() const
Definition api.cc:3609
V8_WARN_UNUSED_RESULT Maybe< bool > Equals(Local< Context > context, Local< Value > that) const
Definition api.cc:4232
bool IsArrayBufferView() const
Definition api.cc:3535
bool IsWasmModuleObject() const
Definition api.cc:3610
bool IsGeneratorFunction() const
Definition api.cc:3663
bool IsWasmNull() const
Definition api.cc:3611
bool IsFunction() const
Definition api.cc:3509
bool StrictEquals(Local< Value > that) const
Definition api.cc:4243
bool FullIsNull() const
Definition api.cc:3486
V8_INLINE bool QuickIsNull() const
Definition v8-value.h:573
V8_WARN_UNUSED_RESULT MaybeLocal< Uint32 > ToUint32(Local< Context > context) const
Definition api.cc:3804
bool IsFloat16Array() const
Definition api.cc:3553
bool IsInt32() const
Definition api.cc:3628
V8_WARN_UNUSED_RESULT MaybeLocal< Primitive > ToPrimitive(Local< Context > context) const
Definition api.cc:3743
static void CheckCast(Data *that)
Definition api.cc:3844
V8_WARN_UNUSED_RESULT MaybeLocal< Number > ToNumber(Local< Context > context) const
Definition api.cc:3772
bool IsDataView() const
Definition api.cc:3561
Maybe< bool > InstanceOf(Local< Context > context, Local< Object > object)
Definition api.cc:4263
bool IsAsyncFunction() const
Definition api.cc:3656
bool IsUint32() const
Definition api.cc:3637
V8_WARN_UNUSED_RESULT MaybeLocal< Integer > ToInteger(Local< Context > context) const
Definition api.cc:3783
V8_WARN_UNUSED_RESULT MaybeLocal< Object > ToObject(Local< Context > context) const
Definition api.cc:3716
bool IsWasmMemoryMapDescriptor() const
Definition api.cc:3608
bool IsGeneratorObject() const
Definition api.cc:3671
static void CheckCast(Value *object)
Definition api.cc:3986
static Local< WasmMemoryMapDescriptor > New(Isolate *isolate, WasmFileDescriptor fd)
Definition api.cc:8907
static void CheckCast(Value *object)
Definition api.cc:3981
Local< ArrayBuffer > Buffer()
Definition api.cc:8838
static MaybeLocal< WasmModuleObject > Compile(Isolate *isolate, MemorySpan< const uint8_t > wire_bytes)
Definition api.cc:8876
CompiledWasmModule GetCompiledModule()
Definition api.cc:8848
static MaybeLocal< WasmModuleObject > FromCompiledModule(Isolate *isolate, const CompiledWasmModule &)
Definition api.cc:8862
static void CheckCast(Value *obj)
Definition api.cc:3992
WasmStreaming(std::unique_ptr< WasmStreamingImpl > impl)
Definition api.cc:11936
void Finish(bool can_use_compiled_module=true)
Definition api.cc:11946
bool SetCompiledModuleBytes(const uint8_t *bytes, size_t size)
Definition api.cc:11950
void SetUrl(const char *url, size_t length)
Definition api.cc:11959
void SetMoreFunctionsCanBeSerializedCallback(std::function< void(CompiledWasmModule)>)
Definition api.cc:11954
void Abort(MaybeLocal< Value > exception)
Definition api.cc:11948
void OnBytesReceived(const uint8_t *bytes, size_t size)
Definition api.cc:11942
static std::shared_ptr< WasmStreaming > Unpack(Isolate *isolate, Local< Value > value)
Definition api.cc:11962
void(*)(const WeakCallbackInfo< T > &data) Callback
V8_INLINE internal::Address *const & slot() const
V8_INLINE void VerifyOnStack() const
static void Abort()
static void SetEntropySource(EntropySource entropy_source)
static StackSlot GetStackStart()
static constexpr TimeDelta FromMicroseconds(int64_t microseconds)
Definition time.h:87
int64_t InMicroseconds() const
Definition time.cc:251
constexpr size_t size() const
Definition vector.h:70
constexpr T * begin() const
Definition vector.h:96
constexpr TimeDelta since_origin() const
Definition time.h:295
DirectHandle< NativeContext > CreateEnvironment(MaybeDirectHandle< JSGlobalProxy > maybe_global_proxy, v8::Local< v8::ObjectTemplate > global_object_template, v8::ExtensionConfiguration *extensions, size_t context_snapshot_index, DeserializeEmbedderFieldsCallback embedder_fields_deserializer, v8::MicrotaskQueue *microtask_queue)
DirectHandle< JSGlobalProxy > NewRemoteContext(MaybeDirectHandle< JSGlobalProxy > maybe_global_proxy, v8::Local< v8::ObjectTemplate > global_object_template)
V8_EXPORT_PRIVATE Tagged< Code > code(Builtin builtin)
Definition builtins.cc:149
const char * bailout_reason() const
const char * name() const
const char * resource_name() const
void ResetCreateHistogramFunction(CreateHistogramCallback f)
Definition counters.cc:185
void ResetCounterFunction(CounterLookupCallback f)
Definition counters.cc:174
void Serialize(v8::OutputStream *stream)
base::TimeTicks start_time() const
base::TimeTicks end_time() const
const SampleInfo & sample(int index) const
CpuProfile * StopProfiling(const char *title)
void ResetDateCache(base::TimezoneCache::TimeZoneDetection time_zone_detection)
Definition date.cc:43
bool PerformSideEffectCheckForCallback(Handle< FunctionTemplateInfo > function)
Definition debug.cc:3248
void IgnoreSideEffectsOnNextCallTo(Handle< FunctionTemplateInfo > function)
Definition debug.cc:3240
bool PerformSideEffectCheckForAccessor(DirectHandle< AccessorInfo > accessor_info, DirectHandle< Object > receiver, AccessorComponent component)
Definition debug.cc:3200
V8_INLINE bool is_null() const
Definition handles.h:693
V8_INLINE V8_WARN_UNUSED_RESULT bool store_aligned_pointer(IsolateForSandbox isolate, Tagged< HeapObject > host, void *ptr)
IndirectHandle< Object > Get(int index)
V8_EXPORT_PRIVATE void Create(Isolate *isolate, Tagged< Object > object, int *index)
Handle< Boolean > ToBoolean(bool value)
MaybeHandle< String > NewStringFromOneByte(base::Vector< const uint8_t > string, AllocationType allocation=AllocationType::kYoung)
Handle< Number > NewNumberFromInt(int32_t value)
V8_WARN_UNUSED_RESULT HandleType< String >::MaybeType NewConsString(HandleType< String > left, HandleType< String > right, AllocationType allocation=AllocationType::kYoung)
Handle< String > NewStringFromAsciiChecked(const char *str, AllocationType allocation=AllocationType::kYoung)
Handle< SwissNameDictionary > NewSwissNameDictionary(int at_least_space_for=kSwissNameDictionaryInitialCapacity, AllocationType allocation=AllocationType::kYoung)
Handle< Struct > NewStruct(InstanceType type, AllocationType allocation=AllocationType::kYoung)
Handle< Number > NewNumber(double value)
Handle< FixedArray > NewFixedArray(int length, AllocationType allocation=AllocationType::kYoung)
Isolate * isolate() const
Definition factory.h:1281
Handle< Symbol > NewSymbol(AllocationType allocation=AllocationType::kOld)
Definition factory.cc:1234
Handle< JSArray > NewJSArray(ElementsKind elements_kind, int length, int capacity, ArrayStorageAllocationMode mode=ArrayStorageAllocationMode::DONT_INITIALIZE_ARRAY_ELEMENTS, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:3211
Handle< Symbol > NewPrivateSymbol(AllocationType allocation=AllocationType::kOld)
Definition factory.cc:1238
DirectHandle< InterceptorInfo > NewInterceptorInfo(AllocationType allocation=AllocationType::kOld)
Definition factory.cc:1530
Handle< JSTypedArray > NewJSTypedArray(ExternalArrayType type, DirectHandle< JSArrayBuffer > buffer, size_t byte_offset, size_t length, bool is_length_tracking=false)
Definition factory.cc:3656
DirectHandle< FunctionTemplateInfo > NewFunctionTemplateInfo(int length, bool do_not_cache)
Definition factory.cc:4645
Handle< JSObject > CopyJSObject(DirectHandle< JSObject > object)
Definition factory.cc:2489
MaybeHandle< JSArrayBuffer > NewJSArrayBufferAndBackingStore(size_t byte_length, InitializedFlag initialized, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:3508
DirectHandle< AccessorInfo > NewAccessorInfo()
Definition factory.cc:1512
Handle< JSObject > NewJSObject(DirectHandle< JSFunction > constructor, AllocationType allocation=AllocationType::kYoung, NewJSObjectType=NewJSObjectType::kNoAPIWrapper)
Definition factory.cc:2985
DirectHandle< SourceTextModule > NewSourceTextModule(DirectHandle< SharedFunctionInfo > code)
Definition factory.cc:3423
Handle< JSArrayBuffer > NewJSSharedArrayBuffer(std::shared_ptr< BackingStore > backing_store)
Definition factory.cc:3553
V8_WARN_UNUSED_RESULT MaybeHandle< String > NewExternalStringFromTwoByte(const v8::String::ExternalStringResource *resource)
Definition factory.cc:1169
Handle< Name > InternalizeName(Handle< T > name)
Definition factory-inl.h:51
V8_WARN_UNUSED_RESULT MaybeHandle< String > NewExternalStringFromOneByte(const v8::String::ExternalOneByteStringResource *resource)
Definition factory.cc:1145
V8_WARN_UNUSED_RESULT MaybeHandle< String > NewStringFromUtf8(base::Vector< const char > str, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:753
DirectHandle< JSSet > NewJSSet()
Definition factory.cc:3603
Handle< SyntheticModule > NewSyntheticModule(DirectHandle< String > module_name, DirectHandle< FixedArray > export_names, v8::Module::SyntheticModuleEvaluationSteps evaluation_steps)
Definition factory.cc:3465
Handle< JSDataViewOrRabGsabDataView > NewJSDataViewOrRabGsabDataView(DirectHandle< JSArrayBuffer > buffer, size_t byte_offset, size_t byte_length, bool is_length_tracking=false)
Definition factory.cc:3700
Handle< Foreign > NewForeign(Address addr, AllocationType allocation_type=AllocationType::kYoung)
V8_WARN_UNUSED_RESULT MaybeHandle< String > NewStringFromTwoByte(base::Vector< const base::uc16 > str, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:906
DirectHandle< JSMap > NewJSMap()
Definition factory.cc:3596
Handle< JSObject > NewExternal(void *value, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:2902
Handle< Context > NewWithContext(DirectHandle< Context > previous, DirectHandle< ScopeInfo > scope_info, DirectHandle< JSReceiver > extension)
Definition factory.cc:1458
Handle< JSArray > NewJSArrayWithElements(DirectHandle< FixedArrayBase > elements, ElementsKind elements_kind, int length, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:3228
Handle< String > InternalizeString(base::Vector< const char > str, bool convert_encoding=false)
Definition factory.h:216
Handle< JSPromise > NewJSPromise()
Definition factory.cc:4526
DirectHandle< JSObject > NewSlowJSObjectWithPropertiesAndElements(DirectHandle< JSPrototype > prototype, DirectHandle< HeapObject > properties, DirectHandle< FixedArrayBase > elements)
Definition factory.cc:3186
Handle< JSArrayBuffer > NewJSArrayBuffer(std::shared_ptr< BackingStore > backing_store, AllocationType allocation=AllocationType::kYoung)
Definition factory.cc:3491
Handle< JSObject > NewError(DirectHandle< JSFunction > constructor, DirectHandle< String > message, DirectHandle< Object > options={})
Definition factory.cc:2799
DirectHandle< ObjectTemplateInfo > NewObjectTemplateInfo(DirectHandle< FunctionTemplateInfo > constructor, bool do_not_cache)
Definition factory.cc:4682
Handle< String > InternalizeUtf8String(base::Vector< const char > str)
Definition factory.cc:608
static uint32_t Hash()
Definition flags.cc:1196
static Tagged< Object > GetTarget(const FunctionCallbackInfo< T > &info)
IndirectHandle< Object > Create(Tagged< Object > value)
V8_INLINE ValueHelper::InternalRepresentationType repr() const
Definition handles.h:90
DetachableVector< Address * > blocks_
Definition api.h:424
DetachableVector< Tagged< NativeContext > > entered_contexts_
Definition api.h:427
V8_EXPORT_PRIVATE void Iterate(v8::internal::RootVisitor *v)
Definition api.cc:12050
static const size_t kEnteredContextsOffset
Definition api.h:388
HandleScopeData handle_scope_data_
Definition api.h:434
HandleScopeImplementer(Isolate *isolate)
Definition api.h:344
void IterateThis(RootVisitor *v)
Definition api.cc:11996
Isolate * isolate() const
Definition api.h:380
DirectHandle< NativeContext > LastEnteredContext()
Definition api-inl.h:349
DetachableVector< Address * > * blocks()
Definition api.h:379
DetachableVector< Tagged< Context > > saved_contexts_
Definition api.h:430
char * RestoreThread(char *from)
Definition api.cc:11990
std::unique_ptr< PersistentHandles > DetachPersistent(Address *first_block)
Definition api.cc:12063
std::optional< Address * > last_handle_before_persistent_block_
Definition api.h:432
HandleType< T > CloseAndEscape(HandleType< T > handle_value)
V8_INLINE Isolate * isolate() const
SnapshotObjectId PushHeapObjectsStats(OutputStream *stream, int64_t *timestamp_us)
HeapSnapshot * GetSnapshot(int index)
HeapSnapshot * TakeSnapshot(const v8::HeapProfiler::HeapSnapshotOptions options)
char last_few_messages[Heap::kTraceRingBufferSize+1]
Definition heap.h:2520
void ConfigureHeap(const v8::ResourceConstraints &constraints, v8::CppHeap *cpp_heap)
Definition heap.cc:4917
V8_INLINE uint64_t external_memory() const
Definition heap-inl.h:67
V8_EXPORT_PRIVATE void SetEmbedderRootsHandler(EmbedderRootsHandler *handler)
Definition heap.cc:6028
V8_EXPORT_PRIVATE void AutomaticallyRestoreInitialHeapLimit(double threshold_percent)
Definition heap.cc:4260
void AddGCEpilogueCallback(v8::Isolate::GCCallbackWithData callback, GCType gc_type_filter, void *data)
Definition heap.cc:6247
V8_EXPORT_PRIVATE void CollectAllAvailableGarbage(GarbageCollectionReason gc_reason)
Definition heap.cc:1327
void AddGCPrologueCallback(v8::Isolate::GCCallbackWithData callback, GCType gc_type_filter, void *data)
Definition heap.cc:6236
V8_EXPORT_PRIVATE int NotifyContextDisposed(bool has_dependent_context)
Definition heap.cc:1848
V8_EXPORT_PRIVATE uint64_t external_memory_limit_for_interrupt()
Definition heap.cc:1471
void SetGetExternallyAllocatedMemoryInBytesCallback(GetExternallyAllocatedMemoryInBytesCallback callback)
Definition heap.h:965
bool MeasureMemory(std::unique_ptr< v8::MeasureMemoryDelegate > delegate, v8::MeasureMemoryExecution execution)
Definition heap.cc:4285
void RecordStats(HeapStats *stats)
Definition heap.cc:5127
void CollectCodeStatistics()
Definition heap.cc:4307
HeapProfiler * heap_profiler() const
Definition heap.h:366
uint64_t UpdateExternalMemory(int64_t delta)
Definition heap.cc:6764
bool HasBeenSetUp() const
Definition heap.cc:451
const base::AddressRegion & code_region()
Definition heap-inl.h:176
void RemoveGCPrologueCallback(v8::Isolate::GCCallbackWithData callback, void *data)
Definition heap.cc:6242
void RemoveGCEpilogueCallback(v8::Isolate::GCCallbackWithData callback, void *data)
Definition heap.cc:6253
std::unique_ptr< v8::MeasureMemoryDelegate > CreateDefaultMeasureMemoryDelegate(v8::Local< v8::Context > context, v8::Local< v8::Promise::Resolver > promise, v8::MeasureMemoryMode mode)
Definition heap.cc:4300
V8_EXPORT_PRIVATE void AddNearHeapLimitCallback(v8::NearHeapLimitCallback, void *data)
Definition heap.cc:4220
uint64_t backing_store_bytes() const
Definition heap.h:625
V8_EXPORT_PRIVATE void RemoveNearHeapLimitCallback(v8::NearHeapLimitCallback callback, size_t heap_limit)
Definition heap.cc:4230
V8_EXPORT_PRIVATE void MemoryPressureNotification(v8::MemoryPressureLevel level, bool is_isolate_locked)
Definition heap.cc:4185
V8_INLINE void SetMessageListeners(Tagged< ArrayList > value)
Definition heap-inl.h:130
v8::CppHeap * cpp_heap() const
Definition heap.h:1112
GlobalHandles * global_handles() const
Definition isolate.h:1416
void set_stack_size(size_t v)
Definition isolate.h:1753
MaybeDirectHandle< Script > CurrentReferrerScript()
Definition isolate.cc:1695
void SetHostCreateShadowRealmContextCallback(HostCreateShadowRealmContextCallback callback)
Definition isolate.cc:6710
bool serializer_enabled() const
Definition isolate.h:1549
AccountingAllocator * allocator()
Definition isolate.h:1979
void SetHostImportModuleDynamicallyCallback(HostImportModuleDynamicallyCallback callback)
Definition isolate.cc:6681
void SetPromiseHook(PromiseHook hook)
Definition isolate.cc:6856
static V8_INLINE Isolate * Current()
Definition isolate-inl.h:35
Counters * counters()
Definition isolate.h:1180
void RequestInterrupt(InterruptCallback callback, void *data)
Definition isolate.cc:1960
CompilationCache * compilation_cache()
Definition isolate.h:1191
DateCache * date_cache() const
Definition isolate.h:1619
const IsolateData * isolate_data() const
Definition isolate.h:1207
void SetPromiseRejectCallback(PromiseRejectCallback callback)
Definition isolate.cc:7011
void SetHostImportModuleWithPhaseDynamicallyCallback(HostImportModuleWithPhaseDynamicallyCallback callback)
Definition isolate.cc:6686
EternalHandles * eternal_handles() const
Definition isolate.h:1420
const v8::Context::BackupIncumbentScope * top_backup_incumbent_scope() const
Definition isolate.h:2150
std::vector< MemoryRange > * GetCodePages() const
Definition isolate.cc:3073
void set_memory_saver_mode_enabled(bool memory_saver_mode_enabled)
Definition isolate.h:2386
void SetFailedAccessCheckCallback(v8::FailedAccessCheckCallback callback)
Definition isolate.cc:1776
HandleScopeImplementer * handle_scope_implementer() const
Definition isolate.h:1397
void DiscardPerThreadDataForThisThread()
Definition isolate.cc:554
bool was_locker_ever_used() const
Definition isolate.h:1729
Bootstrapper * bootstrapper()
Definition isolate.h:1178
MaybeLocal< v8::Context > GetContextFromRecorderContextId(v8::metrics::Recorder::ContextId id)
Definition isolate.cc:7453
void InstallConditionalFeatures(DirectHandle< NativeContext > context)
Definition isolate.cc:3628
Handle< JSMessageObject > CreateMessage(DirectHandle< Object > exception, MessageLocation *location)
Definition isolate.cc:2988
Tagged< Context > context() const
Definition isolate.h:800
Handle< StackTraceInfo > GetDetailedStackTrace(DirectHandle< JSReceiver > error_object)
Definition isolate.cc:1513
v8::metrics::LongTaskStats * GetCurrentLongTaskStats()
Definition isolate.cc:7468
void RemoveCallCompletedCallback(CallCompletedCallback callback)
Definition isolate.cc:6417
v8::metrics::Recorder::ContextId GetOrRegisterRecorderContextId(DirectHandle< NativeContext > context)
Definition isolate.cc:7428
void SetReleaseCppHeapCallback(v8::Isolate::ReleaseCppHeapCallback callback)
Definition isolate.cc:6845
void set_context(Tagged< Context > context)
Definition isolate-inl.h:43
Tagged< Object > Throw(Tagged< Object > exception, MessageLocation *location=nullptr)
Definition isolate.cc:2091
void CancelTerminateExecution()
Definition isolate.cc:1954
DirectHandle< String > CurrentScriptNameOrSourceURL()
Definition isolate.cc:1688
void DetachGlobal(DirectHandle< Context > env)
Definition isolate.cc:7119
TracedHandles * traced_handles()
Definition isolate.h:1418
void PrintCurrentStackTrace(std::ostream &out, PrintCurrentStackTraceFilterCallback should_include_frame_callback=nullptr)
Definition isolate.cc:2860
bool GetStackTraceLimit(Isolate *isolate, int *result)
Definition isolate.cc:1706
void SetCaptureStackTraceForUncaughtExceptions(bool capture, int frame_limit, StackTrace::StackTraceOptions options)
Definition isolate.cc:3612
void AbortConcurrentOptimization(BlockingBehavior blocking_behavior)
Definition isolate.cc:6093
void AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback)
Definition isolate.cc:6395
V8_INLINE HandleScopeData * handle_scope_data()
Definition isolate.h:1393
v8::ArrayBuffer::Allocator * array_buffer_allocator() const
Definition isolate.h:1938
ThreadManager * thread_manager() const
Definition isolate.h:1422
void InitializeLoggingAndCounters()
Definition isolate.cc:5048
ThreadId thread_id() const
Definition isolate.h:821
void SetIdle(bool is_idle)
Definition isolate.cc:7173
StringTable * string_table() const
Definition isolate.h:781
Handle< NativeContext > native_context()
Definition isolate-inl.h:48
void Freeze(bool is_frozen)
Definition isolate.h:2416
DirectHandle< StackTraceInfo > CaptureDetailedStackTrace(int limit, StackTrace::StackTraceOptions options)
Definition isolate.cc:1613
StackGuard * stack_guard()
Definition isolate.h:1198
IsolateGroup * isolate_group() const
Definition isolate.h:1230
void set_array_buffer_allocator_shared(std::shared_ptr< v8::ArrayBuffer::Allocator > allocator)
Definition isolate.h:1942
void AddCallCompletedCallback(CallCompletedCallback callback)
Definition isolate.cc:6410
Builtins * builtins()
Definition isolate.h:1443
bool IsDead() const
Definition isolate.h:1557
V8FileLogger * v8_file_logger() const
Definition isolate.h:1192
void set_battery_saver_mode_enabled(bool battery_saver_mode_enabled)
Definition isolate.h:2382
v8::internal::Factory * factory()
Definition isolate.h:1527
void set_top_backup_incumbent_scope(const v8::Context::BackupIncumbentScope *top_backup_incumbent_scope)
Definition isolate.h:2153
DirectHandle< NativeContext > GetIncumbentContext()
Definition isolate-inl.h:68
void RemoveBeforeCallEnteredCallback(BeforeCallEnteredCallback callback)
Definition isolate.cc:6402
bool should_check_side_effects() const
Definition isolate.h:1493
Handle< JSGlobalProxy > global_proxy()
void set_allow_atomics_wait(bool set)
Definition isolate.h:2130
LocalIsolate * AsLocalIsolate()
Definition isolate.h:2188
void SetExceptionPropagationCallback(ExceptionPropagationCallback callback)
Definition isolate.cc:5037
Debug * debug() const
Definition isolate.h:1474
void SetIsLoading(bool is_loading)
Definition isolate.cc:7139
void ReportPendingMessages(bool report=true)
Definition isolate.cc:3081
void SetPrepareStackTraceCallback(PrepareStackTraceCallback callback)
Definition isolate.cc:6797
void clear_topmost_script_having_context()
Definition isolate-inl.h:63
void SetPriority(v8::Isolate::Priority priority)
Definition isolate.cc:7151
DirectHandle< Symbol > SymbolFor(RootIndex dictionary_index, Handle< String > name, bool private_symbol)
Definition isolate.cc:6360
const std::shared_ptr< metrics::Recorder > & metrics_recorder()
Definition isolate.h:1187
void SetAddCrashKeyCallback(AddCrashKeyCallback callback)
Definition isolate.cc:6838
ThreadLocalTop * thread_local_top()
Definition isolate.h:1331
void set_array_buffer_allocator(v8::ArrayBuffer::Allocator *allocator)
Definition isolate.h:1935
void RegisterTryCatchHandler(v8::TryCatch *that)
Definition isolate.cc:655
void SetAbortOnUncaughtExceptionCallback(v8::Isolate::AbortOnUncaughtExceptionCallback callback)
Definition isolate.cc:3623
void SetHostInitializeImportMetaObjectCallback(HostInitializeImportMetaObjectCallback callback)
Definition isolate.cc:6705
V8_INLINE void SetCppHeapWrappable(IsolateForPointerCompression isolate, void *)
V8_INLINE void * GetCppHeapWrappable(IsolateForPointerCompression isolate) const
static Maybe< bool > Cleanup(Isolate *isolate, DirectHandle< JSFinalizationRegistry > finalization_registry)
Maybe< bool > CollectKeys(DirectHandle< JSReceiver > receiver, DirectHandle< JSReceiver > object)
Definition keys.cc:250
static MaybeHandle< FixedArray > GetKeys(Isolate *isolate, DirectHandle< JSReceiver > object, KeyCollectionMode mode, PropertyFilter filter, GetKeysConversion keys_conversion=GetKeysConversion::kKeepNumbers, bool is_for_in=false, bool skip_indices=false)
Definition keys.cc:97
void set_skip_indices(bool value)
Definition keys.h:90
V8_INLINE DirectHandle< T > ToHandleChecked() const
V8_WARN_UNUSED_RESULT V8_INLINE bool ToHandle(DirectHandle< S > *out) const
V8_INLINE bool is_null() const
V8_INLINE Handle< T > ToHandleChecked() const
v8::MicrotasksPolicy microtasks_policy() const
void PerformCheckpoint(v8::Isolate *isolate) override
unsigned int GetHitLineCount() const
const std::vector< ProfileNode * > * children() const
bool GetLineTicks(v8::CpuProfileNode::LineTick *entries, unsigned int length) const
const std::vector< CpuProfileDeoptInfo > & deopt_infos() const
void set_value(DirectHandle< JSAny > value)
void set_set(DirectHandle< UnionOf< JSAny, FunctionTemplateInfo > > set)
void set_get(DirectHandle< UnionOf< JSAny, FunctionTemplateInfo > > get)
Tagged< T > GetCurrent() const
Definition prototype.h:52
virtual void VisitRootPointers(Root root, const char *description, FullObjectSlot start, FullObjectSlot end)=0
TData * location() const
Definition slots.h:80
void SetDefaultContext(DirectHandle< NativeContext > context, SerializeEmbedderFieldsCallback callback)
Definition snapshot.cc:948
size_t AddContext(DirectHandle< NativeContext > context, SerializeEmbedderFieldsCallback callback)
Definition snapshot.cc:960
size_t AddData(DirectHandle< NativeContext > context, Address object)
Definition snapshot.cc:972
StartupData CreateBlob(SnapshotCreator::FunctionCodeHandling function_code_handling, Snapshot::SerializerFlags serializer_flags=Snapshot::kDefaultSerializerFlags)
Definition snapshot.cc:1043
void SetStackLimit(uintptr_t limit)
V8_INLINE bool IsExternalOneByte() const
Definition string-inl.h:238
V8_INLINE bool IsExternalTwoByte() const
Definition string-inl.h:247
V8_INLINE bool IsExternal() const
Definition string-inl.h:188
size_t GetCurrentMemoryUsage() const
V8_INLINE constexpr StorageType ptr() const
V8_INLINE constexpr bool is_null() const
Definition tagged.h:502
bool IsLockedByCurrentThread() const
Definition v8threads.h:73
static void Move(Address **from, Address **to)
static void Destroy(Address *location)
V8_INLINE FullObjectSlot Create(Address value, Address *slot, TracedReferenceStoreMode store_mode, TracedReferenceHandling reference_handling)
static void Copy(const Address *const *from, Address **to)
void SetCodeEventHandler(uint32_t options, JitCodeEventHandler event_handler)
Definition log.cc:2413
Maybe< bool > ReadHeader() V8_WARN_UNUSED_RESULT
bool ReadUint64(uint64_t *value) V8_WARN_UNUSED_RESULT
MaybeDirectHandle< Object > ReadObjectUsingEntireBufferForLegacyFormat() V8_WARN_UNUSED_RESULT
bool ReadRawBytes(size_t length, const void **data) V8_WARN_UNUSED_RESULT
MaybeDirectHandle< Object > ReadObjectWrapper() V8_WARN_UNUSED_RESULT
bool ReadDouble(double *value) V8_WARN_UNUSED_RESULT
bool ReadUint32(uint32_t *value) V8_WARN_UNUSED_RESULT
void TransferArrayBuffer(uint32_t transfer_id, DirectHandle< JSArrayBuffer > array_buffer)
void SetTreatArrayBufferViewsAsHostObjects(bool mode)
void WriteRawBytes(const void *source, size_t length)
void TransferArrayBuffer(uint32_t transfer_id, DirectHandle< JSArrayBuffer > array_buffer)
Maybe< bool > WriteObject(DirectHandle< Object > object) V8_WARN_UNUSED_RESULT
void WriteDouble(double value)
std::pair< uint8_t *, size_t > Release()
static uint32_t Hash()
Definition version.h:30
static ContextId GetContextId(Local< Context > context)
Definition api.cc:7334
static MaybeLocal< Context > GetContext(Isolate *isolate, ContextId id)
Definition api.cc:7328
RecordWriteMode const mode_
AlignedCachedData * cached_data_
#define V8_ENABLE_SWISS_NAME_DICTIONARY_BOOL
Definition globals.h:242
#define COMPRESS_POINTERS_BOOL
Definition globals.h:99
#define DEBUG_BOOL
Definition globals.h:87
#define V8_ENABLE_SANDBOX_BOOL
Definition globals.h:160
#define FUNCTION_ADDR(f)
Definition globals.h:712
base::TemplateHashMapImpl< Handle< HeapObject >, DependentCode::DependencyGroups, HandleValueEqual, ZoneAllocationPolicy > deps_
uint32_t source_length_
Definition compiler.cc:3786
#define EXPORT_CONTEXTUAL_VARIABLE(VarName)
Definition contextual.h:94
bool is_empty
Definition sweeper.cc:229
int start
Handle< SharedFunctionInfo > info
int end
LineAndColumn current
#define RAB_GSAB_TYPED_ARRAYS(V)
#define TYPED_ARRAYS(V)
#define TYPED_ARRAYS_BASE(V)
#define THROW_NEW_ERROR_RETURN_VALUE(isolate, call, value)
Definition isolate.h:300
#define ASSIGN_RETURN_ON_EXCEPTION_VALUE(isolate, dst, call, value)
Definition isolate.h:276
#define MAYBE_RETURN_ON_EXCEPTION_VALUE(isolate, call, value)
Definition isolate.h:238
#define FOR_WITH_HANDLE_SCOPE(isolate, loop_var_type, init, loop_var, limit_check, increment, body)
Definition isolate.h:457
MicrotaskQueue * microtask_queue
Definition execution.cc:77
base::Vector< const DirectHandle< Object > > args
Definition execution.cc:74
Label label
#define EXPORT_TEMPLATE_DEFINE(export)
Isolate * isolate
std::ostream & impl_
std::vector< std::unique_ptr< InstanceTypeTree > > children
OptionalOpIndex index
int32_t offset
std::string extension
TNode< Context > context
TNode< Object > receiver
SharedFunctionInfoRef shared
TNode< Object > callback
std::string pattern
DirectHandle< JSReceiver > options
double increment
ZoneVector< RpoNumber > & result
ValueType obj_type
LiftoffAssembler::CacheState state
ZoneVector< Entry > entries
Point from
Point to
FunctionLiteral * literal
Definition liveedit.cc:294
const char * name_
std::shared_ptr< NativeModule > native_module_
size_t priority
InstructionOperand source
const int length_
Definition mul-fft.cc:473
v8::PageAllocator PageAllocator
Definition platform.h:22
void InitializeProcess(PageAllocator *page_allocator, size_t desired_heap_size)
Definition platform.cc:92
EmbedderStackState
Definition common.h:15
bool IsInitialized()
Definition platform.cc:90
STL namespace.
unsigned short uint16_t
Definition unicode.cc:39
i::Address ConvertToJSGlobalProxyIfNecessary(i::Address holder_ptr)
Definition api.cc:3821
void * ClearWeak(i::Address *location)
Definition api.cc:654
void AnnotateStrongRetainer(i::Address *location, const char *label)
Definition api.cc:658
void MoveGlobalReference(internal::Address **from, internal::Address **to)
Definition api.cc:640
void ToLocalEmpty()
Definition api.cc:678
i::Address * GlobalizeReference(i::Isolate *i_isolate, i::Address value)
Definition api.cc:623
void MakeWeak(i::Address *location, void *parameter, WeakCallbackInfo< void >::Callback weak_callback, WeakCallbackType type)
Definition api.cc:644
V8_EXPORT v8::Local< v8::Value > GetFunctionTemplateData(v8::Isolate *isolate, v8::Local< v8::Data > raw_target)
Definition api.cc:11880
i::Address * Eternalize(Isolate *v8_isolate, Value *value)
Definition api.cc:666
void InternalFieldOutOfBounds(int index)
Definition api.cc:682
i::Address * CopyGlobalReference(i::Address *from)
Definition api.cc:635
void DisposeGlobal(i::Address *location)
Definition api.cc:662
void FromJustIsNothing()
Definition api.cc:674
V8_INLINE size_t hash_combine(size_t seed, size_t hash)
Definition hashing.h:77
void * Allocate(void *address, size_t size, OS::MemoryPermission access)
void * Realloc(void *memory, size_t size)
Definition memory.h:48
void FatalOOM(OOMType type, const char *msg)
Definition logging.cc:80
void * Calloc(size_t count, size_t size)
Definition memory.h:71
constexpr bool IsInRange(T value, U lower_limit, U higher_limit)
Definition bounds.h:20
constexpr Vector< T > VectorOf(T *start, size_t size)
Definition vector.h:360
OwnedVector< T > OwnedCopyOf(const T *data, size_t size)
Definition vector.h:383
void * Malloc(size_t size)
Definition memory.h:36
void SetDcheckFunction(void(*dcheck_function)(const char *, int, const char *))
Definition logging.cc:72
void Free(void *memory)
Definition memory.h:63
void SetFatalFunction(void(*fatal_function)(const char *, int, const char *))
Definition logging.cc:76
std::pair< Tagged_t, Tagged_t > TaggedAddressRange
bool EnableTrapHandler(bool use_v8_handler)
void SetUnhandledExceptionCallback(v8::UnhandledExceptionCallback unhandled_exception_callback)
KeyCollectionMode
Definition keys.h:28
void DeleteArray(T *array)
Definition allocation.h:63
V8_INLINE IndirectHandle< T > handle(Tagged< T > object, Isolate *isolate)
Definition handles-inl.h:72
bool CanUseFastIteration(Isolate *isolate, DirectHandle< JSArray > array)
Definition api.cc:8193
bool TryCast(Tagged< From > value, Tagged< To > *out)
Definition casting.h:77
void InvokeFinalizationRegistryCleanupFromTask(DirectHandle< NativeContext > native_context, DirectHandle< JSFinalizationRegistry > finalization_registry)
Definition api.cc:12192
constexpr const char * ToString(DeoptimizeKind kind)
Definition globals.h:880
uint32_t DoubleToUint32(double x)
v8::PageAllocator * GetPlatformPageAllocator()
Definition allocation.cc:66
bool InitializeICU(const char *icu_data_file)
Definition icu_util.cc:62
void VerifyHandleIsNonEmpty(bool is_empty)
Definition api.cc:557
bool IsNumeric(Tagged< Object > obj)
bool IsNumber(Tagged< Object > obj)
constexpr InstanceType LAST_STRING_TYPE
GetKeysConversion
Definition keys.h:22
void DisposeTracedReference(internal::Address *location)
Definition api.cc:580
bool ValidateFunctionCallbackInfo(const FunctionCallbackInfo< T > &info)
Definition api.cc:12258
constexpr int kEmbedderDataSlotSize
Definition globals.h:664
unsigned int FastD2UI(double x)
bool IsCustomElementsReceiverMap(Tagged< Map > map)
Tagged(T object) -> Tagged< T >
V8_INLINE IsolateForSandbox GetCurrentIsolateForSandbox()
Definition isolate.h:78
bool IsGeneratorFunction(FunctionKind kind)
bool IsInt32Double(double value)
void InvokeFunctionCallbackOptimized(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition api.cc:12187
V8_INLINE Isolate * GetIsolateFromWritableObject(Tagged< HeapObject > object)
V8_INLINE bool GetIsolateFromHeapObject(Tagged< HeapObject > object, Isolate **isolate)
void CopyTracedReference(const internal::Address *const *from, internal::Address **to)
Definition api.cc:575
bool ValidatePropertyCallbackInfo(const PropertyCallbackInfo< T > &info)
Definition api.cc:12277
V8_INLINE constexpr bool IsSmi(TaggedImpl< kRefType, StorageType > obj)
Definition objects.h:665
i::Address * GlobalizeTracedReference(i::Isolate *i_isolate, i::Address value, internal::Address *slot, TracedReferenceStoreMode store_mode, TracedReferenceHandling reference_handling)
Definition api.cc:562
BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL BUILTIN_FP_CALL int character
bool IsAsyncFunction(FunctionKind kind)
DateBuffer ToDateString(double time_val, DateCache *date_cache, ToDateStringMode mode)
Definition date.cc:572
V8_EXPORT internal::Isolate * IsolateFromNeverReadOnlySpaceObject(Address obj)
void VisitObject(Isolate *isolate, Tagged< HeapObject > object, ObjectVisitor *visitor)
@ HOLEY_NONEXTENSIBLE_ELEMENTS
@ SLOW_STRING_WRAPPER_ELEMENTS
@ PACKED_NONEXTENSIBLE_ELEMENTS
@ SLOW_SLOPPY_ARGUMENTS_ELEMENTS
@ FAST_SLOPPY_ARGUMENTS_ELEMENTS
@ FAST_STRING_WRAPPER_ELEMENTS
V8_INLINE DirectHandle< T > direct_handle(Tagged< T > object, Isolate *isolate)
bool IsImmutableLexicalVariableMode(VariableMode mode)
Definition globals.h:2145
const int kHandleBlockSize
Definition api.h:444
FastIterateResult
Definition api.cc:8200
static const int kInvalidEnumCacheSentinel
bool IsModule(FunctionKind kind)
ShouldThrow GetShouldThrow(Isolate *isolate, Maybe< ShouldThrow > should_throw)
Definition objects.cc:140
bool IsPrimitive(Tagged< Object > obj)
bool V8_EXPORT ValidateCallbackInfo(const FunctionCallbackInfo< void > &info)
Definition api.cc:12301
int32_t ConvertDouble(double d)
Definition api.cc:12211
DONT_OVERRIDE DISABLE_ALLOCATION_SITES HOLEY_ELEMENTS
constexpr uint32_t kGlobalHandleZapValue
Definition globals.h:1007
DONT_OVERRIDE DISABLE_ALLOCATION_SITES DISABLE_ALLOCATION_SITES HOLEY_DOUBLE_ELEMENTS
bool InitializeICUDefaultLocation(const char *exec_path, const char *icu_data_file)
Definition icu_util.cc:39
int32_t DoubleToInt32(double x)
void InvokeFunctionCallbackGeneric(const v8::FunctionCallbackInfo< v8::Value > &info)
Definition api.cc:12182
@ kApiAccessCheckCallbackTag
@ kApiAbortScriptExecutionCallbackTag
const int kSmiValueSize
constexpr bool kPlatformRequiresCodeRange
Definition globals.h:507
V8_EXPORT_PRIVATE FlagValues v8_flags
float DoubleToFloat32(double x)
V8_INLINE bool IsWasmObject(T obj, Isolate *=nullptr)
Definition objects.h:725
uint64_t DoubleToWebIDLUint64(double x)
@ kExternalFloat16Array
Definition globals.h:2459
constexpr size_t kMaximalCodeRangeSize
Definition globals.h:508
double FastUI2D(unsigned x)
static bool IsMinusZero(double value)
MaybeDirectHandle< Object > JsonStringify(Isolate *isolate, Handle< JSAny > object, Handle< JSAny > replacer, Handle< Object > gap)
bool IsPrivateSymbol(Tagged< Object > obj)
void InitializeExternalStartupData(const char *directory_path)
int64_t DoubleToWebIDLInt64(double x)
constexpr int kMaxInt
Definition globals.h:374
void InitializeExternalStartupDataFromFile(const char *snapshot_blob)
void MoveTracedReference(internal::Address **from, internal::Address **to)
Definition api.cc:571
@ ACCESSOR_GETTER
Definition objects.h:879
@ ACCESSOR_SETTER
Definition objects.h:879
void MemCopy(void *dest, const void *src, size_t size)
Definition memcopy.h:124
void InvokeAccessorGetterCallback(v8::Local< v8::Name > property, const v8::PropertyCallbackInfo< v8::Value > &info)
Definition api.cc:12097
V8_EXPORT bool ShouldThrowOnError(internal::Isolate *isolate)
constexpr uint32_t kMaxUInt32
Definition globals.h:387
kInstanceDescriptorsOffset kTransitionsOrPrototypeInfoOffset IsNull(value)||IsJSProxy(value)||IsWasmObject(value)||(IsJSObject(value) &&(HeapLayout
Definition map-inl.h:70
FastIterateResult FastIterateArray(DirectHandle< JSArray > array, Isolate *isolate, v8::Array::IterationCallback callback, void *callback_data)
Definition api.cc:8207
T * NewArray(size_t size)
Definition allocation.h:43
uint32_t GetLength(Tagged< JSArray > array)
Definition api.cc:8179
!IsContextMap !IsContextMap native_context
Definition map-inl.h:877
Tagged< To > Cast(Tagged< From > value, const v8::SourceLocation &loc=INIT_SOURCE_LOCATION_IN_DEBUG)
Definition casting.h:150
void(*)( Isolate *isolate, Local< Context > context, Local< Promise::Resolver > resolver, Local< Value > result, WasmAsyncSuccess success) WasmAsyncResolvePromiseCallback
IntegrityLevel
Definition v8-object.h:228
bool(*)(Local< Context > context) WasmJSPIEnabledCallback
PropertyAttribute
Definition v8-object.h:139
@ DontEnum
Definition v8-object.h:145
@ None
Definition v8-object.h:141
@ DontDelete
Definition v8-object.h:147
@ ReadOnly
Definition v8-object.h:143
JitCodeEventOptions
@ kJitCodeEventEnumExisting
bool(*)(Isolate *isolate, Local< Object > obj) IsJSApiWrapperNativeErrorCallback
KeyCollectionMode
Definition v8-object.h:211
bool(*)(Local< Context > context) JavaScriptCompileHintsMagicEnabledCallback
static constexpr ReleaseStoreTag kReleaseStore
Definition globals.h:2910
static OOMErrorCallback g_oom_error_callback
Definition api.cc:185
CpuProfilingStatus
void(*)(const JitCodeEvent *event) JitCodeEventHandler
static i::DirectHandle< ObjectType > CreateEnvironment(i::Isolate *i_isolate, v8::ExtensionConfiguration *extensions, v8::MaybeLocal< ObjectTemplate > maybe_global_template, v8::MaybeLocal< Value > maybe_global_proxy, size_t context_snapshot_index, i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer, v8::MicrotaskQueue *microtask_queue)
Definition api.cc:6648
void(*)(CrashKeyId id, const std::string &value) AddCrashKeyCallback
void(*)(Local< Name > property, const PropertyCallbackInfo< Value > &info) AccessorNameGetterCallback
Definition v8-object.h:155
GCCallbackFlags
@ kGCCallbackFlagForced
ModifyCodeGenerationFromStringsResult(*)(Local< Context > context, Local< Value > source) ModifyCodeGenerationFromStringsCallback
SideEffectType
Definition v8-object.h:198
MicrotasksPolicy
V8_EXPORT bool TryHandleWebAssemblyTrapPosix(int sig_code, siginfo_t *info, void *context)
void(*)(ExceptionPropagationMessage message) ExceptionPropagationCallback
void * NativeObject
Definition v8-profiler.h:30
bool(*)(const FunctionCallbackInfo< Value > &) ExtensionCallback
static i::CpuProfile * ToInternal(const CpuProfile *profile)
Definition api.cc:11372
Maybe< T > Nothing()
Definition v8-maybe.h:112
static constexpr int kInternalFieldsInWeakCallback
void(*)(void *histogram, int sample) AddHistogramSampleCallback
IndexFilter
Definition v8-object.h:217
void(*)(const char *file, int line, const char *message) DcheckErrorCallback
void(*)(const FunctionCallbackInfo< Value > &) WasmStreamingCallback
bool ToLocal(v8::internal::MaybeDirectHandle< v8::internal::Object > maybe, Local< T > *local)
Definition api.h:303
ContextDependants
Definition v8-isolate.h:181
bool(*)(Local< Context > accessing_context, Local< Object > accessed_object, Local< Value > data) AccessCheckCallback
void(*)(const char *name, int status) LogEventCallback
CpuProfilingLoggingMode
void(*)(const char *file, int line, const char *message) V8FatalErrorCallback
void(*)(PromiseRejectMessage message) PromiseRejectCallback
Definition v8-promise.h:170
CpuProfilingMode
@ kLeafNodeLineNumbers
static const uintptr_t kAlignmentMask
Definition api.cc:5636
void(*)(Isolate *) CallCompletedCallback
void(*)(void *data) MicrotaskCallback
Intrinsic
Definition v8-template.h:41
void(*)(const char *location, const char *message) FatalErrorCallback
V8_INLINE Local< Primitive > Undefined(Isolate *isolate)
ConstructorBehavior
void(*)(Isolate *, void *) MicrotasksCompletedCallbackWithData
v8::internal::DirectHandle< i::UnionOf< i::Smi, i::Foreign > > FromCData(v8::internal::Isolate *isolate, T obj)
Definition api-inl.h:41
BackingStoreInitializationMode
void(*)(Local< Message > message, Local< Value > data) MessageCallback
void(*)(const FunctionCallbackInfo< Value > &info) FunctionCallback
static V8_INLINE bool InternalFieldOK(i::DirectHandle< i::JSReceiver > obj, int index, const char *location)
Definition api.cc:6282
void(*)(Local< Object > target, AccessType type, Local< Value > data) FailedAccessCheckCallback
static i::DirectHandle< i::EmbedderDataArray > EmbedderDataFor(Context *context, int index, bool can_grow, const char *location)
Definition api.cc:873
ExceptionContext
void(*)(Local< Context > context, Local< Module > module, Local< Object > meta) HostInitializeImportMetaObjectCallback
V8_EXPORT bool TryHandleWebAssemblyTrapWindows(EXCEPTION_POINTERS *exception)
uintptr_t(*)(uintptr_t return_addr_location) ReturnAddressLocationResolver
static const uint16_t * Align(const uint16_t *chars)
Definition api.cc:5641
void(*)(Isolate *isolate, void *data) InterruptCallback
KeyConversionMode
Definition v8-object.h:223
static void WriteHelperV2(i::Isolate *i_isolate, const String *string, CharType *buffer, uint32_t offset, uint32_t length, int flags)
Definition api.cc:5953
int *(*)(const char *name) CounterLookupCallback
CppHeapPointerTag
Definition v8-sandbox.h:28
static ScriptOrigin GetScriptOriginForScript(i::Isolate *i_isolate, i::DirectHandle< i::Script > script)
Definition api.cc:187
bool(*)(Local< Context > context) WasmImportedStringsEnabledCallback
Maybe< void > JustVoid()
Definition v8-maybe.h:157
static void CallGCCallbackWithoutData(Isolate *v8_isolate, GCType type, GCCallbackFlags flags, void *data)
Definition api.cc:9841
void *(*)(const char *name, int min, int max, size_t buckets) CreateHistogramCallback
void RegisterExtension(std::unique_ptr< Extension > extension)
Definition api.cc:486
void(*)(PromiseHookType type, Local< Promise > promise, Local< Value > parent) PromiseHook
Definition v8-promise.h:143
bool(*)(Local< Context > context) SharedArrayBufferConstructorEnabledCallback
NewStringType
v8::Local< T > ToApiHandle(v8::internal::DirectHandle< v8::internal::Object > obj)
Definition api.h:297
bool(*)(unsigned char *buffer, size_t length) EntropySource
static const uintptr_t kOneByteMask
Definition api.cc:5635
static Maybe< bool > ObjectSetAccessor(Local< Context > context, Object *self, Local< Name > name, Getter getter, Setter setter, Data data, PropertyAttribute attributes, bool replace_on_access, SideEffectType getter_side_effect_type, SideEffectType setter_side_effect_type)
Definition api.cc:4914
ModifyCodeGenerationFromStringsResult(*)(Local< Context > context, Local< Value > source, bool is_code_like) ModifyCodeGenerationFromStringsCallback2
Local< Context > NewContext(v8::Isolate *external_isolate, v8::ExtensionConfiguration *extensions, v8::MaybeLocal< ObjectTemplate > global_template, v8::MaybeLocal< Value > global_object, size_t context_snapshot_index, i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer, v8::MicrotaskQueue *microtask_queue)
Definition api.cc:6754
void(*)(Local< Name > property, Local< Value > value, const PropertyCallbackInfo< void > &info) AccessorNameSetterCallback
Definition v8-object.h:158
size_t(*)(void *data, size_t current_heap_limit, size_t initial_heap_limit) NearHeapLimitCallback
CpuProfilingNamingMode
bool(*)(Isolate *isolate, Local< String > script_name) PrintCurrentStackTraceFilterCallback
void(*)(Isolate *) BeforeCallEnteredCallback
uint32_t ProfilerId
Definition v8-profiler.h:32
MemoryPressureLevel
Definition v8-isolate.h:175
static int WriteHelper(i::Isolate *i_isolate, const String *string, CharType *buffer, int start, int length, int options)
Definition api.cc:5920
void(*)(const char *location, const OOMDetails &details) OOMErrorCallback
uint32_t SnapshotObjectId
Definition v8-profiler.h:31
MeasureMemoryExecution
bool CopyAndConvertArrayToCppBuffer(Local< Array > src, T *dst, uint32_t max_length)
Definition api-inl.h:287
static bool Unaligned(const uint16_t *chars)
Definition api.cc:5637
BackingStoreOnFailureMode
static constexpr AcquireLoadTag kAcquireLoad
Definition globals.h:2908
Maybe< T > Just(const T &t)
Definition v8-maybe.h:117
bool(*)(int, void *) CompileHintCallback
ModuleImportPhase
MeasureMemoryMode
bool(*)(Local< Context > context, Local< String > source) AllowWasmCodeGenerationCallback
CodeEventType
@ kUnknownType
PropertyHandlerFlags
StateTag
Definition v8-unwinder.h:36
@ OTHER
Definition v8-unwinder.h:42
ScriptType
Definition v8-script.h:397
PropertyFilter
Definition v8-object.h:179
@ SKIP_SYMBOLS
Definition v8-object.h:185
@ ONLY_ENUMERABLE
Definition v8-object.h:182
RegExpError error_
Node * prev_
#define RCS_SCOPE(...)
#define STATIC_CONST_MEMBER_DEFINITION
#define UNREACHABLE()
Definition logging.h:67
#define FATAL(...)
Definition logging.h:47
#define DCHECK_LE(v1, v2)
Definition logging.h:490
#define CHECK_GE(lhs, rhs)
#define DCHECK_NULL(val)
Definition logging.h:491
#define CHECK_IMPLIES(lhs, rhs)
#define CHECK(condition)
Definition logging.h:124
#define CHECK_LT(lhs, rhs)
#define CHECK_LE(lhs, rhs)
#define DCHECK_NOT_NULL(val)
Definition logging.h:492
#define CHECK_NOT_NULL(val)
#define DCHECK_IMPLIES(v1, v2)
Definition logging.h:493
#define DCHECK_NE(v1, v2)
Definition logging.h:486
#define CHECK_NE(lhs, rhs)
#define DCHECK_GE(v1, v2)
Definition logging.h:488
#define CHECK_EQ(lhs, rhs)
#define DCHECK(condition)
Definition logging.h:482
#define DCHECK_LT(v1, v2)
Definition logging.h:489
#define DCHECK_EQ(v1, v2)
Definition logging.h:485
#define DCHECK_GT(v1, v2)
Definition logging.h:487
#define USE(...)
Definition macros.h:293
#define V8_EXPORT_PRIVATE
Definition macros.h:460
CppHeapPointerTag lower_bound
Definition v8-sandbox.h:74
CppHeapPointerTag upper_bound
Definition v8-sandbox.h:75
const CpuProfilingStatus status
IndexedPropertyQueryCallbackV2 query
IndexedPropertyDeleterCallbackV2 deleter
IndexedPropertyGetterCallbackV2 getter
IndexedPropertyEnumeratorCallback enumerator
IndexedPropertyDescriptorCallbackV2 descriptor
IndexedPropertySetterCallbackV2 setter
IndexedPropertyDefinerCallbackV2 definer
i::DirectHandle< i::JSGlobalProxy > Invoke(i::Isolate *i_isolate, i::MaybeDirectHandle< i::JSGlobalProxy > maybe_global_proxy, v8::Local< v8::ObjectTemplate > global_proxy_template, v8::ExtensionConfiguration *extensions, size_t context_snapshot_index, i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer, v8::MicrotaskQueue *microtask_queue)
Definition api.cc:6633
i::DirectHandle< i::NativeContext > Invoke(i::Isolate *i_isolate, i::MaybeDirectHandle< i::JSGlobalProxy > maybe_global_proxy, v8::Local< v8::ObjectTemplate > global_proxy_template, v8::ExtensionConfiguration *extensions, size_t context_snapshot_index, i::DeserializeEmbedderFieldsCallback embedder_fields_deserializer, v8::MicrotaskQueue *microtask_queue)
Definition api.cc:6618
JSEntryStub js_entry_stub
Definition v8-unwinder.h:70
JSEntryStub js_construct_entry_stub
Definition v8-unwinder.h:71
JSEntryStub js_run_microtasks_entry_stub
Definition v8-unwinder.h:72
NamedPropertyDescriptorCallback descriptor
NamedPropertySetterCallback setter
NamedPropertyDeleterCallback deleter
NamedPropertyEnumeratorCallback enumerator
NamedPropertyQueryCallback query
NamedPropertyGetterCallback getter
NamedPropertyDefinerCallback definer
RegisterState & operator=(const RegisterState &other)
Definition api.cc:11911
std::unique_ptr< CalleeSavedRegisters > callee_saved
Definition v8-unwinder.h:32
size_t frames_count
Definition v8-unwinder.h:51
void * external_callback_entry
Definition v8-unwinder.h:52
StateTag vm_state
Definition v8-unwinder.h:56
CompatibilityCheckResult CompatibilityCheck(Isolate *isolate)
Definition api.cc:1747
i::ValueDeserializer deserializer
Definition api.cc:3388
PrivateData(i::Isolate *i_isolate, base::Vector< const uint8_t > data, Delegate *delegate)
Definition api.cc:3384
i::ValueSerializer serializer
Definition api.cc:3291
PrivateData(i::Isolate *i, ValueSerializer::Delegate *delegate)
Definition api.cc:3288
MaybeHandle< FixedArray > wrapped_arguments
static LongTaskStats Get(Isolate *isolate)
Definition api.cc:7342
i::PropertyDescriptor desc
Definition api.cc:4402
#define TRACE_EVENT0(category_group, name)
#define TRACE_DISABLED_BY_DEFAULT(name)
#define TRACE_EVENT_CALL_STATS_SCOPED(isolate, category_group, name)
#define PLUS_ONE(...)
#define CODE_EVENTS_LIST(V)
#define V8_EXPORT
Definition v8config.h:800
#define V8_INLINE
Definition v8config.h:500
#define END_ALLOW_USE_DEPRECATED()
Definition v8config.h:634
#define V8_LIKELY(condition)
Definition v8config.h:661
#define V8_WARN_UNUSED_RESULT
Definition v8config.h:671
#define V8_UNLIKELY(condition)
Definition v8config.h:660
#define START_ALLOW_USE_DEPRECATED()
Definition v8config.h:633
std::unique_ptr< ValueMirror > value
std::unique_ptr< ValueMirror > key
std::shared_ptr< const char[]> source_url_
wasm::ValueType type