code-serializer.cc 28.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 8
#include <memory>

9 10
#include "src/base/logging.h"
#include "src/base/platform/elapsed-timer.h"
11
#include "src/base/platform/platform.h"
12
#include "src/codegen/macro-assembler.h"
13
#include "src/common/globals.h"
Marja Hölttä's avatar
Marja Hölttä committed
14
#include "src/debug/debug.h"
15
#include "src/handles/maybe-handles.h"
16
#include "src/handles/persistent-handles.h"
17
#include "src/heap/heap-inl.h"
18
#include "src/heap/local-factory-inl.h"
19
#include "src/heap/parked-scope.h"
20
#include "src/logging/counters-scopes.h"
21
#include "src/logging/log.h"
22
#include "src/logging/runtime-call-stats-scope.h"
23
#include "src/objects/objects-inl.h"
24
#include "src/objects/shared-function-info.h"
25
#include "src/objects/slots.h"
26
#include "src/objects/visitors.h"
27
#include "src/snapshot/object-deserializer.h"
28
#include "src/snapshot/snapshot-utils.h"
29
#include "src/snapshot/snapshot.h"
30
#include "src/utils/version.h"
31 32 33 34

namespace v8 {
namespace internal {

35
AlignedCachedData::AlignedCachedData(const byte* data, int length)
36 37 38 39 40 41 42 43 44 45
    : 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();
  }
}

46
CodeSerializer::CodeSerializer(Isolate* isolate, uint32_t source_hash)
47
    : Serializer(isolate, Snapshot::kDefaultSerializerFlags),
48
      source_hash_(source_hash) {}
49

50 51
// static
ScriptCompiler::CachedData* CodeSerializer::Serialize(
52
    Handle<SharedFunctionInfo> info) {
53 54
  Isolate* isolate = info->GetIsolate();
  TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.Execute");
55 56
  NestedTimedHistogramScope histogram_timer(
      isolate->counters()->compile_serialize());
57
  RCS_SCOPE(isolate, RuntimeCallCounterId::kCompileSerialize);
58 59
  TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("v8.compile"), "V8.CompileSerialize");

60 61
  base::ElapsedTimer timer;
  if (FLAG_profile_deserialization) timer.Start();
62
  Handle<Script> script(Script::cast(info->script()), isolate);
63 64
  if (FLAG_trace_serializer) {
    PrintF("[Serializing from");
65
    script->name().ShortPrint();
66 67
    PrintF("]\n");
  }
68
#if V8_ENABLE_WEBASSEMBLY
69 70 71
  // TODO(7110): Enable serialization of Asm modules once the AsmWasmData is
  // context independent.
  if (script->ContainsAsmModule()) return nullptr;
72
#endif  // V8_ENABLE_WEBASSEMBLY
73 74

  // Serialize code object.
75
  Handle<String> source(String::cast(script->source()), isolate);
76
  HandleScope scope(isolate);
77 78
  CodeSerializer cs(isolate, SerializedCodeData::SourceHash(
                                 source, script->origin_options()));
79
  DisallowGarbageCollection no_gc;
80
  cs.reference_map()->AddAttachedReference(*source);
81
  AlignedCachedData* cached_data = cs.SerializeSharedFunctionInfo(info);
82 83 84

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

89
  ScriptCompiler::CachedData* result =
90
      new ScriptCompiler::CachedData(cached_data->data(), cached_data->length(),
91
                                     ScriptCompiler::CachedData::BufferOwned);
92 93
  cached_data->ReleaseDataOwnership();
  delete cached_data;
94 95

  return result;
96 97
}

98
AlignedCachedData* CodeSerializer::SerializeSharedFunctionInfo(
99
    Handle<SharedFunctionInfo> info) {
100
  DisallowGarbageCollection no_gc;
101

102 103
  VisitRootPointer(Root::kHandleScope, nullptr,
                   FullObjectSlot(info.location()));
104 105 106
  SerializeDeferredObjects();
  Pad();

107
  SerializedCodeData data(sink_.data(), this);
108 109

  return data.GetScriptData();
110 111
}

