File: thread_state.cc

package info (click to toggle)
chromium 141.0.7390.107-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,254,812 kB
  • sloc: cpp: 35,264,957; ansic: 7,169,920; javascript: 4,250,185; python: 1,460,636; asm: 950,788; xml: 751,751; pascal: 187,972; sh: 89,459; perl: 88,691; objc: 79,953; sql: 53,924; cs: 44,622; fortran: 24,137; makefile: 22,319; tcl: 15,277; php: 14,018; yacc: 8,995; ruby: 7,553; awk: 3,720; lisp: 3,096; lex: 1,330; ada: 727; jsp: 228; sed: 36
file content (372 lines) | stat: -rw-r--r-- 12,797 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "third_party/blink/renderer/platform/heap/thread_state.h"

#include <fstream>
#include <iostream>

#include "base/functional/callback.h"
#include "base/notreached.h"
#include "gin/public/v8_platform.h"
#include "third_party/blink/renderer/platform/bindings/active_script_wrappable_manager.h"
#include "third_party/blink/renderer/platform/bindings/dom_data_store.h"
#include "third_party/blink/renderer/platform/bindings/dom_wrapper_world.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/script_forbidden_scope.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h"
#include "third_party/blink/renderer/platform/heap/custom_spaces.h"
#include "third_party/blink/renderer/platform/heap/thread_state_storage.h"
#include "third_party/blink/renderer/platform/wtf/hash_set.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
#include "v8/include/cppgc/heap-consistency.h"
#include "v8/include/v8-cppgc.h"
#include "v8/include/v8-embedder-heap.h"
#include "v8/include/v8-isolate.h"
#include "v8/include/v8-object.h"
#include "v8/include/v8-profiler.h"
#include "v8/include/v8-traced-handle.h"

namespace blink {

namespace {

// Handler allowing for dropping V8 wrapper objects that can be recreated
// lazily.
class BlinkRootsHandler final : public v8::EmbedderRootsHandler {
 public:
  explicit BlinkRootsHandler(v8::Isolate* isolate) : isolate_(isolate) {}

  // ResetRoot() clears references to V8 wrapper objects in all worlds. It is
  // invoked for references where IsRoot() returned false during young
  // generation garbage collections.
  void ResetRoot(const v8::TracedReference<v8::Value>& handle) final {
    const v8::TracedReference<v8::Object>& traced = handle.As<v8::Object>();
    const bool success = DOMDataStore::ClearWrapperInAnyWorldIfEqualTo(
        ToAnyScriptWrappable(isolate_, traced), traced);
    // Since V8 found a handle, Blink needs to find it as well when trying to
    // remove it. Note that this is even true for the case where a
    // DOMWrapperWorld and DOMDataStore are already unreachable as the internal
    // worldmap contains a weak ref that remains valid until the next full GC
    // call. The weak ref is guaranteed to still be valid because it is only
    // cleared on full GCs and the `BlinkRootsHandler` is used on minor V8 GCs.
    CHECK(success);
  }

  bool TryResetRoot(const v8::TracedReference<v8::Value>& handle) final {
    const v8::TracedReference<v8::Object>& traced = handle.As<v8::Object>();
    return DOMDataStore::ClearInlineStorageWrapperIfEqualTo(
        ToAnyScriptWrappable(isolate_, traced), traced);
  }

