Debian Codegraph @

js/src/vm/OffThreadPromiseRuntimeState.cpp

raw
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*-
2 * vim: set ts=8 sts=2 et sw=2 tw=80:
3 * This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6
7 #include "vm/OffThreadPromiseRuntimeState.h"
8
9 #include "mozilla/Assertions.h" // MOZ_ASSERT{,_IF}
10
11 #include <utility> // mozilla::Swap
12
13 #include "jspubtd.h" // js::CurrentThreadCanAccessRuntime
14
15 #include "js/AllocPolicy.h" // js::ReportOutOfMemory
16 #include "js/HeapAPI.h" // JS::shadow::Zone
17 #include "js/Promise.h" // JS::Dispatchable, JS::DispatchToEventLoopCallback,
18 // JS::DelayedDispatchToEventLoopCallback
19 #include "js/Utility.h" // js_delete, js::AutoEnterOOMUnsafeRegion
20 #include "threading/ProtectedData.h" // js::UnprotectedData
21 #include "vm/HelperThreads.h" // js::AutoLockHelperThreadState
22 #include "vm/JSContext.h" // JSContext
23 #include "vm/PromiseObject.h" // js::PromiseObject
24 #include "vm/Realm.h" // js::AutoRealm
25 #include "vm/Runtime.h" // JSRuntime
26
27 #include "vm/Realm-inl.h" // js::AutoRealm::AutoRealm
28
29 using JS::Handle;
30
31 using js::OffThreadPromiseRuntimeState;
32 using js::OffThreadPromiseTask;
33
34 OffThreadPromiseTask::OffThreadPromiseTask(JSContext* cx,
35 JS::Handle<PromiseObject*> promise)
36 : runtime_(cx->runtime()),
37 promise_(cx, promise),
38 registered_(false),
39 cancellable_(false) {
40 MOZ_ASSERT(runtime_ == promise_->zone()->runtimeFromMainThread());
41 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
42 MOZ_ASSERT(cx->runtime()->offThreadPromiseState.ref().initialized());
43 }
44
45 OffThreadPromiseTask::~OffThreadPromiseTask() {
46 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
47
48 OffThreadPromiseRuntimeState& state = runtime_->offThreadPromiseState.ref();
49 MOZ_ASSERT(state.initialized());
50
51 if (registered_) {
52 unregister(state);
53 }
54 }
55
56 bool OffThreadPromiseTask::init(JSContext* cx) {
57 AutoLockHelperThreadState lock;
58 return init(cx, lock);
59 }
60
61 bool OffThreadPromiseTask::init(JSContext* cx,
62 const AutoLockHelperThreadState& lock) {
63 MOZ_ASSERT(cx->runtime() == runtime_);
64 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
65
66 OffThreadPromiseRuntimeState& state = runtime_->offThreadPromiseState.ref();
67 MOZ_ASSERT(state.initialized());
68
69 state.numRegistered_++;
70 registered_ = true;
71 return true;
72 }
73
74 bool OffThreadPromiseTask::InitCancellable(
75 JSContext* cx, js::UniquePtr<OffThreadPromiseTask>&& task) {
76 AutoLockHelperThreadState lock;
77 return InitCancellable(cx, lock, std::move(task));
78 }
79
80 bool OffThreadPromiseTask::InitCancellable(
81 JSContext* cx, const AutoLockHelperThreadState& lock,
82 js::UniquePtr<OffThreadPromiseTask>&& task) {
83 MOZ_ASSERT(cx->runtime() == task->runtime_);
84 MOZ_ASSERT(CurrentThreadCanAccessRuntime(task->runtime_));
85 OffThreadPromiseRuntimeState& state =
86 task->runtime_->offThreadPromiseState.ref();
87 MOZ_ASSERT(state.initialized());
88
89 if (!task->init(cx, lock)) {
90 ReportOutOfMemory(cx);
91 return false;
92 }
93
94 OffThreadPromiseTask* rawTask = task.release();
95 if (!state.cancellable().putNew(rawTask)) {
96 state.numRegistered_--;
97 rawTask->registered_ = false;
98 ReportOutOfMemory(cx);
99 return false;
100 }
101 rawTask->cancellable_ = true;
102 return true;
103 }
104
105 void OffThreadPromiseTask::unregister(OffThreadPromiseRuntimeState& state) {
106 MOZ_ASSERT(registered_);
107 AutoLockHelperThreadState lock;
108 if (cancellable_) {
109 cancellable_ = false;
110 state.cancellable().remove(this);
111 }
112 state.numRegistered_--;
113 registered_ = false;
114 }
115
116 void OffThreadPromiseTask::run(JSContext* cx,
117 MaybeShuttingDown maybeShuttingDown) {
118 MOZ_ASSERT(cx->runtime() == runtime_);
119 MOZ_ASSERT(CurrentThreadCanAccessRuntime(runtime_));
120 MOZ_ASSERT(registered_);
121
122 // Remove this task from numRegistered_ before calling `resolve`, so that if
123 // `resolve` itself drains the queue reentrantly, the queue will not think
124 // this task is yet to be queued and block waiting for it.
125 //
126 // The unregister method synchronizes on the helper thread lock and ensures
127 // that we don't delete the task while the helper thread is still running.
128 OffThreadPromiseRuntimeState& state = runtime_->offThreadPromiseState.ref();
129 MOZ_ASSERT(state.initialized());
130 unregister(state);
131
132 if (maybeShuttingDown == JS::Dispatchable::NotShuttingDown) {
133 // We can't leave a pending exception when returning to the caller so do
134 // the same thing as Gecko, which is to ignore the error. This should
135 // only happen due to OOM or interruption.
136 AutoRealm ar(cx, promise_);
137 if (!resolve(cx, promise_)) {
138 cx->clearPendingException();
139 }
140 }
141
142 js_delete(this);
143 }
144
145 void OffThreadPromiseTask::transferToRuntime() {
146 MOZ_ASSERT(registered_);
147
148 // The unregister method synchronizes on the helper thread lock and ensures
149 // that we don't delete the task while the helper thread is still running.
150 OffThreadPromiseRuntimeState& state = runtime_->offThreadPromiseState.ref();
151 MOZ_ASSERT(state.initialized());
152
153 // Task is now owned by the state and will be deleted on ::shutdown.
154 state.stealFailedTask(this);
155 }
156
157 /* static */
158 void OffThreadPromiseTask::DestroyUndispatchedTask(OffThreadPromiseTask* task) {
159 MOZ_ASSERT(CurrentThreadCanAccessRuntime(task->runtime_));
160 MOZ_ASSERT(task->registered_);
161 MOZ_ASSERT(task->cancellable_);
162 // Cleanup Steps from 4. in SMDOC for Atomics.waitAsync
163 task->prepareForCancel();
164 js_delete(task);
165 }
166
167 void OffThreadPromiseTask::dispatchResolveAndDestroy() {
168 AutoLockHelperThreadState lock;
169 js::UniquePtr<OffThreadPromiseTask> task(this);
170 DispatchResolveAndDestroy(std::move(task), lock);
171 }
172
173 void OffThreadPromiseTask::dispatchResolveAndDestroy(
174 const AutoLockHelperThreadState& lock) {
175 js::UniquePtr<OffThreadPromiseTask> task(this);
176 DispatchResolveAndDestroy(std::move(task), lock);
177 }
178
179 void OffThreadPromiseTask::removeFromCancellableListAndDispatch() {
180 AutoLockHelperThreadState lock;
181 removeFromCancellableListAndDispatch(lock);
182 }
183
184 void OffThreadPromiseTask::removeFromCancellableListAndDispatch(
185 const AutoLockHelperThreadState& lock) {
186 OffThreadPromiseRuntimeState& state = runtime_->offThreadPromiseState.ref();
187 MOZ_ASSERT(state.initialized());
188 MOZ_ASSERT(state.cancellable().has(this));
189
190 MOZ_ASSERT(registered_);
191 MOZ_ASSERT(cancellable_);
192 cancellable_ = false;
193 // remove this task from the runnable's cancellable list. This ends the
194 // runtime's ownership of the the task.
195 state.cancellable().remove(this);
196
197 // Create a UniquePtr that will be passed to the embedding.
198 js::UniquePtr<OffThreadPromiseTask> task;
199 // move ownership of this task to the newly created pointer
200 task.reset(this);
201 DispatchResolveAndDestroy(std::move(task), lock);
202 }
203
204 /* static */
205 void OffThreadPromiseTask::DispatchResolveAndDestroy(
206 js::UniquePtr<OffThreadPromiseTask>&& task) {
207 AutoLockHelperThreadState lock;
208 DispatchResolveAndDestroy(std::move(task), lock);
209 }
210
211 /* static */
212 void OffThreadPromiseTask::DispatchResolveAndDestroy(
213 js::UniquePtr<OffThreadPromiseTask>&& task,
214 const AutoLockHelperThreadState& lock) {
215 OffThreadPromiseRuntimeState& state =
216 task->runtime()->offThreadPromiseState.ref();
217 MOZ_ASSERT(state.initialized());
218
219 MOZ_ASSERT(task->registered_);
220 MOZ_ASSERT(!task->cancellable_);
221 // If the dispatch succeeds, then we are guaranteed that run() will be
222 // called on an active JSContext of runtime_.
223 {
224 // Hazard analysis can't tell that the callback does not GC.
225 JS::AutoSuppressGCAnalysis nogc;
226 if (state.dispatchToEventLoopCallback_(state.dispatchToEventLoopClosure_,
227 std::move(task))) {
228 return;
229 }
230 }
231
232 // The DispatchToEventLoopCallback has failed to dispatch this task,
233 // indicating that shutdown has begun. Compare the number of failed tasks that
234 // have called dispatchResolveAndDestroy, and when they account for all of
235 // numRegistered_, notify OffThreadPromiseRuntimeState::shutdown that it is
236 // safe to destruct them.
237 if (state.failed().length() == state.numRegistered_) {
238 state.allFailed().notify_one();
239 }
240 }
241
242 OffThreadPromiseRuntimeState::OffThreadPromiseRuntimeState()
243 : dispatchToEventLoopCallback_(nullptr),
244 delayedDispatchToEventLoopCallback_(nullptr),
245 dispatchToEventLoopClosure_(nullptr),
246 numRegistered_(0),
247 internalDispatchQueueClosed_(false) {}
248
249 OffThreadPromiseRuntimeState::~OffThreadPromiseRuntimeState() {
250 MOZ_ASSERT(numRegistered_ == 0);
251 MOZ_ASSERT(internalDispatchQueue_.refNoCheck().empty());
252 MOZ_ASSERT(!initialized());
253 }
254
255 void OffThreadPromiseRuntimeState::init(
256 JS::DispatchToEventLoopCallback callback,
257 JS::DelayedDispatchToEventLoopCallback delayedCallback, void* closure) {
258 MOZ_ASSERT(!initialized());
259
260 dispatchToEventLoopCallback_ = callback;
261 delayedDispatchToEventLoopCallback_ = delayedCallback;
262 dispatchToEventLoopClosure_ = closure;
263
264 MOZ_ASSERT(initialized());
265 }
266
267 bool OffThreadPromiseRuntimeState::dispatchToEventLoop(
268 js::UniquePtr<JS::Dispatchable>&& dispatchable) {
269 return dispatchToEventLoopCallback_(dispatchToEventLoopClosure_,
270 std::move(dispatchable));
271 }
272
273 bool OffThreadPromiseRuntimeState::delayedDispatchToEventLoop(
274 js::UniquePtr<JS::Dispatchable>&& dispatchable, uint32_t delay) {
275 return delayedDispatchToEventLoopCallback_(dispatchToEventLoopClosure_,
276 std::move(dispatchable), delay);
277 }
278
279 /* static */
280 bool OffThreadPromiseRuntimeState::internalDispatchToEventLoop(
281 void* closure, js::UniquePtr<JS::Dispatchable>&& d) {
282 OffThreadPromiseRuntimeState& state =
283 *reinterpret_cast<OffThreadPromiseRuntimeState*>(closure);
284 MOZ_ASSERT(state.usingInternalDispatchQueue());
285 gHelperThreadLock.assertOwnedByCurrentThread();
286
287 if (state.internalDispatchQueueClosed_) {
288 JS::Dispatchable::ReleaseFailedTask(std::move(d));
289 return false;
290 }
291
292 state.dispatchDelayedTasks();
293
294 // The JS API contract is that 'false' means shutdown, so be infallible
295 // here (like Gecko).
296 AutoEnterOOMUnsafeRegion noOOM;
297 if (!state.internalDispatchQueue().pushBack(std::move(d))) {
298 noOOM.crash("internalDispatchToEventLoop");
299 }
300
301 // Wake up internalDrain() if it is waiting for a job to finish.
302 state.internalDispatchQueueAppended().notify_one();
303 return true;
304 }
305
306 // This function (and all related delayedDispatch data structures), are in place
307 // in order to make the JS Shell work as expected with delayed tasks such as
308 // Atomics.waitAsync.
309 bool OffThreadPromiseRuntimeState::internalDelayedDispatchToEventLoop(
310 void* closure, js::UniquePtr<JS::Dispatchable>&& d, uint32_t delay) {
311 OffThreadPromiseRuntimeState& state =
312 *reinterpret_cast<OffThreadPromiseRuntimeState*>(closure);
313 MOZ_ASSERT(state.usingInternalDispatchQueue());
314 gHelperThreadLock.assertOwnedByCurrentThread();
315
316 if (state.internalDispatchQueueClosed_) {
317 return false;
318 }
319
320 state.dispatchDelayedTasks();
321
322 // endTime is calculated synchronously from the moment we call
323 // internalDelayedDispatchToEventLoop. The only current use-case is
324 // Atomics.waitAsync.
325 mozilla::TimeStamp endTime = mozilla::TimeStamp::Now() +
326 mozilla::TimeDuration::FromMilliseconds(delay);
327 if (!state.internalDelayedDispatchPriorityQueue().insert(
328 DelayedDispatchable(std::move(d), endTime))) {
329 JS::Dispatchable::ReleaseFailedTask(std::move(d));
330 return false;
331 }
332
333 return true;
334 }
335
336 void OffThreadPromiseRuntimeState::dispatchDelayedTasks() {
337 MOZ_ASSERT(usingInternalDispatchQueue());
338 gHelperThreadLock.assertOwnedByCurrentThread();
339
340 if (internalDispatchQueueClosed_) {
341 return;
342 }
343
344 mozilla::TimeStamp now = mozilla::TimeStamp::Now();
345 auto& queue = internalDelayedDispatchPriorityQueue();
346
347 while (!queue.empty() && queue.highest().endTime() <= now) {
348 DelayedDispatchable d(std::move(queue.highest()));
349 queue.popHighest();
350
351 AutoEnterOOMUnsafeRegion noOOM;
352 if (!internalDispatchQueue().pushBack(d.dispatchable())) {
353 noOOM.crash("dispatchDelayedTasks");
354 }
355 internalDispatchQueueAppended().notify_one();
356 }
357 }
358
359 bool OffThreadPromiseRuntimeState::usingInternalDispatchQueue() const {
360 return dispatchToEventLoopCallback_ == internalDispatchToEventLoop;
361 }
362
363 void OffThreadPromiseRuntimeState::initInternalDispatchQueue() {
364 init(internalDispatchToEventLoop, internalDelayedDispatchToEventLoop, this);
365 MOZ_ASSERT(usingInternalDispatchQueue());
366 }
367
368 bool OffThreadPromiseRuntimeState::initialized() const {
369 return !!dispatchToEventLoopCallback_;
370 }
371
372 void OffThreadPromiseRuntimeState::internalDrain(JSContext* cx) {
373 MOZ_ASSERT(usingInternalDispatchQueue());
374
375 for (;;) {
376 js::UniquePtr<JS::Dispatchable> d;
377 {
378 AutoLockHelperThreadState lock;
379 dispatchDelayedTasks();
380
381 MOZ_ASSERT(!internalDispatchQueueClosed_);
382 MOZ_ASSERT_IF(!internalDispatchQueue().empty(), numRegistered_ > 0);
383 if (internalDispatchQueue().empty() && !internalHasPending(lock)) {
384 return;
385 }
386
387 // There are extant live dispatched OffThreadPromiseTasks.
388 // If none are in the queue, block until one of them finishes
389 // and enqueues a dispatchable.
390 while (internalDispatchQueue().empty()) {
391 internalDispatchQueueAppended().wait(lock);
392 }
393
394 d = std::move(internalDispatchQueue().front());
395 internalDispatchQueue().popFront();
396 }
397
398 // Don't call Run() with lock held to avoid deadlock.
399 OffThreadPromiseTask::Run(cx, std::move(d),
400 JS::Dispatchable::NotShuttingDown);
401 }
402 }
403
404 bool OffThreadPromiseRuntimeState::internalHasPending() {
405 AutoLockHelperThreadState lock;
406 return internalHasPending(lock);
407 }
408
409 bool OffThreadPromiseRuntimeState::internalHasPending(
410 AutoLockHelperThreadState& lock) {
411 MOZ_ASSERT(usingInternalDispatchQueue());
412
413 MOZ_ASSERT(!internalDispatchQueueClosed_);
414 MOZ_ASSERT_IF(!internalDispatchQueue().empty(), numRegistered_ > 0);
415 return numRegistered_ > cancellable().count();
416 }
417
418 void OffThreadPromiseRuntimeState::stealFailedTask(JS::Dispatchable* task) {
419 js::AutoEnterOOMUnsafeRegion noOOM;
420 if (!failed().pushBack(task)) {
421 noOOM.crash("stealFailedTask");
422 }
423 }
424
425 void OffThreadPromiseRuntimeState::shutdown(JSContext* cx) {
426 if (!initialized()) {
427 return;
428 }
429
430 AutoLockHelperThreadState lock;
431
432 // Cancel all undispatched tasks.
433 for (auto iter = cancellable().modIter(); !iter.done(); iter.next()) {
434 OffThreadPromiseTask* task = iter.get();
435 MOZ_ASSERT(task->cancellable_);
436 iter.remove();
437
438 // Don't call DestroyUndispatchedTask() with lock held to avoid deadlock.
439 {
440 AutoUnlockHelperThreadState unlock(lock);
441 OffThreadPromiseTask::DestroyUndispatchedTask(task);
442 }
443 }
444 MOZ_ASSERT(cancellable().empty());
445
446 // When the shell is using the internal event loop, we must simulate our
447 // requirement of the embedding that, before shutdown, all successfully-
448 // dispatched-to-event-loop tasks have been run.
449 if (usingInternalDispatchQueue()) {
450 DispatchableFifo dispatchQueue;
451 {
452 std::swap(dispatchQueue, internalDispatchQueue());
453 MOZ_ASSERT(internalDispatchQueue().empty());
454 internalDispatchQueueClosed_ = true;
455 }
456
457 // Don't call run() with lock held to avoid deadlock.
458 AutoUnlockHelperThreadState unlock(lock);
459 while (!dispatchQueue.empty()) {
460 js::UniquePtr<JS::Dispatchable> d = std::move(dispatchQueue.front());
461 dispatchQueue.popFront();
462 OffThreadPromiseTask::Run(cx, std::move(d),
463 JS::Dispatchable::ShuttingDown);
464 }
465 }
466
467 // An OffThreadPromiseTask may only be safely deleted on its JSContext's
468 // thread (since it contains a PersistentRooted holding its promise), and
469 // only after it has called DispatchResolveAndDestroy (since that is our
470 // only indication that its owner is done writing into it).
471 //
472 // OffThreadPromiseTasks accepted by the DispatchToEventLoopCallback are
473 // deleted by their 'run' methods. Only DispatchResolveAndDestroy invokes
474 // the callback, and the point of the callback is to call 'run' on the
475 // JSContext's thread, so the conditions above are met.
476 //
477 // But although the embedding's DispatchToEventLoopCallback promises to run
478 // every task it accepts before shutdown, when shutdown does begin it starts
479 // rejecting tasks; we cannot count on 'run' to clean those up for us.
480 // Instead, tasks which fail to run have their ownership passed to the failed_
481 // list; once that count covers everything in numRegisterd_, this function
482 // itself runs only on the JSContext's thread, so we can delete them all here.
483 while (numRegistered_ != failed().length()) {
484 MOZ_ASSERT(failed().length() < numRegistered_);
485 allFailed().wait(lock);
486 }
487
488 {
489 DispatchableFifo failedQueue;
490 {
491 std::swap(failedQueue, failed());
492 MOZ_ASSERT(failed().empty());
493 }
494
495 AutoUnlockHelperThreadState unlock(lock);
496 while (!failedQueue.empty()) {
497 js::UniquePtr<JS::Dispatchable> d = std::move(failedQueue.front());
498 failedQueue.popFront();
499 js_delete(d.release());
500 }
501 }
502
503 // Everything should be empty at this point.
504 MOZ_ASSERT(numRegistered_ == 0);
505
506 // After shutdown, there should be no OffThreadPromiseTask activity in this
507 // JSRuntime. Revert to the !initialized() state to catch bugs.
508 dispatchToEventLoopCallback_ = nullptr;
509 MOZ_ASSERT(!initialized());
510 }
511
512 /* static */
513 js::PromiseObject* OffThreadPromiseTask::ExtractAndForget(
514 OffThreadPromiseTask* task, const AutoLockHelperThreadState& lock) {
515 OffThreadPromiseRuntimeState& state =
516 task->runtime()->offThreadPromiseState.ref();
517 MOZ_ASSERT(state.initialized());
518 MOZ_ASSERT(task->registered_);
519
520 // TODO: This has overlap with removeFromCancellableListAndDispatch.
521 // The two methods should be refactored so that they are consistant and
522 // we don't have unnecessary repetition or distribution of responsibilities.
523 state.numRegistered_--;
524 if (task->cancellable_) {
525 state.cancellable().remove(task);
526 }
527 task->registered_ = false;
528
529 js::PromiseObject* promise = task->promise_;
530 js_delete(task);
531
532 return promise;
533 }