Support for promise rejection events (unhandledrejection)
https://bugs.webkit.org/show_bug.cgi?id=150358
<rdar://problem/28441651>

Reviewed by Saam Barati.

Patch by Joseph Pecoraro and Yusuke Suzuki.

LayoutTests/imported/w3c:

* web-platform-tests/WebCryptoAPI/derive_bits_keys/test_ecdh_bits-expected.txt:
* web-platform-tests/WebCryptoAPI/derive_bits_keys/test_ecdh_keys-expected.txt:
* web-platform-tests/html/semantics/embedded-content/media-elements/event_pause_noautoplay-expected.txt:
* web-platform-tests/html/semantics/embedded-content/media-elements/event_play_noautoplay-expected.txt:
* web-platform-tests/html/semantics/embedded-content/media-elements/paused_true_during_pause-expected.txt:
* web-platform-tests/html/syntax/parsing/html5lib_innerHTML_adoption01-expected.txt:
* web-platform-tests/html/webappapis/scripting/events/body-exposed-window-event-handlers-expected.txt:
* web-platform-tests/streams/piping/close-propagation-forward-expected.txt:
* web-platform-tests/streams/piping/error-propagation-backward-expected.txt:
* web-platform-tests/streams/piping/error-propagation-forward-expected.txt:
* web-platform-tests/streams/piping/flow-control-expected.txt:
* web-platform-tests/streams/piping/general-expected.txt:
* web-platform-tests/user-timing/measure_exceptions_navigation_timing-expected.txt:
Rebaseline expectations to include unhandled promise rejection messages.
Also change how the test harness reports success or failure to use the values
immediately on completion and then allow a run loop cycle before completing
the test to gather the output.

* web-platform-tests/resource-timing/rt-resource-errors.html:
This is our own WPT test yet to be uploaded, so update the test to prevent
an unexpected unhandled rejection.

Source/JavaScriptCore:

Implement support for promise.[[PromiseIsHandled]] and the
HostPromiseRejectionTracker hook for HTML to track promise rejections:
https://tc39.github.io/ecma262/#sec-host-promise-rejection-tracker
https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections

* builtins/BuiltinNames.h:
New private symbols.

* builtins/PromiseOperations.js:
(globalPrivate.newHandledRejectedPromise):
Utility to create a rejected promise with [[PromiseIsHandled]] to true.

(globalPrivate.rejectPromise):
(globalPrivate.initializePromise):
* builtins/PromisePrototype.js:
(then):
Implement standard behavior of [[PromiseIsHandled]] and the host hook.

* runtime/JSPromise.cpp:
(JSC::JSPromise::isHandled):
* runtime/JSPromise.h:
C++ accessors for the [[PromiseIsHandled]] state.

* bytecode/BytecodeIntrinsicRegistry.cpp:
(JSC::BytecodeIntrinsicRegistry::BytecodeIntrinsicRegistry):
* bytecode/BytecodeIntrinsicRegistry.h:
Expose private values for the Reject / Handle enum values in built-ins.

* jsc.cpp:
* runtime/JSGlobalObject.h:
(JSC::JSGlobalObject::promiseResolveFunction):
Add a new GlobalObjectMethodTable hook matching the promise rejection hook.

* runtime/JSGlobalObject.cpp:
(JSC::JSGlobalObject::init):
(JSC::JSGlobalObject::visitChildren):
* runtime/JSGlobalObjectFunctions.cpp:
(JSC::globalFuncHostPromiseRejectionTracker):
* runtime/JSGlobalObjectFunctions.h:
Plumb the builtin hook through to the optional GlobalObjectMethodTable hook.

* inspector/InjectedScriptSource.js:
(InjectedScript.prototype.createFakeValueDescriptor):
Silence possible rejected promises created internally via Web Inspector.

Source/WebCore:

Implement support for the `onunhandledrejection` and `rejectionhandled` events.
They dispatch a new PromiseRejectionEvent using the ES6 HostPromiseRejectionTracker hook:
https://tc39.github.io/ecma262/#sec-host-promise-rejection-tracker
https://html.spec.whatwg.org/multipage/webappapis.html#unhandled-promise-rejections

This is currently implemented only for Documents and not yet Web Workers.

Tests: js/dom/unhandled-promise-rejection-basic.html
       js/dom/unhandled-promise-rejection-bindings-type-error.html
       js/dom/unhandled-promise-rejection-console-no-report.html
       js/dom/unhandled-promise-rejection-console-report.html
       js/dom/unhandled-promise-rejection-handle-during-event.html
       js/dom/unhandled-promise-rejection-handle-in-handler.html
       js/dom/unhandled-promise-rejection-handle.html
       js/dom/unhandled-promise-rejection-order.html

* CMakeLists.txt:
* DerivedSources.cpp:
* DerivedSources.make:
* WebCore.xcodeproj/project.pbxproj:
* dom/DOMAllInOne.cpp:
New files.

* bindings/scripts/CodeGenerator.pm:
(IsPromiseType):
* bindings/scripts/CodeGeneratorJS.pm:
(AddToIncludesForIDLType):
(GetBaseIDLType):
Binding support for Promise<T> attributes.

* bindings/js/JSDOMConvert.h:
* bindings/js/JSDOMConvertPromise.h: Copied from Source/JavaScriptCore/runtime/JSPromise.h.
(WebCore::Converter<IDLPromise<T>>::convert):
(WebCore::JSConverter<IDLPromise<T>>::convert):
Promise<T> binding conversion is currently unimplemented, which only means
web developers creating their own PromiseRejectionEvent will not get
autowrapping of values assigned to `promise` in event initialization.
Engine generated events will have expected behavior.

* bindings/js/JSDOMWindowBase.cpp:
(WebCore::JSDOMWindowBase::promiseRejectionTracker):
* bindings/js/JSDOMWindowBase.h:
* bindings/js/JSWorkerGlobalScopeBase.cpp:
Implement HostPromiseRejectionTracker hook for Document but not Worker.
Passes through to the ScriptExecutionContext's tracker.

* bindings/js/JSMainThreadExecState.cpp:
(WebCore::JSMainThreadExecState::didLeaveScriptContext):
* bindings/js/JSMainThreadExecState.h:
(WebCore::JSMainThreadExecState::~JSMainThreadExecState):
When completing script execution and performing microtasks notify
about rejected promises. Technically this should go inside of
performing a microtask checkpoint, except lacking EventLoop
concepts we use ScriptExecutionState.

* dom/EventNames.h:
* dom/EventNames.in:
* dom/PromiseRejectionEvent.cpp: Added.
(WebCore::PromiseRejectionEvent::PromiseRejectionEvent):
(WebCore::PromiseRejectionEvent::~PromiseRejectionEvent):
* dom/PromiseRejectionEvent.h: Added.
* dom/PromiseRejectionEvent.idl: Added.
New PromiseRejectionEvent event interface.

* dom/GlobalEventHandlers.idl:
New onunhandledrejection and onrejectionhandled.

* dom/RejectedPromiseTracker.cpp: Added.
(WebCore::RejectedPromise::RejectedPromise):
(WebCore::RejectedPromise::globalObject):
(WebCore::RejectedPromise::promise):
(WebCore::UnhandledPromise::UnhandledPromise):
(WebCore::UnhandledPromise::callStack):
(WebCore::RejectedPromiseTracker::RejectedPromiseTracker):
(WebCore::RejectedPromiseTracker::~RejectedPromiseTracker):
(WebCore::createScriptCallStackFromReason):
(WebCore::RejectedPromiseTracker::promiseRejected):
(WebCore::RejectedPromiseTracker::promiseHandled):
(WebCore::RejectedPromiseTracker::processQueueSoon):
(WebCore::RejectedPromiseTracker::reportUnhandledRejections):
(WebCore::RejectedPromiseTracker::reportRejectionHandled):
* dom/RejectedPromiseTracker.h: Added.
Track and report rejected promises. The promises are tracked weakly
allowing them to be collected before they are reported. When reporting
we dispatch PromiseRejectionEvent events, and if the default is not
prevented we log a message to the console.