112 113 114
bool CodeSerializer::SerializeReadOnlyObject(
    HeapObject obj, const DisallowGarbageCollection& no_gc) {
  if (!ReadOnlyHeap::Contains(obj)) return false;
115

116 117 118
  // For objects on the read-only heap, 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.
119
  Address address = obj.address();
120
  BasicMemoryChunk* chunk = BasicMemoryChunk::FromAddress(address);
121
  uint32_t chunk_index = 0;
122
  ReadOnlySpace* const read_only_space = isolate()->heap()->read_only_space();
123 124
  for (ReadOnlyPage* page : read_only_space->pages()) {
    if (chunk == page) break;
125 126
    ++chunk_index;
  }
127
  uint32_t chunk_offset = static_cast<uint32_t>(chunk->Offset(address));
128 129 130
  sink_.Put(kReadOnlyHeapRef, "ReadOnlyHeapRef");
  sink_.PutInt(chunk_index, "ReadOnlyHeapRefChunkIndex");
  sink_.PutInt(chunk_offset, "ReadOnlyHeapRefChunkOffset");
131 132 133
  return true;
}

134
void CodeSerializer::SerializeObjectImpl(Handle<HeapObject> obj) {
135
  ReadOnlyRoots roots(isolate());
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151
  InstanceType instance_type;
  {
    DisallowGarbageCollection no_gc;
    HeapObject raw = *obj;
    if (SerializeHotObject(raw)) return;
    if (SerializeRoot(raw)) return;
    if (SerializeBackReference(raw)) return;
    if (SerializeReadOnlyObject(raw, no_gc)) return;

    instance_type = raw.map().instance_type();
    CHECK(!InstanceTypeChecker::IsCode(instance_type));

    if (ElideObject(raw)) {
      AllowGarbageCollection allow_gc;
      return SerializeObject(roots.undefined_value_handle());
    }
152
  }
153

154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
  if (InstanceTypeChecker::IsScript(instance_type)) {
    Handle<FixedArray> host_options;
    Handle<Object> context_data;
    {
      DisallowGarbageCollection no_gc;
      Script script_obj = Script::cast(*obj);
      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())
      Object raw_context_data = script_obj.context_data();
      if (raw_context_data != roots.undefined_value() &&
          raw_context_data != roots.uninitialized_symbol()) {
        script_obj.set_context_data(roots.undefined_value());
      }
      context_data = handle(raw_context_data, isolate());
      // We don't want to serialize host options to avoid serializing
      // unnecessary object graph.
      host_options = handle(script_obj.host_defined_options(), isolate());
      script_obj.set_host_defined_options(roots.empty_fixed_array());
175
    }
176
    SerializeGeneric(obj);
177 178 179 180 181 182
    {
      DisallowGarbageCollection no_gc;
      Script script_obj = Script::cast(*obj);
      script_obj.set_host_defined_options(*host_options);
      script_obj.set_context_data(*context_data);
    }
183
    return;
184 185 186 187 188 189 190
  } else if (InstanceTypeChecker::IsSharedFunctionInfo(instance_type)) {
    Handle<DebugInfo> debug_info;
    bool restore_bytecode = false;
    {
      DisallowGarbageCollection no_gc;
      SharedFunctionInfo sfi = SharedFunctionInfo::cast(*obj);
      DCHECK(!sfi.IsApiFunction());
191
#if V8_ENABLE_WEBASSEMBLY
192 193 194
      // TODO(7110): Enable serializing of Asm modules once the AsmWasmData
      // is context independent.
      DCHECK(!sfi.HasAsmWasmData());
195
#endif  // V8_ENABLE_WEBASSEMBLY
196

197 198 199 200 201 202 203 204 205
      if (sfi.HasDebugInfo()) {
        // Clear debug info.
        DebugInfo raw_debug_info = sfi.GetDebugInfo();
        if (raw_debug_info.HasInstrumentedBytecodeArray()) {
          restore_bytecode = true;
          sfi.SetActiveBytecodeArray(raw_debug_info.OriginalBytecodeArray());
        }
        sfi.set_script_or_debug_info(raw_debug_info.script(), kReleaseStore);
        debug_info = handle(raw_debug_info, isolate());
206
      }
207
      DCHECK(!sfi.HasDebugInfo());
208
    }
209
    SerializeGeneric(obj);
210
    // Restore debug info
211
    if (!debug_info.is_null()) {
212 213 214 215 216
      DisallowGarbageCollection no_gc;
      SharedFunctionInfo sfi = SharedFunctionInfo::cast(*obj);
      sfi.set_script_or_debug_info(*debug_info, kReleaseStore);
      if (restore_bytecode) {
        sfi.SetActiveBytecodeArray(debug_info->DebugBytecodeArray());
217 218
      }
    }
219
    return;
220 221
  } else if (InstanceTypeChecker::IsUncompiledDataWithoutPreparseDataWithJob(
                 instance_type)) {
222 223 224 225 226 227 228
    Handle<UncompiledDataWithoutPreparseDataWithJob> data =
        Handle<UncompiledDataWithoutPreparseDataWithJob>::cast(obj);
    Address job = data->job();
    data->set_job(kNullAddress);
    SerializeGeneric(data);
    data->set_job(job);
    return;
229 230
  } else if (InstanceTypeChecker::IsUncompiledDataWithPreparseDataAndJob(
                 instance_type)) {
231 232 233 234 235 236 237 238 239
    Handle<UncompiledDataWithPreparseDataAndJob> data =
        Handle<UncompiledDataWithPreparseDataAndJob>::cast(obj);
    Address job = data->job();
    data->set_job(kNullAddress);
    SerializeGeneric(data);
    data->set_job(job);
    return;
  }

