context-serializer.cc 11.8 KB
Newer Older
1 2 3 4
// 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.

5
#include "src/snapshot/context-serializer.h"
6
#include "src/snapshot/startup-serializer.h"
7

8
#include "src/api/api-inl.h"
9
#include "src/execution/microtask-queue.h"
10
#include "src/heap/combined-heap.h"
11
#include "src/numbers/math-random.h"
12
#include "src/objects/objects-inl.h"
13
#include "src/objects/slots.h"
14 15 16 17

namespace v8 {
namespace internal {

18 19 20 21 22
namespace {

// During serialization, puts the native context into a state understood by the
// serializer (e.g. by clearing lists of Code objects).  After serialization,
// the original state is restored.
23
class V8_NODISCARD SanitizeNativeContextScope final {
24 25 26
 public:
  SanitizeNativeContextScope(Isolate* isolate, NativeContext native_context,
                             bool allow_active_isolate_for_testing,
27
                             const DisallowGarbageCollection& no_gc)
28 29
      : isolate_(isolate),
        native_context_(native_context),
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
        microtask_queue_(native_context.microtask_queue()),
        optimized_code_list_(native_context.OptimizedCodeListHead()),
        deoptimized_code_list_(native_context.DeoptimizedCodeListHead()) {
#ifdef DEBUG
    if (!allow_active_isolate_for_testing) {
      // Microtasks.
      DCHECK_EQ(0, microtask_queue_->size());
      DCHECK(!microtask_queue_->HasMicrotasksSuppressions());
      DCHECK_EQ(0, microtask_queue_->GetMicrotasksScopeDepth());
      DCHECK(microtask_queue_->DebugMicrotasksScopeDepthIsZero());
      // Code lists.
      DCHECK(optimized_code_list_.IsUndefined(isolate));
      DCHECK(deoptimized_code_list_.IsUndefined(isolate));
    }
#endif
    Object undefined = ReadOnlyRoots(isolate).undefined_value();
46
    native_context.set_microtask_queue(isolate, nullptr);
47 48 49 50 51 52 53 54
    native_context.SetOptimizedCodeListHead(undefined);
    native_context.SetDeoptimizedCodeListHead(undefined);
  }

  ~SanitizeNativeContextScope() {
    // Restore saved fields.
    native_context_.SetDeoptimizedCodeListHead(optimized_code_list_);
    native_context_.SetOptimizedCodeListHead(deoptimized_code_list_);
55
    native_context_.set_microtask_queue(isolate_, microtask_queue_);
56 57 58
  }

