bool Promise::PerformMicroTaskCheckpoint() { MOZ_ASSERT(NS_IsMainThread(), "Wrong thread!"); CycleCollectedJSContext* context = CycleCollectedJSContext::Get(); // On the main thread, we always use the main promise micro task queue. std::queue<nsCOMPtr<nsIRunnable>>& microtaskQueue = context->GetPromiseMicroTaskQueue(); if (microtaskQueue.empty()) { return false; } AutoSlowOperation aso; do { nsCOMPtr<nsIRunnable> runnable = microtaskQueue.front().forget(); MOZ_ASSERT(runnable); // This function can re-enter, so we remove the element before calling. microtaskQueue.pop(); nsresult rv = runnable->Run(); if (NS_WARN_IF(NS_FAILED(rv))) { return false; } aso.CheckForInterrupt(); context->AfterProcessMicrotask(); } while (!microtaskQueue.empty()); return true; }
void Promise::PerformWorkerDebuggerMicroTaskCheckpoint() { MOZ_ASSERT(!NS_IsMainThread(), "Wrong thread!"); CycleCollectedJSContext* context = CycleCollectedJSContext::Get(); for (;;) { // For a debugger microtask checkpoint, we always use the debugger microtask // queue. std::queue<nsCOMPtr<nsIRunnable>>* microtaskQueue = &context->GetDebuggerPromiseMicroTaskQueue(); if (microtaskQueue->empty()) { break; } nsCOMPtr<nsIRunnable> runnable = microtaskQueue->front().forget(); MOZ_ASSERT(runnable); // This function can re-enter, so we remove the element before calling. microtaskQueue->pop(); nsresult rv = runnable->Run(); if (NS_WARN_IF(NS_FAILED(rv))) { return; } context->AfterProcessMicrotask(); } }
CallbackObject::CallSetup::~CallSetup() { // To get our nesting right we have to destroy our JSAutoRealm first. // In particular, we want to do this before we try reporting any exceptions, // so we end up reporting them while in the realm of our entry point, // not whatever cross-compartment wrappper mCallback might be. // Be careful: the JSAutoRealm might not have been constructed at all! mAr.reset(); // Now, if we have a JSContext, report any pending errors on it, unless we // were told to re-throw them. if (mCx) { bool needToDealWithException = mAutoEntryScript->HasException(); if ((mRealm && mExceptionHandling == eRethrowContentExceptions) || mExceptionHandling == eRethrowExceptions) { mErrorResult.MightThrowJSException(); if (needToDealWithException) { JS::Rooted<JS::Value> exn(mCx); if (mAutoEntryScript->PeekException(&exn) && ShouldRethrowException(exn)) { mAutoEntryScript->ClearException(); MOZ_ASSERT(!mAutoEntryScript->HasException()); mErrorResult.ThrowJSException(mCx, exn); needToDealWithException = false; } } } if (needToDealWithException) { // Either we're supposed to report our exceptions, or we're supposed to // re-throw them but we failed to get the exception value. Either way, // we'll just report the pending exception, if any, once ~mAutoEntryScript // runs. Note that we've already run ~mAr, effectively, so we don't have // to worry about ordering here. if (mErrorResult.IsJSContextException()) { // XXXkhuey bug 1117269. When this is fixed, please consider fixing // ThrowExceptionValueIfSafe over in Exceptions.cpp in the same way. // IsJSContextException shouldn't be true anymore because we will report // the exception on the JSContext ... so throw something else. mErrorResult.ThrowWithCustomCleanup(NS_ERROR_UNEXPECTED); } } } mAutoIncumbentScript.reset(); mAutoEntryScript.reset(); // It is important that this is the last thing we do, after leaving the // realm and undoing all our entry/incumbent script changes CycleCollectedJSContext* ccjs = CycleCollectedJSContext::Get(); if (ccjs) { ccjs->LeaveMicroTask(); } }
/* static */ WorkletThread* WorkletThread::Get() { AssertIsOnWorkletThread(); CycleCollectedJSContext* ccjscx = CycleCollectedJSContext::Get(); MOZ_ASSERT(ccjscx); void* cxPrivate = JS_GetContextPrivate(ccjscx->Context()); MOZ_ASSERT(cxPrivate); return static_cast<WorkletThreadContextPrivate*>(cxPrivate)->GetWorkletThread(); }
void Animation::DoFinishNotification(SyncNotifyFlag aSyncNotifyFlag) { CycleCollectedJSContext* context = CycleCollectedJSContext::Get(); if (aSyncNotifyFlag == SyncNotifyFlag::Sync) { DoFinishNotificationImmediately(); } else if (!mFinishNotificationTask.IsPending()) { RefPtr<nsRunnableMethod<Animation>> runnable = NewRunnableMethod(this, &Animation::DoFinishNotificationImmediately); context->DispatchToMicroTask(do_AddRef(runnable)); mFinishNotificationTask = runnable.forget(); } }
/* static */ void CycleCollectedJSContext::PromiseRejectionTrackerCallback(JSContext* aCx, JS::HandleObject aPromise, PromiseRejectionHandlingState state, void* aData) { #ifdef DEBUG CycleCollectedJSContext* self = static_cast<CycleCollectedJSContext*>(aData); #endif // DEBUG MOZ_ASSERT(aCx == self->Context()); MOZ_ASSERT(Get() == self); if (state == PromiseRejectionHandlingState::Unhandled) { PromiseDebugging::AddUncaughtRejection(aPromise); } else { PromiseDebugging::AddConsumedRejection(aPromise); } }
/* static */ bool CycleCollectedJSContext::EnqueuePromiseJobCallback(JSContext* aCx, JS::HandleObject aJob, JS::HandleObject aAllocationSite, JS::HandleObject aIncumbentGlobal, void* aData) { CycleCollectedJSContext* self = static_cast<CycleCollectedJSContext*>(aData); MOZ_ASSERT(aCx == self->Context()); MOZ_ASSERT(Get() == self); nsIGlobalObject* global = nullptr; if (aIncumbentGlobal) { global = xpc::NativeGlobal(aIncumbentGlobal); } nsCOMPtr<nsIRunnable> runnable = new PromiseJobRunnable(aJob, aAllocationSite, global); self->DispatchToMicroTask(runnable.forget()); return true; }
bool Throw(JSContext* aCx, nsresult aRv, const nsACString& aMessage) { if (aRv == NS_ERROR_UNCATCHABLE_EXCEPTION) { // Nuke any existing exception on aCx, to make sure we're uncatchable. JS_ClearPendingException(aCx); return false; } if (JS_IsExceptionPending(aCx)) { // Don't clobber the existing exception. return false; } CycleCollectedJSContext* context = CycleCollectedJSContext::Get(); nsCOMPtr<nsIException> existingException = context->GetPendingException(); // Make sure to clear the pending exception now. Either we're going to reuse // it (and we already grabbed it), or we plan to throw something else and this // pending exception is no longer relevant. context->SetPendingException(nullptr); // Ignore the pending exception if we have a non-default message passed in. if (aMessage.IsEmpty() && existingException) { nsresult nr; if (NS_SUCCEEDED(existingException->GetResult(&nr)) && aRv == nr) { // Reuse the existing exception. ThrowExceptionObject(aCx, existingException); return false; } } RefPtr<Exception> finalException = CreateException(aRv, aMessage); MOZ_ASSERT(finalException); ThrowExceptionObject(aCx, finalException); return false; }
/* static */ bool WorkletThread::IsOnWorkletThread() { CycleCollectedJSContext* ccjscx = CycleCollectedJSContext::Get(); return ccjscx && ccjscx->GetAsWorkletJSContext(); }
CallbackObject::CallSetup::CallSetup(CallbackObject* aCallback, ErrorResult& aRv, const char* aExecutionReason, ExceptionHandling aExceptionHandling, JS::Realm* aRealm, bool aIsJSImplementedWebIDL) : mCx(nullptr), mRealm(aRealm), mErrorResult(aRv), mExceptionHandling(aExceptionHandling), mIsMainThread(NS_IsMainThread()) { CycleCollectedJSContext* ccjs = CycleCollectedJSContext::Get(); if (ccjs) { ccjs->EnterMicroTask(); } // Compute the caller's subject principal (if necessary) early, before we // do anything that might perturb the relevant state. nsIPrincipal* webIDLCallerPrincipal = nullptr; if (aIsJSImplementedWebIDL) { webIDLCallerPrincipal = nsContentUtils::SubjectPrincipalOrSystemIfNativeCaller(); } JSObject* wrappedCallback = aCallback->CallbackPreserveColor(); if (!wrappedCallback) { aRv.ThrowDOMException( NS_ERROR_DOM_NOT_SUPPORTED_ERR, NS_LITERAL_CSTRING( "Cannot execute callback from a nuked compartment.")); return; } nsIGlobalObject* globalObject = nullptr; { // First, find the real underlying callback. JSObject* realCallback = js::UncheckedUnwrap(wrappedCallback); // Check that it's ok to run this callback. JS-implemented WebIDL is always // OK to run, since it runs with Chrome privileges anyway. if (mIsMainThread && !aIsJSImplementedWebIDL) { // Make sure to use realCallback to get the global of the callback // object, not the wrapper. if (!xpc::Scriptability::Get(realCallback).Allowed()) { aRv.ThrowDOMException( NS_ERROR_DOM_NOT_SUPPORTED_ERR, NS_LITERAL_CSTRING( "Refusing to execute function from global in which " "script is disabled.")); return; } } // Now get the global for this callback. Note that for the case of // JS-implemented WebIDL we never have a window here. nsGlobalWindowInner* win = mIsMainThread && !aIsJSImplementedWebIDL ? xpc::WindowGlobalOrNull(realCallback) : nullptr; if (win) { // We don't want to run script in windows that have been navigated away // from. if (!win->AsInner()->HasActiveDocument()) { aRv.ThrowDOMException( NS_ERROR_DOM_NOT_SUPPORTED_ERR, NS_LITERAL_CSTRING("Refusing to execute function from window " "whose document is no longer active.")); return; } globalObject = win; } else { // No DOM Window. Store the global. globalObject = xpc::NativeGlobal(realCallback); MOZ_ASSERT(globalObject); } } // Bail out if there's no useful global. if (!globalObject->GetGlobalJSObject()) { aRv.ThrowDOMException( NS_ERROR_DOM_NOT_SUPPORTED_ERR, NS_LITERAL_CSTRING("Refusing to execute function from global which is " "being torn down.")); return; } mAutoEntryScript.emplace(globalObject, aExecutionReason, mIsMainThread); mAutoEntryScript->SetWebIDLCallerPrincipal(webIDLCallerPrincipal); nsIGlobalObject* incumbent = aCallback->IncumbentGlobalOrNull(); if (incumbent) { // The callback object traces its incumbent JS global, so in general it // should be alive here. However, it's possible that we could run afoul // of the same IPC global weirdness described above, wherein the // nsIGlobalObject has severed its reference to the JS global. Let's just // be safe here, so that nobody has to waste a day debugging gaia-ui tests. if (!incumbent->GetGlobalJSObject()) { aRv.ThrowDOMException( NS_ERROR_DOM_NOT_SUPPORTED_ERR, NS_LITERAL_CSTRING("Refusing to execute function because our " "incumbent global is being torn down.")); return; } mAutoIncumbentScript.emplace(incumbent); } JSContext* cx = mAutoEntryScript->cx(); // Unmark the callable (by invoking CallbackOrNull() and not the // CallbackPreserveColor() variant), and stick it in a Rooted before it can // go gray again. // Nothing before us in this function can trigger a CC, so it's safe to wait // until here it do the unmark. This allows us to construct mRootedCallable // with the cx from mAutoEntryScript, avoiding the cost of finding another // JSContext. (Rooted<> does not care about requests or compartments.) mRootedCallable.emplace(cx, aCallback->CallbackOrNull()); mRootedCallableGlobal.emplace(cx, aCallback->CallbackGlobalOrNull()); mAsyncStack.emplace(cx, aCallback->GetCreationStack()); if (*mAsyncStack) { mAsyncStackSetter.emplace(cx, *mAsyncStack, aExecutionReason); } // Enter the realm of our callback, so we can actually work with it. // // Note that if the callback is a wrapper, this will not be the same // realm that we ended up in with mAutoEntryScript above, because the // entry point is based off of the unwrapped callback (realCallback). mAr.emplace(cx, *mRootedCallableGlobal); // And now we're ready to go. mCx = cx; }
// https://html.spec.whatwg.org/multipage/embedded-content.html#time-marches-on void TextTrackManager::TimeMarchesOn() { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); mTimeMarchesOnDispatched = false; CycleCollectedJSContext* context = CycleCollectedJSContext::Get(); if (context && context->IsInStableOrMetaStableState()) { // FireTimeUpdate can be called while at stable state following a // current position change which triggered a state watcher in MediaDecoder // (see bug 1443429). // TimeMarchesOn() will modify JS attributes which is forbidden while in // stable state. So we dispatch a task to perform such operation later // instead. DispatchTimeMarchesOn(); return; } WEBVTT_LOG("TimeMarchesOn"); // Early return if we don't have any TextTracks or shutting down. if (!mTextTracks || mTextTracks->Length() == 0 || IsShutdown()) { return; } nsISupports* parentObject = mMediaElement->OwnerDoc()->GetParentObject(); if (NS_WARN_IF(!parentObject)) { return; } nsCOMPtr<nsPIDOMWindowInner> window = do_QueryInterface(parentObject); if (mMediaElement && (!(mMediaElement->GetPlayedOrSeeked()) || mMediaElement->Seeking())) { WEBVTT_LOG("TimeMarchesOn seeking or post return"); return; } // Step 3. double currentPlaybackTime = mMediaElement->CurrentTime(); bool hasNormalPlayback = !mHasSeeked; mHasSeeked = false; WEBVTT_LOG( "TimeMarchesOn mLastTimeMarchesOnCalled %lf currentPlaybackTime %lf " "hasNormalPlayback %d", mLastTimeMarchesOnCalled, currentPlaybackTime, hasNormalPlayback); // Step 1, 2. RefPtr<TextTrackCueList> currentCues = new TextTrackCueList(window); RefPtr<TextTrackCueList> otherCues = new TextTrackCueList(window); bool dummy; for (uint32_t index = 0; index < mTextTracks->Length(); ++index) { TextTrack* ttrack = mTextTracks->IndexedGetter(index, dummy); if (ttrack && ttrack->Mode() != TextTrackMode::Disabled) { // TODO: call GetCueListByTimeInterval on mNewCues? ttrack->GetCurrentCueList(currentCues); } } WEBVTT_LOGV("TimeMarchesOn currentCues %d", currentCues->Length()); // Populate otherCues with 'non-active" cues. if (hasNormalPlayback) { if (currentPlaybackTime < mLastTimeMarchesOnCalled) { // TODO: Add log and find the root cause why the // playback position goes backward. mLastTimeMarchesOnCalled = currentPlaybackTime; } media::Interval<double> interval(mLastTimeMarchesOnCalled, currentPlaybackTime); otherCues = mNewCues->GetCueListByTimeInterval(interval); ; } else { // Seek case. Put the mLastActiveCues into otherCues. otherCues = mLastActiveCues; } for (uint32_t i = 0; i < currentCues->Length(); ++i) { TextTrackCue* cue = (*currentCues)[i]; otherCues->RemoveCue(*cue); } WEBVTT_LOGV("TimeMarchesOn otherCues %d", otherCues->Length()); // Step 4. RefPtr<TextTrackCueList> missedCues = new TextTrackCueList(window); if (hasNormalPlayback) { for (uint32_t i = 0; i < otherCues->Length(); ++i) { TextTrackCue* cue = (*otherCues)[i]; if (cue->StartTime() >= mLastTimeMarchesOnCalled && cue->EndTime() <= currentPlaybackTime) { missedCues->AddCue(*cue); } } } WEBVTT_LOGV("TimeMarchesOn missedCues %d", missedCues->Length()); // Step 5. Empty now. // TODO: Step 6: fire timeupdate? // Step 7. Abort steps if condition 1, 2, 3 are satisfied. // 1. All of the cues in current cues have their active flag set. // 2. None of the cues in other cues have their active flag set. // 3. Missed cues is empty. bool c1 = true; for (uint32_t i = 0; i < currentCues->Length(); ++i) { if (!(*currentCues)[i]->GetActive()) { c1 = false; break; } } bool c2 = true; for (uint32_t i = 0; i < otherCues->Length(); ++i) { if ((*otherCues)[i]->GetActive()) { c2 = false; break; } } bool c3 = (missedCues->Length() == 0); if (c1 && c2 && c3) { mLastTimeMarchesOnCalled = currentPlaybackTime; WEBVTT_LOG("TimeMarchesOn step 7 return, mLastTimeMarchesOnCalled %lf", mLastTimeMarchesOnCalled); return; } // Step 8. Respect PauseOnExit flag if not seek. if (hasNormalPlayback) { for (uint32_t i = 0; i < otherCues->Length(); ++i) { TextTrackCue* cue = (*otherCues)[i]; if (cue && cue->PauseOnExit() && cue->GetActive()) { WEBVTT_LOG("TimeMarchesOn pause the MediaElement"); mMediaElement->Pause(); break; } } for (uint32_t i = 0; i < missedCues->Length(); ++i) { TextTrackCue* cue = (*missedCues)[i]; if (cue && cue->PauseOnExit()) { WEBVTT_LOG("TimeMarchesOn pause the MediaElement"); mMediaElement->Pause(); break; } } } // Step 15. // Sort text tracks in the same order as the text tracks appear // in the media element's list of text tracks, and remove // duplicates. TextTrackListInternal affectedTracks; // Step 13, 14. nsTArray<RefPtr<SimpleTextTrackEvent>> eventList; // Step 9, 10. // For each text track cue in missed cues, prepare an event named // enter for the TextTrackCue object with the cue start time. for (uint32_t i = 0; i < missedCues->Length(); ++i) { TextTrackCue* cue = (*missedCues)[i]; if (cue) { SimpleTextTrackEvent* event = new SimpleTextTrackEvent( NS_LITERAL_STRING("enter"), cue->StartTime(), cue->GetTrack(), cue); eventList.InsertElementSorted( event, CompareSimpleTextTrackEvents(mMediaElement)); affectedTracks.AddTextTrack(cue->GetTrack(), CompareTextTracks(mMediaElement)); } } // Step 11, 17. for (uint32_t i = 0; i < otherCues->Length(); ++i) { TextTrackCue* cue = (*otherCues)[i]; if (cue->GetActive() || missedCues->IsCueExist(cue)) { double time = cue->StartTime() > cue->EndTime() ? cue->StartTime() : cue->EndTime(); SimpleTextTrackEvent* event = new SimpleTextTrackEvent( NS_LITERAL_STRING("exit"), time, cue->GetTrack(), cue); eventList.InsertElementSorted( event, CompareSimpleTextTrackEvents(mMediaElement)); affectedTracks.AddTextTrack(cue->GetTrack(), CompareTextTracks(mMediaElement)); } cue->SetActive(false); } // Step 12, 17. for (uint32_t i = 0; i < currentCues->Length(); ++i) { TextTrackCue* cue = (*currentCues)[i]; if (!cue->GetActive()) { SimpleTextTrackEvent* event = new SimpleTextTrackEvent( NS_LITERAL_STRING("enter"), cue->StartTime(), cue->GetTrack(), cue); eventList.InsertElementSorted( event, CompareSimpleTextTrackEvents(mMediaElement)); affectedTracks.AddTextTrack(cue->GetTrack(), CompareTextTracks(mMediaElement)); } cue->SetActive(true); } // Fire the eventList for (uint32_t i = 0; i < eventList.Length(); ++i) { eventList[i]->Dispatch(); } // Step 16. for (uint32_t i = 0; i < affectedTracks.Length(); ++i) { TextTrack* ttrack = affectedTracks[i]; if (ttrack) { ttrack->DispatchAsyncTrustedEvent(NS_LITERAL_STRING("cuechange")); HTMLTrackElement* trackElement = ttrack->GetTrackElement(); if (trackElement) { trackElement->DispatchTrackRunnable(NS_LITERAL_STRING("cuechange")); } } } mLastTimeMarchesOnCalled = currentPlaybackTime; mLastActiveCues = currentCues; // Step 18. UpdateCueDisplay(); }