240 241 242 243 244
  // NOTE(mmarchini): If we try to serialize an InterpreterData our process
  // will crash since it stores a code object. Instead, we serialize the
  // bytecode array stored within the InterpreterData, which is the important
  // information. On deserialization we'll create our code objects again, if
  // --interpreted-frames-native-stack is on. See v8:9122 for more context
245
#ifndef V8_TARGET_ARCH_ARM
246
  if (V8_UNLIKELY(FLAG_interpreted_frames_native_stack) &&
247 248
      obj->IsInterpreterData()) {
    obj = handle(InterpreterData::cast(*obj).bytecode_array(), isolate());
249
  }
250
#endif  // V8_TARGET_ARCH_ARM
251

252
  // Past this point we should not see any (context-specific) maps anymore.
253
  CHECK(!InstanceTypeChecker::IsMap(instance_type));
254
  // There should be no references to the global object embedded.
255 256
  CHECK(!InstanceTypeChecker::IsJSGlobalProxy(instance_type) &&
        !InstanceTypeChecker::IsJSGlobalObject(instance_type));
257
  // Embedded FixedArrays that need rehashing must support rehashing.
258 259
  CHECK_IMPLIES(obj->NeedsRehashing(cage_base()),
                obj->CanBeRehashed(cage_base()));
260
  // We expect no instantiated function objects or contexts.
261 262
  CHECK(!InstanceTypeChecker::IsJSFunction(instance_type) &&
        !InstanceTypeChecker::IsContext(instance_type));
263

264
  SerializeGeneric(obj);
265 266
}

267
void CodeSerializer::SerializeGeneric(Handle<HeapObject> heap_object) {
268
  // Object has not yet been serialized.  Serialize it here.
269
  ObjectSerializer serializer(this, heap_object, &sink_);
270 271 272
  serializer.Serialize();
}