 private:
59
  Isolate* isolate_;
60 61 62 63 64 65 66 67
  NativeContext native_context_;
  MicrotaskQueue* const microtask_queue_;
  const Object optimized_code_list_;
  const Object deoptimized_code_list_;
};

}  // namespace

68
ContextSerializer::ContextSerializer(
69 70
    Isolate* isolate, Snapshot::SerializerFlags flags,
    StartupSerializer* startup_serializer,
71
    v8::SerializeEmbedderFieldsCallback callback)
72
    : Serializer(isolate, flags),
73
      startup_serializer_(startup_serializer),
74
      serialize_embedder_fields_(callback),
75
      can_be_rehashed_(true) {
76 77 78
  InitializeCodeAddressMap();
}

79 80
ContextSerializer::~ContextSerializer() {
  OutputStatistics("ContextSerializer");
81 82
}

83
void ContextSerializer::Serialize(Context* o,
84
                                  const DisallowGarbageCollection& no_gc) {
85
  context_ = *o;
86
  DCHECK(context_.IsNativeContext());
87 88 89

  // Upon deserialization, references to the global proxy and its map will be
  // replaced.
90 91
  reference_map()->AddAttachedReference(context_.global_proxy());
  reference_map()->AddAttachedReference(context_.global_proxy().map());
92

93
  // The bootstrap snapshot has a code-stub context. When serializing the
94
  // context snapshot, it is chained into the weak context list on the isolate
95 96 97
  // and it's next context pointer may point to the code-stub context.  Clear
  // it before serializing, it will get re-added to the context list
  // explicitly when it's loaded.
98 99
  // TODO(v8:10416): These mutations should not observably affect the running
  // context.
100 101 102
  context_.set(Context::NEXT_CONTEXT_LINK,
               ReadOnlyRoots(isolate()).undefined_value());
  DCHECK(!context_.global_object().IsUndefined());
103
  // Reset math random cache to get fresh random numbers.
104
  MathRandom::ResetContext(context_);
105

106 107 108
  SanitizeNativeContextScope sanitize_native_context(
      isolate(), context_.native_context(), allow_active_isolate_for_testing(),
      no_gc);
109

110
  VisitRootPointer(Root::kStartupObjectCache, nullptr, FullObjectSlot(o));
111
  SerializeDeferredObjects();
112 113 114 115 116 117 118 119

  // Add section for embedder-serialized embedder fields.
  if (!embedder_fields_sink_.data()->empty()) {
    sink_.Put(kEmbedderFieldsData, "embedder fields data");
    sink_.Append(embedder_fields_sink_);
    sink_.Put(kSynchronize, "Finished with embedder fields data");
  }

120 121 122
  Pad();
}

123
void ContextSerializer::SerializeObjectImpl(Handle<HeapObject> obj) {
124 125
  DCHECK(!ObjectIsBytecodeHandler(obj));  // Only referenced in dispatch table.

126 127 128 129 130 131
  if (!allow_active_isolate_for_testing()) {
    // When serializing a snapshot intended for real use, we should not end up
    // at another native context.
    // But in test scenarios there is no way to avoid this. Since we only
    // serialize a single context in these cases, and this context does not
    // have to be executable, we can simply ignore this.
132
    DCHECK_IMPLIES(obj->IsNativeContext(), *obj == context_);
133 134
  }

135
  if (SerializeHotObject(obj)) return;
136

137
  if (SerializeRoot(obj)) return;
138

139
  if (SerializeBackReference(obj)) return;
140

141
  if (startup_serializer_->SerializeUsingReadOnlyObjectCache(&sink_, obj)) {
142 143
    return;
  }
144

145
  if (ShouldBeInTheStartupObjectCache(*obj)) {
146
    startup_serializer_->SerializeUsingStartupObjectCache(&sink_, obj);
147 148 149
    return;
  }

150 151
  // Pointers from the context snapshot to the objects in the startup snapshot
  // should go through the root array or through the startup object cache.
152
  // If this is not the case you may have to add something to the root array.
153
  DCHECK(!startup_serializer_->ReferenceMapContains(obj));
154 155
  // All the internalized strings that the context snapshot needs should be
  // either in the root table or in the startup object cache.
156
  DCHECK(!obj->IsInternalizedString());
157
  // Function and object templates are not context specific.
158
  DCHECK(!obj->IsTemplateInfo());
159

160
  // Clear literal boilerplates and feedback.
161 162 163
  if (obj->IsFeedbackVector()) {
    Handle<FeedbackVector>::cast(obj)->ClearSlots(isolate());
  }
164

165
  // Clear InterruptBudget when serializing FeedbackCell.
166 167
  if (obj->IsFeedbackCell()) {
    Handle<FeedbackCell>::cast(obj)->SetInitialInterruptBudget();
168 169
  }

170
  if (SerializeJSObjectWithEmbedderFields(obj)) {
171
    return;
172 173
  }

174
  if (obj->IsJSFunction()) {
175 176
    // Unconditionally reset the JSFunction to its SFI's code, since we can't
    // serialize optimized code anyway.
177 178
    Handle<JSFunction> closure = Handle<JSFunction>::cast(obj);
    closure->ResetIfBytecodeFlushed();
179
    if (closure->is_compiled()) {
180 181 182
      if (closure->shared().HasBaselineData()) {
        closure->shared().flush_baseline_data();
      }
183 184
      closure->set_code(closure->shared().GetCode(), kReleaseStore);
    }
185 186
  }

187
  CheckRehashability(*obj);
188

189
  // Object has not yet been serialized.  Serialize it here.
190
  ObjectSerializer serializer(this, obj, &sink_);
191 192 193
  serializer.Serialize();
}

194
bool ContextSerializer::ShouldBeInTheStartupObjectCache(HeapObject o) {
195
  // Scripts should be referred only through shared function infos.  We can't
196 197
  // allow them to be part of the context snapshot because they contain a
  // unique ID, and deserializing several context snapshots containing script
198
  // would cause dupes.
199 200 201 202
  DCHECK(!o.IsScript());
  return o.IsName() || o.IsSharedFunctionInfo() || o.IsHeapNumber() ||
         o.IsCode() || o.IsScopeInfo() || o.IsAccessorInfo() ||
         o.IsTemplateInfo() || o.IsClassPositions() ||
203
         o.map() == ReadOnlyRoots(isolate()).fixed_cow_array_map();
204 205
}

206 207 208 209
namespace {
bool DataIsEmpty(const StartupData& data) { return data.raw_size == 0; }
}  // anonymous namespace

210 211 212 213 214
bool ContextSerializer::SerializeJSObjectWithEmbedderFields(
    Handle<HeapObject> obj) {
  if (!obj->IsJSObject()) return false;
  Handle<JSObject> js_obj = Handle<JSObject>::cast(obj);
  int embedder_fields_count = js_obj->GetEmbedderFieldCount();
215 216
  if (embedder_fields_count == 0) return false;
  CHECK_GT(embedder_fields_count, 0);
217
  DCHECK(!js_obj->NeedsRehashing());
218

219
  DisallowGarbageCollection no_gc;
220 221
  DisallowJavascriptExecution no_js(isolate());
  DisallowCompilation no_compile(isolate());
222

223
  v8::Local<v8::Object> api_obj = v8::Utils::ToLocal(js_obj);
224

225
  std::vector<EmbedderDataSlot::RawData> original_embedder_values;
226 227 228 229 230 231 232
  std::vector<StartupData> serialized_data;

  // 1) Iterate embedder fields. Hold onto the original value of the fields.
  //    Ignore references to heap objects since these are to be handled by the
  //    serializer. For aligned pointers, call the serialize callback. Hold
  //    onto the result.
  for (int i = 0; i < embedder_fields_count; i++) {
233
    EmbedderDataSlot embedder_data_slot(*js_obj, i);
234 235
    original_embedder_values.emplace_back(
        embedder_data_slot.load_raw(isolate(), no_gc));
236
    Object object = embedder_data_slot.load_tagged();
237
    if (object.IsHeapObject()) {
238
      DCHECK(IsValidHeapObject(isolate()->heap(), HeapObject::cast(object)));
239 240
      serialized_data.push_back({nullptr, 0});
    } else {
241 242
      // If no serializer is provided and the field was empty, we serialize it
      // by default to nullptr.
243 244
      if (serialize_embedder_fields_.callback == nullptr &&
          object == Smi::zero()) {
245 246 247 248 249 250 251
        serialized_data.push_back({nullptr, 0});
      } else {
        DCHECK_NOT_NULL(serialize_embedder_fields_.callback);
        StartupData data = serialize_embedder_fields_.callback(
            api_obj, i, serialize_embedder_fields_.data);
        serialized_data.push_back(data);
      }
252 253 254 255 256 257 258 259 260 261
    }
  }

  // 2) Embedder fields for which the embedder callback produced non-zero
  //    serialized data should be considered aligned pointers to objects owned
  //    by the embedder. Clear these memory addresses to avoid non-determism
  //    in the snapshot. This is done separately to step 1 to no not interleave
  //    with embedder callbacks.
  for (int i = 0; i < embedder_fields_count; i++) {
    if (!DataIsEmpty(serialized_data[i])) {
262
      EmbedderDataSlot(*js_obj, i).store_raw(isolate(), kNullAddress, no_gc);
263 264
    }
  }
265 266 267

  // 3) Serialize the object. References from embedder fields to heap objects or
  //    smis are serialized regularly.
268
  ObjectSerializer(this, js_obj, &sink_).Serialize();
269 270

  // 4) Obtain back reference for the serialized object.
271 272 273 274
  const SerializerReference* reference =
      reference_map()->LookupReference(js_obj);
  DCHECK_NOT_NULL(reference);
  DCHECK(reference->is_back_reference());
275 276 277 278 279 280

  // 5) Write data returned by the embedder callbacks into a separate sink,
  //    headed by the back reference. Restore the original embedder fields.
  for (int i = 0; i < embedder_fields_count; i++) {
    StartupData data = serialized_data[i];
    if (DataIsEmpty(data)) continue;
281
    // Restore original values from cleared fields.
282 283 284 285
    EmbedderDataSlot(*js_obj, i)
        .store_raw(isolate(), original_embedder_values[i], no_gc);
    embedder_fields_sink_.Put(kNewObject, "embedder field holder");
    embedder_fields_sink_.PutInt(reference->back_ref_index(), "BackRefIndex");
286 287 288 289 290 291 292 293 294 295
    embedder_fields_sink_.PutInt(i, "embedder field index");
    embedder_fields_sink_.PutInt(data.raw_size, "embedder fields data size");
    embedder_fields_sink_.PutRaw(reinterpret_cast<const byte*>(data.data),
                                 data.raw_size, "embedder fields data");
    delete[] data.data;
  }

  // 6) The content of the separate sink is appended eventually to the default
  //    sink. The ensures that during deserialization, we call the deserializer
  //    callback at the end, and can guarantee that the deserialized objects are
296
  //    in a consistent state. See ContextSerializer::Serialize.
297
  return true;
298 299
}

300
void ContextSerializer::CheckRehashability(HeapObject obj) {
301
  if (!can_be_rehashed_) return;
302 303
  if (!obj.NeedsRehashing()) return;
  if (obj.CanBeRehashed()) return;
304 305 306
  can_be_rehashed_ = false;
}

307 308
}  // namespace internal
}  // namespace v8