* dom/ScriptExecutionContext.cpp:
(WebCore::ScriptExecutionContext::reportUnhandledPromiseRejection):
(WebCore::ScriptExecutionContext::ensureRejectedPromiseTrackerSlow):
* dom/ScriptExecutionContext.h:
(WebCore::ScriptExecutionContext::ensureRejectedPromiseTracker):
Each ScriptExecutionContext can own a rejected promise tracker.

* html/HTMLMediaElement.cpp:
(WebCore::HTMLMediaElement::pauseInternal):
https://html.spec.whatwg.org/multipage/embedded-content.html#internal-pause-steps
Internal pause steps say to timeupdate, pause, and rejecting pending play promises
should all happen in a queued task. Here the first two actions are already scheduled
on tasks, but rejecting play promises was not being done in a task, so this makes
that change.

* Modules/streams/ReadableStream.js:
(pipeThrough):
* Modules/streams/ReadableStreamInternals.js:
(readableStreamReaderGenericInitialize):
(readableStreamError):
(readableStreamReaderGenericRelease):
Satisfy parts of the Streams specification which state to set the
[[PromiseIsHandled]] internal state of promises created internally
by the Streams APIs. This prevents some internal promises from
appearing as unhandled promise rejections.

LayoutTests:

* js/dom/unhandled-promise-rejection-basic-expected.txt: Added.
* js/dom/unhandled-promise-rejection-basic.html: Added.
* js/dom/unhandled-promise-rejection-bindings-type-error-expected.txt: Added.
* js/dom/unhandled-promise-rejection-bindings-type-error.html: Added.
* js/dom/unhandled-promise-rejection-console-no-report-expected.txt: Added.
* js/dom/unhandled-promise-rejection-console-no-report.html: Added.
* js/dom/unhandled-promise-rejection-console-report-expected.txt: Added.
* js/dom/unhandled-promise-rejection-console-report.html: Added.
* js/dom/unhandled-promise-rejection-handle-during-event-expected.txt: Added.
* js/dom/unhandled-promise-rejection-handle-during-event.html: Added.
* js/dom/unhandled-promise-rejection-handle-expected.txt: Added.
* js/dom/unhandled-promise-rejection-handle-in-handler-expected.txt: Added.
* js/dom/unhandled-promise-rejection-handle-in-handler.html: Added.
* js/dom/unhandled-promise-rejection-handle.html: Added.
* js/dom/unhandled-promise-rejection-order-expected.txt: Added.
* js/dom/unhandled-promise-rejection-order.html: Added.
New tests specific to the `onunhandledrejection` and `onrejectionhandled` events.

* resources/testharnessreport.js:
(self.testRunner.add_completion_callback.sanitize):
(self.testRunner.add_completion_callback):
Report results immediately and then finish the test after a turn. This way
if the test ends with a pass, but may get unhandled rejections after
completing which should not make the test appear as if it failed. Some tests
have unhandled promise rejections but are expected to pass. Likewise some
tests perform cleanup in their own completion callbacks, which happen after
this initial completion callback, and we want to report results after all
the work is done as it may eliminate non-deterministic debug test output.

* TestExpectations:
Mark some tests as flakey that have sometimes have unhandled promise rejections.
These tests are all various imported tests that use the testharness.

