blob: 84a08c103de33a532cf3fdbcbfb512f5627633d7 [file] [log] [blame]
Ben Murdochda12d292016-06-02 14:46:10 +01001// Copyright 2016 the V8 project authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "src/snapshot/code-serializer.h"
6
7#include "src/code-stubs.h"
8#include "src/log.h"
9#include "src/macro-assembler.h"
10#include "src/profiler/cpu-profiler.h"
11#include "src/snapshot/deserializer.h"
12#include "src/version.h"
13
14namespace v8 {
15namespace internal {
16
17ScriptData* CodeSerializer::Serialize(Isolate* isolate,
18 Handle<SharedFunctionInfo> info,
19 Handle<String> source) {
20 base::ElapsedTimer timer;
21 if (FLAG_profile_deserialization) timer.Start();
22 if (FLAG_trace_serializer) {
23 PrintF("[Serializing from");
24 Object* script = info->script();
25 if (script->IsScript()) Script::cast(script)->name()->ShortPrint();
26 PrintF("]\n");
27 }
28
29 // Serialize code object.
30 SnapshotByteSink sink(info->code()->CodeSize() * 2);
31 CodeSerializer cs(isolate, &sink, *source);
32 DisallowHeapAllocation no_gc;
33 Object** location = Handle<Object>::cast(info).location();
34 cs.VisitPointer(location);
35 cs.SerializeDeferredObjects();
36 cs.Pad();
37
38 SerializedCodeData data(sink.data(), cs);
39 ScriptData* script_data = data.GetScriptData();
40
41 if (FLAG_profile_deserialization) {
42 double ms = timer.Elapsed().InMillisecondsF();
43 int length = script_data->length();
44 PrintF("[Serializing to %d bytes took %0.3f ms]\n", length, ms);
45 }
46
47 return script_data;
48}
49
50void CodeSerializer::SerializeObject(HeapObject* obj, HowToCode how_to_code,
51 WhereToPoint where_to_point, int skip) {
52 int root_index = root_index_map_.Lookup(obj);
53 if (root_index != RootIndexMap::kInvalidRootIndex) {
54 PutRoot(root_index, obj, how_to_code, where_to_point, skip);
55 return;
56 }
57
58 if (SerializeKnownObject(obj, how_to_code, where_to_point, skip)) return;
59
60 FlushSkip(skip);
61
62 if (obj->IsCode()) {
63 Code* code_object = Code::cast(obj);
64 switch (code_object->kind()) {
65 case Code::OPTIMIZED_FUNCTION: // No optimized code compiled yet.
66 case Code::HANDLER: // No handlers patched in yet.
67 case Code::REGEXP: // No regexp literals initialized yet.
68 case Code::NUMBER_OF_KINDS: // Pseudo enum value.
69 case Code::BYTECODE_HANDLER: // No direct references to handlers.
70 CHECK(false);
71 case Code::BUILTIN:
72 SerializeBuiltin(code_object->builtin_index(), how_to_code,
73 where_to_point);
74 return;
75 case Code::STUB:
76 SerializeCodeStub(code_object->stub_key(), how_to_code, where_to_point);
77 return;
78#define IC_KIND_CASE(KIND) case Code::KIND:
79 IC_KIND_LIST(IC_KIND_CASE)
80#undef IC_KIND_CASE
81 SerializeIC(code_object, how_to_code, where_to_point);
82 return;
83 case Code::FUNCTION:
84 DCHECK(code_object->has_reloc_info_for_serialization());
85 SerializeGeneric(code_object, how_to_code, where_to_point);
86 return;
87 case Code::WASM_FUNCTION:
88 case Code::WASM_TO_JS_FUNCTION:
89 case Code::JS_TO_WASM_FUNCTION:
90 UNREACHABLE();
91 }
92 UNREACHABLE();
93 }
94
95 // Past this point we should not see any (context-specific) maps anymore.
96 CHECK(!obj->IsMap());
97 // There should be no references to the global object embedded.
98 CHECK(!obj->IsJSGlobalProxy() && !obj->IsJSGlobalObject());
99 // There should be no hash table embedded. They would require rehashing.
100 CHECK(!obj->IsHashTable());
101 // We expect no instantiated function objects or contexts.
102 CHECK(!obj->IsJSFunction() && !obj->IsContext());
103
104 SerializeGeneric(obj, how_to_code, where_to_point);
105}
106
107void CodeSerializer::SerializeGeneric(HeapObject* heap_object,
108 HowToCode how_to_code,
109 WhereToPoint where_to_point) {
110 // Object has not yet been serialized. Serialize it here.
111 ObjectSerializer serializer(this, heap_object, sink_, how_to_code,
112 where_to_point);
113 serializer.Serialize();
114}
115
116void CodeSerializer::SerializeBuiltin(int builtin_index, HowToCode how_to_code,
117 WhereToPoint where_to_point) {
118 DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
119 (how_to_code == kPlain && where_to_point == kInnerPointer) ||
120 (how_to_code == kFromCode && where_to_point == kInnerPointer));
121 DCHECK_LT(builtin_index, Builtins::builtin_count);
122 DCHECK_LE(0, builtin_index);
123
124 if (FLAG_trace_serializer) {
125 PrintF(" Encoding builtin: %s\n",
126 isolate()->builtins()->name(builtin_index));
127 }
128
129 sink_->Put(kBuiltin + how_to_code + where_to_point, "Builtin");
130 sink_->PutInt(builtin_index, "builtin_index");
131}
132
133void CodeSerializer::SerializeCodeStub(uint32_t stub_key, HowToCode how_to_code,
134 WhereToPoint where_to_point) {
135 DCHECK((how_to_code == kPlain && where_to_point == kStartOfObject) ||
136 (how_to_code == kPlain && where_to_point == kInnerPointer) ||
137 (how_to_code == kFromCode && where_to_point == kInnerPointer));
138 DCHECK(CodeStub::MajorKeyFromKey(stub_key) != CodeStub::NoCache);
139 DCHECK(!CodeStub::GetCode(isolate(), stub_key).is_null());
140
141 int index = AddCodeStubKey(stub_key) + kCodeStubsBaseIndex;
142
143 if (FLAG_trace_serializer) {
144 PrintF(" Encoding code stub %s as %d\n",
145 CodeStub::MajorName(CodeStub::MajorKeyFromKey(stub_key)), index);
146 }
147
148 sink_->Put(kAttachedReference + how_to_code + where_to_point, "CodeStub");
149 sink_->PutInt(index, "CodeStub key");
150}
151
152void CodeSerializer::SerializeIC(Code* ic, HowToCode how_to_code,
153 WhereToPoint where_to_point) {
154 // The IC may be implemented as a stub.
155 uint32_t stub_key = ic->stub_key();
156 if (stub_key != CodeStub::NoCacheKey()) {
157 if (FLAG_trace_serializer) {
158 PrintF(" %s is a code stub\n", Code::Kind2String(ic->kind()));
159 }
160 SerializeCodeStub(stub_key, how_to_code, where_to_point);
161 return;
162 }
163 // The IC may be implemented as builtin. Only real builtins have an
164 // actual builtin_index value attached (otherwise it's just garbage).
165 // Compare to make sure we are really dealing with a builtin.
166 int builtin_index = ic->builtin_index();
167 if (builtin_index < Builtins::builtin_count) {
168 Builtins::Name name = static_cast<Builtins::Name>(builtin_index);
169 Code* builtin = isolate()->builtins()->builtin(name);
170 if (builtin == ic) {
171 if (FLAG_trace_serializer) {
172 PrintF(" %s is a builtin\n", Code::Kind2String(ic->kind()));
173 }
174 DCHECK(ic->kind() == Code::KEYED_LOAD_IC ||
175 ic->kind() == Code::KEYED_STORE_IC);
176 SerializeBuiltin(builtin_index, how_to_code, where_to_point);
177 return;
178 }
179 }
180 // The IC may also just be a piece of code kept in the non_monomorphic_cache.
181 // In that case, just serialize as a normal code object.
182 if (FLAG_trace_serializer) {
183 PrintF(" %s has no special handling\n", Code::Kind2String(ic->kind()));
184 }
185 DCHECK(ic->kind() == Code::LOAD_IC || ic->kind() == Code::STORE_IC);
186 SerializeGeneric(ic, how_to_code, where_to_point);
187}
188
189int CodeSerializer::AddCodeStubKey(uint32_t stub_key) {
190 // TODO(yangguo) Maybe we need a hash table for a faster lookup than O(n^2).
191 int index = 0;
192 while (index < stub_keys_.length()) {
193 if (stub_keys_[index] == stub_key) return index;
194 index++;
195 }
196 stub_keys_.Add(stub_key);
197 return index;
198}
199
200MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
201 Isolate* isolate, ScriptData* cached_data, Handle<String> source) {
202 base::ElapsedTimer timer;
203 if (FLAG_profile_deserialization) timer.Start();
204
205 HandleScope scope(isolate);
206
207 base::SmartPointer<SerializedCodeData> scd(
208 SerializedCodeData::FromCachedData(isolate, cached_data, *source));
209 if (scd.is_empty()) {
210 if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
211 DCHECK(cached_data->rejected());
212 return MaybeHandle<SharedFunctionInfo>();
213 }
214
215 // Prepare and register list of attached objects.
216 Vector<const uint32_t> code_stub_keys = scd->CodeStubKeys();
217 Vector<Handle<Object> > attached_objects = Vector<Handle<Object> >::New(
218 code_stub_keys.length() + kCodeStubsBaseIndex);
219 attached_objects[kSourceObjectIndex] = source;
220 for (int i = 0; i < code_stub_keys.length(); i++) {
221 attached_objects[i + kCodeStubsBaseIndex] =
222 CodeStub::GetCode(isolate, code_stub_keys[i]).ToHandleChecked();
223 }
224
225 Deserializer deserializer(scd.get());
226 deserializer.SetAttachedObjects(attached_objects);
227
228 // Deserialize.
229 Handle<SharedFunctionInfo> result;
230 if (!deserializer.DeserializeCode(isolate).ToHandle(&result)) {
231 // Deserializing may fail if the reservations cannot be fulfilled.
232 if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
233 return MaybeHandle<SharedFunctionInfo>();
234 }
235
236 if (FLAG_profile_deserialization) {
237 double ms = timer.Elapsed().InMillisecondsF();
238 int length = cached_data->length();
239 PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
240 }
241 result->set_deserialized(true);
242
243 if (isolate->logger()->is_logging_code_events() ||
244 isolate->cpu_profiler()->is_profiling()) {
245 String* name = isolate->heap()->empty_string();
246 if (result->script()->IsScript()) {
247 Script* script = Script::cast(result->script());
248 if (script->name()->IsString()) name = String::cast(script->name());
249 }
250 isolate->logger()->CodeCreateEvent(
251 Logger::SCRIPT_TAG, result->abstract_code(), *result, NULL, name);
252 }
253 return scope.CloseAndEscape(result);
254}
255
256class Checksum {
257 public:
258 explicit Checksum(Vector<const byte> payload) {
259#ifdef MEMORY_SANITIZER
260 // Computing the checksum includes padding bytes for objects like strings.
261 // Mark every object as initialized in the code serializer.
262 MSAN_MEMORY_IS_INITIALIZED(payload.start(), payload.length());
263#endif // MEMORY_SANITIZER
264 // Fletcher's checksum. Modified to reduce 64-bit sums to 32-bit.
265 uintptr_t a = 1;
266 uintptr_t b = 0;
267 const uintptr_t* cur = reinterpret_cast<const uintptr_t*>(payload.start());
268 DCHECK(IsAligned(payload.length(), kIntptrSize));
269 const uintptr_t* end = cur + payload.length() / kIntptrSize;
270 while (cur < end) {
271 // Unsigned overflow expected and intended.
272 a += *cur++;
273 b += a;
274 }
275#if V8_HOST_ARCH_64_BIT
276 a ^= a >> 32;
277 b ^= b >> 32;
278#endif // V8_HOST_ARCH_64_BIT
279 a_ = static_cast<uint32_t>(a);
280 b_ = static_cast<uint32_t>(b);
281 }
282
283 bool Check(uint32_t a, uint32_t b) const { return a == a_ && b == b_; }
284
285 uint32_t a() const { return a_; }
286 uint32_t b() const { return b_; }
287
288 private:
289 uint32_t a_;
290 uint32_t b_;
291
292 DISALLOW_COPY_AND_ASSIGN(Checksum);
293};
294
295SerializedCodeData::SerializedCodeData(const List<byte>& payload,
296 const CodeSerializer& cs) {
297 DisallowHeapAllocation no_gc;
298 const List<uint32_t>* stub_keys = cs.stub_keys();
299
300 List<Reservation> reservations;
301 cs.EncodeReservations(&reservations);
302
303 // Calculate sizes.
304 int reservation_size = reservations.length() * kInt32Size;
305 int num_stub_keys = stub_keys->length();
306 int stub_keys_size = stub_keys->length() * kInt32Size;
307 int payload_offset = kHeaderSize + reservation_size + stub_keys_size;
308 int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
309 int size = padded_payload_offset + payload.length();
310
311 // Allocate backing store and create result data.
312 AllocateData(size);
313
314 // Set header values.
315 SetMagicNumber(cs.isolate());
316 SetHeaderValue(kVersionHashOffset, Version::Hash());
317 SetHeaderValue(kSourceHashOffset, SourceHash(cs.source()));
318 SetHeaderValue(kCpuFeaturesOffset,
319 static_cast<uint32_t>(CpuFeatures::SupportedFeatures()));
320 SetHeaderValue(kFlagHashOffset, FlagList::Hash());
321 SetHeaderValue(kNumReservationsOffset, reservations.length());
322 SetHeaderValue(kNumCodeStubKeysOffset, num_stub_keys);
323 SetHeaderValue(kPayloadLengthOffset, payload.length());
324
325 Checksum checksum(payload.ToConstVector());
326 SetHeaderValue(kChecksum1Offset, checksum.a());
327 SetHeaderValue(kChecksum2Offset, checksum.b());
328
329 // Copy reservation chunk sizes.
330 CopyBytes(data_ + kHeaderSize, reinterpret_cast<byte*>(reservations.begin()),
331 reservation_size);
332
333 // Copy code stub keys.
334 CopyBytes(data_ + kHeaderSize + reservation_size,
335 reinterpret_cast<byte*>(stub_keys->begin()), stub_keys_size);
336
337 memset(data_ + payload_offset, 0, padded_payload_offset - payload_offset);
338
339 // Copy serialized data.
340 CopyBytes(data_ + padded_payload_offset, payload.begin(),
341 static_cast<size_t>(payload.length()));
342}
343
344SerializedCodeData::SanityCheckResult SerializedCodeData::SanityCheck(
345 Isolate* isolate, String* source) const {
346 uint32_t magic_number = GetMagicNumber();
347 if (magic_number != ComputeMagicNumber(isolate)) return MAGIC_NUMBER_MISMATCH;
348 uint32_t version_hash = GetHeaderValue(kVersionHashOffset);
349 uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
350 uint32_t cpu_features = GetHeaderValue(kCpuFeaturesOffset);
351 uint32_t flags_hash = GetHeaderValue(kFlagHashOffset);
352 uint32_t c1 = GetHeaderValue(kChecksum1Offset);
353 uint32_t c2 = GetHeaderValue(kChecksum2Offset);
354 if (version_hash != Version::Hash()) return VERSION_MISMATCH;
355 if (source_hash != SourceHash(source)) return SOURCE_MISMATCH;
356 if (cpu_features != static_cast<uint32_t>(CpuFeatures::SupportedFeatures())) {
357 return CPU_FEATURES_MISMATCH;
358 }
359 if (flags_hash != FlagList::Hash()) return FLAGS_MISMATCH;
360 if (!Checksum(Payload()).Check(c1, c2)) return CHECKSUM_MISMATCH;
361 return CHECK_SUCCESS;
362}
363
364uint32_t SerializedCodeData::SourceHash(String* source) const {
365 return source->length();
366}
367
368// Return ScriptData object and relinquish ownership over it to the caller.
369ScriptData* SerializedCodeData::GetScriptData() {
370 DCHECK(owns_data_);
371 ScriptData* result = new ScriptData(data_, size_);
372 result->AcquireDataOwnership();
373 owns_data_ = false;
374 data_ = NULL;
375 return result;
376}
377
378Vector<const SerializedData::Reservation> SerializedCodeData::Reservations()
379 const {
380 return Vector<const Reservation>(
381 reinterpret_cast<const Reservation*>(data_ + kHeaderSize),
382 GetHeaderValue(kNumReservationsOffset));
383}
384
385Vector<const byte> SerializedCodeData::Payload() const {
386 int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
387 int code_stubs_size = GetHeaderValue(kNumCodeStubKeysOffset) * kInt32Size;
388 int payload_offset = kHeaderSize + reservations_size + code_stubs_size;
389 int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
390 const byte* payload = data_ + padded_payload_offset;
391 DCHECK(IsAligned(reinterpret_cast<intptr_t>(payload), kPointerAlignment));
392 int length = GetHeaderValue(kPayloadLengthOffset);
393 DCHECK_EQ(data_ + size_, payload + length);
394 return Vector<const byte>(payload, length);
395}
396
397Vector<const uint32_t> SerializedCodeData::CodeStubKeys() const {
398 int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
399 const byte* start = data_ + kHeaderSize + reservations_size;
400 return Vector<const uint32_t>(reinterpret_cast<const uint32_t*>(start),
401 GetHeaderValue(kNumCodeStubKeysOffset));
402}
403
404SerializedCodeData::SerializedCodeData(ScriptData* data)
405 : SerializedData(const_cast<byte*>(data->data()), data->length()) {}
406
407SerializedCodeData* SerializedCodeData::FromCachedData(Isolate* isolate,
408 ScriptData* cached_data,
409 String* source) {
410 DisallowHeapAllocation no_gc;
411 SerializedCodeData* scd = new SerializedCodeData(cached_data);
412 SanityCheckResult r = scd->SanityCheck(isolate, source);
413 if (r == CHECK_SUCCESS) return scd;
414 cached_data->Reject();
415 source->GetIsolate()->counters()->code_cache_reject_reason()->AddSample(r);
416 delete scd;
417 return NULL;
418}
419
420} // namespace internal
421} // namespace v8