 private:
  v8::Isolate* isolate_;
};

}  // namespace

// static
ThreadState* ThreadState::AttachMainThread() {
  auto* thread_state = new ThreadState(gin::V8Platform::Get());
  ThreadStateStorage::AttachMainThread(
      *thread_state, thread_state->cpp_heap().GetAllocationHandle(),
      thread_state->cpp_heap().GetHeapHandle());
  return thread_state;
}

// static
ThreadState* ThreadState::AttachMainThreadForTesting(v8::Platform* platform) {
  auto* thread_state = new ThreadState(platform);
  ThreadStateStorage::AttachMainThread(
      *thread_state, thread_state->cpp_heap().GetAllocationHandle(),
      thread_state->cpp_heap().GetHeapHandle());
  thread_state->EnableDetachedGarbageCollectionsForTesting();
  return thread_state;
}

// static
ThreadState* ThreadState::AttachCurrentThread() {
  auto* thread_state = new ThreadState(gin::V8Platform::Get());
  ThreadStateStorage::AttachNonMainThread(
      *thread_state, thread_state->cpp_heap().GetAllocationHandle(),
      thread_state->cpp_heap().GetHeapHandle());
  return thread_state;
}

// static
ThreadState* ThreadState::AttachCurrentThreadForTesting(
    v8::Platform* platform) {
  ThreadState* thread_state = new ThreadState(platform);
  ThreadStateStorage::AttachNonMainThread(
      *thread_state, thread_state->cpp_heap().GetAllocationHandle(),
      thread_state->cpp_heap().GetHeapHandle());
  thread_state->EnableDetachedGarbageCollectionsForTesting();
  return thread_state;
}

void ThreadState::RecoverCppHeap(std::unique_ptr<v8::CppHeap> cpp_heap) {
  CHECK(!owning_cpp_heap_);
  CHECK(!cpp_heap_);
  // We want to keep the invariant that the ThreadState does not own a CppHeap
  // while it is attached to an isolate. When it's attached to an isolate, the
  // isolate owns the CppHeap.
  CHECK(!isolate_);
  owning_cpp_heap_ = std::move(cpp_heap);
  cpp_heap_ = owning_cpp_heap_.get();
}

// static
void ThreadState::RecoverCppHeapTrampoline(
    std::unique_ptr<v8::CppHeap> cpp_heap) {
  ThreadState::Current()->RecoverCppHeap(std::move(cpp_heap));
}

void ThreadState::RecoverCppHeapAfterIsolateTearDownForTesting() {
  isolate_->SetReleaseCppHeapCallbackForTesting(RecoverCppHeapTrampoline);
}

// static
void ThreadState::DetachCurrentThread() {
  auto* state = ThreadState::Current();
  DCHECK(state);
  delete state;
}

void ThreadState::AttachToIsolate(
    v8::Isolate* isolate,
    DevToolsCountersCallback dev_tools_counters_callback) {
  CHECK(!owning_cpp_heap_);
  CHECK_EQ(cpp_heap_, isolate->GetCppHeap());
  isolate_ = isolate;
  embedder_roots_handler_ = std::make_unique<BlinkRootsHandler>(isolate);
  isolate_->SetEmbedderRootsHandler(embedder_roots_handler_.get());
  isolate_->AddGCPrologueCallback(GcPrologue);
  isolate_->AddGCEpilogueCallback(GcEpilogue);

  dev_tools_counters_callback_ = dev_tools_counters_callback;
  active_script_wrappable_manager_ =
      MakeGarbageCollected<ActiveScriptWrappableManager>();
}

void ThreadState::DetachFromIsolate() {
  CHECK(!owning_cpp_heap_);
  CHECK_EQ(cpp_heap_, isolate_->GetCppHeap());
  CHECK_EQ(gc_callback_depth_, 0u);

  active_script_wrappable_manager_.Clear();

  isolate_->SetEmbedderRootsHandler(nullptr);
  isolate_->RemoveGCPrologueCallback(GcPrologue);
  isolate_->RemoveGCEpilogueCallback(GcEpilogue);
  isolate_ = nullptr;
  cpp_heap_ = nullptr;
}

std::unique_ptr<v8::CppHeap> ThreadState::ReleaseCppHeap() {
  return std::move(owning_cpp_heap_);
}

ThreadState::ThreadState(v8::Platform* platform)
    : owning_cpp_heap_(v8::CppHeap::Create(
          platform,
          v8::CppHeapCreateParams(CustomSpaces::CreateCustomSpaces()))),
      cpp_heap_(owning_cpp_heap_.get()),
      heap_handle_(cpp_heap_->GetHeapHandle()),
      thread_id_(CurrentThread()) {}

ThreadState::~ThreadState() {
  DCHECK(IsCreationThread());
  owning_cpp_heap_.reset();
  ThreadStateStorage::DetachNonMainThread(*ThreadStateStorage::Current());
}

void ThreadState::CollectAllGarbageForTesting(StackState stack_state) {
  size_t previous_live_bytes = 0;
  for (size_t i = 0; i < 5; i++) {
    // Either triggers unified heap or stand-alone garbage collections.
    cpp_heap().CollectGarbageForTesting(stack_state);
    const size_t live_bytes =
        cpp_heap()
            .CollectStatistics(cppgc::HeapStatistics::kBrief)
            .used_size_bytes;
    if (previous_live_bytes == live_bytes) {
      break;
    }
    previous_live_bytes = live_bytes;
  }
}

void ThreadState::CollectGarbageInYoungGenerationForTesting(
    StackState stack_state) {
  cpp_heap().CollectGarbageInYoungGenerationForTesting(stack_state);
}

namespace {

class CustomSpaceStatisticsReceiverImpl final
    : public v8::CustomSpaceStatisticsReceiver {
 public:
  explicit CustomSpaceStatisticsReceiverImpl(
      base::OnceCallback<void(size_t allocated_node_bytes,
                              size_t allocated_css_bytes)> callback)
      : callback_(std::move(callback)) {}

  ~CustomSpaceStatisticsReceiverImpl() final {
    DCHECK(node_bytes_.has_value());
    DCHECK(css_bytes_.has_value());
    std::move(callback_).Run(*node_bytes_, *css_bytes_);
  }

  void AllocatedBytes(cppgc::CustomSpaceIndex space_index, size_t bytes) final {
    if (space_index.value == NodeSpace::kSpaceIndex.value) {
      node_bytes_ = bytes;
    } else {
      DCHECK_EQ(space_index.value, CSSValueSpace::kSpaceIndex.value);
      css_bytes_ = bytes;
    }
  }

 private:
  base::OnceCallback<void(size_t allocated_node_bytes,
                          size_t allocated_css_bytes)>
      callback_;
  std::optional<size_t> node_bytes_;
  std::optional<size_t> css_bytes_;
};

}  // anonymous namespace

void ThreadState::CollectNodeAndCssStatistics(
    base::OnceCallback<void(size_t allocated_node_bytes,
                            size_t allocated_css_bytes)> callback) {
  std::vector<cppgc::CustomSpaceIndex> spaces{NodeSpace::kSpaceIndex,
                                              CSSValueSpace::kSpaceIndex};
  cpp_heap().CollectCustomSpaceStatisticsAtLastGC(
      std::move(spaces),
      std::make_unique<CustomSpaceStatisticsReceiverImpl>(std::move(callback)));
}

void ThreadState::EnableDetachedGarbageCollectionsForTesting() {
  cpp_heap().EnableDetachedGarbageCollectionsForTesting();
}

bool ThreadState::IsIncrementalMarking() const {
  return cppgc::subtle::HeapState::IsMarking(heap_handle()) &&
         !cppgc::subtle::HeapState::IsInAtomicPause(heap_handle());
}

bool ThreadState::IsSweepingOnOwningThread() const {
  return cppgc::subtle::HeapState::IsSweepingOnOwningThread(heap_handle());
}

namespace {

class BufferedStream final : public v8::OutputStream {
 public:
  explicit BufferedStream(std::streambuf* stream_buffer)
      : out_stream_(stream_buffer) {}