* fast/mediastream/MediaStream-MediaElement-setObject-null-expected.txt:
* http/tests/security/video-cross-origin-caching-expected.txt:
* inspector/debugger/break-on-exception-throw-in-promise-expected.txt:
* inspector/debugger/break-on-uncaught-exception-throw-in-promise-expected.txt:
* inspector/worker/resources-in-worker-expected.txt:
* js/dom/dom-static-property-for-in-iteration-expected.txt:
* js/dom/global-constructors-attributes-dedicated-worker-expected.txt:
* js/promises-tests/promises-tests-2-2-6-expected.txt:
* platform/mac/inspector/model/remote-object-expected.txt:
* webrtc/libwebrtc/release-while-creating-offer-expected.txt:
* webrtc/libwebrtc/release-while-setting-local-description-expected.txt:
Update tests with unhandled promise rejection messages.

* media/W3C/audio/events/event_pause_manual.html:
* media/audio-playback-restriction-play-expected.txt:
* media/audio-playback-restriction-play.html:
* media/click-volume-bar-not-pausing.html:
* media/remote-control-command-is-user-gesture-expected.txt:
* media/remote-control-command-is-user-gesture.html:
* media/track/track-mode.html:
* media/video-autoplay-allowed-but-fullscreen-required.html:
* media/video-display-none-crash.html:
* media/video-main-content-deny-display-none.html:
* media/video-main-content-deny-not-in-dom.html:
* media/video-main-content-deny-not-visible.html:
* media/video-main-content-deny-obscured.html:
* media/video-main-content-deny-too-small.html:
* media/video-multiple-concurrent-playback-expected.txt:
* media/video-play-audio-require-user-gesture-expected.txt:
* media/video-play-audio-require-user-gesture.html:
* media/video-play-pause-events-expected.txt:
* media/video-play-pause-events.html:
* media/video-play-pause-exception-expected.txt:
* media/video-play-pause-exception.html:
* media/video-play-require-user-gesture-expected.txt:
* media/video-play-require-user-gesture.html:
* media/video-preload-expected.txt:
* media/video-preload.html:
* media/video-test.js:
(handlePromise.handle):
Snuff many possible unhandled promise rejections in media via media.play().

* streams/reference-implementation/pipe-to-expected.txt:
* streams/reference-implementation/pipe-to-options-expected.txt:
* streams/reference-implementation/readable-stream-templated-expected.txt:
* streams/reference-implementation/writable-stream-abort-expected.txt:
* streams/reference-implementation/writable-stream-expected.txt:
These stream tests are out of date and produce unhandled rejections.

* streams/shadowing-Promise.html:
Update non-imported tests to prevent unhandled rejection messages.

git-svn-id: http://svn.webkit.org/repository/webkit/trunk@215916 268f45cc-cd09-0410-ab3c-d52691b4dbfc
diff --git a/Source/WebCore/bindings/js/JSMainThreadExecState.cpp b/Source/WebCore/bindings/js/JSMainThreadExecState.cpp
index f49f4a8..3f4b06d 100644
--- a/Source/WebCore/bindings/js/JSMainThreadExecState.cpp
+++ b/Source/WebCore/bindings/js/JSMainThreadExecState.cpp
@@ -27,15 +27,18 @@
 #include "JSMainThreadExecState.h"
 
 #include "Microtasks.h"
-#include "MutationObserver.h"
+#include "RejectedPromiseTracker.h"
+#include "ScriptExecutionContext.h"
+#include "ScriptState.h"
 
 namespace WebCore {
 
 JSC::ExecState* JSMainThreadExecState::s_mainThreadState = 0;
 
-void JSMainThreadExecState::didLeaveScriptContext()
+void JSMainThreadExecState::didLeaveScriptContext(JSC::ExecState* exec)
 {
     MicrotaskQueue::mainThreadQueue().performMicrotaskCheckpoint();
+    scriptExecutionContextFromExecState(exec)->ensureRejectedPromiseTracker().processQueueSoon();
 }
 
 JSC::JSValue functionCallHandlerFromAnyThread(JSC::ExecState* exec, JSC::JSValue functionObject, JSC::CallType callType, const JSC::CallData& callData, JSC::JSValue thisValue, const JSC::ArgList& args, NakedPtr<JSC::Exception>& returnedException)