273 274
namespace {

275
#ifndef V8_TARGET_ARCH_ARM
276 277 278 279 280 281 282
// NOTE(mmarchini): when FLAG_interpreted_frames_native_stack is on, we want to
// create duplicates of InterpreterEntryTrampoline for the deserialized
// functions, otherwise we'll call the builtin IET for those functions (which
// is not what a user of this flag wants).
void CreateInterpreterDataForDeserializedCode(Isolate* isolate,
                                              Handle<SharedFunctionInfo> sfi,
                                              bool log_code_creation) {
283
  Handle<Script> script(Script::cast(sfi->script()), isolate);
284
  String name = ReadOnlyRoots(isolate).empty_string();
285
  if (script->name().IsString()) name = String::cast(script->name());
286 287
  Handle<String> name_handle(name, isolate);

288
  SharedFunctionInfo::ScriptIterator iter(isolate, *script);
289 290
  for (SharedFunctionInfo shared_info = iter.Next(); !shared_info.is_null();
       shared_info = iter.Next()) {
291 292 293
    IsCompiledScope is_compiled(shared_info, isolate);
    if (!is_compiled.is_compiled()) continue;
    DCHECK(shared_info.HasBytecodeArray());
294
    Handle<SharedFunctionInfo> info = handle(shared_info, isolate);
295 296 297 298 299 300 301
    Handle<Code> code = isolate->factory()->CopyCode(Handle<Code>::cast(
        isolate->factory()->interpreter_entry_trampoline_for_profiling()));

    Handle<InterpreterData> interpreter_data =
        Handle<InterpreterData>::cast(isolate->factory()->NewStruct(
            INTERPRETER_DATA_TYPE, AllocationType::kOld));

302
    interpreter_data->set_bytecode_array(info->GetBytecodeArray(isolate));
303
    interpreter_data->set_interpreter_trampoline(ToCodeT(*code));
304 305 306 307 308 309
    if (info->HasBaselineCode()) {
      FromCodeT(info->baseline_code(kAcquireLoad))
          .set_bytecode_or_interpreter_data(*interpreter_data);
    } else {
      info->set_interpreter_data(*interpreter_data);
    }
310 311 312

    if (!log_code_creation) continue;
    Handle<AbstractCode> abstract_code = Handle<AbstractCode>::cast(code);
313 314
    int line_num = script->GetLineNumber(info->StartPosition()) + 1;
    int column_num = script->GetColumnNumber(info->StartPosition()) + 1;
315
    PROFILE(isolate,
316 317
            CodeCreateEvent(LogEventListener::FUNCTION_TAG, abstract_code, info,
                            name_handle, line_num, column_num));
318 319
  }
}
320
#endif  // V8_TARGET_ARCH_ARM
321

322 323
class StressOffThreadDeserializeThread final : public base::Thread {
 public:
324
  explicit StressOffThreadDeserializeThread(Isolate* isolate,
325
                                            AlignedCachedData* cached_data)
326 327
      : Thread(
            base::Thread::Options("StressOffThreadDeserializeThread", 2 * MB)),
328
        isolate_(isolate),
329
        cached_data_(cached_data) {}
330 331

  void Run() final {
332
    LocalIsolate local_isolate(isolate_, ThreadKind::kBackground);
333 334
    UnparkedScope unparked_scope(&local_isolate);
    LocalHandleScope handle_scope(&local_isolate);
335 336
    off_thread_data_ =
        CodeSerializer::StartDeserializeOffThread(&local_isolate, cached_data_);
337 338
  }

339 340 341
  MaybeHandle<SharedFunctionInfo> Finalize(Isolate* isolate,
                                           Handle<String> source,
                                           ScriptOriginOptions origin_options) {
342 343
    return CodeSerializer::FinishOffThreadDeserialize(
        isolate, std::move(off_thread_data_), cached_data_, source,
344
        origin_options);
345 346 347
  }