  WriteResult WriteAsciiChunk(char* data, int size) override {
    out_stream_.write(data, size);
    return kContinue;
  }

  void EndOfStream() override {}

 private:
  std::ostream out_stream_;
};

}  // namespace

void ThreadState::TakeHeapSnapshotForTesting(const char* filename) const {
  CHECK(isolate_);
  v8::HeapProfiler* profiler = isolate_->GetHeapProfiler();
  CHECK(profiler);

  v8::HeapProfiler::HeapSnapshotOptions options;
  options.snapshot_mode = v8::HeapProfiler::HeapSnapshotMode::kExposeInternals;
  const v8::HeapSnapshot* snapshot = profiler->TakeHeapSnapshot(options);

  {
    std::ofstream file_stream;
    if (filename) {
      file_stream.open(filename, std::ios_base::out | std::ios_base::trunc);
    }
    BufferedStream stream(filename ? file_stream.rdbuf() : std::cout.rdbuf());
    snapshot->Serialize(&stream);
  }

  const_cast<v8::HeapSnapshot*>(snapshot)->Delete();
}

bool ThreadState::IsTakingHeapSnapshot() const {
  if (!isolate_) {
    return false;
  }
  v8::HeapProfiler* profiler = isolate_->GetHeapProfiler();
  return profiler && profiler->IsTakingSnapshot();
}

const char* ThreadState::CopyNameForHeapSnapshot(const char* name) const {
  CHECK(isolate_);
  v8::HeapProfiler* profiler = isolate_->GetHeapProfiler();
  CHECK(profiler);
  return profiler->CopyNameForHeapSnapshot(name);
}

// static
void ThreadState::GcPrologue(v8::Isolate* isolate,
                             v8::GCType type,
                             v8::GCCallbackFlags) {
  RUNTIME_CALL_TIMER_SCOPE(isolate, RuntimeCallStats::CounterId::kGcPrologue);

  auto* thread_state = ThreadState::Current();
  CHECK_EQ(thread_state->isolate_, isolate);
  thread_state->gc_callback_depth_++;

  ScriptForbiddenScope::Enter();

  ActiveScriptWrappableManager* const active_script_wrappable_manager =
      thread_state->active_script_wrappable_manager_.Get();
  v8::HandleScope scope(isolate);
  switch (type) {
    case v8::kGCTypeIncrementalMarking:
      // Recomputing ASWs is opportunistic during incremental marking as they
      // only need to be recomputing during the atomic pause for correctness.
      if (active_script_wrappable_manager) {
        active_script_wrappable_manager->RecomputeActiveScriptWrappables(
            ActiveScriptWrappableManager::RecomputeMode::kOpportunistic);
      }
      break;
    case v8::kGCTypeMarkSweepCompact:
      if (active_script_wrappable_manager) {
        active_script_wrappable_manager->RecomputeActiveScriptWrappables(
            ActiveScriptWrappableManager::RecomputeMode::kRequired);
      }
      break;
    default:
      break;
  }
}

// static
void ThreadState::GcEpilogue(v8::Isolate* isolate,
                             v8::GCType,
                             v8::GCCallbackFlags) {
  RUNTIME_CALL_TIMER_SCOPE(isolate, RuntimeCallStats::CounterId::kGcEpilogue);

  auto* thread_state = ThreadState::Current();
  CHECK_EQ(thread_state->isolate_, isolate);
  thread_state->gc_callback_depth_--;

  if (thread_state->dev_tools_counters_callback_) {
    thread_state->dev_tools_counters_callback_(isolate);
  }

  ScriptForbiddenScope::Exit();
}

}  // namespace blink