8d494808ffd239bce8123b4ef5fcdb7cb5c6d71c
[WebKit-https.git] / Source / WebKit / UIProcess / SuspendedPageProxy.cpp
1 /*
2  * Copyright (C) 2018 Apple Inc. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  *    notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  *    notice, this list of conditions and the following disclaimer in the
11  *    documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
14  * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
15  * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
17  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
18  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
19  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
20  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
21  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
23  * THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "config.h"
27 #include "SuspendedPageProxy.h"
28
29 #include "DrawingAreaProxy.h"
30 #include "Logging.h"
31 #include "WebPageMessages.h"
32 #include "WebPageProxy.h"
33 #include "WebPageProxyMessages.h"
34 #include "WebProcessMessages.h"
35 #include "WebProcessPool.h"
36 #include "WebProcessProxy.h"
37 #include <wtf/DebugUtilities.h>
38 #include <wtf/HexNumber.h>
39 #include <wtf/URL.h>
40
41 namespace WebKit {
42 using namespace WebCore;
43
44 static const Seconds suspensionTimeout { 10_s };
45
46 #if !LOG_DISABLED
47 static const HashSet<IPC::StringReference>& messageNamesToIgnoreWhileSuspended()
48 {
49     static NeverDestroyed<HashSet<IPC::StringReference>> messageNames;
50     static std::once_flag onceFlag;
51     std::call_once(onceFlag, [] {
52         messageNames.get().add("BackForwardAddItem");
53         messageNames.get().add("ClearAllEditCommands");
54         messageNames.get().add("DidChangeContentSize");
55         messageNames.get().add("DidChangeMainDocument");
56         messageNames.get().add("DidChangeProgress");
57         messageNames.get().add("DidCommitLoadForFrame");
58         messageNames.get().add("DidDestroyNavigation");
59         messageNames.get().add("DidFinishDocumentLoadForFrame");
60         messageNames.get().add("DidFinishProgress");
61         messageNames.get().add("DidCompletePageTransition");
62         messageNames.get().add("DidFirstLayoutForFrame");
63         messageNames.get().add("DidFirstVisuallyNonEmptyLayoutForFrame");
64         messageNames.get().add("DidNavigateWithNavigationData");
65         messageNames.get().add("DidReachLayoutMilestone");
66         messageNames.get().add("DidRestoreScrollPosition");
67         messageNames.get().add("DidSaveToPageCache");
68         messageNames.get().add("DidStartProgress");
69         messageNames.get().add("DidStartProvisionalLoadForFrame");
70         messageNames.get().add("EditorStateChanged");
71         messageNames.get().add("PageExtendedBackgroundColorDidChange");
72         messageNames.get().add("SetRenderTreeSize");
73         messageNames.get().add("SetStatusText");
74         messageNames.get().add("SetNetworkRequestsInProgress");
75     });
76
77     return messageNames;
78 }
79 #endif
80
81 SuspendedPageProxy::SuspendedPageProxy(WebPageProxy& page, Ref<WebProcessProxy>&& process, uint64_t mainFrameID)
82     : m_page(page)
83     , m_process(WTFMove(process))
84     , m_mainFrameID(mainFrameID)
85 #if PLATFORM(MAC)
86     , m_shouldDelayClosingOnFailure(m_page.drawingArea() && m_page.drawingArea()->type() == DrawingAreaTypeTiledCoreAnimation)
87 #endif
88     , m_suspensionTimeoutTimer(RunLoop::main(), this, &SuspendedPageProxy::suspensionTimedOut)
89 #if PLATFORM(IOS_FAMILY)
90     , m_suspensionToken(m_process->throttler().backgroundActivityToken())
91 #endif
92 {
93     m_process->incrementSuspendedPageCount();
94     m_process->addMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_page.pageID(), *this);
95
96     m_suspensionTimeoutTimer.startOneShot(suspensionTimeout);
97     m_process->send(Messages::WebPage::SetIsSuspended(true), m_page.pageID());
98 }
99
100 SuspendedPageProxy::~SuspendedPageProxy()
101 {
102     m_process->decrementSuspendedPageCount();
103
104     if (m_readyToUnsuspendHandler) {
105         RunLoop::main().dispatch([readyToUnsuspendHandler = WTFMove(m_readyToUnsuspendHandler)]() mutable {
106             readyToUnsuspendHandler(nullptr);
107         });
108     }
109
110     if (m_suspensionState == SuspensionState::Resumed)
111         return;
112
113     // If the suspended page was not consumed before getting destroyed, then close the corresponding page
114     // on the WebProcess side.
115     close();
116
117     if (m_suspensionState == SuspensionState::Suspending)
118         m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_page.pageID());
119
120     // We call maybeShutDown() asynchronously since the SuspendedPage is currently being removed from the WebProcessPool
121     // and we want to avoid re-entering WebProcessPool methods.
122     RunLoop::main().dispatch([process = m_process.copyRef()] {
123         process->maybeShutDown();
124     });
125 }
126
127 void SuspendedPageProxy::waitUntilReadyToUnsuspend(CompletionHandler<void(SuspendedPageProxy*)>&& completionHandler)
128 {
129     if (m_readyToUnsuspendHandler)
130         m_readyToUnsuspendHandler(nullptr);
131
132     switch (m_suspensionState) {
133     case SuspensionState::Suspending:
134         m_readyToUnsuspendHandler = WTFMove(completionHandler);
135         break;
136     case SuspensionState::FailedToSuspend:
137     case SuspensionState::Suspended:
138         completionHandler(this);
139         break;
140     case SuspensionState::Resumed:
141         ASSERT_NOT_REACHED();
142         completionHandler(nullptr);
143         break;
144     }
145 }
146
147 void SuspendedPageProxy::unsuspend()
148 {
149     ASSERT(m_suspensionState == SuspensionState::Suspended);
150
151     m_suspensionState = SuspensionState::Resumed;
152     m_process->send(Messages::WebPage::SetIsSuspended(false), m_page.pageID());
153 }
154
155 void SuspendedPageProxy::close()
156 {
157     ASSERT(m_suspensionState != SuspensionState::Resumed);
158
159     if (m_isClosed)
160         return;
161
162     m_isClosed = true;
163     m_process->send(Messages::WebPage::Close(), m_page.pageID());
164 }
165
166 void SuspendedPageProxy::pageEnteredAcceleratedCompositingMode()
167 {
168     m_shouldDelayClosingOnFailure = false;
169
170     if (m_suspensionState == SuspensionState::FailedToSuspend) {
171         // We needed the failed suspended page to stay alive to avoid flashing. Now we can get rid of it.
172         m_process->processPool().removeSuspendedPage(*this); // Will destroy |this|.
173     }
174 }
175
176 void SuspendedPageProxy::didProcessRequestToSuspend(SuspensionState newSuspensionState)
177 {
178     LOG(ProcessSwapping, "SuspendedPageProxy %s from process %i finished transition to suspended", loggingString(), m_process->processIdentifier());
179
180     ASSERT(m_suspensionState == SuspensionState::Suspending);
181     ASSERT(newSuspensionState == SuspensionState::Suspended || newSuspensionState == SuspensionState::FailedToSuspend);
182
183     m_suspensionState = newSuspensionState;
184
185     m_suspensionTimeoutTimer.stop();
186
187 #if PLATFORM(IOS_FAMILY)
188     m_suspensionToken = nullptr;
189 #endif
190
191     m_process->removeMessageReceiver(Messages::WebPageProxy::messageReceiverName(), m_page.pageID());
192
193     if (m_suspensionState == SuspensionState::FailedToSuspend && !m_shouldDelayClosingOnFailure)
194         close();
195
196     if (m_readyToUnsuspendHandler)
197         m_readyToUnsuspendHandler(this);
198 }
199
200 void SuspendedPageProxy::suspensionTimedOut()
201 {
202     RELEASE_LOG_ERROR(ProcessSwapping, "%p - SuspendedPageProxy::suspensionTimedOut() destroying the suspended page because it failed to suspend in time", this);
203     m_process->processPool().removeSuspendedPage(*this); // Will destroy |this|.
204 }
205
206 void SuspendedPageProxy::didReceiveMessage(IPC::Connection&, IPC::Decoder& decoder)
207 {
208     ASSERT(decoder.messageReceiverName() == Messages::WebPageProxy::messageReceiverName());
209
210     if (decoder.messageName() == Messages::WebPageProxy::DidSuspendAfterProcessSwap::name()) {
211         didProcessRequestToSuspend(SuspensionState::Suspended);
212         return;
213     }
214
215     if (decoder.messageName() == Messages::WebPageProxy::DidFailToSuspendAfterProcessSwap::name()) {
216         didProcessRequestToSuspend(SuspensionState::FailedToSuspend);
217         return;
218     }
219
220 #if !LOG_DISABLED
221     if (!messageNamesToIgnoreWhileSuspended().contains(decoder.messageName()))
222         LOG(ProcessSwapping, "SuspendedPageProxy received unexpected WebPageProxy message '%s'", decoder.messageName().toString().data());
223 #endif
224 }
225
226 void SuspendedPageProxy::didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&)
227 {
228 }
229
230 #if !LOG_DISABLED
231
232 const char* SuspendedPageProxy::loggingString() const
233 {
234     return debugString("(0x", hex(reinterpret_cast<uintptr_t>(this)), " page ID ", m_page.pageID(), ", m_suspensionState ", static_cast<unsigned>(m_suspensionState), ')');
235 }
236
237 #endif
238
239 } // namespace WebKit