Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(1089)

Side by Side Diff: third_party/WebKit/Source/bindings/core/v8/V8ContextSnapshot.cpp

Issue 2841443005: [Bindings] Create and use V8 context snapshots (Closed)
Patch Set: Work for comments Created 3 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "bindings/core/v8/V8ContextSnapshot.h"
6
7 #include <array>
8 #include <cstring>
9
10 #include "bindings/core/v8/GeneratedCodeHelper.h"
11 #include "bindings/core/v8/V8Document.h"
12 #include "bindings/core/v8/V8EventTarget.h"
13 #include "bindings/core/v8/V8HTMLDocument.h"
14 #include "bindings/core/v8/V8Initializer.h"
15 #include "bindings/core/v8/V8Node.h"
16 #include "bindings/core/v8/V8Window.h"
17 #include "platform/bindings/DOMWrapperWorld.h"
18 #include "platform/bindings/V8ObjectConstructor.h"
19 #include "platform/bindings/V8PerIsolateData.h"
20 #include "platform/bindings/V8PrivateProperty.h"
21 #include "platform/instrumentation/tracing/TraceEvent.h"
22 #include "v8/include/v8.h"
23
24 namespace blink {
25
26 namespace {
27
28 intptr_t* g_v8_context_snapshot_reference_table = nullptr;
29
30 // TODO(peria): This method is almost a copy of
31 // V8PerContext::ConstructorForTypeSlowCase(), so merge with it.
haraken 2017/07/10 06:52:08 Yeah, it's error-prone to duplicate the method her
peria 2017/07/10 10:18:43 Acknowledged.
32 v8::Local<v8::Function> ConstructPlainType(v8::Isolate* isolate,
33 const DOMWrapperWorld& world,
34 v8::Local<v8::Context> context,
35 const WrapperTypeInfo* type) {
36 v8::Context::Scope scope(context);
37 // We shouldn't reach this point for the types that are implemented in v8 such
38 // as typed arrays and hence don't have domTemplateFunction.
39 DCHECK(type->dom_template_function);
40 v8::Local<v8::FunctionTemplate> interface_template =
41 type->domTemplate(isolate, world);
42 // Getting the function might fail if we're running out of stack or memory.
43 v8::Local<v8::Function> interface_object =
44 interface_template->GetFunction(context).ToLocalChecked();
45
46 if (type->parent_class) {
47 v8::Local<v8::Object> prototype_template =
48 ConstructPlainType(isolate, world, context, type->parent_class);
49 CHECK(interface_object->SetPrototype(context, prototype_template)
50 .ToChecked());
51 }
52
53 v8::Local<v8::Value> prototype_value =
54 interface_object->Get(context, V8AtomicString(isolate, "prototype"))
55 .ToLocalChecked();
56 CHECK(prototype_value->IsObject());
57 v8::Local<v8::Object> prototype_object = prototype_value.As<v8::Object>();
58 if (prototype_object->InternalFieldCount() ==
59 kV8PrototypeInternalFieldcount &&
60 type->wrapper_type_prototype ==
61 WrapperTypeInfo::kWrapperTypeObjectPrototype) {
62 prototype_object->SetAlignedPointerInInternalField(
63 kV8PrototypeTypeIndex, const_cast<WrapperTypeInfo*>(type));
64 }
65 type->PreparePrototypeAndInterfaceObject(
66 context, world, prototype_object, interface_object, interface_template);
67
68 return interface_object;
69 }
70
71 // TODO(peria): This method is almost a copy of
72 // V8PerContext::CreateWrapperFromCacheSlowCase(), so merge with it.
73 v8::Local<v8::Object> CreatePlainWrapper(v8::Isolate* isolate,
74 const DOMWrapperWorld& world,
75 v8::Local<v8::Context> context,
76 const WrapperTypeInfo* type) {
77 CHECK(V8HTMLDocument::wrapperTypeInfo.Equals(type));
78
79 v8::Context::Scope scope(context);
80 v8::Local<v8::Function> interface_object =
81 ConstructPlainType(isolate, world, context, type);
82 CHECK(!interface_object.IsEmpty());
83 v8::Local<v8::Object> instance_template =
84 V8ObjectConstructor::NewInstance(isolate, interface_object)
85 .ToLocalChecked();
86 v8::Local<v8::Object> wrapper = instance_template->Clone();
87 wrapper->SetAlignedPointerInInternalField(kV8DOMWrapperTypeIndex,
88 const_cast<WrapperTypeInfo*>(type));
89 return wrapper;
90 }
91
92 int GetSnapshotIndexForWorld(const DOMWrapperWorld& world) {
93 return world.IsMainWorld() ? 0 : 1;
94 }
95
96 // Interface templates of those classes are stored in a snapshot without any
97 // runtime enabled features, so we have to install runtime enabled features on
98 // them after instantiation.
99 struct SnapshotInterface {
100 const WrapperTypeInfo* wrapper_type_info;
101 InstallRuntimeEnabledFeaturesOnTemplateFunction install_function;
102 };
103 SnapshotInterface g_snapshot_interfaces[] = {
104 {&V8Window::wrapperTypeInfo,
105 V8Window::InstallRuntimeEnabledFeaturesOnTemplate},
106 {&V8HTMLDocument::wrapperTypeInfo,
107 V8HTMLDocument::InstallRuntimeEnabledFeaturesOnTemplate},
108 {&V8EventTarget::wrapperTypeInfo,
109 V8EventTarget::InstallRuntimeEnabledFeaturesOnTemplate},
110 {&V8Node::wrapperTypeInfo, V8Node::InstallRuntimeEnabledFeaturesOnTemplate},
111 {&V8Document::wrapperTypeInfo,
112 V8Document::InstallRuntimeEnabledFeaturesOnTemplate},
113 };
114 constexpr size_t kSnapshotInterfaceSize =
115 WTF_ARRAY_LENGTH(g_snapshot_interfaces);
116
117 enum class InternalFieldType : uint8_t {
118 kNone,
119 kNodeType,
120 kDocumentType,
121 kHTMLDocumentType,
122 kHTMLDocumentObject,
123 };
124
125 const WrapperTypeInfo* FieldTypeToWrapperTypeInfo(InternalFieldType type) {
126 switch (type) {
127 case InternalFieldType::kNone:
128 NOTREACHED();
129 break;
130 case InternalFieldType::kNodeType:
131 return &V8Node::wrapperTypeInfo;
132 case InternalFieldType::kDocumentType:
133 return &V8Document::wrapperTypeInfo;
134 case InternalFieldType::kHTMLDocumentType:
135 return &V8HTMLDocument::wrapperTypeInfo;
136 case InternalFieldType::kHTMLDocumentObject:
137 return &V8HTMLDocument::wrapperTypeInfo;
138 }
139 NOTREACHED();
140 return nullptr;
141 }
142
143 struct DataForDeserializer {
144 STACK_ALLOCATED();
145 Member<Document> document;
146 };
147
148 int CountExternalReferenceEntries() {
149 if (!g_v8_context_snapshot_reference_table)
150 return 0;
151
152 int count = 0;
153 for (intptr_t* p = g_v8_context_snapshot_reference_table; *p; ++p)
154 ++count;
155 return count;
156 }
157
158 } // namespace
159
160 v8::Local<v8::Context> V8ContextSnapshot::CreateContextFromSnapshot(
161 v8::Isolate* isolate,
162 const DOMWrapperWorld& world,
163 v8::ExtensionConfiguration* extension_configuration,
164 v8::Local<v8::Object> global_proxy,
165 Document* document) {
166 if (!CanCreateContextFromSnapshot(isolate, world, document)) {
167 return v8::Local<v8::Context>();
168 }
169
170 const int index = GetSnapshotIndexForWorld(world);
171 DataForDeserializer data{document};
172 v8::DeserializeInternalFieldsCallback callback =
173 v8::DeserializeInternalFieldsCallback(&DeserializeInternalField, &data);
174 v8::Local<v8::Context> context =
175 v8::Context::FromSnapshot(isolate, index, callback,
176 extension_configuration, global_proxy)
177 .ToLocalChecked();
178 VLOG(1) << "A context is created from snapshot for "
179 << (world.IsMainWorld() ? "" : "non-") << "main world";
180
181 return context;
182 }
183
184 void V8ContextSnapshot::InstallRuntimeEnabledFeatures(
185 v8::Local<v8::Context> context,
186 Document* document) {
187 ScriptState* script_state = ScriptState::From(context);
188 v8::Isolate* isolate = script_state->GetIsolate();
189 const DOMWrapperWorld& world = script_state->World();
190 if (!CanCreateContextFromSnapshot(isolate, world, document)) {
191 return;
192 }
193
194 TRACE_EVENT1("v8", "V8ContextSnapshot::InstallRuntimeEnabled", "IsMainFrame",
195 world.IsMainWorld());
196
197 v8::Local<v8::String> prototype_str = V8AtomicString(isolate, "prototype");
198 V8PerContextData* data = script_state->PerContextData();
199
200 v8::Local<v8::Object> global_proxy = context->Global();
201 {
202 v8::Local<v8::Object> window_wrapper =
203 global_proxy->GetPrototype().As<v8::Object>();
204 const WrapperTypeInfo* type = &V8Window::wrapperTypeInfo;
205 v8::Local<v8::Function> interface = data->ConstructorForType(type);
206 v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
207 .ToLocalChecked()
208 .As<v8::Object>();
209 V8Window::install_runtime_enabled_features_function_(
210 isolate, world, window_wrapper, prototype, interface);
211 }
212 {
213 const WrapperTypeInfo* type = &V8EventTarget::wrapperTypeInfo;
214 v8::Local<v8::Function> interface = data->ConstructorForType(type);
215 v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
216 .ToLocalChecked()
217 .As<v8::Object>();
218 V8EventTarget::InstallRuntimeEnabledFeatures(
219 isolate, world, v8::Local<v8::Object>(), prototype, interface);
220 }
221
222 if (!world.IsMainWorld()) {
223 return;
224 }
225
226 {
haraken 2017/07/10 06:52:08 // The below code handles window.document on the m
peria 2017/07/10 10:18:43 Done.
227 CHECK(document);
228 DCHECK(document->IsHTMLDocument());
229 CHECK(document->ContainsWrapper());
230 v8::Local<v8::Object> document_wrapper =
231 ToV8(document, global_proxy, isolate).As<v8::Object>();
232 const WrapperTypeInfo* type = &V8HTMLDocument::wrapperTypeInfo;
233 v8::Local<v8::Function> interface = data->ConstructorForType(type);
234 v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
235 .ToLocalChecked()
236 .As<v8::Object>();
237 V8HTMLDocument::InstallRuntimeEnabledFeatures(
238 isolate, world, document_wrapper, prototype, interface);
239 }
240 {
241 const WrapperTypeInfo* type = &V8Document::wrapperTypeInfo;
242 v8::Local<v8::Function> interface = data->ConstructorForType(type);
243 v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
244 .ToLocalChecked()
245 .As<v8::Object>();
246 V8Document::InstallRuntimeEnabledFeatures(
247 isolate, world, v8::Local<v8::Object>(), prototype, interface);
248 }
249 {
250 const WrapperTypeInfo* type = &V8Node::wrapperTypeInfo;
251 v8::Local<v8::Function> interface = data->ConstructorForType(type);
252 v8::Local<v8::Object> prototype = interface->Get(context, prototype_str)
253 .ToLocalChecked()
254 .As<v8::Object>();
255 V8Node::InstallRuntimeEnabledFeatures(
256 isolate, world, v8::Local<v8::Object>(), prototype, interface);
257 }
258 }
259
260 void V8ContextSnapshot::EnsureInterfaceTemplates(v8::Isolate* isolate) {
261 if (V8PerIsolateData::From(isolate)->GetV8ContextSnapshotMode() !=
262 V8PerIsolateData::V8ContextSnapshotMode::kUseSnapshot) {
263 return;
264 }
265
266 v8::HandleScope handle_scope(isolate);
267 SnapshotInterface& snapshot_window = g_snapshot_interfaces[0];
268 DCHECK(V8Window::wrapperTypeInfo.Equals(snapshot_window.wrapper_type_info));
269 // Update the install function for V8Window to work for partial interfaces.
270 snapshot_window.install_function =
271 V8Window::install_runtime_enabled_features_on_template_function_;
272
273 EnsureInterfaceTemplatesForWorld(isolate, DOMWrapperWorld::MainWorld());
274 // Any world types other than |kMain| are acceptable for this.
275 RefPtr<DOMWrapperWorld> isolated_world =
276 DOMWrapperWorld::Create(isolate, DOMWrapperWorld::WorldType::kTesting);
haraken 2017/07/10 06:52:08 This creates a new isolated world, right? As I me
peria 2017/07/10 10:18:43 Ah, right. Is there a way to swipe out DOMWraperWo
peria 2017/07/11 06:54:31 My understanding was wrong, and this code works we
haraken 2017/07/11 09:05:12 Makes sense. kTesting => kDeserializeV8ContextSna
277 EnsureInterfaceTemplatesForWorld(isolate, *isolated_world);
278 }
279
280 void V8ContextSnapshot::SetReferenceTable(intptr_t* table) {
281 DCHECK(!g_v8_context_snapshot_reference_table);
282 g_v8_context_snapshot_reference_table = table;
283 }
284
285 intptr_t* V8ContextSnapshot::GetReferenceTable() {
286 return g_v8_context_snapshot_reference_table;
287 }
288
289 v8::StartupData V8ContextSnapshot::TakeSnapshot() {
290 DCHECK_EQ(V8PerIsolateData::From(V8PerIsolateData::MainThreadIsolate())
291 ->GetV8ContextSnapshotMode(),
292 V8PerIsolateData::V8ContextSnapshotMode::kTakeSnapshot);
293
294 v8::SnapshotCreator* creator =
295 V8PerIsolateData::From(V8PerIsolateData::MainThreadIsolate())
296 ->GetSnapshotCreator();
297 v8::Isolate* isolate = creator->GetIsolate();
298 CHECK_EQ(isolate, v8::Isolate::GetCurrent());
299
300 VLOG(1) << "External reference table has " << CountExternalReferenceEntries()
301 << " entries.";
302
303 // Disable all runtime enabled features
304 RuntimeEnabledFeatures::SetStableFeaturesEnabled(false);
305 RuntimeEnabledFeatures::SetExperimentalFeaturesEnabled(false);
306 RuntimeEnabledFeatures::SetTestFeaturesEnabled(false);
307
308 {
309 v8::HandleScope handleScope(isolate);
310 creator->SetDefaultContext(v8::Context::New(isolate));
311
312 TakeSnapshotForWorld(creator, DOMWrapperWorld::MainWorld());
313 // For non main worlds, we can use any type to create a context.
haraken 2017/07/10 06:52:08 It is fine to create an isolated world here becaus
peria 2017/07/10 10:18:43 Acknowledged.
314 TakeSnapshotForWorld(creator,
315 *DOMWrapperWorld::Create(
316 isolate, DOMWrapperWorld::WorldType::kTesting));
317 }
318
319 isolate->RemoveMessageListeners(V8Initializer::MessageHandlerInMainThread);
320
321 return creator->CreateBlob(v8::SnapshotCreator::FunctionCodeHandling::kClear);
322 }
323
324 v8::StartupData V8ContextSnapshot::SerializeInternalField(
325 v8::Local<v8::Object> object,
326 int index,
327 void*) {
328 InternalFieldType field_type = InternalFieldType::kNone;
329 const WrapperTypeInfo* wrapper_type = ToWrapperTypeInfo(object);
330 if (kV8DOMWrapperObjectIndex == index) {
331 if (blink::V8HTMLDocument::wrapperTypeInfo.Equals(wrapper_type)) {
332 field_type = InternalFieldType::kHTMLDocumentObject;
333 }
334 } else if (kV8DOMWrapperTypeIndex == index) {
335 if (blink::V8HTMLDocument::wrapperTypeInfo.Equals(wrapper_type)) {
336 field_type = InternalFieldType::kHTMLDocumentType;
337 } else if (blink::V8Document::wrapperTypeInfo.Equals(wrapper_type)) {
338 field_type = InternalFieldType::kDocumentType;
339 } else if (blink::V8Node::wrapperTypeInfo.Equals(wrapper_type)) {
340 field_type = InternalFieldType::kNodeType;
341 }
342 }
haraken 2017/07/10 06:52:08 Can we add a DCHECK to verify that these wrappers
peria 2017/07/10 10:18:43 Done. But for 'V8HTMLDocument' objects, it is diff
343 CHECK_NE(field_type, InternalFieldType::kNone);
344
345 int size = sizeof(InternalFieldType);
346 // Allocated memory on |data| will be released in
347 // v8::i::PartialSerializer::SerializeEmbedderFields().
348 char* data = new char[size];
349 std::memcpy(data, &field_type, size);
350
351 return {data, size};
352 }
353
354 void V8ContextSnapshot::DeserializeInternalField(v8::Local<v8::Object> object,
355 int index,
356 v8::StartupData payload,
357 void* ptr) {
358 // DeserializeInternalField() expects to be called in the main world
359 // with |document| being HTMLDocument.
haraken 2017/07/10 06:52:08 What happens when a non-main world calls Deseriali
peria 2017/07/10 10:18:43 it goes as far as it passes CHECK_EQ() and NOTREAC
360 CHECK_EQ(payload.raw_size, static_cast<int>(sizeof(InternalFieldType)));
361 InternalFieldType type =
362 *reinterpret_cast<const InternalFieldType*>(payload.data);
363
364 const WrapperTypeInfo* wrapper_type_info = FieldTypeToWrapperTypeInfo(type);
365 switch (type) {
366 case InternalFieldType::kNodeType:
367 case InternalFieldType::kDocumentType:
368 case InternalFieldType::kHTMLDocumentType: {
369 CHECK_EQ(index, kV8DOMWrapperTypeIndex);
370 object->SetAlignedPointerInInternalField(
371 index, const_cast<WrapperTypeInfo*>(wrapper_type_info));
372 return;
373 }
374 case InternalFieldType::kHTMLDocumentObject: {
haraken 2017/07/10 06:52:08 // The below code handles window.document on the m
peria 2017/07/10 10:18:43 Done.
375 CHECK_EQ(index, kV8DOMWrapperObjectIndex);
376 v8::Isolate* isolate = v8::Isolate::GetCurrent();
377 DataForDeserializer* data = static_cast<DataForDeserializer*>(ptr);
378 ScriptWrappable* document = data->document;
379 DCHECK(document);
380
381 // Make reference from wrapper to document
382 object->SetAlignedPointerInInternalField(index, document);
383 // Make reference from document to wrapper
384 CHECK(document->SetWrapper(isolate, wrapper_type_info, object));
385 WrapperTypeInfo::WrapperCreated();
386 return;
387 }
388 case InternalFieldType::kNone:
389 NOTREACHED();
390 return;
391 }
392
393 NOTREACHED();
394 }
395
396 bool V8ContextSnapshot::CanCreateContextFromSnapshot(
397 v8::Isolate* isolate,
398 const DOMWrapperWorld& world,
399 Document* document) {
400 DCHECK(document);
401 if (V8PerIsolateData::From(isolate)->GetV8ContextSnapshotMode() !=
402 V8PerIsolateData::V8ContextSnapshotMode::kUseSnapshot) {
403 return false;
404 }
405
406 // When creating a context for the main world from snapshot, we also need a
407 // HTMLDocument instance. If typeof window.document is not HTMLDocument, e.g.
408 // SVGDocument or XMLDocument, we can't create contexts from the snapshot.
409 return !world.IsMainWorld() || document->IsHTMLDocument();
410 }
411
412 void V8ContextSnapshot::EnsureInterfaceTemplatesForWorld(
413 v8::Isolate* isolate,
414 const DOMWrapperWorld& world) {
415 V8PerIsolateData* data = V8PerIsolateData::From(isolate);
416
417 // A snapshot has some interface templates in it. First
418 // |kSnapshotInterfaceSize| templates are for the main world, and other
haraken 2017/07/10 06:52:08 The first |kSnapshotInterfaceSize| templates are .
peria 2017/07/10 10:18:43 Done.
419 // templates are for isolated worlds.
420 const int index_offset = world.IsMainWorld() ? 0 : kSnapshotInterfaceSize;
421
422 for (size_t i = 0; i < kSnapshotInterfaceSize; ++i) {
423 auto& snapshot_interface = g_snapshot_interfaces[i];
424 const WrapperTypeInfo* wrapper_type_info =
425 snapshot_interface.wrapper_type_info;
426 v8::Local<v8::FunctionTemplate> interface_template =
427 v8::FunctionTemplate::FromSnapshot(isolate, index_offset + i)
428 .ToLocalChecked();
429 snapshot_interface.install_function(isolate, world, interface_template);
430 CHECK(!interface_template.IsEmpty());
431 data->SetInterfaceTemplate(world, wrapper_type_info, interface_template);
432 }
433 }
434
435 void V8ContextSnapshot::TakeSnapshotForWorld(v8::SnapshotCreator* creator,
436 const DOMWrapperWorld& world) {
437 v8::Isolate* isolate = creator->GetIsolate();
438 CHECK_EQ(isolate, v8::Isolate::GetCurrent());
439
440 // Function templates
441 v8::HandleScope handleScope(isolate);
442 std::array<v8::Local<v8::FunctionTemplate>, kSnapshotInterfaceSize>
443 interface_templates;
444 v8::Local<v8::FunctionTemplate> window_template;
445 for (size_t i = 0; i < kSnapshotInterfaceSize; ++i) {
446 const WrapperTypeInfo* wrapper_type_info =
447 g_snapshot_interfaces[i].wrapper_type_info;
448 v8::Local<v8::FunctionTemplate> interface_template =
449 wrapper_type_info->domTemplate(isolate, world);
450 CHECK(!interface_template.IsEmpty());
451 interface_templates[i] = interface_template;
452 if (V8Window::wrapperTypeInfo.Equals(wrapper_type_info)) {
453 window_template = interface_template;
454 }
455 }
456 CHECK(!window_template.IsEmpty());
457
458 v8::Local<v8::ObjectTemplate> window_instance_template =
459 window_template->InstanceTemplate();
460 CHECK(!window_instance_template.IsEmpty());
461
462 v8::Local<v8::Context> context;
463 {
464 V8PerIsolateData::UseCounterDisabledScope use_counter_disabled(
465 V8PerIsolateData::From(isolate));
466 context = v8::Context::New(isolate, nullptr, window_instance_template);
467 }
468 CHECK(!context.IsEmpty());
469
470 // For the main world context, we also prepare a HTMLDocument wrapper,
471 // because it is used for "window.document" in most cases.
haraken 2017/07/10 06:52:08 // For the main world context, we need to prepare
peria 2017/07/10 10:18:43 Done.
472 if (world.IsMainWorld()) {
473 v8::Context::Scope scope(context);
474 v8::Local<v8::Object> document_wrapper = CreatePlainWrapper(
475 isolate, world, context, &V8HTMLDocument::wrapperTypeInfo);
476 int indices[] = {kV8DOMWrapperObjectIndex, kV8DOMWrapperTypeIndex};
477 void* values[] = {nullptr, const_cast<WrapperTypeInfo*>(
478 &V8HTMLDocument::wrapperTypeInfo)};
479 document_wrapper->SetAlignedPointerInInternalFields(
480 WTF_ARRAY_LENGTH(indices), indices, values);
481
482 // Set the cached accessor for window.document.
483 CHECK(V8PrivateProperty::GetWindowDocumentCachedAccessor(isolate).Set(
484 context->Global(), document_wrapper));
485 }
486
487 for (auto& interface_template : interface_templates) {
488 creator->AddTemplate(interface_template);
489 }
490 creator->AddContext(context, SerializeInternalField);
491
492 V8PerIsolateData::From(isolate)->ClearPersistentsForV8ContextSnapshot();
493 }
494
495 } // namespace blink
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698