 private:
348
  Isolate* isolate_;
349 350
  AlignedCachedData* cached_data_;
  CodeSerializer::OffThreadDeserializeData off_thread_data_;
351
};
352

353 354 355
void FinalizeDeserialization(Isolate* isolate,
                             Handle<SharedFunctionInfo> result,
                             const base::ElapsedTimer& timer) {
356
  const bool log_code_creation =
357
      isolate->v8_file_logger()->is_listening_to_code_events() ||
358
      isolate->is_profiling() ||
359
      isolate->log_event_dispatcher()->is_listening_to_code_events();
360

361
#ifndef V8_TARGET_ARCH_ARM
362 363 364
  if (V8_UNLIKELY(FLAG_interpreted_frames_native_stack))
    CreateInterpreterDataForDeserializedCode(isolate, result,
                                             log_code_creation);
365
#endif  // V8_TARGET_ARCH_ARM
366

367 368
  bool needs_source_positions = isolate->NeedsSourcePositionsForProfiling();

369
  if (log_code_creation || FLAG_log_function_events) {
370 371 372 373 374 375
    Handle<Script> script(Script::cast(result->script()), isolate);
    Handle<String> name(script->name().IsString()
                            ? String::cast(script->name())
                            : ReadOnlyRoots(isolate).empty_string(),
                        isolate);

376
    if (FLAG_log_function_events) {
377 378 379 380
      LOG(isolate,
          FunctionEvent("deserialize", script->id(),
                        timer.Elapsed().InMillisecondsF(),
                        result->StartPosition(), result->EndPosition(), *name));
381 382
    }
    if (log_code_creation) {
383
      Script::InitLineEnds(isolate, script);
384 385

      SharedFunctionInfo::ScriptIterator iter(isolate, *script);
386
      for (SharedFunctionInfo info = iter.Next(); !info.is_null();
387
           info = iter.Next()) {
388
        if (info.is_compiled()) {
389 390 391 392 393
          Handle<SharedFunctionInfo> shared_info(info, isolate);
          if (needs_source_positions) {
            SharedFunctionInfo::EnsureSourcePositionsAvailable(isolate,
                                                               shared_info);
          }
394
          DisallowGarbageCollection no_gc;
395 396 397 398
          int line_num =
              script->GetLineNumber(shared_info->StartPosition()) + 1;
          int column_num =
              script->GetColumnNumber(shared_info->StartPosition()) + 1;
399 400 401
          PROFILE(
              isolate,
              CodeCreateEvent(
402 403
                  shared_info->is_toplevel() ? LogEventListener::SCRIPT_TAG
                                             : LogEventListener::FUNCTION_TAG,
404 405
                  handle(shared_info->abstract_code(isolate), isolate),
                  shared_info, name, line_num, column_num));
406 407
        }
      }
408 409
    }
  }
410

411
  if (needs_source_positions) {
412
    Handle<Script> script(Script::cast(result->script()), isolate);
413
    Script::InitLineEnds(isolate, script);
414
  }
415 416 417 418 419 420
}

}  // namespace

MaybeHandle<SharedFunctionInfo> CodeSerializer::Deserialize(
    Isolate* isolate, AlignedCachedData* cached_data, Handle<String> source,
421
    ScriptOriginOptions origin_options) {
422 423 424 425
  if (FLAG_stress_background_compile) {
    StressOffThreadDeserializeThread thread(isolate, cached_data);
    CHECK(thread.Start());
    thread.Join();
426 427
    return thread.Finalize(isolate, source, origin_options);
    // TODO(leszeks): Compare off-thread deserialized data to on-thread.
428 429 430 431 432 433 434
  }

  base::ElapsedTimer timer;
  if (FLAG_profile_deserialization || FLAG_log_function_events) timer.Start();

  HandleScope scope(isolate);

435 436
  SerializedCodeSanityCheckResult sanity_check_result =
      SerializedCodeSanityCheckResult::kSuccess;
437
  const SerializedCodeData scd = SerializedCodeData::FromCachedData(
438
      cached_data, SerializedCodeData::SourceHash(source, origin_options),
439
      &sanity_check_result);
440
  if (sanity_check_result != SerializedCodeSanityCheckResult::kSuccess) {
441 442 443
    if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
    DCHECK(cached_data->rejected());
    isolate->counters()->code_cache_reject_reason()->AddSample(
444
        static_cast<int>(sanity_check_result));
445 446 447 448 449 450 451 452 453 454 455 456 457
    return MaybeHandle<SharedFunctionInfo>();
  }

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

  Handle<SharedFunctionInfo> result;
  if (!maybe_result.ToHandle(&result)) {
    // Deserializing may fail if the reservations cannot be fulfilled.
    if (FLAG_profile_deserialization) PrintF("[Deserializing failed]\n");
    return MaybeHandle<SharedFunctionInfo>();
  }
458

459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477
  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);
  }

  FinalizeDeserialization(isolate, result, timer);

  return scope.CloseAndEscape(result);
}

