1 // Copyright 2018 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/execution/microtask-queue.h"
6
7 #include <stddef.h>
8 #include <algorithm>
9
10 #include "src/api/api-inl.h"
11 #include "src/base/logging.h"
12 #include "src/execution/isolate.h"
13 #include "src/handles/handles-inl.h"
14 #include "src/objects/microtask-inl.h"
15 #include "src/objects/visitors.h"
16 #include "src/roots/roots-inl.h"
17 #include "src/tracing/trace-event.h"
18
19 namespace v8 {
20 namespace internal {
21
22 const size_t MicrotaskQueue::kRingBufferOffset =
23 OFFSET_OF(MicrotaskQueue, ring_buffer_);
24 const size_t MicrotaskQueue::kCapacityOffset =
25 OFFSET_OF(MicrotaskQueue, capacity_);
26 const size_t MicrotaskQueue::kSizeOffset = OFFSET_OF(MicrotaskQueue, size_);
27 const size_t MicrotaskQueue::kStartOffset = OFFSET_OF(MicrotaskQueue, start_);
28 const size_t MicrotaskQueue::kFinishedMicrotaskCountOffset =
29 OFFSET_OF(MicrotaskQueue, finished_microtask_count_);
30
31 const intptr_t MicrotaskQueue::kMinimumCapacity = 8;
32
33 // static
SetUpDefaultMicrotaskQueue(Isolate * isolate)34 void MicrotaskQueue::SetUpDefaultMicrotaskQueue(Isolate* isolate) {
35 DCHECK_NULL(isolate->default_microtask_queue());
36
37 MicrotaskQueue* microtask_queue = new MicrotaskQueue;
38 microtask_queue->next_ = microtask_queue;
39 microtask_queue->prev_ = microtask_queue;
40 isolate->set_default_microtask_queue(microtask_queue);
41 }
42
43 // static
New(Isolate * isolate)44 std::unique_ptr<MicrotaskQueue> MicrotaskQueue::New(Isolate* isolate) {
45 DCHECK_NOT_NULL(isolate->default_microtask_queue());
46
47 std::unique_ptr<MicrotaskQueue> microtask_queue(new MicrotaskQueue);
48
49 // Insert the new instance to the next of last MicrotaskQueue instance.
50 MicrotaskQueue* last = isolate->default_microtask_queue()->prev_;
51 microtask_queue->next_ = last->next_;
52 microtask_queue->prev_ = last;
53 last->next_->prev_ = microtask_queue.get();
54 last->next_ = microtask_queue.get();
55
56 return microtask_queue;
57 }
58
59 MicrotaskQueue::MicrotaskQueue() = default;
60
~MicrotaskQueue()61 MicrotaskQueue::~MicrotaskQueue() {
62 if (next_ != this) {
63 DCHECK_NE(prev_, this);
64 next_->prev_ = prev_;
65 prev_->next_ = next_;
66 }
67 delete[] ring_buffer_;
68 }
69
70 // static
CallEnqueueMicrotask(Isolate * isolate,intptr_t microtask_queue_pointer,Address raw_microtask)71 Address MicrotaskQueue::CallEnqueueMicrotask(Isolate* isolate,
72 intptr_t microtask_queue_pointer,
73 Address raw_microtask) {
74 Microtask microtask = Microtask::cast(Object(raw_microtask));
75 reinterpret_cast<MicrotaskQueue*>(microtask_queue_pointer)
76 ->EnqueueMicrotask(microtask);
77 return ReadOnlyRoots(isolate).undefined_value().ptr();
78 }
79
EnqueueMicrotask(v8::Isolate * v8_isolate,v8::Local<Function> function)80 void MicrotaskQueue::EnqueueMicrotask(v8::Isolate* v8_isolate,
81 v8::Local<Function> function) {
82 Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
83 HandleScope scope(isolate);
84 Handle<CallableTask> microtask = isolate->factory()->NewCallableTask(
85 Utils::OpenHandle(*function), isolate->native_context());
86 EnqueueMicrotask(*microtask);
87 }
88
EnqueueMicrotask(v8::Isolate * v8_isolate,v8::MicrotaskCallback callback,void * data)89 void MicrotaskQueue::EnqueueMicrotask(v8::Isolate* v8_isolate,
90 v8::MicrotaskCallback callback,
91 void* data) {
92 Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
93 HandleScope scope(isolate);
94 Handle<CallbackTask> microtask = isolate->factory()->NewCallbackTask(
95 isolate->factory()->NewForeign(reinterpret_cast<Address>(callback)),
96 isolate->factory()->NewForeign(reinterpret_cast<Address>(data)));
97 EnqueueMicrotask(*microtask);
98 }
99
EnqueueMicrotask(Microtask microtask)100 void MicrotaskQueue::EnqueueMicrotask(Microtask microtask) {
101 if (size_ == capacity_) {
102 // Keep the capacity of |ring_buffer_| power of 2, so that the JIT
103 // implementation can calculate the modulo easily.
104 intptr_t new_capacity = std::max(kMinimumCapacity, capacity_ << 1);
105 ResizeBuffer(new_capacity);
106 }
107
108 DCHECK_LT(size_, capacity_);
109 ring_buffer_[(start_ + size_) % capacity_] = microtask.ptr();
110 ++size_;
111 }
112
PerformCheckpoint(v8::Isolate * v8_isolate)113 void MicrotaskQueue::PerformCheckpoint(v8::Isolate* v8_isolate) {
114 if (!IsRunningMicrotasks() && !GetMicrotasksScopeDepth() &&
115 !HasMicrotasksSuppressions()) {
116 Isolate* isolate = reinterpret_cast<Isolate*>(v8_isolate);
117 RunMicrotasks(isolate);
118 isolate->ClearKeptObjects();
119 }
120 }
121
122 namespace {
123
124 class SetIsRunningMicrotasks {
125 public:
SetIsRunningMicrotasks(bool * flag)126 explicit SetIsRunningMicrotasks(bool* flag) : flag_(flag) {
127 DCHECK(!*flag_);
128 *flag_ = true;
129 }
130
~SetIsRunningMicrotasks()131 ~SetIsRunningMicrotasks() {
132 DCHECK(*flag_);
133 *flag_ = false;
134 }
135
136 private:
137 bool* flag_;
138 };
139
140 } // namespace
141
RunMicrotasks(Isolate * isolate)142 int MicrotaskQueue::RunMicrotasks(Isolate* isolate) {
143 if (!size()) {
144 OnCompleted(isolate);
145 return 0;
146 }
147
148 intptr_t base_count = finished_microtask_count_;
149
150 HandleScope handle_scope(isolate);
151 MaybeHandle<Object> maybe_exception;
152
153 MaybeHandle<Object> maybe_result;
154
155 int processed_microtask_count;
156 {
157 SetIsRunningMicrotasks scope(&is_running_microtasks_);
158 v8::Isolate::SuppressMicrotaskExecutionScope suppress(
159 reinterpret_cast<v8::Isolate*>(isolate));
160 HandleScopeImplementer::EnteredContextRewindScope rewind_scope(
161 isolate->handle_scope_implementer());
162 TRACE_EVENT_BEGIN0("v8.execute", "RunMicrotasks");
163 {
164 TRACE_EVENT_CALL_STATS_SCOPED(isolate, "v8", "V8.RunMicrotasks");
165 maybe_result = Execution::TryRunMicrotasks(isolate, this,
166 &maybe_exception);
167 processed_microtask_count =
168 static_cast<int>(finished_microtask_count_ - base_count);
169 }
170 TRACE_EVENT_END1("v8.execute", "RunMicrotasks", "microtask_count",
171 processed_microtask_count);
172 }
173
174 // If execution is terminating, clean up and propagate that to TryCatch scope.
175 if (maybe_result.is_null() && maybe_exception.is_null()) {
176 delete[] ring_buffer_;
177 ring_buffer_ = nullptr;
178 capacity_ = 0;
179 size_ = 0;
180 start_ = 0;
181 DCHECK(isolate->has_scheduled_exception());
182 isolate->SetTerminationOnExternalTryCatch();
183 OnCompleted(isolate);
184 return -1;
185 }
186 DCHECK_EQ(0, size());
187 OnCompleted(isolate);
188
189 return processed_microtask_count;
190 }
191
IterateMicrotasks(RootVisitor * visitor)192 void MicrotaskQueue::IterateMicrotasks(RootVisitor* visitor) {
193 if (size_) {
194 // Iterate pending Microtasks as root objects to avoid the write barrier for
195 // all single Microtask. If this hurts the GC performance, use a FixedArray.
196 visitor->VisitRootPointers(
197 Root::kStrongRoots, nullptr, FullObjectSlot(ring_buffer_ + start_),
198 FullObjectSlot(ring_buffer_ + std::min(start_ + size_, capacity_)));
199 visitor->VisitRootPointers(
200 Root::kStrongRoots, nullptr, FullObjectSlot(ring_buffer_),
201 FullObjectSlot(ring_buffer_ + std::max(start_ + size_ - capacity_,
202 static_cast<intptr_t>(0))));
203 }
204
205 if (capacity_ <= kMinimumCapacity) {
206 return;
207 }
208
209 intptr_t new_capacity = capacity_;
210 while (new_capacity > 2 * size_) {
211 new_capacity >>= 1;
212 }
213 new_capacity = std::max(new_capacity, kMinimumCapacity);
214 if (new_capacity < capacity_) {
215 ResizeBuffer(new_capacity);
216 }
217 }
218
GetMicrotasksScopeDepth() const219 int MicrotaskQueue::GetMicrotasksScopeDepth() const {
220 return microtasks_depth_;
221 }
222
AddMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback,void * data)223 void MicrotaskQueue::AddMicrotasksCompletedCallback(
224 MicrotasksCompletedCallbackWithData callback, void* data) {
225 CallbackWithData callback_with_data(callback, data);
226 auto pos =
227 std::find(microtasks_completed_callbacks_.begin(),
228 microtasks_completed_callbacks_.end(), callback_with_data);
229 if (pos != microtasks_completed_callbacks_.end()) return;
230 microtasks_completed_callbacks_.push_back(callback_with_data);
231 }
232
RemoveMicrotasksCompletedCallback(MicrotasksCompletedCallbackWithData callback,void * data)233 void MicrotaskQueue::RemoveMicrotasksCompletedCallback(
234 MicrotasksCompletedCallbackWithData callback, void* data) {
235 CallbackWithData callback_with_data(callback, data);
236 auto pos =
237 std::find(microtasks_completed_callbacks_.begin(),
238 microtasks_completed_callbacks_.end(), callback_with_data);
239 if (pos == microtasks_completed_callbacks_.end()) return;
240 microtasks_completed_callbacks_.erase(pos);
241 }
242
FireMicrotasksCompletedCallback(Isolate * isolate) const243 void MicrotaskQueue::FireMicrotasksCompletedCallback(Isolate* isolate) const {
244 std::vector<CallbackWithData> callbacks(microtasks_completed_callbacks_);
245 for (auto& callback : callbacks) {
246 callback.first(reinterpret_cast<v8::Isolate*>(isolate), callback.second);
247 }
248 }
249
get(intptr_t index) const250 Microtask MicrotaskQueue::get(intptr_t index) const {
251 DCHECK_LT(index, size_);
252 Object microtask(ring_buffer_[(index + start_) % capacity_]);
253 return Microtask::cast(microtask);
254 }
255
OnCompleted(Isolate * isolate)256 void MicrotaskQueue::OnCompleted(Isolate* isolate) {
257 FireMicrotasksCompletedCallback(isolate);
258 }
259
ResizeBuffer(intptr_t new_capacity)260 void MicrotaskQueue::ResizeBuffer(intptr_t new_capacity) {
261 DCHECK_LE(size_, new_capacity);
262 Address* new_ring_buffer = new Address[new_capacity];
263 for (intptr_t i = 0; i < size_; ++i) {
264 new_ring_buffer[i] = ring_buffer_[(start_ + i) % capacity_];
265 }
266
267 delete[] ring_buffer_;
268 ring_buffer_ = new_ring_buffer;
269 capacity_ = new_capacity;
270 start_ = 0;
271 }
272
273 } // namespace internal
274 } // namespace v8
275