18#include <unordered_map>
22#ifdef ENABLE_VTUNE_JIT_INTERFACE
23#include "third_party/vtune/v8-vtune.h"
79#include <mach/task_policy.h>
82#ifdef V8_ENABLE_MAGLEV
86#ifdef V8_ENABLE_PARTITION_ALLOC
87#include <partition_alloc/shim/allocator_shim_default_dispatch_to_partition_alloc.h>
100#include "perfetto/tracing/track_event.h"
101#include "perfetto/tracing/track_event_legacy.h"
104#ifdef V8_INTL_SUPPORT
105#include "unicode/locid.h"
112#if defined(V8_OS_WIN)
118#if V8_ENABLE_WEBASSEMBLY
123#define DCHECK(condition) assert(condition)
127#define CHECK(condition) assert(condition)
135thread_local Worker* current_worker_ =
nullptr;
138bool fuzzilli_reprl =
true;
140bool fuzzilli_reprl =
false;
147 void* Allocate(
size_t length)
override {
151 void* AllocateUninitialized(
size_t length)
override {
152 return allocator_->AllocateUninitialized(length);
155 void Free(
void* data,
size_t length)
override {
159 PageAllocator* GetPageAllocator()
override {
165 std::unique_ptr<Allocator>(NewDefaultAllocator());
169class ShellArrayBufferAllocator :
public ArrayBufferAllocatorBase {
171 void* Allocate(
size_t length)
override {
172 if (length >= kVMThreshold)
return AllocateVM(length);
173 return ArrayBufferAllocatorBase::Allocate(length);
176 void* AllocateUninitialized(
size_t length)
override {
177 if (length >= kVMThreshold)
return AllocateVM(length);
178 return ArrayBufferAllocatorBase::AllocateUninitialized(length);
181 void Free(
void* data,
size_t length)
override {
182 if (length >= kVMThreshold) {
183 FreeVM(data, length);
185 ArrayBufferAllocatorBase::Free(data, length);
190 static constexpr size_t kVMThreshold = 65536;
192 void* AllocateVM(
size_t length) {
196 size_t allocated =
RoundUp(length, page_size);
201 void FreeVM(
void* data,
size_t length) {
204 size_t allocated =
RoundUp(length, page_size);
210class MockArrayBufferAllocator :
public ArrayBufferAllocatorBase {
212 void* Allocate(
size_t length)
override {
213 return ArrayBufferAllocatorBase::Allocate(Adjust(length));
216 void* AllocateUninitialized(
size_t length)
override {
217 return ArrayBufferAllocatorBase::AllocateUninitialized(Adjust(length));
220 void Free(
void* data,
size_t length)
override {
221 return ArrayBufferAllocatorBase::Free(data, Adjust(length));
225 size_t Adjust(
size_t length) {
226 const size_t kAllocationLimit = 10 *
i::MB;
233class MockArrayBufferAllocatiorWithLimit :
public MockArrayBufferAllocator {
235 explicit MockArrayBufferAllocatiorWithLimit(
size_t allocation_limit)
236 :
limit_(allocation_limit), space_left_(allocation_limit) {}
239 void* Allocate(
size_t length)
override {
240 if (length > space_left_) {
244 return MockArrayBufferAllocator::Allocate(length);
247 void* AllocateUninitialized(
size_t length)
override {
248 if (length > space_left_) {
252 return MockArrayBufferAllocator::AllocateUninitialized(length);
255 void Free(
void* data,
size_t length)
override {
257 return MockArrayBufferAllocator::Free(data, length);
260 size_t MaxAllocationSize()
const override {
return limit_; }
264 std::atomic<size_t> space_left_;
277class MultiMappedAllocator :
public ArrayBufferAllocatorBase {
279 void* Allocate(
size_t length)
override {
280 if (length < kChunkSize) {
281 return ArrayBufferAllocatorBase::Allocate(length);
284 return AllocateUninitialized(length);
287 void* AllocateUninitialized(
size_t length)
override {
288 if (length < kChunkSize) {
289 return ArrayBufferAllocatorBase::AllocateUninitialized(length);
291 size_t rounded_length =
RoundUp(length, kChunkSize);
292 int prot = PROT_READ | PROT_WRITE;
294 int flags = MAP_SHARED | MAP_ANONYMOUS;
295 void* real_alloc = mmap(
nullptr, kChunkSize, prot, flags, -1, 0);
296 if (
reinterpret_cast<intptr_t
>(real_alloc) == -1) {
299 if (errno == ENOMEM) {
303 FATAL(
"mmap (real) failed with error %d: %s", errno, strerror(errno));
305#ifdef V8_ENABLE_SANDBOX
312 VirtualAddressSpace* vas = i::Sandbox::current()->address_space();
313 i::Address in_sandbox_page_reservation = vas->AllocatePages(
314 VirtualAddressSpace::kNoHint, rounded_length,
315 vas->allocation_granularity(), PagePermissions::kNoAccess);
316 void* virtual_alloc =
317 in_sandbox_page_reservation != 0
318 ?
reinterpret_cast<void*
>(in_sandbox_page_reservation)
319 :
reinterpret_cast<void*
>(-1);
321 void* virtual_alloc =
322 mmap(
nullptr, rounded_length, prot, flags | MAP_NORESERVE, -1, 0);
324 if (
reinterpret_cast<intptr_t
>(virtual_alloc) == -1) {
325 if (errno == ENOMEM) {
327 munmap(real_alloc, kChunkSize);
330 FATAL(
"mmap (virtual) failed with error %d: %s", errno, strerror(errno));
333 i::Address virtual_end = virtual_base + rounded_length;
334 for (
i::Address to_map = virtual_base; to_map < virtual_end;
335 to_map += kChunkSize) {
340 mremap(real_alloc, 0, kChunkSize, MREMAP_MAYMOVE | MREMAP_FIXED,
341 reinterpret_cast<void*
>(to_map));
342 if (
reinterpret_cast<intptr_t
>(
result) == -1) {
343 if (errno == ENOMEM) {
345 munmap(real_alloc, kChunkSize);
346#ifdef V8_ENABLE_SANDBOX
347 vas->FreePages(in_sandbox_page_reservation, rounded_length);
349 munmap(virtual_alloc, rounded_length);
353 FATAL(
"mremap failed with error %d: %s", errno, strerror(errno));
356 base::MutexGuard lock_guard(®ions_mutex_);
357 regions_[virtual_alloc] = real_alloc;
358 return virtual_alloc;
361 void Free(
void* data,
size_t length)
override {
362 if (length < kChunkSize) {
363 return ArrayBufferAllocatorBase::Free(data, length);
365 base::MutexGuard lock_guard(®ions_mutex_);
366 void* real_alloc = regions_[
data];
367 munmap(real_alloc, kChunkSize);
368 size_t rounded_length =
RoundUp(length, kChunkSize);
369#ifdef V8_ENABLE_SANDBOX
370 VirtualAddressSpace* vas = i::Sandbox::current()->address_space();
371 vas->FreePages(
reinterpret_cast<i::Address>(data), rounded_length);
373 munmap(data, rounded_length);
375 regions_.erase(data);
380 static constexpr size_t kChunkSize = 2 * 1024 * 1024;
382 std::unordered_map<void*, void*> regions_;
383 base::Mutex regions_mutex_;
389std::unique_ptr<v8::Platform> g_platform;
392void ThrowError(Isolate* isolate,
const char (&message)[N]) {
393 if (isolate->IsExecutionTerminating())
return;
394 isolate->ThrowError(message);
397void ThrowError(Isolate* isolate, Local<String> message) {
398 if (isolate->IsExecutionTerminating())
return;
399 isolate->ThrowError(message);
402void ThrowException(Isolate* isolate, Local<Value> exception) {
403 if (isolate->IsExecutionTerminating())
return;
404 isolate->ThrowException(exception);
407static MaybeLocal<Value> TryGetValue(
v8::Isolate* isolate,
408 Local<Context> context,
409 Local<v8::Object>
object,
410 const char* property) {
412 if (v8_str.IsEmpty())
return {};
413 return object->Get(context, v8_str.ToLocalChecked());
416static Local<Value> GetValue(
v8::Isolate* isolate, Local<Context> context,
417 Local<v8::Object>
object,
const char* property) {
418 return TryGetValue(isolate, context,
object, property).ToLocalChecked();
421std::shared_ptr<Worker> GetWorkerFromInternalField(Isolate* isolate,
422 Local<Object>
object) {
423 if (object->InternalFieldCount() != 1) {
424 ThrowError(isolate,
"this is not a Worker");
430 if (IsSmi(*handle)) {
431 ThrowError(isolate,
"Worker is defunct because main thread is terminating");
435 return managed->get();
438base::Thread::Options GetThreadOptions(
const char* name) {
443 return base::Thread::Options(name, 2 * i::MB);
452static constexpr char kIncludedCategoriesParam[] =
"included_categories";
453static constexpr char kTraceConfigParam[] =
"trace_config";
455class TraceConfigParser {
458 platform::tracing::TraceConfig* trace_config,
459 const char* json_str) {
460 HandleScope outer_scope(isolate);
462 Context::Scope context_scope(context);
463 HandleScope inner_scope(isolate);
465 Local<String> source =
471 Local<Value> maybe_trace_config_object =
472 GetValue(isolate, context, trace_config_object, kTraceConfigParam);
473 if (maybe_trace_config_object->IsObject()) {
474 trace_config_object = maybe_trace_config_object.As<Object>();
477 UpdateIncludedCategoriesList(isolate, context, trace_config_object,
482 static int UpdateIncludedCategoriesList(
483 v8::Isolate* isolate, Local<Context> context, Local<v8::Object>
object,
484 platform::tracing::TraceConfig* trace_config) {
486 GetValue(isolate, context,
object, kIncludedCategoriesParam);
487 if (value->IsArray()) {
488 Local<Array> v8_array = value.As<Array>();
489 for (
int i = 0, length = v8_array->Length();
i < length; ++
i) {
490 Local<Value> v = v8_array->Get(context,
i)
494 String::Utf8Value str(isolate, v->ToString(context).ToLocalChecked());
495 trace_config->AddIncludedCategory(*str);
497 return v8_array->Length();
509 TraceConfigParser::FillTraceConfig(isolate, trace_config, json_str);
520 std::unique_ptr<base::OS::MemoryMappedFile> file)
522 const char*
data()
const override {
523 return static_cast<char*
>(
file_->memory());
528 std::unique_ptr<base::OS::MemoryMappedFile>
file_;
550std::map<std::string, std::unique_ptr<ScriptCompiler::CachedData>>
563 reinterpret_cast<i::Isolate*
>(isolate)->main_thread_local_isolate(),
565 CHECK(source->IsString());
570 int length = entry->second->length;
571 uint8_t* cache =
new uint8_t[
length];
572 memcpy(cache, entry->second->data, length);
583 reinterpret_cast<i::Isolate*
>(isolate)->main_thread_local_isolate(),
585 CHECK(source->IsString());
586 if (cache_data ==
nullptr)
return;
589 int length = cache_data->
length;
590 uint8_t* cache =
new uint8_t[
length];
591 memcpy(cache, cache_data->
data, length);
629 CHECK(thread.Start());
650MaybeLocal<Script> CompileStreamed(Local<Context> context,
651 ScriptCompiler::StreamedSource* v8_source,
652 Local<String> full_source_string,
653 const ScriptOrigin& origin) {
659MaybeLocal<Module> CompileStreamed(Local<Context> context,
660 ScriptCompiler::StreamedSource* v8_source,
661 Local<String> full_source_string,
662 const ScriptOrigin& origin) {
668MaybeLocal<T> Compile(Local<Context> context, ScriptCompiler::Source* source,
671MaybeLocal<Script> Compile(Local<Context> context,
672 ScriptCompiler::Source* source,
678MaybeLocal<Module> Compile(Local<Context> context,
679 ScriptCompiler::Source* source,
690 if (options.streaming_compile) {
692 std::make_unique<DummySourceStream>(isolate, source),
694 std::unique_ptr<v8::ScriptCompiler::ScriptStreamingTask> streaming_task(
696 std::is_same_v<T, Module>
700 return CompileStreamed<T>(context, &streamed_source, source, origin);
709 Compile<T>(context, &script_source,
718const int kHostDefinedOptionsLength = 2;
719const uint32_t kHostDefinedOptionsMagicConstant = 0xF1F2F3F0;
721const char kDataURLPrefix[] =
"data:text/javascript,";
732class ModuleEmbedderData {
734 class ModuleGlobalHash {
736 explicit ModuleGlobalHash(Isolate* isolate) :
isolate_(isolate) {}
737 size_t operator()(
const Global<Module>& module)
const {
738 return module.Get(isolate_)->GetIdentityHash();
749 explicit ModuleEmbedderData(Isolate* isolate)
751 module_to_specifier_map(10, ModuleGlobalHash(isolate)),
752 json_module_to_parsed_json_map(
753 10, module_to_specifier_map.hash_function()) {}
755 std::string GetModuleSpecifier(Local<Module> module) {
756 Global<Module> global_module(isolate_, module);
757 auto specifier_it = module_to_specifier_map.find(global_module);
758 CHECK(specifier_it != module_to_specifier_map.end());
759 return specifier_it->second;
762 Local<Module> GetModule(
763 std::pair<std::string, ModuleType> module_specifier_and_type) {
764 auto module_it = module_map.find(module_specifier_and_type);
765 CHECK(module_it != module_map.end());
766 return module_it->second.Get(isolate_);
769 Local<Object> GetModuleSource(
770 std::pair<std::string, ModuleType> module_specifier_and_type) {
771 auto module_source_it = module_source_map.find(module_specifier_and_type);
772 CHECK(module_source_it != module_source_map.end());
773 return module_source_it->second.Get(isolate_);
776 Local<Value> GetJsonModuleValue(Local<Module> module) {
778 json_module_to_parsed_json_map.find(Global<Module>(isolate_, module));
779 CHECK(json_value_it != json_module_to_parsed_json_map.end());
780 return json_value_it->second.Get(isolate_);
783 static ModuleType ModuleTypeFromImportSpecifierAndAttributes(
784 Local<Context> context,
const std::string& specifier,
785 Local<FixedArray> import_attributes,
bool hasPositions) {
786 Isolate* isolate = context->GetIsolate();
787 const int kV8AssertionEntrySize = hasPositions ? 3 : 2;
788 for (
int i = 0;
i < import_attributes->Length();
789 i += kV8AssertionEntrySize) {
790 Local<String> v8_assertion_key =
791 import_attributes->Get(context,
i).As<
v8::String>();
792 std::string assertion_key = ToSTLString(isolate, v8_assertion_key);
794 if (assertion_key ==
"type") {
795 Local<String> v8_assertion_value =
796 import_attributes->Get(context,
i + 1).As<
String>();
797 std::string assertion_value = ToSTLString(isolate, v8_assertion_value);
798 if (assertion_value ==
"json") {
808 if (specifier.ends_with(
".wasm")) {
816 std::map<std::pair<std::string, ModuleType>, Global<Module>> module_map;
818 std::map<std::pair<std::string, ModuleType>, Global<Object>>
821 std::unordered_map<Global<Module>, std::string, ModuleGlobalHash>
822 module_to_specifier_map;
825 std::unordered_map<Global<Module>, Global<Value>, ModuleGlobalHash>
826 json_module_to_parsed_json_map;
832enum { kModuleEmbedderDataIndex, kInspectorClientIndex };
834std::shared_ptr<ModuleEmbedderData> InitializeModuleEmbedderData(
835 Local<Context> context) {
837 const size_t kModuleEmbedderDataEstimate = 4 * 1024;
840 i_isolate, kModuleEmbedderDataEstimate,
841 std::make_shared<ModuleEmbedderData>(context->GetIsolate()));
843 context->SetEmbedderData(kModuleEmbedderDataIndex, module_data);
844 return module_data_managed->get();
847std::shared_ptr<ModuleEmbedderData> GetModuleDataFromContext(
848 Local<Context> context) {
850 context->GetEmbedderData(kModuleEmbedderDataIndex);
854 return module_data_managed->get();
857ScriptOrigin CreateScriptOrigin(Isolate* isolate, Local<String> resource_name,
859 Local<PrimitiveArray> options =
861 options->Set(isolate, 0,
863 options->Set(isolate, 1, resource_name);
864 return ScriptOrigin(resource_name, 0, 0,
false, -1, Local<Value>(),
false,
868bool IsValidHostDefinedOptions(Local<Context> context, Local<Data> options,
869 Local<Value> resource_name) {
870 if (!options->IsFixedArray())
return false;
871 Local<FixedArray> array = options.As<
FixedArray>();
872 if (array->Length() != kHostDefinedOptionsLength)
return false;
874 if (!array->Get(context, 0).As<Value>()->Uint32Value(context).To(&magic)) {
877 if (magic != kHostDefinedOptionsMagicConstant)
return false;
878 return array->Get(context, 1).As<
String>()->StrictEquals(resource_name);
881class D8WasmAsyncResolvePromiseTask :
public v8::Task {
883 D8WasmAsyncResolvePromiseTask(
v8::Isolate* isolate,
894 void Run()
override {
898 MicrotasksScope microtasks_scope(context,
904 ? resolver->Resolve(context,
result)
905 : resolver->Reject(context,
result);
908 CHECK(ret.IsJust() ? ret.FromJust() :
isolate_->IsExecutionTerminating());
919void D8WasmAsyncResolvePromiseCallback(
926 g_platform->GetForegroundTaskRunner(isolate)->PostTask(
927 std::make_unique<D8WasmAsyncResolvePromiseTask>(
928 isolate, context, resolver,
result, success));
949 i::UnoptimizedCompileFlags::ForToplevelCompile(
954 flags.set_is_eager(
true);
957 i::ParseInfo parse_info(i_isolate, flags, &compile_state, &reusable_state);
961 if (!i::parsing::ParseProgram(&parse_info, script, i_isolate,
962 i::parsing::ReportStatisticsMode::kYes)) {
967 fprintf(stderr,
"Failed parsing\n");
992 std::shared_ptr<ModuleEmbedderData> module_data =
993 GetModuleDataFromContext(realm);
994 module_data->origin = ToSTLString(isolate, name);
996 for (
int i = 1;
i < options.repeat_compile; ++
i) {
1008 if (options.code_cache_options ==
1016 if (options.compile_only)
return true;
1029 if (options.code_cache_options ==
1031 !isolate->IsExecutionTerminating()) {
1038 data->realm_current_ = data->realm_switch_;
1046 isolate->TerminateExecution();
1051 }
else if (out_result !=
nullptr) {
1061bool IsAbsolutePath(
const std::string& path) {
1062#if defined(V8_OS_WIN)
1065 return path.find(
':') != std::string::npos;
1067 return path[0] ==
'/';
1071std::string GetWorkingDirectory() {
1072#if defined(V8_OS_WIN)
1073 char system_buffer[MAX_PATH];
1076 DWORD len = GetCurrentDirectoryA(MAX_PATH, system_buffer);
1078 return system_buffer;
1080 char curdir[PATH_MAX];
1087std::string DirName(
const std::string& path) {
1088 DCHECK(IsAbsolutePath(path));
1089 size_t last_slash = path.find_last_of(
'/');
1090 DCHECK(last_slash != std::string::npos);
1091 return path.substr(0, last_slash);
1097std::string NormalizePath(
const std::string& path,
1098 const std::string& dir_name) {
1099 std::string absolute_path;
1100 if (IsAbsolutePath(path)) {
1101 absolute_path = path;
1103 absolute_path = dir_name +
'/' + path;
1105 std::replace(absolute_path.begin(), absolute_path.end(),
'\\',
'/');
1106 std::vector<std::string> segments;
1107 std::istringstream segment_stream(absolute_path);
1108 std::string segment;
1109 while (std::getline(segment_stream, segment,
'/')) {
1110 if (segment ==
"..") {
1111 if (!segments.empty()) segments.pop_back();
1112 }
else if (segment !=
".") {
1113 segments.push_back(segment);
1117 std::ostringstream os;
1118 if (segments.size() > 1) {
1119 std::copy(segments.begin(), segments.end() - 1,
1120 std::ostream_iterator<std::string>(os,
"/"));
1121 os << *segments.rbegin();
1124 if (!segments.empty()) os << segments[0];
1134std::string NormalizeModuleSpecifier(
const std::string& specifier,
1135 const std::string& dir_name) {
1136 if (specifier.starts_with(kDataURLPrefix))
return specifier;
1137 return NormalizePath(specifier, dir_name);
1140MaybeLocal<Module> ResolveModuleCallback(Local<Context> context,
1141 Local<String> specifier,
1142 Local<FixedArray> import_attributes,
1143 Local<Module> referrer) {
1144 Isolate* isolate = context->GetIsolate();
1145 std::shared_ptr<ModuleEmbedderData> module_data =
1146 GetModuleDataFromContext(context);
1147 std::string referrer_specifier = module_data->GetModuleSpecifier(referrer);
1149 std::string stl_specifier = ToSTLString(isolate, specifier);
1150 std::string absolute_path =
1151 NormalizeModuleSpecifier(stl_specifier, DirName(referrer_specifier));
1153 ModuleEmbedderData::ModuleTypeFromImportSpecifierAndAttributes(
1154 context, stl_specifier, import_attributes,
true);
1155 return module_data->GetModule(std::make_pair(absolute_path, module_type));
1158MaybeLocal<Object> ResolveModuleSourceCallback(
1159 Local<Context> context, Local<String> specifier,
1160 Local<FixedArray> import_attributes, Local<Module> referrer) {
1161 Isolate* isolate = context->GetIsolate();
1162 std::shared_ptr<ModuleEmbedderData> module_data =
1163 GetModuleDataFromContext(context);
1164 std::string referrer_specifier = module_data->GetModuleSpecifier(referrer);
1166 std::string stl_specifier = ToSTLString(isolate, specifier);
1167 std::string absolute_path =
1168 NormalizeModuleSpecifier(stl_specifier, DirName(referrer_specifier));
1170 ModuleEmbedderData::ModuleTypeFromImportSpecifierAndAttributes(
1171 context, stl_specifier, import_attributes,
true);
1173 return module_data->GetModuleSource(
1174 std::make_pair(absolute_path, module_type));
1181 const std::string& module_specifier,
1183 Isolate* isolate = context->GetIsolate();
1184 DCHECK(IsAbsolutePath(module_specifier));
1185 auto file =
ReadFileData(isolate, module_specifier.c_str());
1187 std::shared_ptr<ModuleEmbedderData> module_data =
1188 GetModuleDataFromContext(context);
1190 std::string msg =
"d8: Error reading module from " + module_specifier;
1192 std::string referrer_specifier =
1193 module_data->GetModuleSpecifier(referrer);
1194 msg +=
"\n imported by " + referrer_specifier;
1202 switch (module_type) {
1208 .ToLocal(&module_source)) {
1220 isolate,
"Module source can not be imported for type")));
1225 module_data->module_source_map
1226 .insert(std::make_pair(std::make_pair(module_specifier, module_type),
1229 return module_source;
1235 const std::string& module_specifier,
1237 Isolate* isolate = context->GetIsolate();
1238 const bool is_data_url = module_specifier.starts_with(kDataURLPrefix);
1242 isolate, module_specifier.c_str() + strlen(kDataURLPrefix));
1244 DCHECK(IsAbsolutePath(module_specifier));
1245 source_text =
ReadFile(isolate, module_specifier.c_str(),
false);
1246 if (source_text.
IsEmpty() && options.fuzzy_module_file_extensions) {
1247 std::string fallback_file_name = module_specifier +
".js";
1248 source_text =
ReadFile(isolate, fallback_file_name.c_str(),
false);
1250 fallback_file_name = module_specifier +
".mjs";
1251 source_text =
ReadFile(isolate, fallback_file_name.c_str());
1256 std::shared_ptr<ModuleEmbedderData> module_data =
1257 GetModuleDataFromContext(context);
1259 std::string msg =
"d8: Error reading module from " + module_specifier;
1261 std::string referrer_specifier =
1262 module_data->GetModuleSpecifier(referrer);
1263 msg +=
"\n imported by " + referrer_specifier;
1280 .ToLocal(&module)) {
1298 CHECK(module_data->json_module_to_parsed_json_map
1307 module_data->module_map
1308 .insert(std::make_pair(std::make_pair(module_specifier, module_type),
1311 CHECK(module_data->module_to_specifier_map
1317 if (is_data_url)
return module;
1319 std::string dir_name = DirName(module_specifier);
1322 for (
int i = 0, length = module_requests->Length();
i < length; ++
i) {
1325 std::string specifier =
1326 ToSTLString(isolate, module_request->GetSpecifier());
1327 std::string normalized_specifier =
1328 NormalizeModuleSpecifier(specifier, dir_name);
1331 ModuleEmbedderData::ModuleTypeFromImportSpecifierAndAttributes(
1332 context, normalized_specifier, import_attributes,
true);
1335 ThrowError(isolate,
"Invalid module type was asserted");
1340 if (module_data->module_source_map.count(
1341 std::make_pair(normalized_specifier, request_module_type))) {
1346 request_module_type)
1351 if (module_data->module_map.count(
1352 std::make_pair(normalized_specifier, request_module_type))) {
1357 request_module_type)
1369 Isolate* isolate = context->GetIsolate();
1371 std::shared_ptr<ModuleEmbedderData> module_data =
1372 GetModuleDataFromContext(context);
1373 Local<Value> json_value = module_data->GetJsonModuleValue(module);
1378 String::NewFromUtf8Literal(isolate, "default",
1379 NewStringType::kInternalized),
1388 resolver->Resolve(context,
Undefined(isolate)).ToChecked();
1389 return resolver->GetPromise();
1400 referrer.Reset(isolate, referrer_);
1419enum ModuleResolutionDataIndex : uint32_t {
1421 kNamespaceOrSource = 1,
1435 module_resolution_data->Get(context, ModuleResolutionDataIndex::kResolver)
1439 module_resolution_data
1440 ->Get(context, ModuleResolutionDataIndex::kNamespaceOrSource)
1444 Local<Context> realm = data->realms_[data->realm_current_].Get(isolate);
1447 resolver->Resolve(realm, namespace_or_source).ToChecked();
1459 module_resolution_data->Get(context, ModuleResolutionDataIndex::kResolver)
1464 Local<Context> realm = data->realms_[data->realm_current_].Get(isolate);
1468 resolver->Reject(realm, info[0]).ToChecked();
1476 context, host_defined_options, resource_name, specifier,
1484 Isolate* isolate = context->GetIsolate();
1491 if (!resource_name->IsNull() &&
1492 !IsValidHostDefinedOptions(context, host_defined_options,
1496 isolate,
"Invalid host defined options")))
1501 import_attributes, resolver);
1505 return resolver->GetPromise();
1511 Isolate* isolate = context->GetIsolate();
1514 std::shared_ptr<ModuleEmbedderData> module_data =
1515 GetModuleDataFromContext(context);
1516 std::string specifier = module_data->GetModuleSpecifier(module);
1522 meta->CreateDataProperty(context, url_key, url).ToChecked();
1528 std::shared_ptr<ModuleEmbedderData> shadow_realm_data =
1529 InitializeModuleEmbedderData(context);
1530 std::shared_ptr<ModuleEmbedderData> initiator_data =
1531 GetModuleDataFromContext(initiator_context);
1535 context->SetSecurityToken(initiator_context->GetSecurityToken());
1536 shadow_realm_data->origin = initiator_data->origin;
1542void RejectPromiseIfExecutionIsNotTerminating(
Isolate* isolate,
1547 if (isolate->IsExecutionTerminating()) {
1550 resolver->Reject(realm, try_catch.
Exception()).ToChecked();
1554Maybe<bool> ChainDynamicImportPromise(Isolate* isolate, Local<Context> realm,
1556 Local<Promise> result_promise,
1557 Local<Value> namespace_or_source) {
1559 if (module_resolution_data->SetPrototypeV2(realm,
v8::Null(isolate))
1563 if (module_resolution_data
1564 ->Set(realm, ModuleResolutionDataIndex::kResolver, resolver)
1568 if (module_resolution_data
1569 ->Set(realm, ModuleResolutionDataIndex::kNamespaceOrSource,
1570 namespace_or_source)
1574 Local<Function> callback_success;
1576 module_resolution_data)
1577 .
ToLocal(&callback_success)) {
1581 Local<Function> callback_failure;
1583 module_resolution_data)
1584 .
ToLocal(&callback_failure)) {
1587 if (result_promise->Then(realm, callback_success, callback_failure)
1618 global_realm.
Reset(isolate, realm);
1619 global_resolver.
Reset(isolate, resolver);
1622 data->DeleteDynamicImportData(import_data_);
1625 std::string specifier = ToSTLString(isolate, v8_specifier);
1628 ModuleEmbedderData::ModuleTypeFromImportSpecifierAndAttributes(
1629 realm, specifier, import_attributes,
false);
1632 ThrowError(isolate,
"Invalid module type was asserted");
1633 RejectPromiseIfExecutionIsNotTerminating(isolate, realm, resolver,
1638 std::shared_ptr<ModuleEmbedderData> module_data =
1639 GetModuleDataFromContext(realm);
1641 std::string source_url = referrer->IsNull()
1642 ? module_data->origin
1643 : ToSTLString(isolate, referrer.
As<
String>());
1644 std::string dir_name =
1645 DirName(NormalizePath(source_url, GetWorkingDirectory()));
1646 std::string absolute_path = NormalizeModuleSpecifier(specifier, dir_name);
1651 auto module_it = module_data->module_source_map.find(
1652 std::make_pair(absolute_path, module_type));
1653 if (module_it != module_data->module_source_map.end()) {
1654 module_source = module_it->second.Get(isolate);
1662 module_resolver->Resolve(realm, module_source).ToChecked();
1664 global_namespace_or_source.
Reset(isolate, module_source);
1665 global_result_promise.
Reset(isolate, module_resolver->GetPromise());
1670 auto module_it = module_data->module_map.find(
1671 std::make_pair(absolute_path, module_type));
1672 if (module_it != module_data->module_map.end()) {
1673 root_module = module_it->second.Get(isolate);
1680 ->InstantiateModule(realm, ResolveModuleCallback,
1681 ResolveModuleSourceCallback)
1682 .FromMaybe(
false)) {
1684 if (maybe_result.
IsEmpty())
break;
1685 global_result_promise.
Reset(
1687 global_namespace_or_source.
Reset(isolate,
1688 root_module->GetModuleNamespace());
1698 if (global_result_promise.
IsEmpty()) {
1702 RejectPromiseIfExecutionIsNotTerminating(isolate, realm, resolver,
1714 heap, i::EmbedderStackStateOrigin::kExplicitInvocation,
1715 StackState::kMayContainHeapPointers);
1724 Local<Value> namespace_or_source = global_namespace_or_source.
Get(isolate);
1731 if (ChainDynamicImportPromise(isolate, realm, resolver, result_promise,
1732 namespace_or_source)
1734 RejectPromiseIfExecutionIsNotTerminating(isolate, realm, resolver,
1752 Local<Context> realm = data->realms_[data->realm_current_].Get(isolate);
1755 std::string absolute_path =
1756 NormalizeModuleSpecifier(file_name, GetWorkingDirectory());
1758 std::shared_ptr<ModuleEmbedderData> module_data =
1759 GetModuleDataFromContext(realm);
1761 auto module_it = module_data->module_map.find(
1763 if (module_it != module_data->module_map.end()) {
1764 root_module = module_it->second.Get(isolate);
1772 global_root_module.
Reset(isolate, root_module);
1774 module_data->origin = absolute_path;
1778 ->InstantiateModule(realm, ResolveModuleCallback,
1779 ResolveModuleSourceCallback)
1780 .FromMaybe(
false)) {
1781 maybe_result = root_module->Evaluate(realm);
1783 global_result_promise.
Reset(isolate,
1788 if (!global_result_promise.
IsEmpty()) {
1797 while (isolate->HasPendingBackgroundTasks() ||
1798 (i::ValueHelper::HandleAsValue(global_result_promise)->State() ==
1801 ->default_microtask_queue()
1816 isolate->ThrowException(result_promise->Result());
1824 auto [stalled_modules, stalled_messages] =
1825 root_module->GetStalledTopLevelAwaitMessages(isolate);
1826 DCHECK_EQ(stalled_modules.size(), stalled_messages.size());
1827 if (stalled_messages.size() > 0) {
1847 std::string absolute_path = NormalizePath(file_name, GetWorkingDirectory());
1849 std::unique_ptr<char[]>
data(
ReadChars(absolute_path.c_str(), &length));
1851 printf(
"Error reading '%s'\n", file_name);
1854 std::stringstream stream(data.get());
1856 while (std::getline(stream, line,
'\n')) {
1863 if (!maybe_value.
ToLocal(&value)) {
1874 :
isolate_(isolate), realms_(nullptr) {
1887#if defined(LEAK_SANITIZER)
1901 if (unhandled_promise == promise) {
1933 return static_cast<int>(
i);
1937#if defined(LEAK_SANITIZER)
1938 import_data_.insert(data);
1942#if defined(LEAK_SANITIZER)
1943 import_data_.erase(data);
1982 "Trying to subscribe to message events from a terminated worker -- "
1983 "consider registering the event handler before the event loop runs.\n");
1992 const std::shared_ptr<Worker>& worker)
const {
2017 data_->realm_count_ = 0;
2018 delete[]
data_->realms_;
2027 data->realm_current_ = data->realm_switch_ =
index_;
2032 data_->realm_current_ =
data_->realm_switch_ = previous_index_;
2048 if (info.Length() < arg_offset || !info[arg_offset]->IsNumber()) {
2049 ThrowError(info.GetIsolate(),
"Invalid argument");
2052 int index = info[arg_offset]
2053 ->Int32Value(info.GetIsolate()->GetCurrentContext())
2056 ThrowError(info.GetIsolate(),
"Invalid realm index");
2067 return g_platform->MonotonicallyIncreasingTime();
2074 double performance_timestamp) {
2081 int64_t internal_value = (delta + kInitialTicks).ToInternalValue();
2083 return internal_value;
2087void SendPerfControlCommand(
const char* command) {
2089 size_t command_len = strlen(command);
2090 ssize_t ret = write(
Shell::options.perf_ctl_fd, command, command_len);
2092 fprintf(stderr,
"perf_ctl write error: %s\n", strerror(errno));
2099 fprintf(stderr,
"perf_ack read error: %s\n", strerror(errno));
2110 info.GetReturnValue().Set(GetTimestamp());
2117 Isolate* isolate = info.GetIsolate();
2120 if (info.Length() < 1 || !info[0]->IsString()) {
2121 ThrowError(info.GetIsolate(),
"Invalid 'name' argument");
2126 double timestamp = GetTimestamp();
2130 ->DefineOwnProperty(context,
2139 ->DefineOwnProperty(context,
2144 ->DefineOwnProperty(context,
2149 info.GetReturnValue().Set(performance_entry);
2152 if (options.scope_linux_perf_to_mark_measure) {
2153 SendPerfControlCommand(
"enable");
2163 Isolate* isolate = info.GetIsolate();
2166 if (info.Length() < 1 || !info[0]->IsString()) {
2167 ThrowError(info.GetIsolate(),
"Invalid 'name' argument");
2172 double start_timestamp = 0;
2173 if (info.Length() >= 2) {
2175 if (options.scope_linux_perf_to_mark_measure) {
2176 SendPerfControlCommand(
"disable");
2181 if (!start_mark->IsObject()) {
2182 ThrowError(info.GetIsolate(),
2183 "Invalid 'startMark' argument: Not an Object");
2189 .
ToLocal(&start_time_field)) {
2192 if (!start_time_field->IsNumber()) {
2193 ThrowError(info.GetIsolate(),
2194 "Invalid 'startMark' argument: No numeric 'startTime' field");
2199 if (info.Length() > 2) {
2200 ThrowError(info.GetIsolate(),
"Too many arguments");
2204 double end_timestamp = GetTimestamp();
2206 if (options.trace_enabled) {
2212 "v8", *utf8,
static_cast<uint64_t
>(hash),
2213 GetTracingTimestampFromPerformanceTimestamp(start_timestamp),
2214 "startTime", start_timestamp);
2216 "v8", *utf8,
static_cast<uint64_t
>(hash),
2217 GetTracingTimestampFromPerformanceTimestamp(end_timestamp));
2222 ->DefineOwnProperty(
2231 ->DefineOwnProperty(context,
2236 ->DefineOwnProperty(
2241 info.GetReturnValue().Set(performance_entry);
2252 if (info.Length() >= 1 && info[0]->IsObject()) {
2254 Local<Value> value = TryGetValue(isolate, context,
object,
"detailed")
2256 if (value.IsEmpty()) {
2260 if (value->IsBoolean() && value->BooleanValue(isolate)) {
2266 info.GetIsolate()->MeasureMemory(
2270 info.GetReturnValue().Set(promise_resolver->GetPromise());
2276 Isolate* isolate = info.GetIsolate();
2278 int index = data->RealmFind(isolate->GetEnteredOrMicrotaskContext());
2279 if (index == -1)
return;
2280 info.GetReturnValue().Set(index);
2286 Isolate* isolate = info.GetIsolate();
2288 if (info.Length() < 1 || !info[0]->IsObject()) {
2289 ThrowError(info.GetIsolate(),
"Invalid argument");
2293 info[0]->ToObject(isolate->GetCurrentContext()).ToLocalChecked();
2295 if (IsJSGlobalProxy(*i_object) &&
2300 if (!object->GetCreationContext(isolate).ToLocal(&creation_context)) {
2301 ThrowError(info.GetIsolate(),
"object doesn't have creation context");
2304 int index = data->RealmFind(creation_context);
2305 if (index == -1)
return;
2306 info.GetReturnValue().Set(index);
2314 int index = data->RealmIndexOrThrow(info, 0);
2315 if (index == -1)
return;
2324 if (IsJSGlobalObject(*i_global)) {
2328 global = Utils::ToLocal(i_global_proxy);
2330 info.GetReturnValue().Set(global);
2337 const char* kGlobalHandleLabel =
"d8::realm";
2338 Isolate* isolate = info.GetIsolate();
2343 index = data->realm_count_;
2347 realm.
Reset(isolate, old_realms[
i]);
2353 delete[] old_realms;
2357 Context::New(isolate,
nullptr, global_template, global_object);
2360 InitializeModuleEmbedderData(context);
2361 data->realms_[
index].Reset(isolate, context);
2362 data->realms_[
index].AnnotateStrongRetainer(kGlobalHandleLabel);
2363 info.GetReturnValue().Set(index);
2370 Isolate* isolate = info.GetIsolate();
2373 data->realms_[
index].Reset();
2393 context->SetSecurityToken(
2394 info.GetIsolate()->GetEnteredOrMicrotaskContext()->GetSecurityToken());
2402 Isolate* isolate = info.GetIsolate();
2404 int index = data->RealmIndexOrThrow(info, 0);
2405 if (index == -1)
return;
2406 if (index == 0 || index == data->realm_current_ ||
2407 index == data->realm_switch_) {
2408 ThrowError(info.GetIsolate(),
"Invalid realm index");
2417 if (!global_object.
IsEmpty()) {
2419 if (!IsJSGlobalProxy(
2425 DisposeRealm(info, index);
2426 CreateRealm(info, index, global_object);
2432 Isolate* isolate = info.GetIsolate();
2434 int index = data->RealmIndexOrThrow(info, 0);
2435 if (index == -1)
return;
2436 if (index == 0 || index == data->realm_current_ ||
2437 index == data->realm_switch_) {
2438 ThrowError(info.GetIsolate(),
"Invalid realm index");
2444 realm->DetachGlobal();
2450 Isolate* isolate = info.GetIsolate();
2452 int index = data->RealmIndexOrThrow(info, 0);
2453 if (index == -1)
return;
2454 if (index == 0 || index == data->realm_current_ ||
2455 index == data->realm_switch_) {
2456 ThrowError(info.GetIsolate(),
"Invalid realm index");
2459 DisposeRealm(info, index);
2465 Isolate* isolate = info.GetIsolate();
2467 int index = data->RealmIndexOrThrow(info, 0);
2468 if (index == -1)
return;
2469 data->realm_switch_ =
index;
2475 Isolate* isolate = info.GetIsolate();
2477 int index = data->RealmIndexOrThrow(info, 0);
2478 if (index == -1)
return;
2479 if (info.Length() < 2) {
2480 ThrowError(isolate,
"Invalid argument");
2485 if (!ReadSource(info, 1, CodeType::kString).
ToLocal(&source)) {
2486 ThrowError(isolate,
"Invalid argument");
2493 if (isolate->IsExecutionTerminating())
return;
2503 if (!script->BindToCurrentContext()
2509 info.GetReturnValue().Set(
result);
2516 Isolate* isolate = info.GetIsolate();
2518 if (data->realm_shared_.IsEmpty())
return;
2519 info.GetReturnValue().Set(data->realm_shared_);
2525 Isolate* isolate = info.GetIsolate();
2527 data->realm_shared_.Reset(isolate, value);
2532 Isolate* isolate = info.GetIsolate();
2537 if (!i::LogFile::IsLoggingToTemporaryFile(file_name)) {
2538 ThrowError(isolate,
"Only capturing from temporary files is supported.");
2542 ThrowError(isolate,
"Logging not enabled.");
2546 std::string raw_log;
2549 ThrowError(isolate,
"Log file does not exist.");
2553 bool exists =
false;
2558 ThrowError(isolate,
"Unable to read log file.");
2563 static_cast<int>(raw_log.size()))
2566 info.GetReturnValue().Set(
result);
2571 Isolate* isolate = info.GetIsolate();
2573 if (info.Length() != 1) {
2574 ThrowError(isolate,
"Expected function as single argument.");
2578 if (!IsHeapObject(*arg_handle) ||
2579 !IsJSFunctionOrBoundFunctionOrWrappedFunction(
2581 ThrowError(isolate,
"Expected function as single argument.");
2590 while (IsJSBoundFunction(*callable)) {
2593 auto bound_target = bound_function->bound_target_function();
2594 if (!IsJSFunctionOrBoundFunctionOrWrappedFunction(bound_target)) {
2596 ThrowError(isolate,
"Expected function as bound target.");
2605 if (!function->shared()->HasBytecodeArray()) {
2606 ThrowError(isolate,
"Function has no BytecodeArray attached.");
2610 handle(function->shared()->GetBytecodeArray(i_isolate), i_isolate);
2611 i::interpreter::BytecodeArrayIterator bytecode_iterator(bytecodes);
2612 bool has_baseline = function->shared()->HasBaselineCode();
2614 std::unique_ptr<i::baseline::BytecodeOffsetIterator> offset_iterator;
2616 bytecode_offsets = handle(
2618 function->shared()->GetCode(i_isolate)->bytecode_offset_table()),
2620 offset_iterator = std::make_unique<i::baseline::BytecodeOffsetIterator>(
2621 bytecode_offsets, bytecodes);
2623 DCHECK_EQ(offset_iterator->current_pc_start_offset(), 0);
2624 DCHECK_EQ(offset_iterator->current_bytecode_offset(),
2626 offset_iterator->Advance();
2628 while (!bytecode_iterator.done()) {
2630 if (offset_iterator->current_bytecode_offset() !=
2631 bytecode_iterator.current_offset()) {
2632 ThrowError(isolate,
"Baseline bytecode offset mismatch.");
2637 for (
i::Address pc = offset_iterator->current_pc_start_offset() + 1;
2639 i::baseline::BytecodeOffsetIterator pc_lookup(bytecode_offsets,
2641 pc_lookup.AdvanceToPCOffset(
pc);
2642 if (pc_lookup.current_bytecode_offset() !=
2643 bytecode_iterator.current_offset()) {
2645 "Baseline bytecode offset mismatch for PC lookup.");
2650 bytecode_iterator.Advance();
2651 if (has_baseline && !bytecode_iterator.done()) {
2652 if (offset_iterator->done()) {
2653 ThrowError(isolate,
"Missing bytecode(s) in baseline offset mapping.");
2656 offset_iterator->Advance();
2659 if (has_baseline && !offset_iterator->done()) {
2660 ThrowError(isolate,
"Excess offsets in baseline offset mapping.");
2667 Isolate* isolate = info.GetIsolate();
2672 Isolate* isolate = info.GetIsolate();
2674 isolate->InstallConditionalFeatures(isolate->GetCurrentContext());
2678 Isolate* isolate = info.GetIsolate();
2679 if (
i::v8_flags.correctness_fuzzer_suppressions) {
2686 if (info.Length() != 1) {
2687 ThrowError(isolate,
"Expected single boolean argument.");
2691 if (!arg->IsBoolean()) {
2692 ThrowError(isolate,
"Expected single boolean argument.");
2704 info.GetReturnValue().Set(wrap);
2711 Isolate* isolate = info.GetIsolate();
2720 Isolate* isolate = info.GetIsolate();
2739 Isolate* isolate = info.GetIsolate();
2740 if (
i::v8_flags.correctness_fuzzer_suppressions) {
2746 "d8.promise.setHooks is disabled with "
2747 "--correctness-fuzzer-suppressions");
2750#ifdef V8_ENABLE_JAVASCRIPT_PROMISE_HOOKS
2754 context->SetPromiseHooks(
2763 "d8.promise.setHooks is disabled due to missing build flag "
2764 "v8_enabale_javascript_in_promise_hooks");
2771 Isolate* isolate = info.GetIsolate();
2777 for (
int i = 0;
i < info.Length();
i++) {
2779 if (!serializer.
WriteValue(context, info[
i]).To(&ok))
return;
2783 std::pair<uint8_t*, size_t> pair = serializer.
Release();
2785 memcpy(buffer->GetBackingStore()->Data(), pair.first, pair.second);
2788 info.GetReturnValue().Set(buffer);
2794 Isolate* isolate = info.GetIsolate();
2798 if (!info[0]->IsArrayBuffer()) {
2799 ThrowError(isolate,
"Can only deserialize from an ArrayBuffer");
2802 std::shared_ptr<BackingStore> backing_store =
2805 isolate,
static_cast<const uint8_t*
>(backing_store->Data()),
2806 backing_store->ByteLength());
2808 if (!deserializer.
ReadHeader(context).To(&ok))
return;
2811 info.GetReturnValue().Set(
result);
2817 Isolate* isolate = info.GetIsolate();
2819 if (!info[0]->IsFunction()) {
2820 ThrowError(isolate,
"The OnProfileEnd listener has to be a function");
2824 profiler_end_callback_[
isolate] =
2831 return profiler_end_callback_.find(isolate) != profiler_end_callback_.end();
2837 if (options.enable_inspector)
return;
2840 profiler_end_callback_.erase(isolate);
2847 console->DisposeProfiler();
2853 Isolate* isolate = info.GetIsolate();
2857 if (console && console->profiler()) {
2858 console->profiler()->CollectSample(isolate);
2863 CHECK(HasOnProfileEndListener(isolate));
2870 auto& callback_pair = profiler_end_callback_[
isolate];
2871 callback = callback_pair.first.Get(isolate);
2872 context = callback_pair.second.Get(isolate);
2880 int first_arg_index = 0) {
2881 for (
int i = first_arg_index;
i < info.Length();
i++) {
2883 if (
i != first_arg_index) {
2892 if (arg->IsSymbol()) {
2893 arg = arg.
As<
Symbol>()->Description(info.GetIsolate());
2895 if (!arg->ToString(info.GetIsolate()->GetCurrentContext())
2896 .ToLocal(&str_obj)) {
2902 size_t n = fwrite(*str,
sizeof(**str), str.
length(), file);
2904 printf(
"Error in fwrite\n");
2914 fprintf(file,
"\n");
2942 if (*file_name ==
nullptr) {
2943 ThrowError(info.GetIsolate(),
"Error converting filename to string");
2947 if (info.Length() == 2 &&
2948 (info[1]->IsArrayBuffer() || info[1]->IsArrayBufferView())) {
2950 if (file ==
nullptr) {
2951 ThrowError(info.GetIsolate(),
"Error opening file");
2957 if (info[1]->IsArrayBuffer()) {
2959 length = buffer->ByteLength();
2960 data = buffer->Data();
2964 length = buffer_view->ByteLength();
2965 data =
static_cast<uint8_t*
>(buffer_view->Buffer()->
Data()) +
2966 buffer_view->ByteOffset();
2968 fwrite(data, 1, length, file);
2971 if (file ==
nullptr) {
2972 ThrowError(info.GetIsolate(),
"Error opening file");
2983 if (*file_name ==
nullptr) {
2984 ThrowError(info.GetIsolate(),
"Error converting filename to string");
2987 if (info.Length() == 2) {
2989 if (*format && std::strcmp(*format,
"binary") == 0) {
2995 if (!ReadFile(info.GetIsolate(), *file_name).ToLocal(&source))
return;
2996 info.GetReturnValue().Set(source);
2999#if V8_TARGET_OS_LINUX && V8_ENABLE_WEBASSEMBLY
3005 if (*file_name ==
nullptr) {
3006 ThrowError(info.GetIsolate(),
"Error converting filename to string");
3010 int file_descriptor = open(*file_name, O_RDWR);
3014 info.GetReturnValue().Set(
3020 static const int kBufferSize = 256;
3021 char buffer[kBufferSize];
3031 char* input =
nullptr;
3032 input = fgets(buffer, kBufferSize, stdin);
3034 length =
static_cast<int>(strlen(buffer));
3037 }
else if (buffer[length - 1] !=
'\n') {
3039 isolate, accumulator,
3042 }
else if (length > 1 && buffer[length - 2] ==
'\\') {
3043 buffer[length - 2] =
'\n';
3051 isolate, accumulator,
3061 Isolate* isolate = info.GetIsolate();
3062 for (
int i = 0;
i < info.Length();
i++) {
3065 if (*file_name ==
nullptr) {
3066 std::ostringstream oss;
3067 oss <<
"Cannot convert file[" <<
i <<
"] name to string.";
3074 if (!ReadFile(isolate, *file_name).
ToLocal(&source))
return;
3076 info.GetIsolate(), source,
3078 options.quiet_load ? kNoReportExceptions : kReportExceptions)) {
3079 std::ostringstream oss;
3080 oss <<
"Error executing file: \"" << *file_name <<
'"';
3115 Isolate* isolate = info.GetIsolate();
3117 if (info.Length() == 0 || !info[0]->IsFunction())
return;
3120 g_platform->GetForegroundTaskRunner(isolate)->PostTask(
3121 std::make_unique<SetTimeoutTask>(isolate, context,
callback));
3124#ifdef V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
3125void Shell::GetContinuationPreservedEmbedderData(
3127 info.GetReturnValue().Set(
3128 info.GetIsolate()->GetContinuationPreservedEmbedderData());
3135 info.GetReturnValue().Set(context->GetExtrasBindingObject());
3141 Isolate* isolate = info.GetIsolate();
3142 if (info.Length() > index && info[index]->IsObject()) {
3146 if (!TryGetValue(isolate, context,
object,
"type").
ToLocal(&value)) {
3147 *code_type = CodeType::kNone;
3150 if (!value->IsString()) {
3151 *code_type = CodeType::kInvalid;
3155 value->ToString(context).ToLocalChecked();
3157 if (strcmp(
"classic", *str) == 0) {
3158 *code_type = CodeType::kFileName;
3159 }
else if (strcmp(
"string", *str) == 0) {
3160 *code_type = CodeType::kString;
3161 }
else if (strcmp(
"function", *str) == 0) {
3162 *code_type = CodeType::kFunction;
3164 *code_type = CodeType::kInvalid;
3166 if (arguments !=
nullptr) {
3167 bool got_arguments =
3168 TryGetValue(isolate, context,
object,
"arguments").ToLocal(arguments);
3172 *code_type = CodeType::kNone;
3182 function->FunctionProtoToString(context);
3184 if (!maybe_function_string.
ToLocal(&function_string)) {
3185 ThrowError(isolate,
"Failed to convert function to string");
3192 if (!arguments.IsEmpty() && !arguments->IsUndefined()) {
3193 if (!arguments->IsArray()) {
3194 ThrowError(isolate,
"'arguments' must be an array");
3199 for (uint32_t
i = 0;
i < array->Length(); ++
i) {
3205 if (!maybe_argument.
ToLocal(&argument)) {
3206 ThrowError(isolate,
"Failed to get argument");
3211 ThrowError(isolate,
"Failed to convert argument to string");
3230 ReadCodeTypeAndArguments(info, index + 1, &code_type, &arguments);
3232 Isolate* isolate = info.GetIsolate();
3234 if (code_type == CodeType::kNone) {
3235 code_type = default_type;
3237 switch (code_type) {
3238 case CodeType::kFunction:
3239 if (!info[index]->IsFunction()) {
3243 if (!FunctionAndArgumentsToString(info[index].As<Function>(), arguments,
3244 &source, isolate)) {
3248 case CodeType::kFileName: {
3249 if (!info[index]->IsString()) {
3258 case CodeType::kString:
3259 if (!info[index]->IsString()) {
3264 case CodeType::kNone:
3265 case CodeType::kInvalid:
3273 Isolate* isolate = info.GetIsolate();
3275 if (info.Length() < 1 || (!info[0]->IsString() && !info[0]->IsFunction())) {
3276 ThrowError(isolate,
"1st argument must be a string or a function");
3281 if (!ReadSource(info, 0, CodeType::kFileName).
ToLocal(&source)) {
3282 ThrowError(isolate,
"Invalid argument");
3286 if (!info.IsConstructCall()) {
3287 ThrowError(isolate,
"Worker must be constructed with new");
3298 if (info.Length() > 1 && info[1]->IsObject()) {
3300 if (!TryGetValue(isolate, isolate->GetCurrentContext(),
3301 info[1].As<
Object>(),
"flushDenormals")
3305 if (!value->IsUndefined()) {
3306 flush_denormals = value->BooleanValue(isolate);
3314 reinterpret_cast<i::Isolate*
>(isolate)->main_thread_local_isolate(),
3315 workers_mutex_.Pointer());
3316 if (!allow_new_workers_)
return;
3320 ThrowError(isolate,
"Can't get worker script");
3327 auto worker = std::make_shared<Worker>(isolate, *script, flush_denormals);
3329 const size_t kWorkerSizeEstimate = 4 * 1024 * 1024;
3332 info.This()->SetInternalField(0, Utils::ToLocal(managed));
3337 ThrowError(isolate,
"Can't start thread");
3346 Isolate* isolate = info.GetIsolate();
3349 if (info.Length() < 1) {
3350 ThrowError(isolate,
"Invalid argument");
3354 std::shared_ptr<Worker> worker =
3355 GetWorkerFromInternalField(isolate, info.This());
3356 if (!worker.get()) {
3363 std::unique_ptr<SerializationData> data =
3366 worker->PostMessage(std::move(data));
3372 Isolate* isolate = info.GetIsolate();
3374 std::shared_ptr<Worker> worker =
3375 GetWorkerFromInternalField(isolate, info.This());
3376 if (!worker.get()) {
3380 std::unique_ptr<SerializationData> data = worker->GetMessage(isolate);
3384 info.GetReturnValue().Set(value);
3394 std::unique_ptr<SerializationData> data)
3405 MicrotasksScope::kDoNotRunMicrotasks);
3411 if (!onmessage->IsFunction())
return;
3415 try_catch.SetVerbose(
true);
3421 ->CreateDataProperty(
3423 String::NewFromUtf8Literal(
isolate_,
"data",
3424 NewStringType::kInternalized),
3437 std::unique_ptr<SerializationData>
data_;
3447 std::shared_ptr<Worker> worker)
3448 :
isolate_(isolate), worker_(
std::move(worker)) {}
3457 auto callback_pair =
3458 PerIsolateData::Get(
isolate_)->GetWorkerOnMessage(worker_);
3463 if (callback_pair.second.IsEmpty())
return;
3465 std::unique_ptr<SerializationData>
result;
3466 while ((
result = worker_->TryGetMessage())) {
3468 g_platform->GetForegroundTaskRunner(
isolate_)->PostTask(
3469 std::make_unique<OnMessageFromWorkerTask>(
3470 isolate_, callback_pair.first, callback_pair.second,
3487 :
isolate_(isolate), worker_(
std::move(worker)) {}
3490 PerIsolateData::Get(
isolate_)->UnregisterWorker(std::move(worker_));
3501 Isolate* isolate = info.GetIsolate();
3504 std::shared_ptr<Worker> worker =
3505 GetWorkerFromInternalField(isolate, info.This());
3506 if (!worker.get()) {
3513 info.GetReturnValue().Set(
callback);
3520 Isolate* isolate = info.GetIsolate();
3523 if (info.Length() < 1) {
3524 ThrowError(isolate,
"Invalid argument");
3528 std::shared_ptr<Worker> worker =
3529 GetWorkerFromInternalField(isolate, info.This());
3530 if (!worker.get()) {
3535 if (!
callback->IsFunction())
return;
3543 Isolate* isolate = info.GetIsolate();
3545 std::shared_ptr<Worker> worker =
3546 GetWorkerFromInternalField(isolate, info.This());
3547 if (!worker.get())
return;
3548 worker->Terminate();
3554 Isolate* isolate = info.GetIsolate();
3556 std::shared_ptr<Worker> worker =
3557 GetWorkerFromInternalField(isolate, info.This());
3558 if (!worker.get()) {
3563 ->main_thread_local_isolate()
3564 ->ExecuteMainThreadWhileParked([worker](
const i::ParkedScope& parked) {
3565 worker->TerminateAndWaitForThread(parked);
3570 int exit_code = (*info)[0]
3571 ->Int32Value(info->GetIsolate()->GetCurrentContext())
3573 Isolate* isolate = info->GetIsolate();
3574 ResetOnProfileEndListener(isolate);
3588 [](
const i::ParkedScope& parked) { WaitForRunningWorkers(parked); });
3595 OnExit(isolate,
false);
3601bool SkipTerminationForFuzzing() {
3604 if (
i::v8_flags.correctness_fuzzer_suppressions)
return true;
3609 if (fuzzilli_reprl)
return true;
3617 if (SkipTerminationForFuzzing())
return;
3618 auto v8_isolate = info.GetIsolate();
3619 if (!v8_isolate->IsExecutionTerminating()) {
3629 if (SkipTerminationForFuzzing())
return;
3630 auto v8_isolate = info.GetIsolate();
3632 if (!v8_isolate->IsExecutionTerminating()) v8_isolate->TerminateExecution();
3643 info.GetReturnValue().Set(
3652 bool enter_context = context.IsEmpty();
3653 if (enter_context) {
3659 return *value ? *
value :
"<string conversion failed>";
3663 const char* exception_string = ToCString(exception);
3664 if (message.IsEmpty()) {
3667 printf(
"%s\n", exception_string);
3668 }
else if (message->GetScriptOrigin().Options().IsWasm()) {
3670 int function_index = message->GetWasmFunctionIndex();
3671 int offset = message->GetStartColumn(context).FromJust();
3672 printf(
"wasm-function[%d]:0x%x: %s\n", function_index,
offset,
3677 message->GetScriptOrigin().ResourceName());
3678 const char* filename_string = ToCString(
filename);
3679 int linenum = message->GetLineNumber(context).FromMaybe(-1);
3680 printf(
"%s:%i: %s\n", filename_string, linenum, exception_string);
3682 if (message->GetSourceLine(context).ToLocal(&sourceline)) {
3685 const char* sourceline_string = ToCString(sourcelinevalue);
3686 printf(
"%s\n", sourceline_string);
3688 int start = message->GetStartColumn(context).FromJust();
3692 int end = message->GetEndColumn(context).FromJust();
3701 .
ToLocal(&stack_trace_string) &&
3702 stack_trace_string->IsString()) {
3704 printf(
"%s\n", ToCString(stack_trace));
3707 if (enter_context) context->Exit();
3712 if (isolate->IsExecutionTerminating()) {
3713 printf(
"Got Execution Termination Exception\n");
3722 name_[kMaxNameSize - 1] =
'\0';
3723 is_histogram_ = is_histogram;
3727 count_.fetch_add(1, std::memory_order_relaxed);
3728 sample_total_.fetch_add(sample, std::memory_order_relaxed);
3732 magic_number_ = 0xDEADFACE;
3733 max_counters_ = kMaxCounters;
3735 counters_in_use_ = 0;
3739 if (counters_in_use_ == kMaxCounters)
return nullptr;
3747 (counters_file_ ==
nullptr) ?
nullptr : counters_file_->memory();
3748 if (memory ==
nullptr) {
3749 printf(
"Could not map counters file %s\n", name);
3753 isolate->SetCounterFunction(LookupCounter);
3754 isolate->SetCreateHistogramFunction(CreateHistogram);
3755 isolate->SetAddHistogramSampleFunction(AddHistogramSample);
3762 auto map_entry = counter_map_->find(name);
3763 if (map_entry != counter_map_->end()) {
3764 counter = map_entry->second;
3768 if (counter ==
nullptr) {
3771 counter = (*counter_map_)[
name];
3773 if (counter ==
nullptr) {
3775 if (counter ==
nullptr) {
3779 (*counter_map_)[
name] = counter;
3780 counter->
Bind(name, is_histogram);
3789 Counter* counter = GetCounter(name,
false);
3790 return counter ? counter->
ptr() :
nullptr;
3795 return GetCounter(name,
true);
3807 if (stringify_function_.IsEmpty()) {
3814 stringify_function_.Reset(
3815 isolate, script->Run(context).ToLocalChecked().As<
Function>());
3846 static_cast<uint16_t
>(instance_type));
3852 return event_target;
3859 node->Inherit(event_target);
3862 data->SetDomNodeCtor(node);
3867 isolate, NodeTypeCallback,
Local<Value>(), signature, 0,
3872 nodeType->SetAcceptAnyReceiver(
false);
3873 proto_template->SetAccessorProperty(
3878 element->Inherit(node);
3882 html_element->Inherit(element);
3886 div_element->Inherit(html_element);
3895 global_template->Set(isolate,
"version",
3899 global_template->Set(isolate,
"printErr",
3901 global_template->Set(isolate,
"write",
3904 global_template->Set(isolate,
"writeFile",
3907 global_template->Set(isolate,
"read",
3909 global_template->Set(isolate,
"readbuffer",
3911 global_template->Set(isolate,
"readline",
3913 global_template->Set(isolate,
"load",
3915 global_template->Set(isolate,
"setTimeout",
3920 if (!options.omit_quit) {
3923 global_template->Set(isolate,
"testRunner",
3926 global_template->Set(isolate,
"performance",
3937 global_template->Set(isolate,
"async_hooks",
3941 return global_template;
3946 AddOSMethods(isolate, os_template);
3947 os_template->Set(isolate,
"name",
3962 worker_fun_template->SetClassName(
3964 worker_fun_template->ReadOnlyPrototype();
3965 worker_fun_template->PrototypeTemplate()->Set(
3966 isolate,
"terminate",
3969 worker_fun_template->PrototypeTemplate()->Set(
3970 isolate,
"terminateAndWait",
3973 worker_fun_template->PrototypeTemplate()->Set(
3974 isolate,
"postMessage",
3977 worker_fun_template->PrototypeTemplate()->Set(
3978 isolate,
"getMessage",
3981 worker_fun_template->PrototypeTemplate()->SetAccessorProperty(
3988 worker_fun_template->InstanceTemplate()->SetInternalFieldCount(1);
3989 return worker_fun_template;
3994 async_hooks_templ->Set(isolate,
"createHook",
3996 async_hooks_templ->Set(
3997 isolate,
"executionAsyncId",
3999 async_hooks_templ->Set(
4000 isolate,
"triggerAsyncId",
4002 return async_hooks_templ;
4012 return test_template;
4017 performance_template->Set(isolate,
"now",
4019 performance_template->Set(isolate,
"mark",
4021 performance_template->Set(isolate,
"measure",
4023 performance_template->Set(
4024 isolate,
"measureMemory",
4026 return performance_template;
4031 realm_template->Set(isolate,
"current",
4033 realm_template->Set(isolate,
"owner",
4035 realm_template->Set(isolate,
"global",
4037 realm_template->Set(isolate,
"create",
4039 realm_template->Set(
4040 isolate,
"createAllowCrossRealmAccess",
4042 realm_template->Set(isolate,
"navigate",
4044 realm_template->Set(isolate,
"detachGlobal",
4046 realm_template->Set(isolate,
"dispose",
4048 realm_template->Set(isolate,
"switch",
4050 realm_template->Set(isolate,
"eval",
4052 realm_template->SetNativeDataProperty(
4055 return realm_template;
4062 file_template->Set(isolate,
"read",
4064 file_template->Set(isolate,
"execute",
4066#if V8_TARGET_OS_LINUX && V8_ENABLE_WEBASSEMBLY
4067 if (
i::v8_flags.experimental_wasm_memory_control) {
4069 isolate,
"create_wasm_memory_map_descriptor",
4073 d8_template->Set(isolate,
"file", file_template);
4077 log_template->Set(isolate,
"getAndStop",
4080 d8_template->Set(isolate,
"log", log_template);
4086 dom_template->Set(isolate,
"EventTarget", event_target);
4087 dom_template->Set(isolate,
"Div",
4089 d8_template->Set(isolate,
"dom", dom_template);
4095 if (!
i::v8_flags.correctness_fuzzer_suppressions) {
4097 isolate,
"verifySourcePositions",
4103 if (options.expose_fast_api &&
i::v8_flags.turbo_fast_api_calls &&
4105 test_template->Set(isolate,
"FastCAPI",
4107 test_template->Set(isolate,
"LeafInterfaceType",
4113 isolate,
"installConditionalFeatures",
4118 test_template->Set(isolate,
"enableJSPI",
4122 isolate,
"setFlushDenormals",
4125 d8_template->Set(isolate,
"test", test_template);
4129 promise_template->Set(
4130 isolate,
"setHooks",
4133 d8_template->Set(isolate,
"promise", promise_template);
4137 debugger_template->Set(
4141 debugger_template->Set(
4145 d8_template->Set(isolate,
"debugger", debugger_template);
4149 serializer_template->Set(
4150 isolate,
"serialize",
4152 serializer_template->Set(
4153 isolate,
"deserialize",
4156 d8_template->Set(isolate,
"serializer", serializer_template);
4160 profiler_template->Set(
4161 isolate,
"setOnProfileEndListener",
4163 profiler_template->Set(
4164 isolate,
"triggerSample",
4166 d8_template->Set(isolate,
"profiler", profiler_template);
4170 if (!
i::v8_flags.correctness_fuzzer_suppressions) {
4173 constants_template->Set(
4177 constants_template->Set(
4180 Number::New(isolate, i::JSArray::kMaxFastArrayLength));
4182 d8_template->Set(isolate,
"constants", constants_template);
4184#ifdef V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
4186 isolate,
"getContinuationPreservedEmbedderDataViaAPIForTesting",
4189 d8_template->Set(isolate,
"terminateNow",
4191 d8_template->Set(isolate,
"terminate",
4193 d8_template->Set(isolate,
"getExtrasBindingObject",
4195 if (!options.omit_quit) {
4202 switch (message->ErrorLevel()) {
4221 return *value ? *
value :
"<string conversion failed>";
4223 Isolate* isolate = message->GetIsolate();
4225 const char* msg_string = ToCString(msg);
4228 message->GetScriptOrigin().ResourceName());
4229 const char* filename_string = ToCString(
filename);
4230 Maybe<int> maybeline = message->GetLineNumber(isolate->GetCurrentContext());
4232 printf(
"%s:%i: %s\n", filename_string, linenum, msg_string);
4236 if (options.ignore_unhandled_promises)
return;
4252 bool capture_exceptions =
4254 isolate->SetCaptureStackTraceForUncaughtExceptions(
true);
4258 if (exception->IsObject()) {
4261 if (!exception->IsNativeError() &&
4262 (message.IsEmpty() || message->GetStackTrace().IsEmpty())) {
4268 isolate->SetCaptureStackTraceForUncaughtExceptions(capture_exceptions);
4274 bool isOnMainThread) {
4276 isolate->SetWasmAsyncResolvePromiseCallback(
4277 D8WasmAsyncResolvePromiseCallback);
4278 if (isOnMainThread) {
4284 isolate->AddMessageListenerWithErrorLevel(
4291 isolate->SetHostImportModuleDynamicallyCallback(
4293 isolate->SetHostImportModuleWithPhaseDynamicallyCallback(
4295 isolate->SetHostInitializeImportMetaObjectCallback(
4297 isolate->SetHostCreateShadowRealmContextCallback(
4311 reinterpret_cast<i::Isolate*
>(isolate)->main_thread_local_isolate(),
4312 context_mutex_.Pointer());
4317 if (context.IsEmpty()) {
4318 DCHECK(isolate->IsExecutionTerminating());
4325 InitializeModuleEmbedderData(context);
4327 if (options.include_arguments) {
4328 const std::vector<const char*>&
args = options.arguments;
4329 int size =
static_cast<int>(
args.size());
4331 for (
int i = 0;
i <
size;
i++) {
4335 array->Set(context, index, arg).FromJust();
4339 context->Global()->Set(context, name, array).FromJust();
4346 context->GetExtrasBindingObject()->Get(context, name).ToLocalChecked();
4347 context->Global()->Set(context, name, console).FromJust();
4350 return handle_scope.
Escape(context);
4361 ->GetDispatchCountersObject();
4362 std::ofstream dispatch_counters_stream(
4363 i::v8_flags.trace_ignition_dispatches_output_file);
4375void WriteLcovDataForRange(std::vector<uint32_t>* lines,
int start_line,
4376 int end_line, uint32_t count) {
4378 lines->resize(std::max(
static_cast<size_t>(end_line + 1), lines->size()), 0);
4381 (*lines)[start_line] = std::max((*lines)[start_line], count);
4382 (*lines)[end_line] = std::max((*lines)[end_line], count);
4384 for (
int k = start_line + 1; k < end_line; k++) (*lines)[k] =
count;
4387void WriteLcovDataForNamedRange(std::ostream& sink,
4388 std::vector<uint32_t>* lines,
4389 const std::string& name,
int start_line,
4390 int end_line, uint32_t count) {
4391 WriteLcovDataForRange(lines, start_line, end_line, count);
4392 sink <<
"FN:" << start_line + 1 <<
"," << name << std::endl;
4393 sink <<
"FNDA:" << count <<
"," << name << std::endl;
4402 std::ofstream sink(file, std::ofstream::app);
4403 for (
size_t i = 0;
i < coverage.ScriptCount();
i++) {
4408 if (!script->Name().ToLocal(&name))
continue;
4409 std::string file_name = ToSTLString(isolate, name);
4411 if (!std::ifstream(file_name).good())
continue;
4413 sink << NormalizePath(file_name, GetWorkingDirectory()) << std::endl;
4414 std::vector<uint32_t> lines;
4422 script->GetSourceLocation(function_data.
StartOffset());
4424 script->GetSourceLocation(function_data.
EndOffset());
4426 int end_line =
end.GetLineNumber();
4427 uint32_t count = function_data.
Count();
4430 std::stringstream name_stream;
4431 if (function_data.
Name().ToLocal(&function_name)) {
4432 name_stream << ToSTLString(isolate, function_name);
4434 name_stream <<
"<" << start_line + 1 <<
"-";
4435 name_stream <<
start.GetColumnNumber() <<
">";
4438 WriteLcovDataForNamedRange(sink, &lines, name_stream.str(), start_line,
4443 for (
size_t k = 0; k < function_data.
BlockCount(); k++) {
4445 int start_line = LineFromOffset(script, block_data.
StartOffset());
4446 int end_line = LineFromOffset(script, block_data.
EndOffset() - 1);
4447 uint32_t count = block_data.
Count();
4448 WriteLcovDataForRange(&lines, start_line, end_line, count);
4452 for (
size_t j = 0; j < lines.size(); j++) {
4453 sink <<
"DA:" << (j + 1) <<
"," << lines[j] << std::endl;
4455 sink <<
"end_of_record" << std::endl;
4467 worker->EnterTerminatedState();
4475 isolate->DumpAndResetStats();
4480 if (options.simulate_errors && is_valid_fuzz_script()) {
4491 if (options.dump_counters || options.dump_counters_nvp) {
4493 std::vector<std::pair<std::string, Counter*>> counters(
4494 counter_map_->begin(), counter_map_->end());
4495 std::sort(counters.begin(), counters.end());
4497 if (options.dump_counters_nvp) {
4499 for (
const auto& pair : counters) {
4500 std::string
key = pair.first;
4501 Counter* counter = pair.second;
4503 std::cout <<
"\"c:" <<
key <<
"\"=" << counter->
count() <<
"\n";
4507 std::cout <<
"\"" <<
key <<
"\"=" << counter->
count() <<
"\n";
4512 constexpr int kNameBoxSize = 64;
4513 constexpr int kValueBoxSize = 13;
4514 std::cout <<
"+" << std::string(kNameBoxSize,
'-') <<
"+"
4515 << std::string(kValueBoxSize,
'-') <<
"+\n";
4516 std::cout <<
"| Name" << std::string(kNameBoxSize - 5,
' ') <<
"| Value"
4517 << std::string(kValueBoxSize - 6,
' ') <<
"|\n";
4518 std::cout <<
"+" << std::string(kNameBoxSize,
'-') <<
"+"
4519 << std::string(kValueBoxSize,
'-') <<
"+\n";
4520 for (
const auto& pair : counters) {
4521 std::string
key = pair.first;
4522 Counter* counter = pair.second;
4524 std::cout <<
"| c:" << std::setw(kNameBoxSize - 4) << std::left <<
key
4525 <<
" | " << std::setw(kValueBoxSize - 2) << std::right
4526 << counter->
count() <<
" |\n";
4527 std::cout <<
"| t:" << std::setw(kNameBoxSize - 4) << std::left <<
key
4528 <<
" | " << std::setw(kValueBoxSize - 2) << std::right
4531 std::cout <<
"| " << std::setw(kNameBoxSize - 2) << std::left <<
key
4532 <<
" | " << std::setw(kValueBoxSize - 2) << std::right
4533 << counter->
count() <<
" |\n";
4536 std::cout <<
"+" << std::string(kNameBoxSize,
'-') <<
"+"
4537 << std::string(kValueBoxSize,
'-') <<
"+\n";
4541 if (options.dump_system_memory_stats) {
4543 std::cout <<
"System peak memory usage (kb): " << peak_memory_usage
4553 delete counters_file_;
4554 delete counter_map_;
4562 std::unique_ptr<base::RandomNumberGenerator> rng;
4565 rng = std::make_unique<base::RandomNumberGenerator>(seed);
4567 rng = std::make_unique<base::RandomNumberGenerator>();
4570 double p = rng->NextDouble();
4572 ControlFlowViolation();
4573 }
else if (p < 0.2) {
4575 }
else if (p < 0.3) {
4577 }
else if (p < 0.4) {
4578 ObservableDifference();
4579 }
else if (p < 0.5) {
4580 UndefinedBehavior();
4581 }
else if (p < 0.6) {
4583 }
else if (p < 0.7) {
4584 UseOfUninitializedValue();
4590 void (*func)() = (
void (*)()) &
Dummy;
4601 FATAL(
"Fake error.");
4606 printf(
"___fake_difference___\n");
4617#if defined(__clang__)
4618 std::vector<bool>* storage =
new std::vector<bool>(3);
4620 USE(storage->at(1));
4626#if defined(__clang__)
4627 int uninitialized[1];
4628 if (uninitialized[0])
USE(uninitialized);
4633 if (options.read_from_tcp_port >= 0) {
4634 return ReadCharsFromTcpPort(name, size_out);
4638 if (file ==
nullptr)
return nullptr;
4640 fseek(file, 0, SEEK_END);
4641 size_t size = ftell(file);
4644 char* chars =
new char[size + 1];
4646 for (
size_t i = 0;
i <
size;) {
4647 i += fread(&chars[
i], 1, size -
i, file);
4655 *size_out =
static_cast<int>(
size);
4662 std::unique_ptr<char[]>
data(ReadChars(name, &length));
4664 if (data.get() ==
nullptr) {
4667 std::stringstream stream(data.get());
4669 std::vector<std::string> lines;
4670 while (std::getline(stream, line,
'\n')) {
4671 lines.emplace_back(line);
4674 int size =
static_cast<int>(lines.size());
4676 for (
int i = 0;
i <
size; ++
i) {
4679 static_cast<int>(lines[
i].
length()));
4681 if (!maybe_str.
ToLocal(&str)) {
4684 exports->Set(isolate,
i, str);
4691 static_assert(
sizeof(char) ==
sizeof(uint8_t),
4692 "char and uint8_t should both have 1 byte");
4693 Isolate* isolate = info.GetIsolate();
4697 ThrowError(isolate,
"Error loading file");
4701 uint8_t* data =
reinterpret_cast<uint8_t*
>(ReadChars(*
filename, &length));
4702 if (data ==
nullptr) {
4703 ThrowError(isolate,
"Error reading file");
4707 memcpy(buffer->GetBackingStore()->Data(), data, length);
4710 info.GetReturnValue().Set(buffer);
4715 info.GetReturnValue().Set(ReadFromStdin(info.GetIsolate()));
4720 Isolate* isolate,
const char* name,
bool should_throw) {
4721 std::unique_ptr<base::OS::MemoryMappedFile>
file(
4726 std::ostringstream oss;
4727 oss <<
"Error loading file: " <<
name;
4740 bool should_throw) {
4741 auto file = ReadFileData(isolate, name, should_throw);
4745 int size =
static_cast<int>(file->size());
4746 char* chars =
static_cast<char*
>(file->memory());
4747 if (
i::v8_flags.use_external_strings && i::String::IsAscii(chars, size)) {
4757 if (file ==
nullptr)
return;
4758 fwrite(buffer, 1, buffer_size, file);
4778 if (input.IsEmpty())
break;
4780 success = ExecuteString(isolate, input, name, kReportExceptions,
4784 if (!FinishExecuting(isolate, context)) success =
false;
4789 if (options.test_shell) {
4790 if (!
result->IsUndefined()) {
4794 fwrite(*str,
sizeof(**str), str.
length(), stdout);
4799 fwrite(*str,
sizeof(**str), str.
length(), stdout);
4818 std::unique_ptr<v8_inspector::StringBuffer> message)
override {
4819 Send(message->string());
4822 std::unique_ptr<v8_inspector::StringBuffer> message)
override {
4823 Send(message->string());
4830 int length =
static_cast<int>(
string.length());
4836 reinterpret_cast<const uint8_t*
>(
string.characters8()),
4840 reinterpret_cast<const uint16_t*
>(
string.characters16()),
4844 isolate_,
"receive", NewStringType::kInternalized);
4847 context->Global()->Get(context, callback_name).ToLocalChecked();
4856 isolate_,
"message", NewStringType::kInternalized);
4858 isolate_,
"Maximum call stack size exceeded");
4860 DCHECK(value->StrictEquals(expected));
4874 if (!connect)
return;
4883 context->SetAlignedPointerInEmbedderData(kInspectorClientIndex,
this);
4888 FunctionTemplate::New(
isolate_, SendInspectorMessage)
4889 ->GetFunction(context)
4892 isolate_,
"send", NewStringType::kInternalized);
4893 CHECK(context->Global()->Set(context, function_name, function).FromJust());
4902 isolate_,
"handleInspectorMessage", NewStringType::kInternalized);
4905 context->Global()->Get(context, callback_name).ToLocalChecked();
4906 if (!
callback->IsFunction())
return;
4913 heap, i::EmbedderStackStateOrigin::kExplicitInvocation,
4914 v8::StackState::kMayContainHeapPointers);
4933 context->GetAlignedPointerFromEmbedderData(kInspectorClientIndex));
4934 return inspector_client->
session_.get();
4946 Isolate* isolate = info.GetIsolate();
4949 info.GetReturnValue().Set(Undefined(isolate));
4950 Local<String> message = info[0]->ToString(context).ToLocalChecked();
4952 InspectorClient::GetSession(context);
4953 uint32_t length = message->Length();
4954 std::unique_ptr<uint16_t[]> buffer(
new uint16_t[length]);
4955 message->WriteV2(isolate, 0, length, buffer.get());
4961 info.GetReturnValue().Set(True(isolate));
4964 static const int kContextGroupId = 1;
4967 std::unique_ptr<v8_inspector::V8InspectorSession>
session_;
4968 std::unique_ptr<v8_inspector::V8Inspector::Channel>
channel_;
4969 bool is_paused =
false;
4980 size_t input_length = strlen(input);
4981 size_t suffix_length = strlen(suffix);
4982 if (suffix_length <= input_length) {
4983 return strcmp(input + input_length - suffix_length, suffix) == 0;
4989 bool success =
true;
4991 if (fuzzilli_reprl) {
4999 char* buffer =
new char[script_size + 1];
5001 size_t remaining = script_size;
5002 while (remaining > 0) {
5003 ssize_t rv = read(
REPRL_DRFD, ptr, remaining);
5008 buffer[script_size] = 0;
5021 for (
int i = begin_offset_;
i < end_offset_; ++
i) {
5022 const char* arg = argv_[
i];
5023 if (strcmp(arg,
"-e") == 0 &&
i + 1 < end_offset_) {
5044 }
else if (strcmp(arg,
"--module") == 0 &&
i + 1 < end_offset_) {
5053 }
else if (strcmp(arg,
"--json") == 0 &&
i + 1 < end_offset_) {
5062 }
else if (arg[0] ==
'-') {
5073 printf(
"Error reading '%s'\n", arg);
5088 :
base::Thread(GetThreadOptions(
"IsolateThread")), group_(group) {}
5105 reinterpret_cast<i::Isolate*
>(isolate)->main_thread_local_isolate());
5112 DCHECK(isolate->IsExecutionTerminating());
5115 global_context.
Reset(isolate, context);
5124 global_context.
Get(isolate)->Enter();
5126 global_context.
Get(isolate)->Exit();
5149 if (
thread_ ==
nullptr)
return;
5155 if (
thread_ ==
nullptr)
return;
5161 data_.push_back(std::move(data));
5165 std::unique_ptr<SerializationData>* out_data) {
5168 if (
data_.empty())
return false;
5169 *out_data = std::move(
data_[0]);
5176 return data_.empty();
5185 bool flush_denormals)
5187 flush_denormals_(flush_denormals),
5188 parent_isolate_(parent_isolate) {
5204 std::shared_ptr<Worker> worker,
5210 worker->thread_ = thread;
5211 if (!thread->Start())
return false;
5213 worker->started_semaphore_.ParkedWait(
5214 reinterpret_cast<i::Isolate*
>(requester)->main_thread_local_isolate());
5225 auto worker = std::move(
worker_);
5227 worker->ExecuteInThread();
5234 std::shared_ptr<Worker> worker,
5235 std::unique_ptr<SerializationData> data)
5236 :
i::CancelableTask(task_manager),
5244 std::unique_ptr<SerializationData>
data_;
5258 std::shared_ptr<Worker> worker)
5259 :
i::CancelableTask(task_manager), worker_(worker) {}
5263 CHECK(worker_->state_.compare_exchange_strong(expected,
5272 std::unique_ptr<SerializationData>
result;
5278 reinterpret_cast<i::Isolate*
>(requester)->main_thread_local_isolate());
5284 std::unique_ptr<SerializationData>
result;
5307 std::unique_ptr<v8::Task> task(
5337 if (!maybe_onmessage.
ToLocal(&onmessage) || !onmessage->IsFunction())
return;
5341 try_catch.SetVerbose(
true);
5347 ->CreateDataProperty(
5385 current_worker_ = worker;
5444 if (postmessage_fun_template->GetFunction(context).ToLocal(
5445 &postmessage_fun)) {
5458 if (close_fun_template->GetFunction(context).ToLocal(&close_fun)) {
5471 if (importScripts_fun_template->GetFunction(context).ToLocal(
5472 &importScripts_fun)) {
5492 bool handler_present;
5505 maybe_onmessage.
ToLocal(&onmessage) && onmessage->IsFunction();
5507 if (handler_present) {
5533 this->shared_from_this()));
5538 Isolate* isolate = info.GetIsolate();
5541 if (info.Length() < 1) {
5542 ThrowError(isolate,
"Invalid argument");
5548 std::unique_ptr<SerializationData> data =
5551 DCHECK(info.Data()->IsExternal());
5553 Worker* worker =
static_cast<Worker*
>(this_value->Value());
5556 worker->out_semaphore_.Signal();
5557 g_platform->GetForegroundTaskRunner(worker->parent_isolate_)
5558 ->PostTask(std::make_unique<CheckMessageFromWorkerTask>(
5559 worker->parent_isolate_, worker->shared_from_this()));
5569 Isolate* isolate = info.GetIsolate();
5571 DCHECK(info.Data()->IsExternal());
5573 Worker* worker =
static_cast<Worker*
>(this_value->Value());
5577#ifdef V8_TARGET_OS_WIN
5587std::vector<char*> utf8_filenames;
5588#include <shellapi.h>
5590char* ConvertUtf16StringToUtf8(
const wchar_t* str) {
5592 static_assert(
sizeof(wchar_t) == 2,
"wrong wchar_t size");
5594 WideCharToMultiByte(CP_UTF8, 0, str, -1,
nullptr, 0,
nullptr, FALSE);
5596 char* utf8_str =
new char[len];
5597 utf8_filenames.push_back(utf8_str);
5598 WideCharToMultiByte(CP_UTF8, 0, str, -1, utf8_str, len,
nullptr, FALSE);
5603void PreProcessUnicodeFilenameArg(
char* argv[],
int i) {
5605 wchar_t** wargv = CommandLineToArgvW(GetCommandLineW(), &argc);
5606 argv[
i] = ConvertUtf16StringToUtf8(wargv[
i]);
5614bool FlagMatches(
const char* flag,
char** arg,
bool keep_flag =
false) {
5615 if (strcmp(*arg, flag) == 0) {
5625bool FlagWithArgMatches(
const char (&flag)[N],
char** flag_value,
int argc,
5626 char* argv[],
int*
i) {
5627 char* current_arg = argv[*
i];
5631 if (strncmp(current_arg, flag, N - 1) == 0) {
5633 if (current_arg[N - 1] ==
'=') {
5634 *flag_value = argv[*
i] +
N;
5639 if (current_arg[N - 1] ==
'\0') {
5643 *flag_value = argv[*
i];
5649 flag_value =
nullptr;
5656 bool logfile_per_isolate =
false;
5657 options.d8_path = argv[0];
5658 for (
int i = 0;
i < argc;
i++) {
5659 char* flag_value =
nullptr;
5660 if (FlagMatches(
"--", &argv[
i])) {
5662 for (;
i < argc;
i++) {
5663 options.arguments.push_back(argv[
i]);
5667 }
else if (FlagMatches(
"--no-arguments", &argv[
i])) {
5668 options.include_arguments =
false;
5669 }
else if (FlagMatches(
"--simulate-errors", &argv[
i])) {
5670 options.simulate_errors =
true;
5671 }
else if (FlagMatches(
"--fuzzing", &argv[
i],
true) ||
5672 FlagMatches(
"--no-abort-on-contradictory-flags", &argv[
i],
5674 FlagMatches(
"--noabort-on-contradictory-flags", &argv[
i],
5677 }
else if (FlagMatches(
"--abort-on-contradictory-flags", &argv[
i],
5680 }
else if (FlagMatches(
"--logfile-per-isolate", &argv[
i])) {
5681 logfile_per_isolate =
true;
5682 }
else if (FlagMatches(
"--shell", &argv[
i])) {
5683 options.interactive_shell =
true;
5684 }
else if (FlagMatches(
"--test", &argv[
i])) {
5685 options.test_shell =
true;
5686 }
else if (FlagMatches(
"--notest", &argv[
i]) ||
5687 FlagMatches(
"--no-test", &argv[
i])) {
5688 options.test_shell =
false;
5689 }
else if (FlagMatches(
"--send-idle-notification", &argv[
i])) {
5690 options.send_idle_notification =
true;
5691 }
else if (FlagMatches(
"--invoke-weak-callbacks", &argv[
i])) {
5692 options.invoke_weak_callbacks =
true;
5695 options.send_idle_notification =
true;
5696 }
else if (FlagMatches(
"--omit-quit", &argv[
i])) {
5697 options.omit_quit =
true;
5698 }
else if (FlagMatches(
"--no-wait-for-background-tasks", &argv[
i])) {
5701 options.wait_for_background_tasks =
false;
5702 }
else if (FlagMatches(
"-f", &argv[
i],
true)) {
5706 }
else if (FlagMatches(
"--ignore-unhandled-promises", &argv[
i])) {
5707 options.ignore_unhandled_promises =
true;
5708 }
else if (FlagMatches(
"--isolate", &argv[
i],
true)) {
5709 options.num_isolates++;
5710 }
else if (FlagMatches(
"--throws", &argv[
i])) {
5711 options.expected_to_throw =
true;
5712 }
else if (FlagMatches(
"--no-fail", &argv[
i])) {
5713 options.no_fail =
true;
5714 }
else if (FlagMatches(
"--dump-counters", &argv[
i])) {
5716 options.dump_counters =
true;
5717 }
else if (FlagMatches(
"--dump-counters-nvp", &argv[
i])) {
5719 options.dump_counters_nvp =
true;
5720 }
else if (FlagMatches(
"--dump-system-memory-stats", &argv[
i])) {
5721 options.dump_system_memory_stats =
true;
5722 }
else if (FlagWithArgMatches(
"--icu-data-file", &flag_value, argc, argv,
5724 options.icu_data_file = flag_value;
5725 }
else if (FlagWithArgMatches(
"--icu-locale", &flag_value, argc, argv,
5727 options.icu_locale = flag_value;
5728#ifdef V8_USE_EXTERNAL_STARTUP_DATA
5729 }
else if (FlagWithArgMatches(
"--snapshot_blob", &flag_value, argc, argv,
5731 options.snapshot_blob = flag_value;
5733 }
else if (FlagMatches(
"--cache", &argv[
i]) ||
5734 FlagWithArgMatches(
"--cache", &flag_value, argc, argv, &
i)) {
5735 if (!flag_value || strcmp(flag_value,
"code") == 0) {
5737 options.code_cache_options =
5739 }
else if (strcmp(flag_value,
"none") == 0) {
5742 }
else if (strcmp(flag_value,
"after-execute") == 0) {
5744 options.code_cache_options =
5746 }
else if (strcmp(flag_value,
"full-code-cache") == 0) {
5748 options.code_cache_options =
5751 fprintf(stderr,
"Unknown option to --cache.\n");
5754 }
else if (FlagMatches(
"--streaming-compile", &argv[
i])) {
5755 options.streaming_compile =
true;
5756 }
else if ((FlagMatches(
"--no-streaming-compile", &argv[
i])) ||
5757 (FlagMatches(
"--nostreaming-compile", &argv[
i]))) {
5758 options.streaming_compile =
false;
5759 }
else if (FlagMatches(
"--enable-tracing", &argv[
i])) {
5760 options.trace_enabled =
true;
5761 }
else if (FlagWithArgMatches(
"--trace-path", &flag_value, argc, argv,
5763 options.trace_path = flag_value;
5764 }
else if (FlagWithArgMatches(
"--trace-config", &flag_value, argc, argv,
5766 options.trace_config = flag_value;
5767 }
else if (FlagMatches(
"--enable-inspector", &argv[
i])) {
5768 options.enable_inspector =
true;
5769 }
else if (FlagWithArgMatches(
"--lcov", &flag_value, argc, argv, &
i)) {
5770 options.lcov_file = flag_value;
5772 }
else if (FlagMatches(
"--scope-linux-perf-to-mark-measure", &argv[
i])) {
5773 options.scope_linux_perf_to_mark_measure =
true;
5774 }
else if (FlagWithArgMatches(
"--perf-ctl-fd", &flag_value, argc, argv,
5776 options.perf_ctl_fd = atoi(flag_value);
5777 }
else if (FlagWithArgMatches(
"--perf-ack-fd", &flag_value, argc, argv,
5779 options.perf_ack_fd = atoi(flag_value);
5781 }
else if (FlagMatches(
"--disable-in-process-stack-traces", &argv[
i])) {
5782 options.disable_in_process_stack_traces =
true;
5784 }
else if (FlagWithArgMatches(
"--read-from-tcp-port", &flag_value, argc,
5786 options.read_from_tcp_port = atoi(flag_value);
5788 }
else if (FlagMatches(
"--enable-os-system", &argv[
i])) {
5789 options.enable_os_system =
true;
5790 }
else if (FlagMatches(
"--no-apply-priority", &argv[
i])) {
5791 options.apply_priority =
false;
5792 }
else if (FlagMatches(
"--quiet-load", &argv[
i])) {
5793 options.quiet_load =
true;
5794 }
else if (FlagWithArgMatches(
"--thread-pool-size", &flag_value, argc, argv,
5796 options.thread_pool_size = atoi(flag_value);
5797 }
else if (FlagMatches(
"--stress-delay-tasks", &argv[
i])) {
5799 options.stress_delay_tasks =
true;
5800 }
else if (FlagMatches(
"--cpu-profiler", &argv[
i])) {
5801 options.cpu_profiler =
true;
5802 }
else if (FlagMatches(
"--cpu-profiler-print", &argv[
i])) {
5803 options.cpu_profiler =
true;
5804 options.cpu_profiler_print =
true;
5805 }
else if (FlagMatches(
"--stress-deserialize", &argv[
i])) {
5806 options.stress_deserialize =
true;
5807 }
else if (FlagMatches(
"--compile-only", &argv[
i])) {
5808 options.compile_only =
true;
5809 }
else if (FlagWithArgMatches(
"--repeat-compile", &flag_value, argc, argv,
5811 options.repeat_compile = atoi(flag_value);
5812 }
else if (FlagWithArgMatches(
"--max-serializer-memory", &flag_value, argc,
5815 options.max_serializer_memory = atoi(flag_value) *
i::MB;
5817 }
else if (FlagMatches(
"--fuzzilli-enable-builtins-coverage", &argv[
i])) {
5818 options.fuzzilli_enable_builtins_coverage =
true;
5819 }
else if (FlagMatches(
"--fuzzilli-coverage-statistics", &argv[
i])) {
5820 options.fuzzilli_coverage_statistics =
true;
5822 }
else if (FlagMatches(
"--no-fuzzy-module-file-extensions", &argv[
i])) {
5823 DCHECK(options.fuzzy_module_file_extensions);
5824 options.fuzzy_module_file_extensions =
false;
5825#if defined(V8_ENABLE_ETW_STACK_WALKING)
5826 }
else if (FlagMatches(
"--enable-etw-stack-walking", &argv[
i])) {
5827 options.enable_etw_stack_walking =
true;
5830#if defined(V8_ENABLE_SYSTEM_INSTRUMENTATION)
5831 }
else if (FlagMatches(
"--enable-system-instrumentation", &argv[
i])) {
5832 options.enable_system_instrumentation =
true;
5833 options.trace_enabled =
true;
5835#if defined(V8_OS_WIN)
5838 i::v8_flags.interpreted_frames_native_stack =
true;
5841#if V8_ENABLE_WEBASSEMBLY
5842 }
else if (FlagMatches(
"--wasm-trap-handler", &argv[
i])) {
5843 options.wasm_trap_handler =
true;
5844 }
else if (FlagMatches(
"--no-wasm-trap-handler", &argv[
i])) {
5845 options.wasm_trap_handler =
false;
5847 }
else if (FlagMatches(
"--expose-fast-api", &argv[
i])) {
5848 options.expose_fast_api =
true;
5849 }
else if (FlagMatches(
"--flush-denormals", &argv[
i])) {
5850 options.flush_denormals =
true;
5852#ifdef V8_TARGET_OS_WIN
5853 PreProcessUnicodeFilenameArg(argv,
i);
5859 if (options.scope_linux_perf_to_mark_measure) {
5860 if (options.perf_ctl_fd == -1 || options.perf_ack_fd == -1) {
5862 "Flag --scope-linux-perf-to-mark-measure requires both "
5863 "--perf-ctl-fd and --perf-ack-fd\n");
5866 SendPerfControlCommand(
"disable");
5872 " shell [options] [--shell] [<file>...]\n"
5873 " d8 [options] [-e <string>] [--shell] [--module|]"
5875 " -e execute a string in V8\n"
5876 " --shell run an interactive JavaScript shell\n"
5877 " --module execute a file as a JavaScript module\n";
5878 using HelpOptions = i::FlagList::HelpOptions;
5880 i::FlagList::SetFlagsFromCommandLine(&argc, argv,
true,
5881 HelpOptions(HelpOptions::kExit, usage));
5882 i::FlagList::ResolveContradictionsWhenFuzzing();
5884 options.mock_arraybuffer_allocator =
i::v8_flags.mock_arraybuffer_allocator;
5885 options.mock_arraybuffer_allocator_limit =
5888 options.multi_mapped_mock_allocator =
i::v8_flags.multi_mapped_mock_allocator;
5891 if (
i::v8_flags.stress_snapshot && options.expose_fast_api &&
5893 FATAL(
"Flag --expose-fast-api is incompatible with --stress-snapshot.");
5897 options.isolate_sources =
new SourceGroup[options.num_isolates];
5900 current->
Begin(argv, 1);
5901 for (
int i = 1;
i < argc;
i++) {
5902 const char* str = argv[
i];
5903 if (strcmp(str,
"--isolate") == 0) {
5906 current->Begin(argv,
i + 1);
5907 }
else if (strcmp(str,
"--module") == 0 || strcmp(str,
"--json") == 0) {
5909 }
else if (strncmp(str,
"--", 2) == 0) {
5910 if (!
i::v8_flags.correctness_fuzzer_suppressions) {
5911 printf(
"Warning: unknown flag %s.\nTry --help for options\n", str);
5913 }
else if (strcmp(str,
"-e") == 0 &&
i + 1 < argc) {
5914 set_script_executed();
5915 }
else if (strncmp(str,
"-", 1) != 0) {
5917 set_script_executed();
5922 if (!logfile_per_isolate && options.num_isolates) {
5932 for (
int i = 1;
i < options.num_isolates; ++
i) {
5933 options.isolate_sources[
i].StartExecuteInThread();
5938 const bool keep_context_alive =
5939 last_run && (use_interactive_shell() ||
i::v8_flags.stress_snapshot);
5940 bool success = RunMainIsolate(isolate, keep_context_alive);
5941 CollectGarbage(isolate);
5947 for (
int i = 1;
i < options.num_isolates; ++
i) {
5949 options.isolate_sources[
i].JoinThread(parked);
5951 options.isolate_sources[
i].WaitForThread(parked);
5954 WaitForRunningWorkers(parked);
5959 if (success && last_run &&
i::v8_flags.stress_snapshot) {
5961 static constexpr bool kClearRecompilableData =
true;
5970 if (i_isolate->maglev_concurrent_dispatcher()->is_enabled()) {
5971 i_isolate->maglev_concurrent_dispatcher()->AwaitCompileJobs();
5976 i::Deoptimizer::DeoptimizeAll(i_isolate);
5980 i::GarbageCollectionReason::kSnapshotCreator);
5981 i::Snapshot::ClearReconstructableDataForSerialization(
5982 i_isolate, kClearRecompilableData);
5983 i::Snapshot::SerializeDeserializeAndVerifyForTesting(i_isolate, i_context);
5987 printf(
"%i pending unhandled Promise rejection(s) detected.\n",
6003 if (options.lcov_file) {
6010 if (!CreateEvaluationContext(isolate).
ToLocal(&context)) {
6011 DCHECK(isolate->IsExecutionTerminating());
6018 global_context.
Reset(isolate, context);
6019 if (keep_context_alive) {
6020 evaluation_context_.Reset(isolate, context);
6025 options.enable_inspector);
6026 bool success =
true;
6031 global_context.
Get(isolate)->Enter();
6032 if (!options.isolate_sources[0].Execute(isolate)) success =
false;
6033 global_context.
Get(isolate)->Exit();
6035 if (!FinishExecuting(isolate, global_context)) success =
false;
6036 WriteLcovData(isolate, options.lcov_file);
6041 if (options.send_idle_notification) {
6042 isolate->ContextDisposedNotification(
6045 if (options.invoke_weak_callbacks) {
6049 isolate->LowMemoryNotification();
6061 if (isolate->IsExecutionTerminating())
return true;
6069 if (isolate->IsExecutionTerminating())
return true;
6070 if (try_catch.
HasCaught())
return false;
6072 if (isolate->IsExecutionTerminating())
return true;
6080 inner_try_catch.SetVerbose(
true);
6085 if (inner_try_catch.HasCaught())
return false;
6086 if (isolate->IsExecutionTerminating())
return true;
6090 if (!ran_a_task)
break;
6092 if (g_default_platform->IdleTasksEnabled(isolate)) {
6095 if (try_catch.
HasCaught())
return false;
6096 if (isolate->IsExecutionTerminating())
return true;
6103 auto get_waiting_behaviour = [
isolate]() {
6104 if (options.wait_for_background_tasks &&
6105 isolate->HasPendingBackgroundTasks()) {
6116 if (get_waiting_behaviour() ==
6119 "There is outstanding work after executing all tasks in predictable "
6120 "mode -- this would deadlock.");
6128 if (!CompleteMessageLoop(isolate))
return false;
6133 context.Get(isolate)->Enter();
6134 bool result = HandleUnhandledPromiseRejections(isolate);
6135 context.Get(isolate)->Exit();
6145 if (options.ignore_unhandled_promises)
return true;
6147 int count = data->HandleUnhandledPromiseRejections();
6157 serializer_(isolate, this),
6158 current_memory_usage_(0) {}
6168 if (!PrepareTransfer(context, transfer).To(&ok)) {
6169 return Nothing<bool>();
6171 serializer_.WriteHeader();
6173 if (!serializer_.WriteValue(context, value).To(&ok)) {
6175 return Nothing<bool>();
6178 if (!FinalizeTransfer().To(&ok)) {
6179 return Nothing<bool>();
6182 std::pair<uint8_t*, size_t> pair = serializer_.Release();
6183 data_->data_.reset(pair.first);
6184 data_->size_ = pair.second;
6191 to->insert(to->end(), std::make_move_iterator(backing_stores_.begin()),
6192 std::make_move_iterator(backing_stores_.end()));
6193 backing_stores_.clear();
6199 isolate_->ThrowException(Exception::Error(message));
6205 for (
size_t index = 0; index < shared_array_buffers_.size(); ++
index) {
6206 if (shared_array_buffers_[index] == shared_array_buffer) {
6207 return Just<uint32_t>(
static_cast<uint32_t
>(index));
6211 size_t index = shared_array_buffers_.size();
6212 shared_array_buffers_.emplace_back(
isolate_, shared_array_buffer);
6213 data_->sab_backing_stores_.push_back(
6214 shared_array_buffer->GetBackingStore());
6215 return Just<uint32_t>(
static_cast<uint32_t
>(index));
6221 for (
size_t index = 0; index < wasm_modules_.size(); ++
index) {
6222 if (wasm_modules_[index] == module) {
6223 return Just<uint32_t>(
static_cast<uint32_t
>(index));
6227 size_t index = wasm_modules_.size();
6228 wasm_modules_.emplace_back(
isolate_, module);
6229 data_->compiled_wasm_modules_.push_back(module->GetCompiledModule());
6230 return Just<uint32_t>(
static_cast<uint32_t
>(index));
6234 size_t* actual_size)
override {
6237 current_memory_usage_ +=
size;
6238 if (current_memory_usage_ > Shell::options.max_serializer_memory) {
6242 void*
result = base::Realloc(old_buffer, size);
6251 data_->shared_value_conveyor_.emplace(std::move(conveyor));
6257 if (transfer->IsArray()) {
6259 uint32_t length = transfer_array->Length();
6262 if (transfer_array->Get(context,
i).ToLocal(&element)) {
6263 if (!element->IsArrayBuffer()) {
6265 "Transfer array elements must be an ArrayBuffer");
6266 return Nothing<bool>();
6271 if (std::find(array_buffers_.begin(), array_buffers_.end(),
6272 array_buffer) != array_buffers_.end()) {
6274 "ArrayBuffer occurs in the transfer array more than once");
6275 return Nothing<bool>();
6278 serializer_.TransferArrayBuffer(
6279 static_cast<uint32_t
>(array_buffers_.size()), array_buffer);
6280 array_buffers_.emplace_back(
isolate_, array_buffer);
6282 return Nothing<bool>();
6286 }
else if (transfer->IsUndefined()) {
6289 isolate_->ThrowError(
"Transfer list must be an Array or undefined");
6290 return Nothing<bool>();
6295 for (
const auto& global_array_buffer : array_buffers_) {
6298 if (!array_buffer->IsDetachable()) {
6300 "ArrayBuffer is not detachable and could not be transferred");
6301 return Nothing<bool>();
6304 auto backing_store = array_buffer->GetBackingStore();
6305 data_->backing_stores_.push_back(std::move(backing_store));
6307 return Nothing<bool>();
6317 std::unique_ptr<SerializationData>
data_;
6329 deserializer_(isolate, data->data(), data->size(), this),
6331 deserializer_.SetSupportsLegacyWireFormat(
true);
6339 if (!deserializer_.ReadHeader(context).To(&read_header)) {
6344 for (
const auto& backing_store :
data_->backing_stores()) {
6346 ArrayBuffer::New(
isolate_, std::move(backing_store));
6347 deserializer_.TransferArrayBuffer(index++, array_buffer);
6350 return deserializer_.ReadValue(context);
6354 Isolate* isolate, uint32_t clone_id)
override {
6356 if (clone_id < data_->sab_backing_stores().
size()) {
6357 return SharedArrayBuffer::New(
6358 isolate_, std::move(
data_->sab_backing_stores().at(clone_id)));
6364 Isolate* isolate, uint32_t transfer_id)
override {
6366 if (transfer_id >=
data_->compiled_wasm_modules().size())
return {};
6367 return WasmModuleObject::FromCompiledModule(
6373 if (
data_->shared_value_conveyor()) {
6374 return &
data_->shared_value_conveyor().value();
6382 std::unique_ptr<SerializationData>
data_;
6408 i::Deoptimizer::DeoptimizeAll(i_isolate);
6417 std::unique_ptr<SerializationData>
data;
6418 if (serializer.
WriteValue(context, value, transfer).To(&ok)) {
6425 Isolate* isolate, std::unique_ptr<SerializationData> data) {
6432 workers_mutex_.Pointer()->AssertHeld();
6433 running_workers_.insert(worker);
6438 auto it = running_workers_.find(worker);
6439 if (it != running_workers_.end()) running_workers_.erase(it);
6446 std::unordered_set<std::shared_ptr<Worker>> workers_copy;
6449 allow_new_workers_ =
false;
6450 workers_copy.swap(running_workers_);
6453 for (
auto& worker : workers_copy) {
6454 worker->TerminateAndWaitForThread(parked);
6459 DCHECK(running_workers_.empty());
6460 allow_new_workers_ =
true;
6466void d8_sigterm_handler(
int signal, siginfo_t* info,
void* context) {
6469 if (signal == SIGTERM) {
6470 FATAL(
"d8: Received SIGTERM signal (likely due to a TIMEOUT)\n");
6477void d8_install_sigterm_handler() {
6480 struct sigaction sa;
6481 sa.sa_sigaction = d8_sigterm_handler;
6482 sigemptyset(&sa.sa_mask);
6484 if (sigaction(SIGTERM, &sa, NULL) == -1) {
6485 FATAL(
"Could not install SIGTERM handler");
6493#if defined(V8_ENABLE_PARTITION_ALLOC)
6494#if PA_BUILDFLAG(USE_PARTITION_ALLOC_AS_MALLOC)
6495 allocator_shim::ConfigurePartitionsForTesting();
6496 allocator_shim::internal::PartitionAllocMalloc::Allocator()
6497 ->EnableThreadCacheIfSupported();
6501 if (!SetOptions(argc, argv))
return 1;
6502 if (!
i::v8_flags.fuzzing) d8_install_sigterm_handler();
6509 if (options.apply_priority) {
6510 struct task_category_policy category = {.role =
6511 TASK_FOREGROUND_APPLICATION};
6512 task_policy_set(mach_task_self(), TASK_CATEGORY_POLICY,
6513 (task_policy_t)&category, TASK_CATEGORY_POLICY_COUNT);
6514 pthread_set_qos_class_self_np(QOS_CLASS_USER_INTERACTIVE, 0);
6518#ifdef V8_INTL_SUPPORT
6519 if (options.icu_locale !=
nullptr) {
6520 icu::Locale locale(options.icu_locale);
6521 UErrorCode error_code = U_ZERO_ERROR;
6522 icu::Locale::setDefault(locale, error_code);
6527 options.disable_in_process_stack_traces
6531 std::ofstream trace_file;
6532 std::unique_ptr<platform::tracing::TracingController> tracing;
6533 if (options.trace_enabled && !
i::v8_flags.verify_predictable) {
6534 tracing = std::make_unique<platform::tracing::TracingController>();
6536 if (!options.enable_etw_stack_walking) {
6537 const char* trace_path =
6538 options.trace_path ? options.trace_path :
"v8_trace.json";
6539 trace_file.open(trace_path);
6540 if (!trace_file.good()) {
6541 printf(
"Cannot open trace file '%s' for writing: %s.\n", trace_path,
6547#ifdef V8_USE_PERFETTO
6550 perfetto::TracingInitArgs init_args;
6551 init_args.backends = perfetto::BackendType::kInProcessBackend;
6552 perfetto::Tracing::Initialize(init_args);
6554 tracing->InitializeForPerfetto(&trace_file);
6557#if defined(V8_ENABLE_SYSTEM_INSTRUMENTATION)
6558 if (options.enable_system_instrumentation) {
6563 CreateSystemInstrumentationTraceWriter());
6566 if (!trace_buffer) {
6573 tracing->Initialize(trace_buffer);
6583 std::move(tracing));
6587 in_process_stack_dumping, std::move(tracing),
6591 g_default_platform = g_platform.get();
6595 if (options.stress_delay_tasks) {
6596 int64_t random_seed =
i::v8_flags.fuzzer_random_seed;
6597 if (!random_seed) random_seed =
i::v8_flags.random_seed;
6603 if (
i::v8_flags.trace_turbo_cfg_file ==
nullptr) {
6606 if (
i::v8_flags.redirect_code_traces_to ==
nullptr) {
6618 if (options.snapshot_blob) {
6625 ShellArrayBufferAllocator shell_array_buffer_allocator;
6626 MockArrayBufferAllocator mock_arraybuffer_allocator;
6627 const size_t memory_limit =
6628 options.mock_arraybuffer_allocator_limit * options.num_isolates;
6629 MockArrayBufferAllocatiorWithLimit mock_arraybuffer_allocator_with_limit(
6630 memory_limit >= options.mock_arraybuffer_allocator_limit
6632 : std::numeric_limits<size_t>::max());
6634 MultiMappedAllocator multi_mapped_mock_allocator;
6636 if (options.mock_arraybuffer_allocator) {
6643 }
else if (options.multi_mapped_mock_allocator) {
6650#ifdef ENABLE_VTUNE_JIT_INTERFACE
6660 if (options.dump_counters || options.dump_counters_nvp ||
6661 i::TracingFlags::is_gc_stats_enabled()) {
6667#if V8_ENABLE_WEBASSEMBLY
6669 constexpr bool kUseDefaultTrapHandler =
true;
6671 FATAL(
"Could not register trap handler");
6680 "V8 is running with experimental features enabled. Stability and "
6681 "security will suffer.\n");
6688 if (options.fuzzilli_enable_builtins_coverage) {
6690 i::BasicBlockProfiler::Get()
6691 ->GetCoverageBitmap(
reinterpret_cast<i::Isolate*
>(isolate))
6694 char helo[] =
"HELO";
6696 fuzzilli_reprl =
false;
6699 if (memcmp(helo,
"HELO", 4) != 0) {
6700 FATAL(
"REPRL: Invalid response from parent");
6707 Initialize(isolate, &console);
6713 if (fuzzilli_reprl) {
6714 unsigned action = 0;
6715 ssize_t nread = read(
REPRL_CRFD, &action, 4);
6716 if (nread != 4 || action !=
'cexe') {
6717 FATAL(
"REPRL: Unknown action: %u", action);
6724 if (options.trace_enabled) {
6726 if (options.trace_config) {
6728 char* trace_config_json_str = ReadChars(options.trace_config, &size);
6730 isolate, trace_config_json_str);
6731 delete[] trace_config_json_str;
6735 if (options.enable_system_instrumentation) {
6743 if (options.cpu_profiler) {
6751 for (
int i = 0;
i < options.stress_runs &&
result == 0;
i++) {
6752 printf(
"============ Run %d/%d ============\n",
i + 1,
6753 options.stress_runs.
get());
6754 bool last_run =
i == options.stress_runs - 1;
6755 result = RunMain(isolate, last_run);
6761 ->main_thread_local_isolate()
6762 ->ExecuteMainThreadWhileParked([&
result]() {
6763 printf(
"============ Run: Produce code cache ============\n");
6776 Initialize(isolate2, &console2);
6779 result = RunMain(isolate2,
false);
6780 ResetOnProfileEndListener(isolate2);
6792 options.compile_options ==
6794 options.compile_options.Overwrite(
6798 printf(
"============ Run: Consume code cache ============\n");
6800 result = RunMain(isolate,
true);
6801 options.compile_options.Overwrite(
6804 bool last_run =
true;
6805 result = RunMain(isolate, last_run);
6810 if (use_interactive_shell()) {
6814 if (
i::v8_flags.trace_ignition_dispatches_output_file !=
nullptr) {
6815 WriteIgnitionDispatchCountersFile(isolate);
6818 if (options.cpu_profiler) {
6821 if (options.cpu_profiler_print) {
6824 profile->GetTopDownRoot());
6833 if (fuzzilli_reprl) {
6834 int status =
result << 8;
6835 std::vector<bool> bitmap;
6836 if (options.fuzzilli_enable_builtins_coverage) {
6837 bitmap = i::BasicBlockProfiler::Get()->GetCoverageBitmap(
6841 if (options.fuzzilli_coverage_statistics) {
6843 for (
bool b : bitmap) {
6846 static int iteration_counter = 0;
6847 std::ofstream covlog(
"covlog.txt", std::ios::app);
6848 covlog << iteration_counter <<
"\t" << tot <<
"\t"
6850 << bitmap.size() << std::endl;
6851 iteration_counter++;
6859 if (options.fuzzilli_enable_builtins_coverage) {
6860 i::BasicBlockProfiler::Get()->ResetCounts(
6865 }
while (fuzzilli_reprl);
6868 cached_code_map_.clear();
6869 evaluation_context_.Reset();
6870 stringify_function_.Reset();
6871 ResetOnProfileEndListener(isolate);
6872 CollectGarbage(isolate);
6874 OnExit(isolate,
true);
6878 if (options.trace_enabled) {
6883#ifdef V8_TARGET_OS_WIN
6886 for (
char* utf8_str : utf8_filenames) {
6889 utf8_filenames.clear();
RegisterAllocator * allocator_
uint8_t data_[MAX_STACK_LENGTH]
union v8::internal::@341::BuiltinMetadata::KindSpecificData data
static Local< ArrayBuffer > New(Isolate *isolate, size_t byte_length, BackingStoreInitializationMode initialization_mode=BackingStoreInitializationMode::kZeroInitialized)
static Local< Array > New(Isolate *isolate, int length=0)
Local< Object > CreateHook(const v8::FunctionCallbackInfo< v8::Value > &info)
CheckMessageFromWorkerTask(v8::Isolate *isolate, std::shared_ptr< Worker > worker)
std::shared_ptr< Worker > worker_
std::shared_ptr< Worker > worker_
CleanUpWorkerTask(v8::Isolate *isolate, std::shared_ptr< Worker > worker)
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())
Counter * GetNextCounter()
bool is_histogram() const
static const int kMaxNameSize
void Bind(const char *name, bool histogram)
void AddSample(int32_t sample)
CpuProfilingStatus StartProfiling(Local< String > title, CpuProfilingOptions options, std::unique_ptr< DiscardedSamplesDelegate > delegate=nullptr)
static CpuProfiler * New(Isolate *isolate, CpuProfilingNamingMode=kDebugNaming, CpuProfilingLoggingMode=kLazyLogging)
CpuProfile * StopProfiling(Local< String > title)
static int GetStressRuns()
static void DeoptimizeAll(Isolate *isolate)
Deserializer(Isolate *isolate, std::unique_ptr< SerializationData > data)
Deserializer & operator=(const Deserializer &)=delete
Deserializer(const Deserializer &)=delete
const SharedValueConveyor * GetSharedValueConveyor(Isolate *isolate) override
MaybeLocal< WasmModuleObject > GetWasmModuleFromId(Isolate *isolate, uint32_t transfer_id) override
std::unique_ptr< SerializationData > data_
ValueDeserializer deserializer_
MaybeLocal< SharedArrayBuffer > GetSharedArrayBufferFromId(Isolate *isolate, uint32_t clone_id) override
MaybeLocal< Value > ReadValue(Local< Context > context)
size_t GetMoreData(const uint8_t **src) override
DummySourceStream(Isolate *isolate, Local< String > source)
std::unique_ptr< uint16_t[]> source_buffer_
V8_INLINE Local< T > Escape(Local< T > value)
static Local< Message > CreateMessage(Isolate *isolate, Local< Value > exception)
static Local< Value > TypeError(Local< String > message, Local< Value > options={})
static Local< Value > SyntaxError(Local< String > message, Local< Value > options={})
static Local< Value > Error(Local< String > message, Local< Value > options={})
size_t length() const override
ExternalOwningOneByteStringResource(std::unique_ptr< base::OS::MemoryMappedFile > file)
ExternalOwningOneByteStringResource()=default
std::unique_ptr< base::OS::MemoryMappedFile > file_
const char * data() const override
static Local< External > New(Isolate *isolate, void *value)
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)
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)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Call(v8::Isolate *isolate, Local< Context > context, Local< Value > recv, int argc, Local< Value > argv[])
static void ControlFlowViolation()
static void ObservableDifference()
static void UseAfterFree()
static void UseOfUninitializedValue()
static void UndefinedBehavior()
static void SimulateErrors()
void runMessageLoopOnPause(int contextGroupId) override
Global< Context > context_
static v8_inspector::V8InspectorSession * GetSession(Local< Context > context)
void quitMessageLoopOnPause() override
InspectorClient(Isolate *isolate, const Global< Context > &global_context, bool connect)
std::unique_ptr< v8_inspector::V8Inspector > inspector_
static void SendInspectorMessage(const v8::FunctionCallbackInfo< v8::Value > &info)
std::unique_ptr< v8_inspector::V8InspectorSession > session_
std::unique_ptr< v8_inspector::V8Inspector::Channel > channel_
Local< Context > ensureDefaultContextInGroup(int group_id) override
void flushProtocolNotifications() override
~InspectorFrontend() override=default
void sendResponse(int callId, std::unique_ptr< v8_inspector::StringBuffer > message) override
void sendNotification(std::unique_ptr< v8_inspector::StringBuffer > message) override
Global< Context > context_
void Send(const v8_inspector::StringView &string)
InspectorFrontend(Local< Context > context)
static Local< Integer > New(Isolate *isolate, int32_t value)
void SetWasmJSPIEnabledCallback(WasmJSPIEnabledCallback callback)
V8_INLINE void SetData(uint32_t slot, void *data)
void InstallConditionalFeatures(Local< Context > context)
static Isolate * New(const CreateParams ¶ms)
void TerminateExecution()
bool IsExecutionTerminating()
static V8_WARN_UNUSED_RESULT MaybeLocal< String > Stringify(Local< Context > context, Local< Value > json_object, Local< String > gap=Local< String >())
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > Parse(Local< Context > context, Local< String > json_string)
V8_INLINE Local< S > As() const
static V8_INLINE Local< T > Cast(Local< S > that)
static V8_INLINE Local< T > New(Isolate *isolate, Local< T > that)
V8_WARN_UNUSED_RESULT V8_INLINE bool ToLocal(Local< S > *out) const
V8_INLINE Local< T > ToLocalChecked()
V8_INLINE bool IsEmpty() const
V8_INLINE bool IsJust() const
V8_INLINE T FromJust() const &
static std::unique_ptr< MeasureMemoryDelegate > Default(Isolate *isolate, Local< Context > context, Local< Promise::Resolver > promise_resolver, MeasureMemoryMode mode)
static void PerformCheckpoint(Isolate *isolate)
static Local< Module > CreateSyntheticModule(Isolate *isolate, Local< String > module_name, const MemorySpan< const Local< String > > &export_names, SyntheticModuleEvaluationSteps evaluation_steps)
static Local< Number > New(Isolate *isolate, double value)
static Local< ObjectTemplate > New(Isolate *isolate, Local< FunctionTemplate > constructor=Local< FunctionTemplate >())
static Local< Object > New(Isolate *isolate)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > Get(Local< Context > context, Local< Value > key)
v8::Global< v8::Value > callback_
OnMessageFromWorkerTask(v8::Isolate *isolate, v8::Local< v8::Context > context, v8::Local< v8::Value > callback, std::unique_ptr< SerializationData > data)
v8::Global< v8::Context > context_
std::unique_ptr< SerializationData > data_
virtual size_t AllocatePageSize()=0
ExplicitRealmScope(PerIsolateData *data, int index)
Local< Context > context() const
RealmScope(Isolate *isolate, const Global< Context > &context)
std::pair< Local< Context >, Local< Function > > GetWorkerOnMessage(const std::shared_ptr< Worker > &worker) const
Local< FunctionTemplate > GetDomNodeCtor() const
void UnregisterWorker(const std::shared_ptr< Worker > &worker)
void AddDynamicImportData(DynamicImportData *)
AsyncHooks * GetAsyncHooks()
static PerIsolateData * Get(Isolate *isolate)
void SubscribeWorkerOnMessage(const std::shared_ptr< Worker > &worker, Local< Context > context, Local< Function > callback)
Global< Context > * realms_
std::set< std::shared_ptr< Worker > > registered_workers_
void SetDomNodeCtor(Local< FunctionTemplate > ctor)
Global< FunctionTemplate > test_api_object_ctor_
void RemoveUnhandledPromise(Local< Promise > promise)
AsyncHooks * async_hooks_wrapper_
bool HasRunningSubscribedWorkers()
bool ignore_unhandled_promises_
void RegisterWorker(std::shared_ptr< Worker > worker)
Global< FunctionTemplate > dom_node_ctor_
int RealmFind(Local< Context > context)
PerIsolateData(Isolate *isolate)
void DeleteDynamicImportData(DynamicImportData *)
void AddUnhandledPromise(Local< Promise > promise, Local< Message > message, Local< Value > exception)
Local< FunctionTemplate > GetTestApiObjectCtor() const
int RealmIndexOrThrow(const v8::FunctionCallbackInfo< v8::Value > &info, int arg_offset)
std::map< std::shared_ptr< Worker >, std::pair< Global< Context >, Global< Function > > > worker_message_callbacks_
std::vector< std::tuple< Global< Promise >, Global< Message >, Global< Value > > > unhandled_promises_
void SetTestApiObjectCtor(Local< FunctionTemplate > ctor)
int HandleUnhandledPromiseRejections()
V8_INLINE void AnnotateStrongRetainer(const char *label)
V8_INLINE Local< T > Get(Isolate *isolate) const
static Local< PrimitiveArray > New(Isolate *isolate, int length)
std::shared_ptr< Worker > worker_
std::unique_ptr< SerializationData > data_
void RunInternal() override
ProcessMessageTask(i::CancelableTaskManager *task_manager, std::shared_ptr< Worker > worker, std::unique_ptr< SerializationData > data)
static V8_WARN_UNUSED_RESULT MaybeLocal< Resolver > New(Local< Context > context)
void ConfigureDefaults(uint64_t physical_memory, uint64_t virtual_memory_limit)
static V8_EXPORT void InitializeBeforeThreadCreation()
static CachedData * CreateCodeCache(Local< UnboundScript > unbound_script)
static V8_WARN_UNUSED_RESULT MaybeLocal< Module > CompileModule(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
static V8_WARN_UNUSED_RESULT MaybeLocal< UnboundScript > CompileUnboundScript(Isolate *isolate, Source *source, CompileOptions options=kNoCompileOptions, NoCacheReason no_cache_reason=kNoCacheNoReason)
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)
V8_INLINE Local< Data > GetHostDefinedOptions() const
static V8_WARN_UNUSED_RESULT MaybeLocal< Script > Compile(Local< Context > context, Local< String > source, ScriptOrigin *origin=nullptr)
void Enqueue(std::unique_ptr< SerializationData > data)
bool Dequeue(std::unique_ptr< SerializationData > *data)
std::vector< Global< SharedArrayBuffer > > shared_array_buffers_
std::vector< std::shared_ptr< v8::BackingStore > > backing_stores_
Maybe< bool > PrepareTransfer(Local< Context > context, Local< Value > transfer)
std::vector< Global< WasmModuleObject > > wasm_modules_
Maybe< uint32_t > GetWasmModuleTransferId(Isolate *isolate, Local< WasmModuleObject > module) override
Serializer(Isolate *isolate)
bool AdoptSharedValueConveyor(Isolate *isolate, SharedValueConveyor &&conveyor) override
Maybe< uint32_t > GetSharedArrayBufferId(Isolate *isolate, Local< SharedArrayBuffer > shared_array_buffer) override
Maybe< bool > FinalizeTransfer()
void AppendBackingStoresTo(std::vector< std::shared_ptr< BackingStore > > *to)
std::unique_ptr< SerializationData > data_
void ThrowDataCloneError(Local< String > message) override
Maybe< bool > WriteValue(Local< Context > context, Local< Value > value, Local< Value > transfer)
Serializer & operator=(const Serializer &)=delete
std::vector< Global< ArrayBuffer > > array_buffers_
Serializer(const Serializer &)=delete
void * ReallocateBufferMemory(void *old_buffer, size_t size, size_t *actual_size) override
std::unique_ptr< SerializationData > Release()
ValueSerializer serializer_
void FreeBufferMemory(void *buffer) override
size_t current_memory_usage_
v8::Global< v8::Function > callback_
SetTimeoutTask(v8::Isolate *isolate, v8::Local< v8::Context > context, v8::Local< v8::Function > callback)
v8::Global< v8::Context > context_
@ kProduceCacheAfterExecute
DisallowReassignment< int > stress_runs
static void RealmCurrent(const v8::FunctionCallbackInfo< v8::Value > &info)
static void InstallConditionalFeatures(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WriteChars(const char *name, uint8_t *buffer, size_t buffer_size)
static void WriteStdout(const v8::FunctionCallbackInfo< v8::Value > &info)
static int Main(int argc, char *argv[])
static CounterCollection * counters_
static void WorkerTerminateAndWait(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< Promise > HostImportModuleDynamically(Local< Context > context, Local< Data > host_defined_options, Local< Value > resource_name, Local< String > specifier, Local< FixedArray > import_attributes)
static MaybeLocal< Context > CreateEvaluationContext(Isolate *isolate)
static void AddHistogramSample(void *histogram, int sample)
static base::OS::MemoryMappedFile * counters_file_
static void update_script_size(int size)
static std::map< Isolate *, std::pair< Global< Function >, Global< Context > > > profiler_end_callback_
static void RealmGlobal(const v8::FunctionCallbackInfo< v8::Value > &info)
static Local< ObjectTemplate > CreatePerformanceTemplate(Isolate *isolate)
static void RealmCreate(const v8::FunctionCallbackInfo< v8::Value > &info)
static void PerformanceMark(const v8::FunctionCallbackInfo< v8::Value > &info)
static Global< Function > stringify_function_
static void ScheduleTermination(const v8::FunctionCallbackInfo< v8::Value > &info)
static bool ExecuteModule(Isolate *isolate, const char *file_name)
static std::unique_ptr< base::OS::MemoryMappedFile > ReadFileData(Isolate *isolate, const char *name, bool should_throw=true)
static std::map< std::string, std::unique_ptr< ScriptCompiler::CachedData > > cached_code_map_
static Local< FunctionTemplate > CreateLeafInterfaceTypeTemplate(Isolate *isolate)
static MaybeLocal< Value > DeserializeValue(Isolate *isolate, std::unique_ptr< SerializationData > data)
static Local< FunctionTemplate > CreateEventTargetTemplate(Isolate *isolate)
static void PerformanceMeasure(const v8::FunctionCallbackInfo< v8::Value > &info)
static Local< ObjectTemplate > CreateD8Template(Isolate *isolate)
static void WorkerOnMessageGetter(const v8::FunctionCallbackInfo< v8::Value > &info)
static void ProfilerTriggerSample(const v8::FunctionCallbackInfo< v8::Value > &info)
static base::LazyMutex cached_code_mutex_
static char * ReadChars(const char *name, int *size_out)
static void ReadCodeTypeAndArguments(const v8::FunctionCallbackInfo< v8::Value > &info, int index, CodeType *code_type, Local< Value > *arguments=nullptr)
static void CreateWasmMemoryMapDescriptor(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WriteLcovData(v8::Isolate *isolate, const char *file)
static void RealmDetachGlobal(const v8::FunctionCallbackInfo< v8::Value > &info)
static void AsyncHooksExecutionAsyncId(const v8::FunctionCallbackInfo< v8::Value > &info)
static std::unordered_set< std::shared_ptr< Worker > > running_workers_
static bool RunMainIsolate(Isolate *isolate, bool keep_context_alive)
static void ResetOnProfileEndListener(Isolate *isolate)
static void SetFlushDenormals(const v8::FunctionCallbackInfo< v8::Value > &info)
static Local< ObjectTemplate > CreateRealmTemplate(Isolate *isolate)
static base::OnceType quit_once_
static void WorkerPostMessage(const v8::FunctionCallbackInfo< v8::Value > &info)
static void PerformanceMeasureMemory(const v8::FunctionCallbackInfo< v8::Value > &info)
static void RealmSharedGet(Local< Name > property, const PropertyCallbackInfo< Value > &info)
static void EnableDebugger(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WaitForRunningWorkers(const i::ParkedScope &parked)
static Local< String > WasmLoadSourceMapCallback(Isolate *isolate, const char *name)
static void * CreateHistogram(const char *name, int min, int max, size_t buckets)
static void NodeTypeCallback(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WorkerTerminate(const v8::FunctionCallbackInfo< v8::Value > &info)
static void SerializerSerialize(const v8::FunctionCallbackInfo< v8::Value > &info)
static bool ExecuteString(Isolate *isolate, Local< String > source, Local< String > name, ReportExceptions report_exceptions, Global< Value > *out_result=nullptr)
static int RunMain(Isolate *isolate, bool last_run)
static MaybeLocal< PrimitiveArray > ReadLines(Isolate *isolate, const char *name)
static void RealmSharedSet(Local< Name > property, Local< Value > value, const PropertyCallbackInfo< void > &info)
static void AsyncHooksTriggerAsyncId(const v8::FunctionCallbackInfo< v8::Value > &info)
static void ReadBuffer(const v8::FunctionCallbackInfo< v8::Value > &info)
static void RealmSwitch(const v8::FunctionCallbackInfo< v8::Value > &info)
static void HostInitializeImportMetaObject(Local< Context > context, Local< Module > module, Local< Object > meta)
static Local< ObjectTemplate > CreateTestRunnerTemplate(Isolate *isolate)
static void ModuleResolutionSuccessCallback(const v8::FunctionCallbackInfo< v8::Value > &info)
static bool allow_new_workers_
static int DeserializationRunCount()
static void Quit(const v8::FunctionCallbackInfo< v8::Value > &info)
static void AsyncHooksCreateHook(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WriteFile(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< Context > HostCreateShadowRealmContext(Local< Context > initiator_context)
static void Version(const v8::FunctionCallbackInfo< v8::Value > &info)
static void RunShell(Isolate *isolate)
static void TestVerifySourcePositions(const v8::FunctionCallbackInfo< v8::Value > &info)
static base::LazyMutex workers_mutex_
static void SetPromiseHooks(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< Object > FetchModuleSource(v8::Local< v8::Module > origin_module, v8::Local< v8::Context > context, const std::string &file_name, ModuleType module_type)
static std::atomic< bool > valid_fuzz_script_
static base::Mutex counter_mutex_
static Local< ObjectTemplate > CreateOSTemplate(Isolate *isolate)
static const base::TimeTicks kInitialTicks
static void DoHostImportModuleDynamically(void *data)
static base::Mutex profiler_end_callback_lock_
static Counter * GetCounter(const char *name, bool is_histogram)
static void TriggerOnProfileEndListener(Isolate *isolate, std::string profile)
static Local< FunctionTemplate > CreateNodeTemplates(Isolate *isolate, Local< FunctionTemplate > event_target)
static bool FunctionAndArgumentsToString(Local< Function > function, Local< Value > arguments, Local< String > *source, Isolate *isolate)
static void OnExit(Isolate *isolate, bool dispose)
static void RemoveRunningWorker(const std::shared_ptr< Worker > &worker)
static bool SetOptions(int argc, char *argv[])
static void RealmDispose(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< Context > CreateRealm(const v8::FunctionCallbackInfo< v8::Value > &info, int index, v8::MaybeLocal< Value > global_object)
static Local< FunctionTemplate > CreateWorkerTemplate(Isolate *isolate)
static void ReadLine(const v8::FunctionCallbackInfo< v8::Value > &info)
static void SerializerDeserialize(const v8::FunctionCallbackInfo< v8::Value > &info)
static bool LoadJSON(Isolate *isolate, const char *file_name)
static Local< ObjectTemplate > CreateAsyncHookTemplate(Isolate *isolate)
static void WorkerOnMessageSetter(const v8::FunctionCallbackInfo< v8::Value > &info)
static int * LookupCounter(const char *name)
static void PerformanceNow(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< String > ReadFile(Isolate *isolate, const char *name, bool should_throw=true)
static CounterCollection local_counters_
static void WriteIgnitionDispatchCountersFile(v8::Isolate *isolate)
static CounterMap * counter_map_
static void LogGetAndStop(const v8::FunctionCallbackInfo< v8::Value > &info)
static uint64_t GetTracingTimestampFromPerformanceTimestamp(double performance_timestamp)
static void PromiseRejectCallback(v8::PromiseRejectMessage reject_message)
static bool HandleUnhandledPromiseRejections(Isolate *isolate)
static void QuitOnce(v8::FunctionCallbackInfo< v8::Value > *info)
static double GetTimestamp()
static bool HasOnProfileEndListener(Isolate *isolate)
static void EnableJSPI(const v8::FunctionCallbackInfo< v8::Value > &info)
static void SetTimeout(const v8::FunctionCallbackInfo< v8::Value > &info)
static void set_script_executed()
static MaybeLocal< Module > FetchModuleTree(v8::Local< v8::Module > origin_module, v8::Local< v8::Context > context, const std::string &file_name, ModuleType module_type)
static std::atomic< bool > script_executed_
static Global< Context > evaluation_context_
static bool CompleteMessageLoop(Isolate *isolate)
static void Initialize(Isolate *isolate, D8Console *console, bool isOnMainThread=true)
static void ExecuteFile(const v8::FunctionCallbackInfo< v8::Value > &info)
static Local< String > Stringify(Isolate *isolate, Local< Value > value)
static std::unique_ptr< SerializationData > SerializeValue(Isolate *isolate, Local< Value > value, Local< Value > transfer)
static void CollectGarbage(Isolate *isolate)
static std::atomic< int > unhandled_promise_rejections_
static ArrayBuffer::Allocator * array_buffer_allocator
static void TerminateNow(const v8::FunctionCallbackInfo< v8::Value > &info)
static void RealmCreateAllowCrossRealmAccess(const v8::FunctionCallbackInfo< v8::Value > &info)
static Local< FunctionTemplate > CreateTestFastCApiTemplate(Isolate *isolate)
static void StoreInCodeCache(Isolate *isolate, Local< Value > name, const ScriptCompiler::CachedData *data)
static void RealmEval(const v8::FunctionCallbackInfo< v8::Value > &info)
static void RealmOwner(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< String > ReadSource(const v8::FunctionCallbackInfo< v8::Value > &info, int index, CodeType default_type)
static void DisableDebugger(const v8::FunctionCallbackInfo< v8::Value > &info)
static void RealmNavigate(const v8::FunctionCallbackInfo< v8::Value > &info)
static void AddRunningWorker(std::shared_ptr< Worker > worker)
static void ProfilerSetOnProfileEndListener(const v8::FunctionCallbackInfo< v8::Value > &info)
static MaybeLocal< Promise > HostImportModuleWithPhaseDynamically(Local< Context > context, Local< Data > host_defined_options, Local< Value > resource_name, Local< String > specifier, ModuleImportPhase phase, Local< FixedArray > import_attributes)
static base::LazyMutex context_mutex_
static Local< ObjectTemplate > CreateGlobalTemplate(Isolate *isolate)
static ScriptCompiler::CachedData * LookupCodeCache(Isolate *isolate, Local< Value > name)
static void DisposeRealm(const v8::FunctionCallbackInfo< v8::Value > &info, int index)
static MaybeLocal< Value > JSONModuleEvaluationSteps(Local< Context > context, Local< Module > module)
static ShellOptions options
static void ModuleResolutionFailureCallback(const v8::FunctionCallbackInfo< v8::Value > &info)
static void ReportException(Isolate *isolate, Local< Message > message, Local< Value > exception)
static void Print(const v8::FunctionCallbackInfo< v8::Value > &info)
static void PrintErr(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WorkerGetMessage(const v8::FunctionCallbackInfo< v8::Value > &info)
static void MapCounters(v8::Isolate *isolate, const char *name)
static bool EmptyMessageQueues(Isolate *isolate)
static void GetExtrasBindingObject(const v8::FunctionCallbackInfo< v8::Value > &info)
static void WorkerNew(const v8::FunctionCallbackInfo< v8::Value > &info)
static Local< String > ReadFromStdin(Isolate *isolate)
static bool FinishExecuting(Isolate *isolate, const Global< Context > &context)
static MaybeLocal< T > CompileString(Isolate *isolate, Local< Context > context, Local< String > source, const ScriptOrigin &origin)
static Local< Signature > New(Isolate *isolate, Local< FunctionTemplate > receiver=Local< FunctionTemplate >())
IsolateThread(SourceGroup *group)
void JoinThread(const i::ParkedScope &parked)
void Begin(char **argv, int offset)
i::ParkingSemaphore next_semaphore_
void StartExecuteInThread()
i::ParkingSemaphore done_semaphore_
bool Execute(Isolate *isolate)
void WaitForThread(const i::ParkedScope &parked)
static void StartThreadForTaskAndJoin(v8::ScriptCompiler::ScriptStreamingTask *task)
StreamerThread(v8::ScriptCompiler::ScriptStreamingTask *task)
v8::ScriptCompiler::ScriptStreamingTask * task_
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)
static Local< String > Concat(Isolate *isolate, Local< String > left, Local< String > right)
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewExternalOneByte(Isolate *isolate, ExternalOneByteStringResource *resource)
static V8_INLINE Local< String > Empty(Isolate *isolate)
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromTwoByte(Isolate *isolate, const uint16_t *data, NewStringType type=NewStringType::kNormal, int length=-1)
static V8_WARN_UNUSED_RESULT MaybeLocal< String > NewFromOneByte(Isolate *isolate, const uint8_t *data, NewStringType type=NewStringType::kNormal, int length=-1)
static Local< Symbol > GetToStringTag(Isolate *isolate)
std::shared_ptr< Worker > worker_
TerminateTask(i::CancelableTaskManager *task_manager, std::shared_ptr< Worker > worker)
void RunInternal() override
void SetVerbose(bool value)
Local< v8::Message > Message() const
bool HasTerminated() const
Local< Value > Exception() const
static V8_WARN_UNUSED_RESULT MaybeLocal< Value > StackTrace(Local< Context > context, Local< Value > exception)
static v8::internal::Handle< To > OpenHandle(v8::Local< From > handle)
static v8::internal::DirectHandle< To > OpenDirectHandle(v8::Local< From > handle)
static void DisposePlatform()
static const char * GetVersion()
static void InitializeExternalStartupDataFromFile(const char *snapshot_blob)
static void InitializePlatform(Platform *platform)
static void InitializeExternalStartupData(const char *directory_path)
static bool InitializeICUDefaultLocation(const char *exec_path, const char *icu_data_file=nullptr)
static V8_INLINE bool Initialize()
static void SetFlagsFromString(const char *str)
static bool EnableWebAssemblyTrapHandler(bool use_v8_signal_handler)
V8_WARN_UNUSED_RESULT Maybe< bool > ReadHeader(Local< Context > context)
V8_WARN_UNUSED_RESULT MaybeLocal< Value > ReadValue(Local< Context > context)
V8_WARN_UNUSED_RESULT std::pair< uint8_t *, size_t > Release()
V8_WARN_UNUSED_RESULT Maybe< bool > WriteValue(Local< Context > context, Local< Value > value)
bool BooleanValue(Isolate *isolate) const
int32_t WasmFileDescriptor
static Local< WasmMemoryMapDescriptor > New(Isolate *isolate, WasmFileDescriptor fd)
static MaybeLocal< WasmModuleObject > Compile(Isolate *isolate, MemorySpan< const uint8_t > wire_bytes)
std::shared_ptr< Worker > worker_
i::CancelableTaskManager * task_manager_
std::shared_ptr< TaskRunner > task_runner_
std::unique_ptr< SerializationData > TryGetMessage()
void ProcessMessage(std::unique_ptr< SerializationData > data)
i::ParkingSemaphore started_semaphore_
friend class ProcessMessageTask
base::Mutex worker_mutex_
friend class TerminateTask
static void Close(const v8::FunctionCallbackInfo< v8::Value > &info)
Worker(Isolate *parent_isolate, const char *script, bool flush_denormals)
Global< Context > context_
static void PostMessageOut(const v8::FunctionCallbackInfo< v8::Value > &info)
void PostMessage(std::unique_ptr< SerializationData > data)
void EnterTerminatedState()
std::atomic< State > state_
i::ParkingSemaphore out_semaphore_
static bool StartWorkerThread(Isolate *requester, std::shared_ptr< Worker > worker, base::Thread::Priority priority)
std::unique_ptr< SerializationData > GetMessage(Isolate *requester)
static void SetCurrentWorker(Worker *worker)
void TerminateAndWaitForThread(const i::ParkedScope &parked)
SerializationDataQueue out_queue_
static void ImportScripts(const v8::FunctionCallbackInfo< v8::Value > &info)
Isolate * parent_isolate_
static Worker * GetCurrentWorker()
V8_INLINE bool IsEmpty() const
static V8_BASE_EXPORT bool GetFlushDenormals()
static V8_BASE_EXPORT void SetFlushDenormals(bool)
static MemoryMappedFile * create(const char *name, size_t size, void *initial)
static MemoryMappedFile * open(const char *name, FileMode mode=FileMode::kReadWrite)
static void ExitProcess(int exit_code)
static FILE * FOpen(const char *path, const char *mode)
static int GetPeakMemoryUsageKb()
static void StrNCpy(char *dest, int length, const char *src, size_t n)
static int64_t AmountOfPhysicalMemory()
static int64_t AmountOfVirtualMemory()
Thread(const Options &options)
V8_WARN_UNUSED_RESULT bool Start()
static constexpr int64_t kMillisecondsPerSecond
static constexpr TimeDelta FromMillisecondsD(double milliseconds)
double InMillisecondsF() const
BlockData GetBlockData(size_t i) const
MaybeLocal< String > Name() const
size_t BlockCount() const
FunctionData GetFunctionData(size_t i) const
size_t FunctionCount() const
Local< debug::Script > GetScript() const
static void SelectMode(Isolate *isolate, CoverageMode mode)
static Coverage CollectPrecise(Isolate *isolate)
int GetLineNumber() const
V8_EXPORT_PRIVATE void CollectAllAvailableGarbage(GarbageCollectionReason gc_reason)
debug::ConsoleDelegate * console_delegate()
bool is_shared_space_isolate() const
LocalIsolate * main_thread_local_isolate()
OptimizingCompileDispatcher * optimizing_compile_dispatcher()
bool is_execution_terminating()
ThreadManager * thread_manager() const
Tagged< Object > TerminateExecution()
V8FileLogger * v8_file_logger() const
bool get_capture_stack_trace_for_uncaught_exceptions() const
bool concurrent_recompilation_enabled()
LocalHeap * main_thread_local_heap()
Tagged< Object > StackOverflow()
V8_INLINE void ExecuteMainThreadWhileParked(Callback callback)
V8_INLINE void ExecuteMainThreadWhileParked(Callback callback)
V8_INLINE void ParkedWait(LocalIsolate *local_isolate)
PendingCompilationErrorHandler * pending_error_handler()
AstValueFactory * ast_value_factory() const
Handle< Script > CreateScript(IsolateT *isolate, DirectHandle< String > source, MaybeDirectHandle< FixedArray > maybe_wrapped_arguments, ScriptOriginOptions origin_options, NativesFlag natives=NOT_NATIVES_CODE)
V8_EXPORT_PRIVATE void ReportErrors(Isolate *isolate, Handle< Script > script) const
void PrepareErrors(IsolateT *isolate, AstValueFactory *ast_value_factory)
void Print(int indent) const
bool HasOverflowed() const
bool IsLockedByCurrentThread() const
V8_EXPORT_PRIVATE void Unlock()
V8_EXPORT_PRIVATE std::string file_name() const
V8_EXPORT_PRIVATE bool is_logging()
V8_EXPORT_PRIVATE FILE * TearDownAndGetLogFile()
virtual void dispatchProtocolMessage(StringView message)=0
static std::unique_ptr< V8Inspector > create(v8::Isolate *, V8InspectorClient *)
void sanitizer_cov_reset_edgeguards()
uint32_t sanitizer_cov_count_discovered_edges()
void cov_update_builtins_basic_block_coverage(const std::vector< bool > &cov_map)
void cov_init_builtins_edges(uint32_t num_edges)
Handle< Context > context_
base::Vector< const DirectHandle< Object > > args
v8::Global< v8::Promise::Resolver > resolver_
int main(int argc, const char *argv[])
ZoneVector< RpoNumber > & result
LiftoffAssembler::CacheState state
InstructionOperand source
V8_INLINE size_t hash_combine(size_t seed, size_t hash)
void CallOnce(OnceType *once, std::function< void()> init_func)
void EnsureConsoleOutput()
std::atomic< uint8_t > OnceType
FILE * Fopen(const char *filename, const char *mode)
LazyStaticInstance< Mutex, DefaultConstructTrait< Mutex >, ThreadSafeInitOnceTrait >::type LazyMutex
void SetConsoleDelegate(Isolate *v8_isolate, ConsoleDelegate *delegate)
void SetDebugDelegate(Isolate *v8_isolate, DebugDelegate *delegate)
constexpr int kFunctionEntryBytecodeOffset
constexpr NullMaybeHandleType kNullMaybeHandle
void * AllocatePages(v8::PageAllocator *page_allocator, void *hint, size_t size, size_t alignment, PageAllocator::Permission access)
int g_num_isolates_for_testing
bool V8_EXPORT ValidateCallbackInfo(const FunctionCallbackInfo< void > &info)
size_t AllocatePageSize()
@ kD8ModuleEmbedderDataTag
V8_EXPORT_PRIVATE FlagValues v8_flags
LanguageMode construct_language_mode(bool strict_bit)
std::string ReadFile(const char *filename, bool *exists, bool verbose)
void FreePages(v8::PageAllocator *page_allocator, void *address, const size_t size)
too high values may cause the compiler to set high thresholds for inlining to as much as possible avoid inlined allocation of objects that cannot escape trace load stores from virtual maglev objects use TurboFan fast string builder analyze liveness of environment slots and zap dead values trace TurboFan load elimination emit data about basic block usage in builtins to this enable builtin reordering when run mksnapshot flag for emit warnings when applying builtin profile data verify register allocation in TurboFan randomly schedule instructions to stress dependency tracking enable store store elimination in TurboFan rewrite far to near simulate GC compiler thread race related to allow float parameters to be passed in simulator mode JS Wasm Run additional turbo_optimize_inlined_js_wasm_wrappers enable experimental feedback collection in generic lowering enable Turboshaft s WasmLoadElimination enable Turboshaft s low level load elimination for JS enable Turboshaft s escape analysis for string concatenation use enable Turbolev features that we want to ship in the not too far future trace individual Turboshaft reduction steps trace intermediate Turboshaft reduction steps invocation count threshold for early optimization Enables optimizations which favor memory size over execution speed Enables sampling allocation profiler with X as a sample interval min size of a semi the new space consists of two semi spaces max size of the Collect garbage after Collect garbage after keeps maps alive for< n > old space garbage collections print one detailed trace line in allocation gc speed threshold for starting incremental marking via a task in percent of available threshold for starting incremental marking immediately in percent of available Use a single schedule for determining a marking schedule between JS and C objects schedules the minor GC task with kUserVisible priority max worker number of concurrent for NumberOfWorkerThreads start background threads that allocate memory concurrent_array_buffer_sweeping use parallel threads to clear weak refs in the atomic pause trace progress of the incremental marking trace object counts and memory usage * MB
static constexpr int kMaxFixedArrayCapacity
Tagged< To > Cast(Tagged< From > value, const v8::SourceLocation &loc=INIT_SOURCE_LOCATION_IN_DEBUG)
static platform::tracing::TraceConfig * CreateTraceConfigFromJSON(v8::Isolate *isolate, const char *json_str)
v8_inspector::String16 String
V8_INLINE Local< Primitive > Null(Isolate *isolate)
std::unordered_map< std::string, Counter * > CounterMap
bool ends_with(const char *input, const char *suffix)
@ kPromiseHandlerAddedAfterReject
@ kPromiseRejectAfterResolved
@ kPromiseResolveAfterResolved
void WriteToFile(FILE *file, const v8::FunctionCallbackInfo< v8::Value > &info, int first_arg_index=0)
bool ToLocal(v8::internal::MaybeDirectHandle< v8::internal::Object > maybe, Local< T > *local)
void(*)(PromiseRejectMessage message) PromiseRejectCallback
V8_INLINE Local< Primitive > Undefined(Isolate *isolate)
static void PrintMessageCallback(Local< Message > message, Local< Value > error)
Local< FunctionTemplate > NewDOMFunctionTemplate(Isolate *isolate, JSApiInstanceType instance_type)
constexpr Isolate * kProcessGlobalPredictablePlatformWorkerTaskQueue
constexpr std::array< std::remove_cv_t< T >, N > to_array(T(&a)[N])
std::unique_ptr< Platform > MakePredictablePlatform(std::unique_ptr< Platform > platform)
bool check_d8_flag_contradictions
void WriteAndFlush(FILE *file, const v8::FunctionCallbackInfo< v8::Value > &info)
std::unique_ptr< Platform > MakeDelayedTasksPlatform(std::unique_ptr< Platform > platform, int64_t random_seed)
static v8::debug::DebugDelegate dummy_delegate
Maybe< T > Just(const T &t)
#define DCHECK_LE(v1, v2)
#define CHECK_GE(lhs, rhs)
#define CHECK_GT(lhs, rhs)
#define CHECK_LT(lhs, rhs)
#define DCHECK_NOT_NULL(val)
#define CHECK_NOT_NULL(val)
#define DCHECK_GE(v1, v2)
#define CHECK_EQ(lhs, rhs)
#define DCHECK(condition)
#define DCHECK_LT(v1, v2)
#define DCHECK_EQ(v1, v2)
constexpr T RoundUp(T x, intptr_t m)
const AsyncStreamingDecoder::MoreFunctionsCanBeSerializedCallback callback_
Global< String > specifier
DynamicImportData(Isolate *isolate_, Local< Context > context_, Local< Value > referrer_, Local< String > specifier_, ModuleImportPhase phase_, Local< FixedArray > import_attributes_, Local< Promise::Resolver > resolver_)
Global< Context > context
Global< Promise::Resolver > resolver
Global< FixedArray > import_attributes
CounterLookupCallback counter_lookup_callback
CreateHistogramCallback create_histogram_callback
ResourceConstraints constraints
AddHistogramSampleCallback add_histogram_sample_callback
JitCodeEventHandler code_event_handler
ArrayBuffer::Allocator * array_buffer_allocator
#define TRACE_EVENT_COPY_NESTABLE_ASYNC_END_WITH_TIMESTAMP0( category_group, name, id, timestamp)
#define TRACE_EVENT_COPY_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP1( category_group, name, id, timestamp, arg1_name, arg1_val)
#define V8_TRAP_HANDLER_SUPPORTED
#define V8_TARGET_OS_STRING
std::unique_ptr< ValueMirror > value
std::unique_ptr< ValueMirror > key