// Copyright 2007-2010 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include "include/v8-extension.h" #include "include/v8-function.h" #include "include/v8-locker.h" #include "src/api/api-inl.h" #include "src/codegen/compilation-cache.h" #include "src/codegen/compiler.h" #include "src/codegen/script-details.h" #include "src/common/assert-scope.h" #include "src/heap/heap-inl.h" #include "src/heap/parked-scope.h" #include "src/heap/read-only-heap.h" #include "src/heap/safepoint.h" #include "src/heap/spaces.h" #include "src/numbers/hash-seed-inl.h" #include "src/objects/js-array-buffer-inl.h" #include "src/objects/js-regexp-inl.h" #include "src/objects/objects-inl.h" #include "src/runtime/runtime.h" #include "src/snapshot/code-serializer.h" #include "src/snapshot/context-deserializer.h" #include "src/snapshot/context-serializer.h" #include "src/snapshot/read-only-deserializer.h" #include "src/snapshot/read-only-serializer.h" #include "src/snapshot/shared-heap-deserializer.h" #include "src/snapshot/shared-heap-serializer.h" #include "src/snapshot/snapshot-compression.h" #include "src/snapshot/snapshot.h" #include "src/snapshot/startup-deserializer.h" #include "src/snapshot/startup-serializer.h" #include "test/cctest/cctest.h" #include "test/cctest/heap/heap-utils.h" #include "test/cctest/setup-isolate-for-tests.h" namespace v8 { namespace internal { enum CodeCacheType { kLazy, kEager, kAfterExecute }; void DisableAlwaysOpt() { // Isolates prepared for serialization do not optimize. The only exception is // with the flag --always-turbofan. v8_flags.always_turbofan = false; } // A convenience struct to simplify management of the blobs required to // deserialize an isolate. struct StartupBlobs { base::Vector startup; base::Vector read_only; base::Vector shared_space; void Dispose() { startup.Dispose(); read_only.Dispose(); shared_space.Dispose(); } }; // TestSerializer is used for testing isolate serialization. class TestSerializer { public: static v8::Isolate* NewIsolateInitialized() { const bool kEnableSerializer = true; DisableEmbeddedBlobRefcounting(); v8::Isolate* v8_isolate = NewIsolate(kEnableSerializer); v8::Isolate::Scope isolate_scope(v8_isolate); i::Isolate* isolate = reinterpret_cast(v8_isolate); isolate->InitWithoutSnapshot(); return v8_isolate; } // Wraps v8::Isolate::New, but with a test isolate under the hood. // Allows flexibility to bootstrap with or without snapshot even when // the production Isolate class has one or the other behavior baked in. static v8::Isolate* NewIsolate(const v8::Isolate::CreateParams& params) { const bool kEnableSerializer = false; v8::Isolate* v8_isolate = NewIsolate(kEnableSerializer); v8::Isolate::Initialize(v8_isolate, params); return v8_isolate; } static v8::Isolate* NewIsolateFromBlob(const StartupBlobs& blobs) { SnapshotData startup_snapshot(blobs.startup); SnapshotData read_only_snapshot(blobs.read_only); SnapshotData shared_space_snapshot(blobs.shared_space); const bool kEnableSerializer = false; v8::Isolate* v8_isolate = NewIsolate(kEnableSerializer); v8::Isolate::Scope isolate_scope(v8_isolate); i::Isolate* isolate = reinterpret_cast(v8_isolate); isolate->InitWithSnapshot(&startup_snapshot, &read_only_snapshot, &shared_space_snapshot, false); return v8_isolate; } private: // Creates an Isolate instance configured for testing. static v8::Isolate* NewIsolate(bool with_serializer) { i::Isolate* isolate = i::Isolate::New(); v8::Isolate* v8_isolate = reinterpret_cast(isolate); if (with_serializer) isolate->enable_serializer(); isolate->set_array_buffer_allocator(CcTest::array_buffer_allocator()); isolate->setup_delegate_ = new SetupIsolateDelegateForTests; return v8_isolate; } }; static base::Vector WritePayload( base::Vector payload) { int length = payload.length(); uint8_t* blob = NewArray(length); memcpy(blob, payload.begin(), length); return base::Vector(const_cast(blob), length); } namespace { // Convenience wrapper around the convenience wrapper. v8::StartupData CreateSnapshotDataBlob(const char* embedded_source) { v8::StartupData data = CreateSnapshotDataBlobInternal( v8::SnapshotCreator::FunctionCodeHandling::kClear, embedded_source); return data; } } // namespace static StartupBlobs Serialize(v8::Isolate* isolate) { // We have to create one context. One reason for this is so that the builtins // can be loaded from self hosted JS builtins and their addresses can be // processed. This will clear the pending fixups array, which would otherwise // contain GC roots that would confuse the serialization/deserialization // process. v8::Isolate::Scope isolate_scope(isolate); { v8::HandleScope scope(isolate); v8::Context::New(isolate); } Isolate* i_isolate = reinterpret_cast(isolate); heap::CollectAllAvailableGarbage(i_isolate->heap()); IsolateSafepointScope safepoint(i_isolate->heap()); HandleScope scope(i_isolate); DisallowGarbageCollection no_gc; ReadOnlySerializer read_only_serializer(i_isolate, Snapshot::kDefaultSerializerFlags); read_only_serializer.SerializeReadOnlyRoots(); SharedHeapSerializer shared_space_serializer( i_isolate, Snapshot::kDefaultSerializerFlags, &read_only_serializer); StartupSerializer ser(i_isolate, Snapshot::kDefaultSerializerFlags, &read_only_serializer, &shared_space_serializer); ser.SerializeStrongReferences(no_gc); ser.SerializeWeakReferencesAndDeferred(); shared_space_serializer.FinalizeSerialization(); read_only_serializer.FinalizeSerialization(); SnapshotData startup_snapshot(&ser); SnapshotData read_only_snapshot(&read_only_serializer); SnapshotData shared_space_snapshot(&shared_space_serializer); return {WritePayload(startup_snapshot.RawData()), WritePayload(read_only_snapshot.RawData()), WritePayload(shared_space_snapshot.RawData())}; } base::Vector ConstructSource(base::Vector head, base::Vector body, base::Vector tail, int repeats) { size_t source_length = head.size() + body.size() * repeats + tail.size(); char* source = NewArray(source_length); CopyChars(source, head.begin(), head.length()); for (int i = 0; i < repeats; i++) { CopyChars(source + head.length() + i * body.length(), body.begin(), body.length()); } CopyChars(source + head.length() + repeats * body.length(), tail.begin(), tail.length()); return base::VectorOf(source, source_length); } static v8::Isolate* Deserialize(const StartupBlobs& blobs) { v8::Isolate* isolate = TestSerializer::NewIsolateFromBlob(blobs); CHECK(isolate); return isolate; } static void SanityCheck(v8::Isolate* v8_isolate) { Isolate* isolate = reinterpret_cast(v8_isolate); v8::HandleScope scope(v8_isolate); #ifdef VERIFY_HEAP HeapVerifier::VerifyHeap(isolate->heap()); #endif CHECK(isolate->global_object()->IsJSObject()); CHECK(isolate->native_context()->IsContext()); isolate->factory()->InternalizeString(base::StaticCharVector("Empty")); } void TestStartupSerializerOnceImpl() { v8::Isolate* isolate = TestSerializer::NewIsolateInitialized(); StartupBlobs blobs = Serialize(isolate); isolate->Dispose(); isolate = Deserialize(blobs); { v8::HandleScope handle_scope(isolate); v8::Isolate::Scope isolate_scope(isolate); v8::Local env = v8::Context::New(isolate); env->Enter(); SanityCheck(isolate); } isolate->Dispose(); blobs.Dispose(); FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(StartupSerializerOnce) { DisableAlwaysOpt(); TestStartupSerializerOnceImpl(); } UNINITIALIZED_TEST(StartupSerializerTwice) { DisableAlwaysOpt(); v8::Isolate* isolate = TestSerializer::NewIsolateInitialized(); StartupBlobs blobs1 = Serialize(isolate); StartupBlobs blobs2 = Serialize(isolate); isolate->Dispose(); blobs1.Dispose(); isolate = Deserialize(blobs2); { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local env = v8::Context::New(isolate); env->Enter(); SanityCheck(isolate); } isolate->Dispose(); blobs2.Dispose(); FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(StartupSerializerOnceRunScript) { DisableAlwaysOpt(); v8::Isolate* isolate = TestSerializer::NewIsolateInitialized(); StartupBlobs blobs = Serialize(isolate); isolate->Dispose(); isolate = Deserialize(blobs); { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local env = v8::Context::New(isolate); env->Enter(); const char* c_source = "\"1234\".length"; v8::Local script = v8_compile(c_source); v8::Maybe result = script->Run(isolate->GetCurrentContext()) .ToLocalChecked() ->Int32Value(isolate->GetCurrentContext()); CHECK_EQ(4, result.FromJust()); } isolate->Dispose(); blobs.Dispose(); FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(StartupSerializerTwiceRunScript) { DisableAlwaysOpt(); v8::Isolate* isolate = TestSerializer::NewIsolateInitialized(); StartupBlobs blobs1 = Serialize(isolate); StartupBlobs blobs2 = Serialize(isolate); isolate->Dispose(); blobs1.Dispose(); isolate = Deserialize(blobs2); { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local env = v8::Context::New(isolate); env->Enter(); const char* c_source = "\"1234\".length"; v8::Local script = v8_compile(c_source); v8::Maybe result = script->Run(isolate->GetCurrentContext()) .ToLocalChecked() ->Int32Value(isolate->GetCurrentContext()); CHECK_EQ(4, result.FromJust()); } isolate->Dispose(); blobs2.Dispose(); FreeCurrentEmbeddedBlob(); } static void SerializeContext(base::Vector* startup_blob_out, base::Vector* read_only_blob_out, base::Vector* shared_space_blob_out, base::Vector* context_blob_out) { v8::Isolate* v8_isolate = TestSerializer::NewIsolateInitialized(); Isolate* isolate = reinterpret_cast(v8_isolate); Heap* heap = isolate->heap(); { v8::Isolate::Scope isolate_scope(v8_isolate); v8::Persistent env; { HandleScope scope(isolate); env.Reset(v8_isolate, v8::Context::New(v8_isolate)); } CHECK(!env.IsEmpty()); { v8::HandleScope handle_scope(v8_isolate); v8::Local::New(v8_isolate, env)->Enter(); } // If we don't do this then we end up with a stray root pointing at the // context even after we have disposed of env. heap::CollectAllAvailableGarbage(heap); { v8::HandleScope handle_scope(v8_isolate); v8::Local::New(v8_isolate, env)->Exit(); } HandleScope scope(isolate); i::Context raw_context = i::Context::cast(*v8::Utils::OpenPersistent(env)); env.Reset(); IsolateSafepointScope safepoint(heap); DisallowGarbageCollection no_gc; SnapshotByteSink read_only_sink; ReadOnlySerializer read_only_serializer(isolate, Snapshot::kDefaultSerializerFlags); read_only_serializer.SerializeReadOnlyRoots(); SharedHeapSerializer shared_space_serializer( isolate, Snapshot::kDefaultSerializerFlags, &read_only_serializer); SnapshotByteSink startup_sink; StartupSerializer startup_serializer( isolate, Snapshot::kDefaultSerializerFlags, &read_only_serializer, &shared_space_serializer); startup_serializer.SerializeStrongReferences(no_gc); SnapshotByteSink context_sink; ContextSerializer context_serializer( isolate, Snapshot::kDefaultSerializerFlags, &startup_serializer, v8::SerializeInternalFieldsCallback()); context_serializer.Serialize(&raw_context, no_gc); startup_serializer.SerializeWeakReferencesAndDeferred(); shared_space_serializer.FinalizeSerialization(); read_only_serializer.FinalizeSerialization(); SnapshotData read_only_snapshot(&read_only_serializer); SnapshotData shared_space_snapshot(&shared_space_serializer); SnapshotData startup_snapshot(&startup_serializer); SnapshotData context_snapshot(&context_serializer); *context_blob_out = WritePayload(context_snapshot.RawData()); *startup_blob_out = WritePayload(startup_snapshot.RawData()); *read_only_blob_out = WritePayload(read_only_snapshot.RawData()); *shared_space_blob_out = WritePayload(shared_space_snapshot.RawData()); } v8_isolate->Dispose(); } #ifdef SNAPSHOT_COMPRESSION UNINITIALIZED_TEST(SnapshotCompression) { DisableAlwaysOpt(); base::Vector startup_blob; base::Vector read_only_blob; base::Vector shared_space_blob; base::Vector context_blob; SerializeContext(&startup_blob, &read_only_blob, &shared_space_blob, &context_blob); SnapshotData original_snapshot_data(context_blob); SnapshotData compressed = i::SnapshotCompression::Compress(&original_snapshot_data); SnapshotData decompressed = i::SnapshotCompression::Decompress(compressed.RawData()); CHECK_EQ(context_blob, decompressed.RawData()); startup_blob.Dispose(); read_only_blob.Dispose(); shared_space_blob.Dispose(); context_blob.Dispose(); } #endif // SNAPSHOT_COMPRESSION UNINITIALIZED_TEST(ContextSerializerContext) { DisableAlwaysOpt(); base::Vector startup_blob; base::Vector read_only_blob; base::Vector shared_space_blob; base::Vector context_blob; SerializeContext(&startup_blob, &read_only_blob, &shared_space_blob, &context_blob); StartupBlobs blobs = {startup_blob, read_only_blob, shared_space_blob}; v8::Isolate* v8_isolate = TestSerializer::NewIsolateFromBlob(blobs); CHECK(v8_isolate); { v8::Isolate::Scope isolate_scope(v8_isolate); Isolate* isolate = reinterpret_cast(v8_isolate); HandleScope handle_scope(isolate); Handle root; Handle global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy( JSGlobalProxy::SizeWithEmbedderFields(0)); { SnapshotData snapshot_data(context_blob); root = ContextDeserializer::DeserializeContext( isolate, &snapshot_data, false, global_proxy, v8::DeserializeInternalFieldsCallback()) .ToHandleChecked(); CHECK(root->IsContext()); CHECK(Handle::cast(root)->global_proxy() == *global_proxy); } Handle root2; { SnapshotData snapshot_data(context_blob); root2 = ContextDeserializer::DeserializeContext( isolate, &snapshot_data, false, global_proxy, v8::DeserializeInternalFieldsCallback()) .ToHandleChecked(); CHECK(root2->IsContext()); CHECK(!root.is_identical_to(root2)); } context_blob.Dispose(); } v8_isolate->Dispose(); blobs.Dispose(); FreeCurrentEmbeddedBlob(); } static void SerializeCustomContext( base::Vector* startup_blob_out, base::Vector* read_only_blob_out, base::Vector* shared_space_blob_out, base::Vector* context_blob_out) { v8::Isolate* v8_isolate = TestSerializer::NewIsolateInitialized(); Isolate* isolate = reinterpret_cast(v8_isolate); { v8::Isolate::Scope isolate_scope(v8_isolate); v8::Persistent env; { HandleScope scope(isolate); env.Reset(v8_isolate, v8::Context::New(v8_isolate)); } CHECK(!env.IsEmpty()); { v8::HandleScope handle_scope(v8_isolate); v8::Local::New(v8_isolate, env)->Enter(); // After execution, e's function context refers to the global object. CompileRun( "var e;" "(function() {" " e = function(s) { return eval (s); }" "})();" "var o = this;" "var r = Math.random();" "var c = Math.sin(0) + Math.cos(0);" "var f = (function(a, b) { return a + b; }).bind(1, 2, 3);" "var s = parseInt('12345');" "var p = 0;" "(async ()=>{ p = await 42; })();"); base::Vector source = ConstructSource( base::StaticCharVector("function g() { return [,"), base::StaticCharVector("1,"), base::StaticCharVector("];} a = g(); b = g(); b.push(1);"), 100000); v8::MaybeLocal source_str = v8::String::NewFromUtf8(v8_isolate, source.begin(), v8::NewStringType::kNormal, source.length()); CompileRun(source_str.ToLocalChecked()); source.Dispose(); } // If we don't do this then we end up with a stray root pointing at the // context even after we have disposed of env. heap::CollectAllAvailableGarbage(isolate->heap()); { v8::HandleScope handle_scope(v8_isolate); v8::Local::New(v8_isolate, env)->Exit(); } HandleScope scope(isolate); i::Context raw_context = i::Context::cast(*v8::Utils::OpenPersistent(env)); env.Reset(); IsolateSafepointScope safepoint(isolate->heap()); DisallowGarbageCollection no_gc; SnapshotByteSink read_only_sink; ReadOnlySerializer read_only_serializer(isolate, Snapshot::kDefaultSerializerFlags); read_only_serializer.SerializeReadOnlyRoots(); SharedHeapSerializer shared_space_serializer( isolate, Snapshot::kDefaultSerializerFlags, &read_only_serializer); SnapshotByteSink startup_sink; StartupSerializer startup_serializer( isolate, Snapshot::kDefaultSerializerFlags, &read_only_serializer, &shared_space_serializer); startup_serializer.SerializeStrongReferences(no_gc); SnapshotByteSink context_sink; ContextSerializer context_serializer( isolate, Snapshot::kDefaultSerializerFlags, &startup_serializer, v8::SerializeInternalFieldsCallback()); context_serializer.Serialize(&raw_context, no_gc); startup_serializer.SerializeWeakReferencesAndDeferred(); shared_space_serializer.FinalizeSerialization(); read_only_serializer.FinalizeSerialization(); SnapshotData read_only_snapshot(&read_only_serializer); SnapshotData shared_space_snapshot(&shared_space_serializer); SnapshotData startup_snapshot(&startup_serializer); SnapshotData context_snapshot(&context_serializer); *context_blob_out = WritePayload(context_snapshot.RawData()); *startup_blob_out = WritePayload(startup_snapshot.RawData()); *read_only_blob_out = WritePayload(read_only_snapshot.RawData()); *shared_space_blob_out = WritePayload(shared_space_snapshot.RawData()); } v8_isolate->Dispose(); } UNINITIALIZED_TEST(ContextSerializerCustomContext) { DisableAlwaysOpt(); base::Vector startup_blob; base::Vector read_only_blob; base::Vector shared_space_blob; base::Vector context_blob; SerializeCustomContext(&startup_blob, &read_only_blob, &shared_space_blob, &context_blob); StartupBlobs blobs = {startup_blob, read_only_blob, shared_space_blob}; v8::Isolate* v8_isolate = TestSerializer::NewIsolateFromBlob(blobs); CHECK(v8_isolate); { v8::Isolate::Scope isolate_scope(v8_isolate); Isolate* isolate = reinterpret_cast(v8_isolate); HandleScope handle_scope(isolate); Handle root; Handle global_proxy = isolate->factory()->NewUninitializedJSGlobalProxy( JSGlobalProxy::SizeWithEmbedderFields(0)); { SnapshotData snapshot_data(context_blob); root = ContextDeserializer::DeserializeContext( isolate, &snapshot_data, false, global_proxy, v8::DeserializeInternalFieldsCallback()) .ToHandleChecked(); CHECK(root->IsContext()); Handle context = Handle::cast(root); // Add context to the weak native context list context->set(Context::NEXT_CONTEXT_LINK, isolate->heap()->native_contexts_list(), UPDATE_WRITE_BARRIER); isolate->heap()->set_native_contexts_list(*context); CHECK(context->global_proxy() == *global_proxy); Handle o = isolate->factory()->NewStringFromAsciiChecked("o"); Handle global_object(context->global_object(), isolate); Handle property = JSReceiver::GetDataProperty(isolate, global_object, o); CHECK(property.is_identical_to(global_proxy)); v8::Local v8_context = v8::Utils::ToLocal(context); v8::Context::Scope context_scope(v8_context); double r = CompileRun("r") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Value(); CHECK(0.0 <= r && r < 1.0); // Math.random still works. double random = CompileRun("Math.random()") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Value(); CHECK(0.0 <= random && random < 1.0); double c = CompileRun("c") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Value(); CHECK_EQ(1, c); int f = CompileRun("f()") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Int32Value(v8_isolate->GetCurrentContext()) .FromJust(); CHECK_EQ(5, f); f = CompileRun("e('f()')") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Int32Value(v8_isolate->GetCurrentContext()) .FromJust(); CHECK_EQ(5, f); v8::Local s = CompileRun("s") ->ToString(v8_isolate->GetCurrentContext()) .ToLocalChecked(); CHECK(s->Equals(v8_isolate->GetCurrentContext(), v8_str("12345")) .FromJust()); v8::Local p = CompileRun("p") ->ToString(v8_isolate->GetCurrentContext()) .ToLocalChecked(); CHECK( p->Equals(v8_isolate->GetCurrentContext(), v8_str("42")).FromJust()); int a = CompileRun("a.length") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Int32Value(v8_isolate->GetCurrentContext()) .FromJust(); CHECK_EQ(100001, a); int b = CompileRun("b.length") ->ToNumber(v8_isolate->GetCurrentContext()) .ToLocalChecked() ->Int32Value(v8_isolate->GetCurrentContext()) .FromJust(); CHECK_EQ(100002, b); } context_blob.Dispose(); } v8_isolate->Dispose(); blobs.Dispose(); FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlob1) { DisableAlwaysOpt(); const char* source1 = "function f() { return 42; }"; DisableEmbeddedBlobRefcounting(); v8::StartupData data1 = CreateSnapshotDataBlob(source1); v8::Isolate::CreateParams params1; params1.snapshot_blob = &data1; params1.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate1 = TestSerializer::NewIsolate(params1); { v8::Isolate::Scope i_scope(isolate1); v8::HandleScope h_scope(isolate1); v8::Local context = v8::Context::New(isolate1); v8::Context::Scope c_scope(context); v8::Maybe result = CompileRun("f()")->Int32Value(isolate1->GetCurrentContext()); CHECK_EQ(42, result.FromJust()); CHECK(CompileRun("this.g")->IsUndefined()); } isolate1->Dispose(); delete[] data1.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } static void UnreachableCallback(const FunctionCallbackInfo& info) { UNREACHABLE(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobOverwriteGlobal) { DisableAlwaysOpt(); const char* source1 = "function f() { return 42; }"; DisableEmbeddedBlobRefcounting(); v8::StartupData data1 = CreateSnapshotDataBlob(source1); v8::Isolate::CreateParams params1; params1.snapshot_blob = &data1; params1.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test that the snapshot overwrites the object template when there are // duplicate global properties. v8::Isolate* isolate1 = TestSerializer::NewIsolate(params1); { v8::Isolate::Scope i_scope(isolate1); v8::HandleScope h_scope(isolate1); v8::Local global_template = v8::ObjectTemplate::New(isolate1); global_template->Set( isolate1, "f", v8::FunctionTemplate::New(isolate1, UnreachableCallback)); v8::Local context = v8::Context::New(isolate1, nullptr, global_template); v8::Context::Scope c_scope(context); v8::Maybe result = CompileRun("f()")->Int32Value(isolate1->GetCurrentContext()); CHECK_EQ(42, result.FromJust()); } isolate1->Dispose(); delete[] data1.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobStringNotInternalized) { DisableAlwaysOpt(); const char* source1 = R"javascript( // String would be internalized if it came from a literal so create "AB" // via a function call. var global = String.fromCharCode(65, 66); function f() { return global; } )javascript"; DisableEmbeddedBlobRefcounting(); v8::StartupData data1 = CreateSnapshotDataBlob(source1); v8::Isolate::CreateParams params1; params1.snapshot_blob = &data1; params1.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate1 = TestSerializer::NewIsolate(params1); { v8::Isolate::Scope i_scope(isolate1); v8::HandleScope h_scope(isolate1); v8::Local context = v8::Context::New(isolate1); v8::Context::Scope c_scope(context); v8::Local result = CompileRun("f()").As(); CHECK(result->IsString()); i::String str = *v8::Utils::OpenHandle(*result.As()); CHECK_EQ(std::string(str.ToCString().get()), "AB"); CHECK(!str.IsInternalizedString()); CHECK(!i::ReadOnlyHeap::Contains(str)); } isolate1->Dispose(); delete[] data1.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } namespace { void TestCustomSnapshotDataBlobWithIrregexpCode( v8::SnapshotCreator::FunctionCodeHandling function_code_handling) { DisableAlwaysOpt(); const char* source = "var re1 = /\\/\\*[^*]*\\*+([^/*][^*]*\\*+)*\\//;\n" "function f() { return '/* a comment */'.search(re1); }\n" "function g() { return 'not a comment'.search(re1); }\n" "function h() { return '// this is a comment'.search(re1); }\n" "var re2 = /a/;\n" "function i() { return '/* a comment */'.search(re2); }\n" "f(); f(); g(); g(); h(); h(); i(); i();\n"; DisableEmbeddedBlobRefcounting(); v8::StartupData data1 = CreateSnapshotDataBlobInternal(function_code_handling, source); v8::Isolate::CreateParams params1; params1.snapshot_blob = &data1; params1.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate1 = TestSerializer::NewIsolate(params1); { v8::Isolate::Scope i_scope(isolate1); v8::HandleScope h_scope(isolate1); v8::Local context = v8::Context::New(isolate1); v8::Context::Scope c_scope(context); { // Check that compiled irregexp code has been flushed prior to // serialization. i::Handle re = Utils::OpenHandle(*CompileRun("re1").As()); CHECK(!re->HasCompiledCode()); } { v8::Maybe result = CompileRun("f()")->Int32Value(isolate1->GetCurrentContext()); CHECK_EQ(0, result.FromJust()); } { v8::Maybe result = CompileRun("g()")->Int32Value(isolate1->GetCurrentContext()); CHECK_EQ(-1, result.FromJust()); } { v8::Maybe result = CompileRun("h()")->Int32Value(isolate1->GetCurrentContext()); CHECK_EQ(-1, result.FromJust()); } { // Check that ATOM regexp remains valid. i::Handle re = Utils::OpenHandle(*CompileRun("re2").As()); CHECK_EQ(re->type_tag(), JSRegExp::ATOM); CHECK(!re->HasCompiledCode()); } } isolate1->Dispose(); delete[] data1.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } } // namespace UNINITIALIZED_TEST(CustomSnapshotDataBlobWithIrregexpCodeKeepCode) { TestCustomSnapshotDataBlobWithIrregexpCode( v8::SnapshotCreator::FunctionCodeHandling::kKeep); } UNINITIALIZED_TEST(CustomSnapshotDataBlobWithIrregexpCodeClearCode) { TestCustomSnapshotDataBlobWithIrregexpCode( v8::SnapshotCreator::FunctionCodeHandling::kClear); } UNINITIALIZED_TEST(SnapshotChecksum) { DisableAlwaysOpt(); const char* source1 = "function f() { return 42; }"; DisableEmbeddedBlobRefcounting(); v8::StartupData data1 = CreateSnapshotDataBlob(source1); CHECK(i::Snapshot::VerifyChecksum(&data1)); const_cast(data1.data)[142] = data1.data[142] ^ 4; // Flip a bit. CHECK(!i::Snapshot::VerifyChecksum(&data1)); delete[] data1.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } struct InternalFieldData { uint32_t data; }; v8::StartupData SerializeInternalFields(v8::Local holder, int index, void* data) { if (data == reinterpret_cast(2000)) { // Used for SnapshotCreatorTemplates test. We check that none of the fields // have been cleared yet. CHECK_NOT_NULL(holder->GetAlignedPointerFromInternalField(1)); } else { CHECK_EQ(reinterpret_cast(2016), data); } if (index != 1) return {nullptr, 0}; InternalFieldData* embedder_field = static_cast( holder->GetAlignedPointerFromInternalField(index)); if (embedder_field == nullptr) return {nullptr, 0}; int size = sizeof(*embedder_field); char* payload = new char[size]; // We simply use memcpy to serialize the content. memcpy(payload, embedder_field, size); return {payload, size}; } std::vector deserialized_data; void DeserializeInternalFields(v8::Local holder, int index, v8::StartupData payload, void* data) { if (payload.raw_size == 0) { holder->SetAlignedPointerInInternalField(index, nullptr); return; } CHECK_EQ(reinterpret_cast(2017), data); InternalFieldData* embedder_field = new InternalFieldData{0}; memcpy(embedder_field, payload.data, payload.raw_size); holder->SetAlignedPointerInInternalField(index, embedder_field); deserialized_data.push_back(embedder_field); } using Int32Expectations = std::vector>; void TestInt32Expectations(const Int32Expectations& expectations) { for (const auto& e : expectations) { ExpectInt32(std::get<0>(e), std::get<1>(e)); } } void TypedArrayTestHelper( const char* code, const Int32Expectations& expectations, const char* code_to_run_after_restore = nullptr, const Int32Expectations& after_restore_expectations = Int32Expectations(), v8::ArrayBuffer::Allocator* allocator = nullptr) { DisableAlwaysOpt(); i::v8_flags.allow_natives_syntax = true; DisableEmbeddedBlobRefcounting(); v8::StartupData blob; { v8::SnapshotCreator creator; v8::Isolate* isolate = creator.GetIsolate(); { v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); CompileRun(code); TestInt32Expectations(expectations); creator.SetDefaultContext( context, v8::SerializeInternalFieldsCallback( SerializeInternalFields, reinterpret_cast(2016))); } blob = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear); } v8::Isolate::CreateParams create_params; create_params.snapshot_blob = &blob; create_params.array_buffer_allocator = allocator != nullptr ? allocator : CcTest::array_buffer_allocator(); v8::Isolate* isolate = TestSerializer::NewIsolate(create_params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New( isolate, nullptr, v8::MaybeLocal(), v8::MaybeLocal(), v8::DeserializeInternalFieldsCallback(DeserializeInternalFields, reinterpret_cast(2017))); CHECK(deserialized_data.empty()); // We do not expect any embedder data. v8::Context::Scope c_scope(context); TestInt32Expectations(expectations); if (code_to_run_after_restore) { CompileRun(code_to_run_after_restore); } TestInt32Expectations(after_restore_expectations); } isolate->Dispose(); delete[] blob.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobWithOffHeapTypedArray) { const char* code = "var x = new Uint8Array(128);" "x[0] = 12;" "var arr = new Array(17);" "arr[1] = 24;" "var y = new Uint32Array(arr);" "var buffer = new ArrayBuffer(128);" "var z = new Int16Array(buffer);" "z[0] = 48;"; Int32Expectations expectations = {std::make_tuple("x[0]", 12), std::make_tuple("y[1]", 24), std::make_tuple("z[0]", 48)}; TypedArrayTestHelper(code, expectations); } UNINITIALIZED_TEST(CustomSnapshotDataBlobSharedArrayBuffer) { const char* code = "var x = new Int32Array([12, 24, 48, 96]);" "var y = new Uint8Array(x.buffer)"; Int32Expectations expectations = { std::make_tuple("x[0]", 12), std::make_tuple("x[1]", 24), #if !V8_TARGET_BIG_ENDIAN std::make_tuple("y[0]", 12), std::make_tuple("y[1]", 0), std::make_tuple("y[2]", 0), std::make_tuple("y[3]", 0), std::make_tuple("y[4]", 24) #else std::make_tuple("y[3]", 12), std::make_tuple("y[2]", 0), std::make_tuple("y[1]", 0), std::make_tuple("y[0]", 0), std::make_tuple("y[7]", 24) #endif }; TypedArrayTestHelper(code, expectations); } UNINITIALIZED_TEST(CustomSnapshotDataBlobArrayBufferWithOffset) { const char* code = "var x = new Int32Array([12, 24, 48, 96]);" "var y = new Int32Array(x.buffer, 4, 2)"; Int32Expectations expectations = { std::make_tuple("x[1]", 24), std::make_tuple("x[2]", 48), std::make_tuple("y[0]", 24), std::make_tuple("y[1]", 48), }; // Verify that the typed arrays use the same buffer (not independent copies). const char* code_to_run_after_restore = "x[2] = 57; y[0] = 42;"; Int32Expectations after_restore_expectations = { std::make_tuple("x[1]", 42), std::make_tuple("y[1]", 57), }; TypedArrayTestHelper(code, expectations, code_to_run_after_restore, after_restore_expectations); } UNINITIALIZED_TEST(CustomSnapshotDataBlobDataView) { const char* code = "var x = new Int8Array([1, 2, 3, 4]);" "var v = new DataView(x.buffer)"; Int32Expectations expectations = {std::make_tuple("v.getInt8(0)", 1), std::make_tuple("v.getInt8(1)", 2), std::make_tuple("v.getInt16(0)", 258), std::make_tuple("v.getInt16(1)", 515)}; TypedArrayTestHelper(code, expectations); } namespace { class AlternatingArrayBufferAllocator : public v8::ArrayBuffer::Allocator { public: AlternatingArrayBufferAllocator() : allocation_fails_(false), allocator_(v8::ArrayBuffer::Allocator::NewDefaultAllocator()) {} ~AlternatingArrayBufferAllocator() { delete allocator_; } void* Allocate(size_t length) override { allocation_fails_ = !allocation_fails_; if (allocation_fails_) return nullptr; return allocator_->Allocate(length); } void* AllocateUninitialized(size_t length) override { return this->Allocate(length); } void Free(void* data, size_t size) override { allocator_->Free(data, size); } void* Reallocate(void* data, size_t old_length, size_t new_length) override { return allocator_->Reallocate(data, old_length, new_length); } private: bool allocation_fails_; v8::ArrayBuffer::Allocator* allocator_; }; } // anonymous namespace UNINITIALIZED_TEST(CustomSnapshotManyArrayBuffers) { const char* code = "var buffers = [];" "for (let i = 0; i < 70; i++) buffers.push(new Uint8Array(1000));"; Int32Expectations expectations = {std::make_tuple("buffers.length", 70)}; std::unique_ptr allocator( new AlternatingArrayBufferAllocator()); TypedArrayTestHelper(code, expectations, nullptr, Int32Expectations(), allocator.get()); } UNINITIALIZED_TEST(CustomSnapshotDataBlobDetachedArrayBuffer) { const char* code = "var x = new Int16Array([12, 24, 48]);" "%ArrayBufferDetach(x.buffer);"; Int32Expectations expectations = {std::make_tuple("x.buffer.byteLength", 0), std::make_tuple("x.length", 0)}; DisableAlwaysOpt(); i::v8_flags.allow_natives_syntax = true; DisableEmbeddedBlobRefcounting(); v8::StartupData blob; { v8::SnapshotCreator creator; v8::Isolate* isolate = creator.GetIsolate(); { v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); CompileRun(code); TestInt32Expectations(expectations); creator.SetDefaultContext( context, v8::SerializeInternalFieldsCallback( SerializeInternalFields, reinterpret_cast(2016))); } blob = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear); } v8::Isolate::CreateParams create_params; create_params.snapshot_blob = &blob; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate = TestSerializer::NewIsolate(create_params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New( isolate, nullptr, v8::MaybeLocal(), v8::MaybeLocal(), v8::DeserializeInternalFieldsCallback(DeserializeInternalFields, reinterpret_cast(2017))); v8::Context::Scope c_scope(context); TestInt32Expectations(expectations); v8::Local x = CompileRun("x"); CHECK(x->IsTypedArray()); i::Handle array = i::Handle::cast(v8::Utils::OpenHandle(*x)); CHECK(array->WasDetached()); } isolate->Dispose(); delete[] blob.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } i::Handle GetBufferFromTypedArray( v8::Local typed_array) { CHECK(typed_array->IsTypedArray()); i::Handle view = i::Handle::cast( v8::Utils::OpenHandle(*typed_array)); return i::handle(i::JSArrayBuffer::cast(view->buffer()), view->GetIsolate()); } UNINITIALIZED_TEST(CustomSnapshotDataBlobOnOrOffHeapTypedArray) { const char* code = "var x = new Uint8Array(8);" "x[0] = 12;" "x[7] = 24;" "var y = new Int16Array([12, 24, 48]);" "var z = new Int32Array(64);" "z[0] = 96;"; Int32Expectations expectations = { std::make_tuple("x[0]", 12), std::make_tuple("x[7]", 24), std::make_tuple("y[2]", 48), std::make_tuple("z[0]", 96)}; DisableAlwaysOpt(); i::v8_flags.allow_natives_syntax = true; DisableEmbeddedBlobRefcounting(); v8::StartupData blob; { v8::SnapshotCreator creator; v8::Isolate* isolate = creator.GetIsolate(); { v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); CompileRun(code); TestInt32Expectations(expectations); i::Handle buffer = GetBufferFromTypedArray(CompileRun("x")); // The resulting buffer should be on-heap. CHECK(buffer->IsEmpty()); creator.SetDefaultContext( context, v8::SerializeInternalFieldsCallback( SerializeInternalFields, reinterpret_cast(2016))); } blob = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear); } v8::Isolate::CreateParams create_params; create_params.snapshot_blob = &blob; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate = TestSerializer::NewIsolate(create_params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New( isolate, nullptr, v8::MaybeLocal(), v8::MaybeLocal(), v8::DeserializeInternalFieldsCallback(DeserializeInternalFields, reinterpret_cast(2017))); v8::Context::Scope c_scope(context); TestInt32Expectations(expectations); i::Handle buffer = GetBufferFromTypedArray(CompileRun("x")); // The resulting buffer should be on-heap. CHECK(buffer->IsEmpty()); buffer = GetBufferFromTypedArray(CompileRun("y")); CHECK(buffer->IsEmpty()); buffer = GetBufferFromTypedArray(CompileRun("z")); // The resulting buffer should be off-heap. CHECK(!buffer->IsEmpty()); } isolate->Dispose(); delete[] blob.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobTypedArrayNoEmbedderFieldCallback) { const char* code = "var x = new Uint8Array(8);"; DisableAlwaysOpt(); i::v8_flags.allow_natives_syntax = true; DisableEmbeddedBlobRefcounting(); v8::StartupData blob; { v8::SnapshotCreator creator; v8::Isolate* isolate = creator.GetIsolate(); { v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); CompileRun(code); creator.SetDefaultContext(context, v8::SerializeInternalFieldsCallback()); } blob = creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear); } v8::Isolate::CreateParams create_params; create_params.snapshot_blob = &blob; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate = TestSerializer::NewIsolate(create_params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New( isolate, nullptr, v8::MaybeLocal(), v8::MaybeLocal(), v8::DeserializeInternalFieldsCallback()); v8::Context::Scope c_scope(context); } isolate->Dispose(); delete[] blob.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlob2) { DisableAlwaysOpt(); const char* source2 = "function f() { return g() * 2; }" "function g() { return 43; }" "/./.test('a')"; DisableEmbeddedBlobRefcounting(); v8::StartupData data2 = CreateSnapshotDataBlob(source2); v8::Isolate::CreateParams params2; params2.snapshot_blob = &data2; params2.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate2 = TestSerializer::NewIsolate(params2); { v8::Isolate::Scope i_scope(isolate2); v8::HandleScope h_scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope c_scope(context); v8::Maybe result = CompileRun("f()")->Int32Value(isolate2->GetCurrentContext()); CHECK_EQ(86, result.FromJust()); result = CompileRun("g()")->Int32Value(isolate2->GetCurrentContext()); CHECK_EQ(43, result.FromJust()); } isolate2->Dispose(); delete[] data2.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } static void SerializationFunctionTemplate( const v8::FunctionCallbackInfo& info) { CHECK(i::ValidateCallbackInfo(info)); info.GetReturnValue().Set(info[0]); } UNINITIALIZED_TEST(CustomSnapshotDataBlobOutdatedContextWithOverflow) { DisableAlwaysOpt(); const char* source1 = "var o = {};" "(function() {" " function f1(x) { return f2(x) instanceof Array; }" " function f2(x) { return foo.bar(x); }" " o.a = f2.bind(null);" " o.b = 1;" " o.c = 2;" " o.d = 3;" " o.e = 4;" "})();\n"; const char* source2 = "o.a(42)"; DisableEmbeddedBlobRefcounting(); v8::StartupData data = CreateSnapshotDataBlob(source1); v8::Isolate::CreateParams params; params.snapshot_blob = &data; params.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate = TestSerializer::NewIsolate(params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local global = v8::ObjectTemplate::New(isolate); v8::Local property = v8::ObjectTemplate::New(isolate); v8::Local function = v8::FunctionTemplate::New(isolate, SerializationFunctionTemplate); property->Set(isolate, "bar", function); global->Set(isolate, "foo", property); v8::Local context = v8::Context::New(isolate, nullptr, global); v8::Context::Scope c_scope(context); v8::Local result = CompileRun(source2); v8::Maybe compare = v8_str("42")->Equals(isolate->GetCurrentContext(), result); CHECK(compare.FromJust()); } isolate->Dispose(); delete[] data.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobWithLocker) { DisableAlwaysOpt(); DisableEmbeddedBlobRefcounting(); v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate0 = v8::Isolate::New(create_params); { v8::Locker locker(isolate0); v8::Isolate::Scope i_scope(isolate0); v8::HandleScope h_scope(isolate0); v8::Local context = v8::Context::New(isolate0); v8::Context::Scope c_scope(context); v8::Maybe result = CompileRun("Math.cos(0)")->Int32Value(isolate0->GetCurrentContext()); CHECK_EQ(1, result.FromJust()); } isolate0->Dispose(); const char* source1 = "function f() { return 42; }"; DisableEmbeddedBlobRefcounting(); v8::StartupData data1 = CreateSnapshotDataBlob(source1); v8::Isolate::CreateParams params1; params1.snapshot_blob = &data1; params1.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate1 = TestSerializer::NewIsolate(params1); { v8::Locker locker(isolate1); v8::Isolate::Scope i_scope(isolate1); v8::HandleScope h_scope(isolate1); v8::Local context = v8::Context::New(isolate1); v8::Context::Scope c_scope(context); v8::Maybe result = CompileRun("f()")->Int32Value(context); CHECK_EQ(42, result.FromJust()); } isolate1->Dispose(); delete[] data1.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobStackOverflow) { DisableAlwaysOpt(); const char* source = "var a = [0];" "var b = a;" "for (var i = 0; i < 10000; i++) {" " var c = [i];" " b.push(c);" " b.push(c);" " b = c;" "}"; DisableEmbeddedBlobRefcounting(); v8::StartupData data = CreateSnapshotDataBlob(source); v8::Isolate::CreateParams params; params.snapshot_blob = &data; params.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate = TestSerializer::NewIsolate(params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope c_scope(context); const char* test = "var sum = 0;" "while (a) {" " sum += a[0];" " a = a[1];" "}" "sum"; v8::Maybe result = CompileRun(test)->Int32Value(isolate->GetCurrentContext()); CHECK_EQ(9999 * 5000, result.FromJust()); } isolate->Dispose(); delete[] data.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } bool IsCompiled(const char* name) { return i::Handle::cast( v8::Utils::OpenHandle(*CompileRun(name))) ->shared() .is_compiled(); } UNINITIALIZED_TEST(SnapshotDataBlobWithWarmup) { DisableAlwaysOpt(); const char* warmup = "Math.abs(1); Math.random = 1;"; DisableEmbeddedBlobRefcounting(); v8::StartupData cold = CreateSnapshotDataBlob(nullptr); v8::StartupData warm = WarmUpSnapshotDataBlobInternal(cold, warmup); delete[] cold.data; v8::Isolate::CreateParams params; params.snapshot_blob = &warm; params.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate = TestSerializer::NewIsolate(params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope c_scope(context); // Running the warmup script has effect on whether functions are // pre-compiled, but does not pollute the context. CHECK(IsCompiled("Math.abs")); CHECK(IsCompiled("String.raw")); CHECK(CompileRun("Math.random")->IsFunction()); } isolate->Dispose(); delete[] warm.data; FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobWithWarmup) { DisableAlwaysOpt(); const char* source = "function f() { return Math.abs(1); }\n" "function g() { return String.raw(1); }\n" "Object.valueOf(1);" "var a = 5"; const char* warmup = "a = f()"; DisableEmbeddedBlobRefcounting(); v8::StartupData cold = CreateSnapshotDataBlob(source); v8::StartupData warm = WarmUpSnapshotDataBlobInternal(cold, warmup); delete[] cold.data; v8::Isolate::CreateParams params; params.snapshot_blob = &warm; params.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate = TestSerializer::NewIsolate(params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope c_scope(context); // Running the warmup script has effect on whether functions are // pre-compiled, but does not pollute the context. CHECK(IsCompiled("f")); CHECK(IsCompiled("Math.abs")); CHECK(!IsCompiled("g")); CHECK(IsCompiled("String.raw")); CHECK(IsCompiled("Array.prototype.lastIndexOf")); CHECK_EQ(5, CompileRun("a")->Int32Value(context).FromJust()); } isolate->Dispose(); delete[] warm.data; FreeCurrentEmbeddedBlob(); } namespace { v8::StartupData CreateCustomSnapshotWithKeep() { v8::SnapshotCreator creator; v8::Isolate* isolate = creator.GetIsolate(); { v8::HandleScope handle_scope(isolate); { v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str( "function f() { return Math.abs(1); }\n" "function g() { return String.raw(1); }"); v8::ScriptOrigin origin(isolate, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin); CompileRun(isolate->GetCurrentContext(), &source, v8::ScriptCompiler::kEagerCompile); creator.SetDefaultContext(context); } } return creator.CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kKeep); } } // namespace UNINITIALIZED_TEST(CustomSnapshotDataBlobWithKeep) { DisableAlwaysOpt(); DisableEmbeddedBlobRefcounting(); v8::StartupData blob = CreateCustomSnapshotWithKeep(); { v8::Isolate::CreateParams params; params.snapshot_blob = &blob; params.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate = TestSerializer::NewIsolate(params); { v8::Isolate::Scope isolate_scope(isolate); v8::HandleScope handle_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope context_scope(context); CHECK(IsCompiled("f")); CHECK(IsCompiled("g")); } isolate->Dispose(); } delete[] blob.data; FreeCurrentEmbeddedBlob(); } UNINITIALIZED_TEST(CustomSnapshotDataBlobImmortalImmovableRoots) { DisableAlwaysOpt(); // Flood the startup snapshot with shared function infos. If they are // serialized before the immortal immovable root, the root will no longer end // up on the first page. base::Vector source = ConstructSource(base::StaticCharVector("var a = [];"), base::StaticCharVector("a.push(function() {return 7});"), base::StaticCharVector("\0"), 10000); DisableEmbeddedBlobRefcounting(); v8::StartupData data = CreateSnapshotDataBlob(source.begin()); v8::Isolate::CreateParams params; params.snapshot_blob = &data; params.array_buffer_allocator = CcTest::array_buffer_allocator(); // Test-appropriate equivalent of v8::Isolate::New. v8::Isolate* isolate = TestSerializer::NewIsolate(params); { v8::Isolate::Scope i_scope(isolate); v8::HandleScope h_scope(isolate); v8::Local context = v8::Context::New(isolate); v8::Context::Scope c_scope(context); CHECK_EQ(7, CompileRun("a[0]()")->Int32Value(context).FromJust()); } isolate->Dispose(); source.Dispose(); delete[] data.data; // We can dispose of the snapshot blob now. FreeCurrentEmbeddedBlob(); } TEST(TestThatAlwaysSucceeds) {} TEST(TestCheckThatAlwaysFails) { bool ArtificialFailure = false; CHECK(ArtificialFailure); } TEST(TestFatal) { GRACEFUL_FATAL("fatal"); } int CountBuiltins() { // Check that we have not deserialized any additional builtin. HeapObjectIterator iterator(CcTest::heap()); DisallowGarbageCollection no_gc; int counter = 0; for (HeapObject obj = iterator.Next(); !obj.is_null(); obj = iterator.Next()) { if (obj.IsCode() && Code::cast(obj).kind() == CodeKind::BUILTIN) counter++; } return counter; } static Handle CompileScript( Isolate* isolate, Handle source, const ScriptDetails& script_details, AlignedCachedData* cached_data, v8::ScriptCompiler::CompileOptions options) { return Compiler::GetSharedFunctionInfoForScriptWithCachedData( isolate, source, script_details, cached_data, options, ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE) .ToHandleChecked(); } static Handle CompileScriptAndProduceCache( Isolate* isolate, Handle source, const ScriptDetails& script_details, AlignedCachedData** out_cached_data, v8::ScriptCompiler::CompileOptions options) { Handle sfi = Compiler::GetSharedFunctionInfoForScript( isolate, source, script_details, options, ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE) .ToHandleChecked(); std::unique_ptr cached_data( ScriptCompiler::CreateCodeCache(ToApiHandle(sfi))); uint8_t* buffer = NewArray(cached_data->length); MemCopy(buffer, cached_data->data, cached_data->length); *out_cached_data = new i::AlignedCachedData(buffer, cached_data->length); (*out_cached_data)->AcquireDataOwnership(); return sfi; } TEST(CodeSerializerWithProfiler) { v8_flags.enable_lazy_source_positions = true; v8_flags.stress_lazy_source_positions = false; LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); const char* source = "1 + 1"; Handle orig_source = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); Handle copy_source = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); CHECK(!orig_source.is_identical_to(copy_source)); CHECK(orig_source->Equals(*copy_source)); AlignedCachedData* cache = nullptr; ScriptDetails default_script_details; Handle orig = CompileScriptAndProduceCache( isolate, orig_source, default_script_details, &cache, v8::ScriptCompiler::kNoCompileOptions); CHECK(!orig->GetBytecodeArray(isolate).HasSourcePositionTable()); isolate->SetIsProfiling(true); // This does not assert that no compilation can happen as source position // collection could trigger it. Handle copy = CompileScript(isolate, copy_source, default_script_details, cache, v8::ScriptCompiler::kConsumeCodeCache); // Since the profiler is now enabled, source positions should be collected // after deserialization. CHECK(copy->GetBytecodeArray(isolate).HasSourcePositionTable()); delete cache; } void TestCodeSerializerOnePlusOneImpl(bool verify_builtins_count = true) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); const char* source = "1 + 1"; Handle orig_source = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); Handle copy_source = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); CHECK(!orig_source.is_identical_to(copy_source)); CHECK(orig_source->Equals(*copy_source)); AlignedCachedData* cache = nullptr; ScriptDetails default_script_details; Handle orig = CompileScriptAndProduceCache( isolate, orig_source, default_script_details, &cache, v8::ScriptCompiler::kNoCompileOptions); int builtins_count = CountBuiltins(); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, copy_source, default_script_details, cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); CHECK(Script::cast(copy->script()).source() == *copy_source); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle global(isolate->context().global_object(), isolate); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK_EQ(2, Handle::cast(copy_result)->value()); if (verify_builtins_count) CHECK_EQ(builtins_count, CountBuiltins()); delete cache; } TEST(CodeSerializerOnePlusOne) { TestCodeSerializerOnePlusOneImpl(); } // See bug v8:9122 TEST(CodeSerializerOnePlusOneWithInterpretedFramesNativeStack) { v8_flags.interpreted_frames_native_stack = true; // We pass false because this test will create IET copies (which are // builtins). TestCodeSerializerOnePlusOneImpl(false); } TEST(CodeSerializerOnePlusOneWithDebugger) { v8::HandleScope scope(CcTest::isolate()); static v8::debug::DebugDelegate dummy_delegate; v8::debug::SetDebugDelegate(CcTest::isolate(), &dummy_delegate); TestCodeSerializerOnePlusOneImpl(); } TEST(CodeSerializerPromotedToCompilationCache) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); v8::HandleScope scope(CcTest::isolate()); const char* source = "1 + 1"; Handle src = isolate->factory()->NewStringFromAsciiChecked(source); AlignedCachedData* cache = nullptr; Handle default_host_defined_options = isolate->factory()->NewFixedArray(2); default_host_defined_options->set(0, Smi::FromInt(0)); const char* default_host_defined_option_1_string = "custom string"; Handle default_host_defined_option_1 = isolate->factory()->NewStringFromAsciiChecked( default_host_defined_option_1_string); default_host_defined_options->set(1, *default_host_defined_option_1); ScriptDetails default_script_details(src); default_script_details.host_defined_options = default_host_defined_options; CompileScriptAndProduceCache(isolate, src, default_script_details, &cache, v8::ScriptCompiler::kNoCompileOptions); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, src, default_script_details, cache, v8::ScriptCompiler::kConsumeCodeCache); } { ScriptDetails script_details(src); script_details.host_defined_options = default_script_details.host_defined_options; auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK_EQ(*lookup_result.toplevel_sfi().ToHandleChecked(), *copy); } { // Lookup with strictly equal host_defined_options should succeed: ScriptDetails script_details(src); Handle host_defined_options = isolate->factory()->NewFixedArray(2); host_defined_options->set(0, default_host_defined_options->get(0)); Handle host_defined_option_1 = isolate->factory()->NewStringFromAsciiChecked( default_host_defined_option_1_string); host_defined_options->set(1, *host_defined_option_1); script_details.host_defined_options = host_defined_options; auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK_EQ(*lookup_result.toplevel_sfi().ToHandleChecked(), *copy); } { // Lookup with different string with same contents should succeed: ScriptDetails script_details( isolate->factory()->NewStringFromAsciiChecked(source)); script_details.host_defined_options = default_script_details.host_defined_options; auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK_EQ(*lookup_result.toplevel_sfi().ToHandleChecked(), *copy); } { // Lookup with different name string should fail: ScriptDetails script_details( isolate->factory()->NewStringFromAsciiChecked("other")); auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK(lookup_result.script().is_null() && lookup_result.toplevel_sfi().is_null()); } { // Lookup with different position should fail: ScriptDetails script_details(src); script_details.line_offset = 0xFF; auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK(lookup_result.script().is_null() && lookup_result.toplevel_sfi().is_null()); } { // Lookup with different position should fail: ScriptDetails script_details(src); script_details.column_offset = 0xFF; auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK(lookup_result.script().is_null() && lookup_result.toplevel_sfi().is_null()); } { // Lookup with different language mode should fail: ScriptDetails script_details(src); auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kStrict); CHECK(lookup_result.script().is_null() && lookup_result.toplevel_sfi().is_null()); } { // Lookup with different script_options should fail ScriptOriginOptions origin_options(false, true); CHECK_NE(ScriptOriginOptions().Flags(), origin_options.Flags()); ScriptDetails script_details(src, origin_options); auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK(lookup_result.script().is_null() && lookup_result.toplevel_sfi().is_null()); } { // Lookup with different host_defined_options should fail: ScriptDetails script_details(src); script_details.host_defined_options = isolate->factory()->NewFixedArray(5); auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK(lookup_result.script().is_null() && lookup_result.toplevel_sfi().is_null()); } // Compile the script again with different options. ScriptDetails alternative_script_details(src); Handle alternative_toplevel_sfi = Compiler::GetSharedFunctionInfoForScript( isolate, src, alternative_script_details, ScriptCompiler::kNoCompileOptions, ScriptCompiler::kNoCacheNoReason, NOT_NATIVES_CODE) .ToHandleChecked(); CHECK_NE(*copy, *alternative_toplevel_sfi); { // The original script can still be found. ScriptDetails script_details(src); script_details.host_defined_options = default_script_details.host_defined_options; auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK_EQ(*lookup_result.toplevel_sfi().ToHandleChecked(), *copy); } { // The new script can also be found. ScriptDetails script_details(src); auto lookup_result = isolate->compilation_cache()->LookupScript( src, script_details, LanguageMode::kSloppy); CHECK_EQ(*lookup_result.toplevel_sfi().ToHandleChecked(), *alternative_toplevel_sfi); } delete cache; } TEST(CodeSerializerInternalizedString) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); const char* source = "'string1'"; Handle orig_source = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); Handle copy_source = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); CHECK(!orig_source.is_identical_to(copy_source)); CHECK(orig_source->Equals(*copy_source)); Handle global(isolate->context().global_object(), isolate); i::AlignedCachedData* cached_data = nullptr; Handle orig = CompileScriptAndProduceCache( isolate, orig_source, ScriptDetails(), &cached_data, v8::ScriptCompiler::kNoCompileOptions); Handle orig_fun = Factory::JSFunctionBuilder{isolate, orig, isolate->native_context()} .Build(); Handle orig_result = Execution::CallScript(isolate, orig_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK(orig_result->IsInternalizedString()); int builtins_count = CountBuiltins(); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, copy_source, ScriptDetails(), cached_data, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); CHECK(Script::cast(copy->script()).source() == *copy_source); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); CHECK_NE(*orig_fun, *copy_fun); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK(orig_result.is_identical_to(copy_result)); Handle expected = isolate->factory()->NewStringFromAsciiChecked("string1"); CHECK(Handle::cast(copy_result)->Equals(*expected)); CHECK_EQ(builtins_count, CountBuiltins()); delete cached_data; } TEST(CodeSerializerLargeCodeObject) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); // The serializer only tests the shared code, which is always the unoptimized // code. Don't even bother generating optimized code to avoid timeouts. v8_flags.always_turbofan = false; base::Vector source = ConstructSource( base::StaticCharVector("var j=1; if (j == 0) {"), base::StaticCharVector( "for (let i of Object.prototype) for (let k = 0; k < 0; ++k);"), base::StaticCharVector("} j=7; j"), 2000); Handle source_str = isolate->factory()->NewStringFromUtf8(source).ToHandleChecked(); Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache, v8::ScriptCompiler::kNoCompileOptions); CHECK(isolate->heap()->InSpace(orig->abstract_code(isolate), LO_SPACE)); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_str, ScriptDetails(), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); int result_int; CHECK(copy_result->ToInt32(&result_int)); CHECK_EQ(7, result_int); delete cache; source.Dispose(); } TEST(CodeSerializerLargeCodeObjectWithIncrementalMarking) { if (!v8_flags.incremental_marking) return; if (!v8_flags.compact) return; ManualGCScope manual_gc_scope; v8_flags.always_turbofan = false; const char* filter_flag = "--turbo-filter=NOTHING"; FlagList::SetFlagsFromString(filter_flag, strlen(filter_flag)); heap::ManualEvacuationCandidatesSelectionScope manual_evacuation_candidate_selection_scope(manual_gc_scope); LocalContext context; Isolate* isolate = CcTest::i_isolate(); Heap* heap = isolate->heap(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); base::Vector source = ConstructSource( base::StaticCharVector("var j=1; if (j == 0) {"), base::StaticCharVector("for (var i = 0; i < Object.prototype; i++);"), base::StaticCharVector("} j=7; var s = 'happy_hippo'; j"), 20000); Handle source_str = isolate->factory()->NewStringFromUtf8(source).ToHandleChecked(); // Create a string on an evacuation candidate in old space. Handle moving_object; Page* ec_page; { AlwaysAllocateScopeForTesting always_allocate(heap); heap::SimulateFullSpace(heap->old_space()); moving_object = isolate->factory()->InternalizeString( isolate->factory()->NewStringFromAsciiChecked("happy_hippo")); ec_page = Page::FromHeapObject(*moving_object); } Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache, v8::ScriptCompiler::kNoCompileOptions); CHECK(heap->InSpace(orig->abstract_code(isolate), LO_SPACE)); // Pretend that incremental marking is on when deserialization begins. heap::ForceEvacuationCandidate(ec_page); heap::SimulateIncrementalMarking(heap, false); IncrementalMarking* marking = heap->incremental_marking(); CHECK(marking->black_allocation()); CHECK(marking->IsCompacting()); CHECK(MarkCompactCollector::IsOnEvacuationCandidate(*moving_object)); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_str, ScriptDetails(), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); // We should have missed a write barrier. Complete incremental marking // to flush out the bug. heap::SimulateIncrementalMarking(heap, true); heap::CollectAllGarbage(heap); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); int result_int; CHECK(copy_result->ToInt32(&result_int)); CHECK_EQ(7, result_int); delete cache; source.Dispose(); } TEST(CodeSerializerLargeStrings) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); Factory* f = isolate->factory(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); base::Vector source_s = ConstructSource( base::StaticCharVector("var s = \""), base::StaticCharVector("abcdef"), base::StaticCharVector("\";"), 1000000); base::Vector source_t = ConstructSource( base::StaticCharVector("var t = \""), base::StaticCharVector("uvwxyz"), base::StaticCharVector("\"; s + t"), 999999); Handle source_str = f->NewConsString(f->NewStringFromUtf8(source_s).ToHandleChecked(), f->NewStringFromUtf8(source_t).ToHandleChecked()) .ToHandleChecked(); Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache, v8::ScriptCompiler::kNoCompileOptions); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_str, ScriptDetails(), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK_EQ(6 * 1999999, Handle::cast(copy_result)->length()); Handle property = JSReceiver::GetDataProperty( isolate, isolate->global_object(), f->NewStringFromAsciiChecked("s")); CHECK(isolate->heap()->InSpace(HeapObject::cast(*property), LO_SPACE)); property = JSReceiver::GetDataProperty(isolate, isolate->global_object(), f->NewStringFromAsciiChecked("t")); CHECK(isolate->heap()->InSpace(HeapObject::cast(*property), LO_SPACE)); // Make sure we do not serialize too much, e.g. include the source string. CHECK_LT(cache->length(), 13000000); delete cache; source_s.Dispose(); source_t.Dispose(); } TEST(CodeSerializerThreeBigStrings) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); Factory* f = isolate->factory(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); const int32_t length_of_a = kMaxRegularHeapObjectSize * 2; const int32_t length_of_b = kMaxRegularHeapObjectSize / 2; const int32_t length_of_c = kMaxRegularHeapObjectSize / 2; base::Vector source_a = ConstructSource( base::StaticCharVector("var a = \""), base::StaticCharVector("a"), base::StaticCharVector("\";"), length_of_a); Handle source_a_str = f->NewStringFromUtf8(source_a).ToHandleChecked(); base::Vector source_b = ConstructSource( base::StaticCharVector("var b = \""), base::StaticCharVector("b"), base::StaticCharVector("\";"), length_of_b); Handle source_b_str = f->NewStringFromUtf8(source_b).ToHandleChecked(); base::Vector source_c = ConstructSource( base::StaticCharVector("var c = \""), base::StaticCharVector("c"), base::StaticCharVector("\";"), length_of_c); Handle source_c_str = f->NewStringFromUtf8(source_c).ToHandleChecked(); Handle source_str = f->NewConsString( f->NewConsString(source_a_str, source_b_str).ToHandleChecked(), source_c_str) .ToHandleChecked(); Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache, v8::ScriptCompiler::kNoCompileOptions); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_str, ScriptDetails(), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); USE(Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array())); v8::Maybe result = CompileRun("(a + b).length") ->Int32Value(CcTest::isolate()->GetCurrentContext()); CHECK_EQ(length_of_a + length_of_b, result.FromJust()); result = CompileRun("(b + c).length") ->Int32Value(CcTest::isolate()->GetCurrentContext()); CHECK_EQ(length_of_b + length_of_c, result.FromJust()); Heap* heap = isolate->heap(); v8::Local result_str = CompileRun("a") ->ToString(CcTest::isolate()->GetCurrentContext()) .ToLocalChecked(); CHECK(heap->InSpace(*v8::Utils::OpenHandle(*result_str), LO_SPACE)); result_str = CompileRun("b") ->ToString(CcTest::isolate()->GetCurrentContext()) .ToLocalChecked(); CHECK(heap->InSpace(*v8::Utils::OpenHandle(*result_str), OLD_SPACE)); result_str = CompileRun("c") ->ToString(CcTest::isolate()->GetCurrentContext()) .ToLocalChecked(); CHECK(heap->InSpace(*v8::Utils::OpenHandle(*result_str), OLD_SPACE)); delete cache; source_a.Dispose(); source_b.Dispose(); source_c.Dispose(); } class SerializerOneByteResource : public v8::String::ExternalOneByteStringResource { public: SerializerOneByteResource(const char* data, size_t length) : data_(data), length_(length), dispose_count_(0) {} const char* data() const override { return data_; } size_t length() const override { return length_; } void Dispose() override { dispose_count_++; } int dispose_count() { return dispose_count_; } private: const char* data_; size_t length_; int dispose_count_; }; class SerializerTwoByteResource : public v8::String::ExternalStringResource { public: SerializerTwoByteResource(const uint16_t* data, size_t length) : data_(data), length_(length), dispose_count_(0) {} ~SerializerTwoByteResource() override { DeleteArray(data_); } const uint16_t* data() const override { return data_; } size_t length() const override { return length_; } void Dispose() override { dispose_count_++; } int dispose_count() { return dispose_count_; } private: const uint16_t* data_; size_t length_; int dispose_count_; }; TEST(CodeSerializerExternalString) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. v8::HandleScope scope(CcTest::isolate()); // Obtain external internalized one-byte string. SerializerOneByteResource one_byte_resource("one_byte", 8); Handle one_byte_string = isolate->factory()->NewStringFromAsciiChecked("one_byte"); one_byte_string = isolate->factory()->InternalizeString(one_byte_string); one_byte_string->MakeExternal(&one_byte_resource); CHECK(one_byte_string->IsExternalOneByteString()); CHECK(one_byte_string->IsInternalizedString()); // Obtain external internalized two-byte string. size_t two_byte_length; uint16_t* two_byte = AsciiToTwoByteString(u"two_byte 🤓", &two_byte_length); SerializerTwoByteResource two_byte_resource(two_byte, two_byte_length); Handle two_byte_string = isolate->factory() ->NewStringFromTwoByte(base::VectorOf(two_byte, two_byte_length)) .ToHandleChecked(); two_byte_string = isolate->factory()->InternalizeString(two_byte_string); two_byte_string->MakeExternal(&two_byte_resource); CHECK(two_byte_string->IsExternalTwoByteString()); CHECK(two_byte_string->IsInternalizedString()); const char* source = "var o = {} \n" "o.one_byte = 7; \n" "o.two_byte = 8; \n" "o.one_byte + o.two_byte; \n"; Handle source_string = isolate->factory() ->NewStringFromUtf8(base::CStrVector(source)) .ToHandleChecked(); Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache( isolate, source_string, ScriptDetails(), &cache, v8::ScriptCompiler::kNoCompileOptions); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_string, ScriptDetails(), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK_EQ(15.0, copy_result->Number()); // This avoids the GC from trying to free stack allocated resources. i::Handle::cast(one_byte_string) ->SetResource(isolate, nullptr); i::Handle::cast(two_byte_string) ->SetResource(isolate, nullptr); delete cache; } TEST(CodeSerializerLargeExternalString) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. Factory* f = isolate->factory(); v8::HandleScope scope(CcTest::isolate()); // Create a huge external internalized string to use as variable name. base::Vector string = ConstructSource( base::StaticCharVector(""), base::StaticCharVector("abcdef"), base::StaticCharVector(""), 999999); Handle name = f->NewStringFromUtf8(string).ToHandleChecked(); SerializerOneByteResource one_byte_resource( reinterpret_cast(string.begin()), string.length()); name = f->InternalizeString(name); name->MakeExternal(&one_byte_resource); CHECK(name->IsExternalOneByteString()); CHECK(name->IsInternalizedString()); CHECK(isolate->heap()->InSpace(*name, LO_SPACE)); // Create the source, which is "var = 42; ". Handle source_str = f->NewConsString( f->NewConsString(f->NewStringFromAsciiChecked("var "), name) .ToHandleChecked(), f->NewConsString(f->NewStringFromAsciiChecked(" = 42; "), name) .ToHandleChecked()) .ToHandleChecked(); Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache(isolate, source_str, ScriptDetails(), &cache, v8::ScriptCompiler::kNoCompileOptions); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_str, ScriptDetails(), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK_EQ(42.0, copy_result->Number()); // This avoids the GC from trying to free stack allocated resources. i::Handle::cast(name)->SetResource(isolate, nullptr); delete cache; string.Dispose(); } TEST(CodeSerializerExternalScriptName) { LocalContext context; Isolate* isolate = CcTest::i_isolate(); isolate->compilation_cache() ->DisableScriptAndEval(); // Disable same-isolate code cache. Factory* f = isolate->factory(); v8::HandleScope scope(CcTest::isolate()); const char* source = "var a = [1, 2, 3, 4];" "a.reduce(function(x, y) { return x + y }, 0)"; Handle source_string = f->NewStringFromUtf8(base::CStrVector(source)).ToHandleChecked(); const SerializerOneByteResource one_byte_resource("one_byte", 8); Handle name = f->NewExternalStringFromOneByte(&one_byte_resource).ToHandleChecked(); CHECK(name->IsExternalOneByteString()); CHECK(!name->IsInternalizedString()); Handle global(isolate->context().global_object(), isolate); AlignedCachedData* cache = nullptr; Handle orig = CompileScriptAndProduceCache( isolate, source_string, ScriptDetails(name), &cache, v8::ScriptCompiler::kNoCompileOptions); Handle copy; { DisallowCompilation no_compile_expected(isolate); copy = CompileScript(isolate, source_string, ScriptDetails(name), cache, v8::ScriptCompiler::kConsumeCodeCache); } CHECK_NE(*orig, *copy); Handle copy_fun = Factory::JSFunctionBuilder{isolate, copy, isolate->native_context()} .Build(); Handle copy_result = Execution::CallScript(isolate, copy_fun, global, isolate->factory()->empty_fixed_array()) .ToHandleChecked(); CHECK_EQ(10.0, copy_result->Number()); // This avoids the GC from trying to free stack allocated resources. i::Handle::cast(name)->SetResource(isolate, nullptr); delete cache; } static bool toplevel_test_code_event_found = false; static void SerializerLogEventListener(const v8::JitCodeEvent* event) { if (event->type == v8::JitCodeEvent::CODE_ADDED && (memcmp(event->name.str, "Script:~ test", 13) == 0 || memcmp(event->name.str, "Script: test", 12) == 0)) { toplevel_test_code_event_found = true; } } v8::ScriptCompiler::CachedData* CompileRunAndProduceCache( const char* js_source, CodeCacheType cacheType = CodeCacheType::kLazy) { v8::ScriptCompiler::CachedData* cache; v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate1 = v8::Isolate::New(create_params); { v8::Isolate::Scope iscope(isolate1); v8::HandleScope scope(isolate1); v8::Local context = v8::Context::New(isolate1); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str(js_source); v8::ScriptOrigin origin(isolate1, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin); v8::ScriptCompiler::CompileOptions options; switch (cacheType) { case CodeCacheType::kEager: options = v8::ScriptCompiler::kEagerCompile; break; case CodeCacheType::kLazy: case CodeCacheType::kAfterExecute: options = v8::ScriptCompiler::kNoCompileOptions; break; default: UNREACHABLE(); } v8::Local script = v8::ScriptCompiler::CompileUnboundScript(isolate1, &source, options) .ToLocalChecked(); if (cacheType != CodeCacheType::kAfterExecute) { cache = ScriptCompiler::CreateCodeCache(script); } v8::Local result = script->BindToCurrentContext() ->Run(isolate1->GetCurrentContext()) .ToLocalChecked(); v8::Local result_string = result->ToString(isolate1->GetCurrentContext()).ToLocalChecked(); CHECK(result_string->Equals(isolate1->GetCurrentContext(), v8_str("abcdef")) .FromJust()); if (cacheType == CodeCacheType::kAfterExecute) { cache = ScriptCompiler::CreateCodeCache(script); } CHECK(cache); } isolate1->Dispose(); return cache; } TEST(CodeSerializerIsolates) { const char* js_source = "function f() { return 'abc'; }; f() + 'def'"; v8::ScriptCompiler::CachedData* cache = CompileRunAndProduceCache(js_source); v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate2 = v8::Isolate::New(create_params); isolate2->SetJitCodeEventHandler(v8::kJitCodeEventDefault, SerializerLogEventListener); toplevel_test_code_event_found = false; { v8::Isolate::Scope iscope(isolate2); v8::HandleScope scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str(js_source); v8::ScriptOrigin origin(isolate2, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin, cache); v8::Local script; { DisallowCompilation no_compile(reinterpret_cast(isolate2)); script = v8::ScriptCompiler::CompileUnboundScript( isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); } CHECK(!cache->rejected); v8::Local result = script->BindToCurrentContext() ->Run(isolate2->GetCurrentContext()) .ToLocalChecked(); CHECK(result->ToString(isolate2->GetCurrentContext()) .ToLocalChecked() ->Equals(isolate2->GetCurrentContext(), v8_str("abcdef")) .FromJust()); } CHECK(toplevel_test_code_event_found); isolate2->Dispose(); } TEST(CodeSerializerIsolatesEager) { const char* js_source = "function f() {" " return function g() {" " return 'abc';" " }" "}" "f()() + 'def'"; v8::ScriptCompiler::CachedData* cache = CompileRunAndProduceCache(js_source, CodeCacheType::kEager); v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate2 = v8::Isolate::New(create_params); isolate2->SetJitCodeEventHandler(v8::kJitCodeEventDefault, SerializerLogEventListener); toplevel_test_code_event_found = false; { v8::Isolate::Scope iscope(isolate2); v8::HandleScope scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str(js_source); v8::ScriptOrigin origin(isolate2, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin, cache); v8::Local script; { DisallowCompilation no_compile(reinterpret_cast(isolate2)); script = v8::ScriptCompiler::CompileUnboundScript( isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); } CHECK(!cache->rejected); v8::Local result = script->BindToCurrentContext() ->Run(isolate2->GetCurrentContext()) .ToLocalChecked(); CHECK(result->ToString(isolate2->GetCurrentContext()) .ToLocalChecked() ->Equals(isolate2->GetCurrentContext(), v8_str("abcdef")) .FromJust()); } CHECK(toplevel_test_code_event_found); isolate2->Dispose(); } TEST(CodeSerializerAfterExecute) { // We test that no compilations happen when running this code. Forcing // to always optimize breaks this test. bool prev_always_turbofan_value = v8_flags.always_turbofan; v8_flags.always_turbofan = false; const char* js_source = "function f() { return 'abc'; }; f() + 'def'"; v8::ScriptCompiler::CachedData* cache = CompileRunAndProduceCache(js_source, CodeCacheType::kAfterExecute); v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate2 = v8::Isolate::New(create_params); Isolate* i_isolate2 = reinterpret_cast(isolate2); { v8::Isolate::Scope iscope(isolate2); v8::HandleScope scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str(js_source); v8::ScriptOrigin origin(isolate2, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin, cache); v8::Local script; { DisallowCompilation no_compile_expected(i_isolate2); script = v8::ScriptCompiler::CompileUnboundScript( isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); } CHECK(!cache->rejected); Handle sfi = v8::Utils::OpenHandle(*script); CHECK(sfi->HasBytecodeArray()); { DisallowCompilation no_compile_expected(i_isolate2); v8::Local result = script->BindToCurrentContext() ->Run(isolate2->GetCurrentContext()) .ToLocalChecked(); v8::Local result_string = result->ToString(isolate2->GetCurrentContext()).ToLocalChecked(); CHECK( result_string->Equals(isolate2->GetCurrentContext(), v8_str("abcdef")) .FromJust()); } } isolate2->Dispose(); // Restore the flags. v8_flags.always_turbofan = prev_always_turbofan_value; } TEST(CodeSerializerFlagChange) { const char* js_source = "function f() { return 'abc'; }; f() + 'def'"; v8::ScriptCompiler::CachedData* cache = CompileRunAndProduceCache(js_source); v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate2 = v8::Isolate::New(create_params); v8_flags.allow_natives_syntax = true; // Flag change should trigger cache reject. FlagList::EnforceFlagImplications(); { v8::Isolate::Scope iscope(isolate2); v8::HandleScope scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str(js_source); v8::ScriptOrigin origin(isolate2, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin, cache); v8::ScriptCompiler::CompileUnboundScript( isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); CHECK(cache->rejected); } isolate2->Dispose(); } TEST(CodeSerializerBitFlip) { i::v8_flags.verify_snapshot_checksum = true; const char* js_source = "function f() { return 'abc'; }; f() + 'def'"; v8::ScriptCompiler::CachedData* cache = CompileRunAndProduceCache(js_source); // Arbitrary bit flip. int arbitrary_spot = 237; CHECK_LT(arbitrary_spot, cache->length); const_cast(cache->data)[arbitrary_spot] ^= 0x40; v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate2 = v8::Isolate::New(create_params); { v8::Isolate::Scope iscope(isolate2); v8::HandleScope scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope context_scope(context); v8::Local source_str = v8_str(js_source); v8::ScriptOrigin origin(isolate2, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin, cache); v8::ScriptCompiler::CompileUnboundScript( isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); CHECK(cache->rejected); } isolate2->Dispose(); } TEST(CodeSerializerWithHarmonyScoping) { const char* source1 = "'use strict'; let x = 'X'"; const char* source2 = "'use strict'; let y = 'Y'"; const char* source3 = "'use strict'; x + y"; v8::ScriptCompiler::CachedData* cache; v8::Isolate::CreateParams create_params; create_params.array_buffer_allocator = CcTest::array_buffer_allocator(); v8::Isolate* isolate1 = v8::Isolate::New(create_params); { v8::Isolate::Scope iscope(isolate1); v8::HandleScope scope(isolate1); v8::Local context = v8::Context::New(isolate1); v8::Context::Scope context_scope(context); CompileRun(source1); CompileRun(source2); v8::Local source_str = v8_str(source3); v8::ScriptOrigin origin(isolate1, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin); v8::Local script = v8::ScriptCompiler::CompileUnboundScript( isolate1, &source, v8::ScriptCompiler::kNoCompileOptions) .ToLocalChecked(); cache = v8::ScriptCompiler::CreateCodeCache(script); CHECK(cache); v8::Local result = script->BindToCurrentContext() ->Run(isolate1->GetCurrentContext()) .ToLocalChecked(); v8::Local result_str = result->ToString(isolate1->GetCurrentContext()).ToLocalChecked(); CHECK(result_str->Equals(isolate1->GetCurrentContext(), v8_str("XY")) .FromJust()); } isolate1->Dispose(); v8::Isolate* isolate2 = v8::Isolate::New(create_params); { v8::Isolate::Scope iscope(isolate2); v8::HandleScope scope(isolate2); v8::Local context = v8::Context::New(isolate2); v8::Context::Scope context_scope(context); // Reverse order of prior running scripts. CompileRun(source2); CompileRun(source1); v8::Local source_str = v8_str(source3); v8::ScriptOrigin origin(isolate2, v8_str("test")); v8::ScriptCompiler::Source source(source_str, origin, cache); v8::Local script; { DisallowCompilation no_compile(reinterpret_cast(isolate2)); script = v8::ScriptCompiler::CompileUnboundScript( isolate2, &source, v8::ScriptCompiler::kConsumeCodeCache) .ToLocalChecked(); } v8::Local result = script->BindToCurrentContext() ->Run(isolate2->GetCurrentContext()) .ToLocalChecked(); v8::Local result_str = result->ToString(isolate2->GetCurrentContext()).ToLocalChecked(); CHECK(result_str->Equals(isolate2->GetCurrentContext(), v8_str("XY")) .FromJust()); } isolate2->Dispose(); } TEST(Regress503552) { if (!v8_flags.incremental_marking) return; // Test that the code serializer can deal with weak cells that form a linked // list during incremental marking. CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope scope(isolate); Handle source = isolate->factory()->NewStringFromAsciiChecked( "function f() {} function g() {}"); AlignedCachedData* cached_data = nullptr; Handle shared = CompileScriptAndProduceCache( isolate, source, ScriptDetails(), &cached_data, v8::ScriptCompiler::kNoCompileOptions); delete cached_data; heap::SimulateIncrementalMarking(isolate->heap()); v8::ScriptCompiler::CachedData* cache_data = CodeSerializer::Serialize(isolate, shared); delete cache_data; } static void CodeSerializerMergeDeserializedScript(bool retain_toplevel_sfi) { v8_flags.stress_background_compile = false; CcTest::InitializeVM(); Isolate* isolate = CcTest::i_isolate(); HandleScope outer_scope(isolate); Handle source = isolate->factory()->NewStringFromAsciiChecked( "(function () {return 123;})"); AlignedCachedData* cached_data = nullptr; Handle