code-serializer.cc 15.7 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "src/snapshot/code-serializer.h"

7
#include "src/counters.h"
Marja Hölttä's avatar
Marja Hölttä committed
8
#include "src/debug/debug.h"
9
#include "src/heap/heap-inl.h"
10 11
#include "src/log.h"
#include "src/macro-assembler.h"
12
#include "src/objects-inl.h"
13
#include "src/objects/slots.h"
14
#include "src/snapshot/object-deserializer.h"
15
#include "src/snapshot/snapshot.h"
16
#include "src/version.h"
17
#include "src/visitors.h"
18 19 20 21

namespace v8 {
namespace internal {

22 23 24 25 26 27 28 29 30 31 32
ScriptData::ScriptData(const byte* data, int length)
    : owns_data_(false), rejected_(false), data_(data), length_(length) {
  if (!IsAligned(reinterpret_cast<intptr_t>(data), kPointerAlignment)) {
    byte* copy = NewArray<byte>(length);
    DCHECK(IsAligned(reinterpret_cast<intptr_t>(copy), kPointerAlignment));
    CopyBytes(copy, data, length);
    data_ = copy;
    AcquireDataOwnership();
  }
}

33 34 35 36 37
CodeSerializer::CodeSerializer(Isolate* isolate, uint32_t source_hash)
    : Serializer(isolate), source_hash_(source_hash) {
  allocator()->UseCustomChunkSize(FLAG_serialization_chunk_size);
}

38 39
// static
ScriptCompiler::CachedData* CodeSerializer::Serialize(
40
    Handle<SharedFunctionInfo> info) {
41 42 43 44 45 46 47
  Isolate* isolate = info->GetIsolate();
  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
  HistogramTimerScope histogram_timer(isolate->counters()->compile_serialize());
  RuntimeCallTimerScope runtimeTimer(isolate,
                                     RuntimeCallCounterId::kCompileSerialize);
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileSerialize");

48 49
  base::ElapsedTimer timer;
  if (FLAG_profile_deserialization) timer.Start();
50
  Handle<Script> script(Script::cast(info->script()), isolate);
51 52
  if (FLAG_trace_serializer) {
    PrintF("[Serializing from");
53
    script->name()->ShortPrint();
54 55
    PrintF("]\n");
  }
56 57 58
  // TODO(7110): Enable serialization of Asm modules once the AsmWasmData is
  // context independent.
  if (script->ContainsAsmModule()) return nullptr;
59

60 61
  isolate->heap()->read_only_space()->ClearStringPaddingIfNeeded();

62
  // Serialize code object.
63
  Handle<String> source(String::cast(script->source()), isolate);
64 65
  CodeSerializer cs(isolate, SerializedCodeData::SourceHash(
                                 source, script->origin_options()));
66
  DisallowHeapAllocation no_gc;
67 68
  cs.reference_map()->AddAttachedReference(
      reinterpret_cast<void*>(source->ptr()));
69
  ScriptData* script_data = cs.SerializeSharedFunctionInfo(info);
70 71 72

  if (FLAG_profile_deserialization) {
    double ms = timer.Elapsed().InMillisecondsF();
73
    int length = script_data->length();
74 75 76
    PrintF("[Serializing to %d bytes took %0.3f ms]\n", length, ms);
  }

77 78 79 80 81 82 83
  ScriptCompiler::CachedData* result =
      new ScriptCompiler::CachedData(script_data->data(), script_data->length(),
                                     ScriptCompiler::CachedData::BufferOwned);
  script_data->ReleaseDataOwnership();
  delete script_data;

  return result;
84 85
}

86 87
ScriptData* CodeSerializer::SerializeSharedFunctionInfo(
    Handle<SharedFunctionInfo> info) {
88 89
  DisallowHeapAllocation no_gc;

90 91
  VisitRootPointer(Root::kHandleScope, nullptr,
                   FullObjectSlot(info.location()));
92 93 94
  SerializeDeferredObjects();
  Pad();

95
  SerializedCodeData data(sink_.data(), this);
96 97

  return data.GetScriptData();
98 99
}

100
bool CodeSerializer::SerializeReadOnlyObject(HeapObject obj) {
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116
  PagedSpace* read_only_space = isolate()->heap()->read_only_space();
  if (!read_only_space->Contains(obj)) return false;

  // For objects in RO_SPACE, never serialize the object, but instead create a
  // back reference that encodes the page number as the chunk_index and the
  // offset within the page as the chunk_offset.
  Address address = obj->address();
  Page* page = Page::FromAddress(address);
  uint32_t chunk_index = 0;
  for (Page* p : *read_only_space) {
    if (p == page) break;
    ++chunk_index;
  }
  uint32_t chunk_offset = static_cast<uint32_t>(page->Offset(address));
  SerializerReference back_reference =
      SerializerReference::BackReference(RO_SPACE, chunk_index, chunk_offset);
117
  reference_map()->Add(reinterpret_cast<void*>(obj->ptr()), back_reference);
118
  CHECK(SerializeBackReference(obj));
119 120 121
  return true;
}

122 123
void CodeSerializer::SerializeObject(HeapObject obj) {
  if (SerializeHotObject(obj)) return;
124

125
  if (SerializeRoot(obj)) return;
126

127
  if (SerializeBackReference(obj)) return;
128

129
  if (SerializeReadOnlyObject(obj)) return;
130

131
  CHECK(!obj->IsCode());
132

133
  ReadOnlyRoots roots(isolate());
134
  if (ElideObject(obj)) {
135
    return SerializeObject(roots.undefined_value());
136
  }
137 138

  if (obj->IsScript()) {
139
    Script script_obj = Script::cast(obj);
140 141 142 143
    DCHECK_NE(script_obj->compilation_type(), Script::COMPILATION_TYPE_EVAL);
    // We want to differentiate between undefined and uninitialized_symbol for
    // context_data for now. It is hack to allow debugging for scripts that are
    // included as a part of custom snapshot. (see debug::Script::IsEmbedded())
144
    Object context_data = script_obj->context_data();
145 146 147
    if (context_data != roots.undefined_value() &&
        context_data != roots.uninitialized_symbol()) {
      script_obj->set_context_data(roots.undefined_value());
148 149 150
    }
    // We don't want to serialize host options to avoid serializing unnecessary
    // object graph.
151
    FixedArray host_options = script_obj->host_defined_options();
152
    script_obj->set_host_defined_options(roots.empty_fixed_array());
153
    SerializeGeneric(obj);
154 155 156
    script_obj->set_host_defined_options(host_options);
    script_obj->set_context_data(context_data);
    return;
157 158
  }

159
  if (obj->IsSharedFunctionInfo()) {
160
    SharedFunctionInfo sfi = SharedFunctionInfo::cast(obj);
161 162 163
    // TODO(7110): Enable serializing of Asm modules once the AsmWasmData
    // is context independent.
    DCHECK(!sfi->IsApiFunction() && !sfi->HasAsmWasmData());
164

165
    DebugInfo debug_info;
166
    BytecodeArray debug_bytecode_array;
167 168 169 170 171 172 173
    if (sfi->HasDebugInfo()) {
      // Clear debug info.
      debug_info = sfi->GetDebugInfo();
      if (debug_info->HasInstrumentedBytecodeArray()) {
        debug_bytecode_array = debug_info->DebugBytecodeArray();
        sfi->SetDebugBytecodeArray(debug_info->OriginalBytecodeArray());
      }
174
      sfi->set_script_or_debug_info(debug_info->script());
175 176
    }
    DCHECK(!sfi->HasDebugInfo());
177

178
    SerializeGeneric(obj);
179 180

    // Restore debug info
181
    if (!debug_info.is_null()) {
182
      sfi->set_script_or_debug_info(debug_info);
183
      if (!debug_bytecode_array.is_null()) {
184 185 186
        sfi->SetDebugBytecodeArray(debug_bytecode_array);
      }
    }
187 188 189
    return;
  }

190 191 192 193 194
  if (obj->IsBytecodeArray()) {
    // Clear the stack frame cache if present
    BytecodeArray::cast(obj)->ClearFrameCacheFromSourcePositionTable();
  }

195 196 197 198
  // Past this point we should not see any (context-specific) maps anymore.
  CHECK(!obj->IsMap());
  // There should be no references to the global object embedded.
  CHECK(!obj->IsJSGlobalProxy() && !obj->IsJSGlobalObject());
199 200
  // Embedded FixedArrays that need rehashing must support rehashing.
  CHECK_IMPLIES(obj->NeedsRehashing(), obj->CanBeRehashed());
201 202 203
  // We expect no instantiated function objects or contexts.
  CHECK(!obj->IsJSFunction() && !obj->IsContext());

204
  SerializeGeneric(obj);
205 206
}

207
void CodeSerializer::SerializeGeneric(HeapObject heap_object) {
208
  // Object has not yet been serialized.  Serialize it here.
209
  ObjectSerializer serializer(this, heap_object, &sink_);
210 211 212 213
  serializer.Serialize();
}

MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
214 215
    Isolate* isolate, ScriptData* cached_data, Handle<String> source,
    ScriptOriginOptions origin_options) {
216
  base::ElapsedTimer timer;
217
  if (FLAG_profile_deserialization || FLAG_log_function_events) timer.Start();
218 219 220

  HandleScope scope(isolate);

221 222 223
  SerializedCodeData::SanityCheckResult sanity_check_result =
      SerializedCodeData::CHECK_SUCCESS;
  const SerializedCodeData scd = SerializedCodeData::FromCachedData(
224 225
      isolate, cached_data,
      SerializedCodeData::SourceHash(source, origin_options),
226 227
      &sanity_check_result);
  if (sanity_check_result != SerializedCodeData::CHECK_SUCCESS) {
228 229
    if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
    DCHECK(cached_data->rejected());
230
    isolate->counters()->code_cache_reject_reason()->AddSample(
231
        sanity_check_result);
232 233 234 235
    return MaybeHandle<SharedFunctionInfo>();
  }

  // Deserialize.
236 237 238 239 240
  MaybeHandle<SharedFunctionInfo> maybe_result =
      ObjectDeserializer::DeserializeSharedFunctionInfo(isolate, &scd, source);

  Handle<SharedFunctionInfo> result;
  if (!maybe_result.ToHandle(&result)) {
241 242 243 244 245 246 247 248 249 250 251
    // Deserializing may fail if the reservations cannot be fulfilled.
    if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
    return MaybeHandle<SharedFunctionInfo>();
  }

  if (FLAG_profile_deserialization) {
    double ms = timer.Elapsed().InMillisecondsF();
    int length = cached_data->length();
    PrintF("[Deserializing from %d bytes took %0.3f ms]\n", length, ms);
  }

252 253 254 255
  bool log_code_creation =
      isolate->logger()->is_listening_to_code_events() ||
      isolate->is_profiling() ||
      isolate->code_event_dispatcher()->IsListeningToCodeEvents();
256
  if (log_code_creation || FLAG_log_function_events) {
257
    String name = ReadOnlyRoots(isolate).empty_string();
258 259 260 261 262 263 264 265
    Script script = Script::cast(result->script());
    Handle<Script> script_handle(script, isolate);
    if (script->name()->IsString()) name = String::cast(script->name());
    if (FLAG_log_function_events) {
      LOG(isolate,
          FunctionEvent("deserialize", script->id(),
                        timer.Elapsed().InMillisecondsF(),
                        result->StartPosition(), result->EndPosition(), name));
266 267
    }
    if (log_code_creation) {
268 269 270 271 272 273 274 275 276 277 278 279 280
      Script::InitLineEnds(Handle<Script>(script, isolate));
      DisallowHeapAllocation no_gc;
      SharedFunctionInfo::ScriptIterator iter(isolate, script);
      for (i::SharedFunctionInfo info = iter.Next(); !info.is_null();
           info = iter.Next()) {
        if (info->is_compiled()) {
          int line_num = script->GetLineNumber(info->StartPosition()) + 1;
          int column_num = script->GetColumnNumber(info->StartPosition()) + 1;
          PROFILE(isolate, CodeCreateEvent(CodeEventListener::SCRIPT_TAG,
                                           info->abstract_code(), info, name,
                                           line_num, column_num));
        }
      }
281 282
    }
  }
283 284 285 286 287

  if (isolate->NeedsSourcePositionsForProfiling()) {
    Handle<Script> script(Script::cast(result->script()), isolate);
    Script::InitLineEnds(script);
  }
288 289 290 291
  return scope.CloseAndEscape(result);
}


292
SerializedCodeData::SerializedCodeData(const std::vector<byte>* payload,
293
                                       const CodeSerializer* cs) {
294
  DisallowHeapAllocation no_gc;
295
  std::vector<Reservation> reservations = cs->EncodeReservations();
296 297

  // Calculate sizes.
298 299
  uint32_t reservation_size =
      static_cast<uint32_t>(reservations.size()) * kUInt32Size;
300
  uint32_t num_stub_keys = 0;  // TODO(jgruber): Remove.
301 302 303 304 305
  uint32_t stub_keys_size = num_stub_keys * kUInt32Size;
  uint32_t payload_offset = kHeaderSize + reservation_size + stub_keys_size;
  uint32_t padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
  uint32_t size =
      padded_payload_offset + static_cast<uint32_t>(payload->size());
306
  DCHECK(IsAligned(size, kPointerAlignment));
307 308 309 310

  // Allocate backing store and create result data.
  AllocateData(size);

311 312 313
  // Zero out pre-payload data. Part of that is only used for padding.
  memset(data_, 0, padded_payload_offset);

314
  // Set header values.
315
  SetMagicNumber();
316
  SetHeaderValue(kVersionHashOffset, Version::Hash());
317
  SetHeaderValue(kSourceHashOffset, cs->source_hash());
318
  SetHeaderValue(kFlagHashOffset, FlagList::Hash());
319 320 321
  SetHeaderValue(kNumReservationsOffset,
                 static_cast<uint32_t>(reservations.size()));
  SetHeaderValue(kPayloadLengthOffset, static_cast<uint32_t>(payload->size()));
322

323 324 325
  // Zero out any padding in the header.
  memset(data_ + kUnalignedHeaderSize, 0, kHeaderSize - kUnalignedHeaderSize);

326
  // Copy reservation chunk sizes.
327 328
  CopyBytes(data_ + kHeaderSize,
            reinterpret_cast<const byte*>(reservations.data()),
329 330 331
            reservation_size);

  // Copy serialized data.
332 333
  CopyBytes(data_ + padded_payload_offset, payload->data(),
            static_cast<size_t>(payload->size()));
334

335 336 337
  Checksum checksum(ChecksummedContent());
  SetHeaderValue(kChecksumPartAOffset, checksum.a());
  SetHeaderValue(kChecksumPartBOffset, checksum.b());
338 339 340
}

SerializedCodeData::SanityCheckResult SerializedCodeData::SanityCheck(
341
    Isolate* isolate, uint32_t expected_source_hash) const {
342
  if (this->size_ < kHeaderSize) return INVALID_HEADER;
343
  uint32_t magic_number = GetMagicNumber();
344
  if (magic_number != kMagicNumber) return MAGIC_NUMBER_MISMATCH;
345 346 347
  uint32_t version_hash = GetHeaderValue(kVersionHashOffset);
  uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
  uint32_t flags_hash = GetHeaderValue(kFlagHashOffset);
348
  uint32_t payload_length = GetHeaderValue(kPayloadLengthOffset);
349 350
  uint32_t c1 = GetHeaderValue(kChecksumPartAOffset);
  uint32_t c2 = GetHeaderValue(kChecksumPartBOffset);
351
  if (version_hash != Version::Hash()) return VERSION_MISMATCH;
352
  if (source_hash != expected_source_hash) return SOURCE_MISMATCH;
353
  if (flags_hash != FlagList::Hash()) return FLAGS_MISMATCH;
354 355 356
  uint32_t max_payload_length =
      this->size_ -
      POINTER_SIZE_ALIGN(kHeaderSize +
357
                         GetHeaderValue(kNumReservationsOffset) * kInt32Size);
358
  if (payload_length > max_payload_length) return LENGTH_MISMATCH;
359
  if (!Checksum(ChecksummedContent()).Check(c1, c2)) return CHECKSUM_MISMATCH;
360 361 362
  return CHECK_SUCCESS;
}

363 364 365 366 367 368 369 370 371
uint32_t SerializedCodeData::SourceHash(Handle<String> source,
                                        ScriptOriginOptions origin_options) {
  const uint32_t source_length = source->length();

  static constexpr uint32_t kModuleFlagMask = (1 << 31);
  const uint32_t is_module = origin_options.IsModule() ? kModuleFlagMask : 0;
  DCHECK_EQ(0, source_length & kModuleFlagMask);

  return source_length | is_module;
372 373 374 375 376 377 378 379
}

// Return ScriptData object and relinquish ownership over it to the caller.
ScriptData* SerializedCodeData::GetScriptData() {
  DCHECK(owns_data_);
  ScriptData* result = new ScriptData(data_, size_);
  result->AcquireDataOwnership();
  owns_data_ = false;
380
  data_ = nullptr;
381 382 383
  return result;
}

384
std::vector<SerializedData::Reservation> SerializedCodeData::Reservations()
385
    const {
386 387 388 389 390
  uint32_t size = GetHeaderValue(kNumReservationsOffset);
  std::vector<Reservation> reservations(size);
  memcpy(reservations.data(), data_ + kHeaderSize,
         size * sizeof(SerializedData::Reservation));
  return reservations;
391 392 393 394
}

Vector<const byte> SerializedCodeData::Payload() const {
  int reservations_size = GetHeaderValue(kNumReservationsOffset) * kInt32Size;
395
  int payload_offset = kHeaderSize + reservations_size;
396 397 398 399 400 401 402 403 404 405 406
  int padded_payload_offset = POINTER_SIZE_ALIGN(payload_offset);
  const byte* payload = data_ + padded_payload_offset;
  DCHECK(IsAligned(reinterpret_cast<intptr_t>(payload), kPointerAlignment));
  int length = GetHeaderValue(kPayloadLengthOffset);
  DCHECK_EQ(data_ + size_, payload + length);
  return Vector<const byte>(payload, length);
}

SerializedCodeData::SerializedCodeData(ScriptData* data)
    : SerializedData(const_cast<byte*>(data->data()), data->length()) {}

407
SerializedCodeData SerializedCodeData::FromCachedData(
408 409
    Isolate* isolate, ScriptData* cached_data, uint32_t expected_source_hash,
    SanityCheckResult* rejection_result) {
410
  DisallowHeapAllocation no_gc;
411 412 413 414 415 416 417
  SerializedCodeData scd(cached_data);
  *rejection_result = scd.SanityCheck(isolate, expected_source_hash);
  if (*rejection_result != CHECK_SUCCESS) {
    cached_data->Reject();
    return SerializedCodeData(nullptr, 0);
  }
  return scd;
418 419 420 421
}

}  // namespace internal
}  // namespace v8