CodeSerializer::OffThreadDeserializeData
CodeSerializer::StartDeserializeOffThread(LocalIsolate* local_isolate,
                                          AlignedCachedData* cached_data) {
  OffThreadDeserializeData result;

  DCHECK(!local_isolate->heap()->HasPersistentHandles());

  const SerializedCodeData scd =
478 479 480
      SerializedCodeData::FromCachedDataWithoutSource(
          cached_data, &result.sanity_check_result);
  if (result.sanity_check_result != SerializedCodeSanityCheckResult::kSuccess) {
481 482 483 484 485 486 487 488 489
    // Exit early but don't report yet, we'll re-check this when finishing on
    // the main thread
    DCHECK(cached_data->rejected());
    return result;
  }

  MaybeHandle<SharedFunctionInfo> local_maybe_result =
      OffThreadObjectDeserializer::DeserializeSharedFunctionInfo(
          local_isolate, &scd, &result.scripts);
490

491 492 493 494 495 496 497 498 499 500
  result.maybe_result =
      local_isolate->heap()->NewPersistentMaybeHandle(local_maybe_result);
  result.persistent_handles = local_isolate->heap()->DetachPersistentHandles();

  return result;
}

MaybeHandle<SharedFunctionInfo> CodeSerializer::FinishOffThreadDeserialize(
    Isolate* isolate, OffThreadDeserializeData&& data,
    AlignedCachedData* cached_data, Handle<String> source,
501
    ScriptOriginOptions origin_options) {
502 503 504 505 506
  base::ElapsedTimer timer;
  if (FLAG_profile_deserialization || FLAG_log_function_events) timer.Start();

  HandleScope scope(isolate);

507 508 509 510 511 512 513 514 515 516
  // Do a source sanity check now that we have the source. It's important for
  // FromPartiallySanityCheckedCachedData call that the sanity_check_result
  // holds the result of the off-thread sanity check.
  SerializedCodeSanityCheckResult sanity_check_result =
      data.sanity_check_result;
  const SerializedCodeData scd =
      SerializedCodeData::FromPartiallySanityCheckedCachedData(
          cached_data, SerializedCodeData::SourceHash(source, origin_options),
          &sanity_check_result);
  if (sanity_check_result != SerializedCodeSanityCheckResult::kSuccess) {
517 518 519 520
    // The only case where the deserialization result could exist despite a
    // check failure is on a source mismatch, since we can't test for this
    // off-thread.
    DCHECK_IMPLIES(!data.maybe_result.is_null(),
521 522 523 524 525 526 527
                   sanity_check_result ==
                       SerializedCodeSanityCheckResult::kSourceMismatch);
    // The only kind of sanity check we can't test for off-thread is a source
    // mismatch.
    DCHECK_IMPLIES(sanity_check_result != data.sanity_check_result,
                   sanity_check_result ==
                       SerializedCodeSanityCheckResult::kSourceMismatch);
528 529 530
    if (FLAG_profile_deserialization) PrintF("[Cached code failed check]\n");
    DCHECK(cached_data->rejected());
    isolate->counters()->code_cache_reject_reason()->AddSample(
531
        static_cast<int>(sanity_check_result));
532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
    return MaybeHandle<SharedFunctionInfo>();
  }

  Handle<SharedFunctionInfo> result;
  if (!data.maybe_result.ToHandle(&result)) {
    // Deserializing may fail if the reservations cannot be fulfilled.
    if (FLAG_profile_deserialization) {
      PrintF("[Off-thread deserializing failed]\n");
    }
    return MaybeHandle<SharedFunctionInfo>();
  }

  // Change the result persistent handle into a regular handle.
  DCHECK(data.persistent_handles->Contains(result.location()));
  result = handle(*result, isolate);

  // Fix up the source on the script. This should be the only deserialized
  // script, and the off-thread deserializer should have set its source to
  // the empty string.
  DCHECK_EQ(data.scripts.size(), 1);
  DCHECK_EQ(result->script(), *data.scripts[0]);
  DCHECK_EQ(Script::cast(result->script()).source(),
            ReadOnlyRoots(isolate).empty_string());
  Script::cast(result->script()).set_source(*source);

  // Fix up the script list to include the newly deserialized script.
  Handle<WeakArrayList> list = isolate->factory()->script_list();
  for (Handle<Script> script : data.scripts) {
    DCHECK(data.persistent_handles->Contains(script.location()));
    list =
        WeakArrayList::AddToEnd(isolate, list, MaybeObjectHandle::Weak(script));
  }
  isolate->heap()->SetRootScriptList(*list);

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

  FinalizeDeserialization(isolate, result, timer);

575 576 577
  return scope.CloseAndEscape(result);
}

578
SerializedCodeData::SerializedCodeData(const std::vector<byte>* payload,
579
                                       const CodeSerializer* cs) {
580
  DisallowGarbageCollection no_gc;
581 582

  // Calculate sizes.
583
  uint32_t size = kHeaderSize + static_cast<uint32_t>(payload->size());
584
  DCHECK(IsAligned(size, kPointerAlignment));
585 586 587 588

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

589
  // Zero out pre-payload data. Part of that is only used for padding.
590
  memset(data_, 0, kHeaderSize);
591

592
  // Set header values.
593
  SetMagicNumber();
594
  SetHeaderValue(kVersionHashOffset, Version::Hash());
595
  SetHeaderValue(kSourceHashOffset, cs->source_hash());
596
  SetHeaderValue(kFlagHashOffset, FlagList::Hash());
597
  SetHeaderValue(kPayloadLengthOffset, static_cast<uint32_t>(payload->size()));
598

599 600 601
  // Zero out any padding in the header.
  memset(data_ + kUnalignedHeaderSize, 0, kHeaderSize - kUnalignedHeaderSize);

602
  // Copy serialized data.
603
  CopyBytes(data_ + kHeaderSize, payload->data(),
604
            static_cast<size_t>(payload->size()));
605 606 607
  uint32_t checksum =
      FLAG_verify_snapshot_checksum ? Checksum(ChecksummedContent()) : 0;
  SetHeaderValue(kChecksumOffset, checksum);
608 609
}

610 611 612 613 614 615 616 617
SerializedCodeSanityCheckResult SerializedCodeData::SanityCheck(
    uint32_t expected_source_hash) const {
  SerializedCodeSanityCheckResult result = SanityCheckWithoutSource();
  if (result != SerializedCodeSanityCheckResult::kSuccess) return result;
  return SanityCheckJustSource(expected_source_hash);
}

SerializedCodeSanityCheckResult SerializedCodeData::SanityCheckJustSource(
618
    uint32_t expected_source_hash) const {
619
  uint32_t source_hash = GetHeaderValue(kSourceHashOffset);
620 621 622 623
  if (source_hash != expected_source_hash) {
    return SerializedCodeSanityCheckResult::kSourceMismatch;
  }
  return SerializedCodeSanityCheckResult::kSuccess;
624 625
}

626 627 628 629 630
SerializedCodeSanityCheckResult SerializedCodeData::SanityCheckWithoutSource()
    const {
  if (this->size_ < kHeaderSize) {
    return SerializedCodeSanityCheckResult::kInvalidHeader;
  }
631
  uint32_t magic_number = GetMagicNumber();
632 633 634
  if (magic_number != kMagicNumber) {
    return SerializedCodeSanityCheckResult::kMagicNumberMismatch;
  }
635
  uint32_t version_hash = GetHeaderValue(kVersionHashOffset);
636 637 638
  if (version_hash != Version::Hash()) {
    return SerializedCodeSanityCheckResult::kVersionMismatch;
  }
639
  uint32_t flags_hash = GetHeaderValue(kFlagHashOffset);
640 641 642
  if (flags_hash != FlagList::Hash()) {
    return SerializedCodeSanityCheckResult::kFlagsMismatch;
  }
643
  uint32_t payload_length = GetHeaderValue(kPayloadLengthOffset);
644
  uint32_t max_payload_length = this->size_ - kHeaderSize;
645 646 647
  if (payload_length > max_payload_length) {
    return SerializedCodeSanityCheckResult::kLengthMismatch;
  }
648 649 650 651 652
  if (FLAG_verify_snapshot_checksum) {
    uint32_t checksum = GetHeaderValue(kChecksumOffset);
    if (Checksum(ChecksummedContent()) != checksum) {
      return SerializedCodeSanityCheckResult::kChecksumMismatch;
    }
653 654
  }
  return SerializedCodeSanityCheckResult::kSuccess;
655 656
}

657
uint32_t SerializedCodeData::SourceHash(Handle<String> source,
658
                                        ScriptOriginOptions origin_options) {
659 660 661
  const uint32_t source_length = source->length();

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

  return source_length | is_module;
666 667 668
}

// Return ScriptData object and relinquish ownership over it to the caller.
669
AlignedCachedData* SerializedCodeData::GetScriptData() {
670
  DCHECK(owns_data_);
671
  AlignedCachedData* result = new AlignedCachedData(data_, size_);
672 673
  result->AcquireDataOwnership();
  owns_data_ = false;
674
  data_ = nullptr;
675 676 677
  return result;
}

678
base::Vector<const byte> SerializedCodeData::Payload() const {
679
  const byte* payload = data_ + kHeaderSize;
680 681 682
  DCHECK(IsAligned(reinterpret_cast<intptr_t>(payload), kPointerAlignment));
  int length = GetHeaderValue(kPayloadLengthOffset);
  DCHECK_EQ(data_ + size_, payload + length);
683
  return base::Vector<const byte>(payload, length);
684 685
}

686
SerializedCodeData::SerializedCodeData(AlignedCachedData* data)
687 688
    : SerializedData(const_cast<byte*>(data->data()), data->length()) {}

689
SerializedCodeData SerializedCodeData::FromCachedData(
690
    AlignedCachedData* cached_data, uint32_t expected_source_hash,
691
    SerializedCodeSanityCheckResult* rejection_result) {
692
  DisallowGarbageCollection no_gc;
693
  SerializedCodeData scd(cached_data);
694
  *rejection_result = scd.SanityCheck(expected_source_hash);
695
  if (*rejection_result != SerializedCodeSanityCheckResult::kSuccess) {
696 697 698 699
    cached_data->Reject();
    return SerializedCodeData(nullptr, 0);
  }
  return scd;
700 701
}

702
SerializedCodeData SerializedCodeData::FromCachedDataWithoutSource(
703 704
    AlignedCachedData* cached_data,
    SerializedCodeSanityCheckResult* rejection_result) {
705 706 707
  DisallowGarbageCollection no_gc;
  SerializedCodeData scd(cached_data);
  *rejection_result = scd.SanityCheckWithoutSource();
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736
  if (*rejection_result != SerializedCodeSanityCheckResult::kSuccess) {
    cached_data->Reject();
    return SerializedCodeData(nullptr, 0);
  }
  return scd;
}

SerializedCodeData SerializedCodeData::FromPartiallySanityCheckedCachedData(
    AlignedCachedData* cached_data, uint32_t expected_source_hash,
    SerializedCodeSanityCheckResult* rejection_result) {
  DisallowGarbageCollection no_gc;
  // The previous call to FromCachedDataWithoutSource may have already rejected
  // the cached data, so re-use the previous rejection result if it's not a
  // success.
  if (*rejection_result != SerializedCodeSanityCheckResult::kSuccess) {
    // FromCachedDataWithoutSource doesn't check the source, so there can't be
    // a source mismatch.
    DCHECK_NE(*rejection_result,
              SerializedCodeSanityCheckResult::kSourceMismatch);
    cached_data->Reject();
    return SerializedCodeData(nullptr, 0);
  }
  SerializedCodeData scd(cached_data);
  *rejection_result = scd.SanityCheckJustSource(expected_source_hash);
  if (*rejection_result != SerializedCodeSanityCheckResult::kSuccess) {
    // This check only checks the source, so the only possible failure is a
    // source mismatch.
    DCHECK_EQ(*rejection_result,
              SerializedCodeSanityCheckResult::kSourceMismatch);
737 738 739 740 741 742
    cached_data->Reject();
    return SerializedCodeData(nullptr, 0);
  }
  return scd;
}

743 744
}  // namespace internal
}  // namespace v8