Overly aggressive timer throttling in service workers
[WebKit-https.git] / Source / WebKit / UIProcess / WebProcessProxy.h
1 /*
2  * Copyright (C) 2010-2017 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 #pragma once
27
28 #include "APIUserInitiatedAction.h"
29 #include "BackgroundProcessResponsivenessTimer.h"
30 #include "ChildProcessProxy.h"
31 #include "MessageReceiverMap.h"
32 #include "PluginInfoStore.h"
33 #include "ProcessLauncher.h"
34 #include "ProcessTerminationReason.h"
35 #include "ProcessThrottler.h"
36 #include "ProcessThrottlerClient.h"
37 #include "ResponsivenessTimer.h"
38 #include "VisibleWebPageCounter.h"
39 #include "WebConnectionToWebProcess.h"
40 #include "WebProcessProxyMessages.h"
41 #include <WebCore/MessagePortChannelProvider.h>
42 #include <WebCore/MessagePortIdentifier.h>
43 #include <WebCore/Process.h>
44 #include <WebCore/SharedStringHash.h>
45 #include <memory>
46 #include <pal/SessionID.h>
47 #include <wtf/Forward.h>
48 #include <wtf/HashMap.h>
49 #include <wtf/HashSet.h>
50 #include <wtf/RefCounted.h>
51 #include <wtf/RefPtr.h>
52
53 namespace API {
54 class Navigation;
55 class PageConfiguration;
56 }
57
58 namespace WebCore {
59 class ResourceRequest;
60 class URL;
61 struct PluginInfo;
62 struct SecurityOriginData;
63 }
64
65 namespace WebKit {
66
67 class NetworkProcessProxy;
68 class ObjCObjectGraph;
69 class PageClient;
70 class SuspendedPageProxy;
71 class UserMediaCaptureManagerProxy;
72 class VisitedLinkStore;
73 class WebBackForwardListItem;
74 class WebFrameProxy;
75 class WebPageGroup;
76 class WebPageProxy;
77 class WebProcessPool;
78 class WebUserContentControllerProxy;
79 class WebsiteDataStore;
80 enum class WebsiteDataType;
81 struct WebNavigationDataStore;
82 struct WebPageCreationParameters;
83 struct WebsiteData;
84
85 #if PLATFORM(IOS)
86 enum ForegroundWebProcessCounterType { };
87 typedef RefCounter<ForegroundWebProcessCounterType> ForegroundWebProcessCounter;
88 typedef ForegroundWebProcessCounter::Token ForegroundWebProcessToken;
89 enum BackgroundWebProcessCounterType { };
90 typedef RefCounter<BackgroundWebProcessCounterType> BackgroundWebProcessCounter;
91 typedef BackgroundWebProcessCounter::Token BackgroundWebProcessToken;
92 #endif
93
94 class WebProcessProxy : public ChildProcessProxy, public ResponsivenessTimer::Client, private ProcessThrottlerClient {
95 public:
96     typedef HashMap<uint64_t, RefPtr<WebFrameProxy>> WebFrameProxyMap;
97     typedef HashMap<uint64_t, WebPageProxy*> WebPageProxyMap;
98     typedef HashMap<uint64_t, RefPtr<API::UserInitiatedAction>> UserInitiatedActionMap;
99
100     enum class IsInPrewarmedPool {
101         No,
102         Yes
103     };
104
105     static Ref<WebProcessProxy> create(WebProcessPool&, WebsiteDataStore&, IsInPrewarmedPool);
106     ~WebProcessProxy();
107
108     WebConnection* webConnection() const { return m_webConnection.get(); }
109
110     WebProcessPool& processPool() { return m_processPool; }
111
112     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2
113     WebsiteDataStore& websiteDataStore() const { return m_websiteDataStore.get(); }
114
115     static WebProcessProxy* processForIdentifier(WebCore::ProcessIdentifier);
116     static WebPageProxy* webPage(uint64_t pageID);
117     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
118     void addExistingWebPage(WebPageProxy&, uint64_t pageID);
119     void removeWebPage(WebPageProxy&, uint64_t pageID);
120
121     typename WebPageProxyMap::ValuesConstIteratorRange pages() const { return m_pageMap.values(); }
122     unsigned pageCount() const { return m_pageMap.size(); }
123     unsigned visiblePageCount() const { return m_visiblePageCounter.value(); }
124
125     virtual bool isServiceWorkerProcess() const { return false; }
126
127     void addVisitedLinkStore(VisitedLinkStore&);
128     void addWebUserContentControllerProxy(WebUserContentControllerProxy&, WebPageCreationParameters&);
129     void didDestroyVisitedLinkStore(VisitedLinkStore&);
130     void didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy&);
131
132     RefPtr<API::UserInitiatedAction> userInitiatedActivity(uint64_t);
133
134     ResponsivenessTimer& responsivenessTimer() { return m_responsivenessTimer; }
135     bool isResponsive() const;
136
137     WebFrameProxy* webFrame(uint64_t) const;
138     bool canCreateFrame(uint64_t frameID) const;
139     void frameCreated(uint64_t, WebFrameProxy&);
140     void disconnectFramesFromPage(WebPageProxy*); // Including main frame.
141     size_t frameCountInPage(WebPageProxy*) const; // Including main frame.
142
143     VisibleWebPageToken visiblePageToken() const;
144
145     void testIncomingSyncIPCMessageWhileWaitingForSyncReply(bool& handled);
146
147     void updateTextCheckerState();
148
149     void willAcquireUniversalFileReadSandboxExtension() { m_mayHaveUniversalFileReadSandboxExtension = true; }
150     void assumeReadAccessToBaseURL(const String&);
151     bool hasAssumedReadAccessToURL(const WebCore::URL&) const;
152
153     bool checkURLReceivedFromWebProcess(const String&);
154     bool checkURLReceivedFromWebProcess(const WebCore::URL&);
155
156     static bool fullKeyboardAccessEnabled();
157
158     void didSaveToPageCache();
159     void releasePageCache();
160
161     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, Function<void(WebsiteData)>&& completionHandler);
162     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince, Function<void()>&& completionHandler);
163     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>&, Function<void()>&& completionHandler);
164     static void deleteWebsiteDataForTopPrivatelyControlledDomainsInAllPersistentDataStores(OptionSet<WebsiteDataType>, Vector<String>&& topPrivatelyControlledDomains, bool shouldNotifyPages, Function<void (const HashSet<String>&)>&& completionHandler);
165     static void topPrivatelyControlledDomainsWithWebsiteData(OptionSet<WebsiteDataType> dataTypes, bool shouldNotifyPage, Function<void(HashSet<String>&&)>&& completionHandler);
166     static void notifyPageStatisticsAndDataRecordsProcessed();
167     static void notifyPageStatisticsTelemetryFinished(API::Object* messageBody);
168
169     void enableSuddenTermination();
170     void disableSuddenTermination();
171     bool isSuddenTerminationEnabled() { return !m_numberOfTimesSuddenTerminationWasDisabled; }
172
173     void requestTermination(ProcessTerminationReason);
174
175     void stopResponsivenessTimer();
176
177     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
178     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
179
180 #if PLATFORM(COCOA)
181     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
182     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
183 #endif
184
185     void windowServerConnectionStateChanged();
186
187     void processReadyToSuspend();
188     void didCancelProcessSuspension();
189
190     void setIsHoldingLockedFiles(bool);
191
192     ProcessThrottler& throttler() { return m_throttler; }
193
194     void isResponsive(WTF::Function<void(bool isWebProcessResponsive)>&&);
195     void didReceiveMainThreadPing();
196     void didReceiveBackgroundResponsivenessPing();
197
198     void memoryPressureStatusChanged(bool isUnderMemoryPressure) { m_isUnderMemoryPressure = isUnderMemoryPressure; }
199     bool isUnderMemoryPressure() const { return m_isUnderMemoryPressure; }
200     void didExceedInactiveMemoryLimitWhileActive();
201
202     void processTerminated();
203
204     void didExceedCPULimit();
205     void didExceedActiveMemoryLimit();
206     void didExceedInactiveMemoryLimit();
207
208     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>&&);
209
210     void didCommitProvisionalLoad() { m_hasCommittedAnyProvisionalLoads = true; }
211     bool hasCommittedAnyProvisionalLoads() const { return m_hasCommittedAnyProvisionalLoads; }
212
213     void suspendWebPageProxy(WebPageProxy&, API::Navigation&);
214     void suspendedPageWasDestroyed(SuspendedPageProxy&);
215
216 #if ENABLE(EXTRA_ZOOM_MODE)
217     void takeBackgroundActivityTokenForFullscreenInput();
218     void releaseBackgroundActivityTokenForFullscreenInput();
219 #endif
220
221     bool isInPrewarmedPool() const { return m_isInPrewarmedPool; }
222     void setIsInPrewarmedPool(bool isInPrewarmedPool) { m_isInPrewarmedPool = isInPrewarmedPool; }
223
224 protected:
225     static uint64_t generatePageID();
226     WebProcessProxy(WebProcessPool&, WebsiteDataStore&, IsInPrewarmedPool);
227
228     // ChildProcessProxy
229     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
230     void connectionWillOpen(IPC::Connection&) override;
231     void processWillShutDown(IPC::Connection&) override;
232
233     // ProcessLauncher::Client
234     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
235
236 private:
237     // Called when the web process has crashed or we know that it will terminate soon.
238     // Will potentially cause the WebProcessProxy object to be freed.
239     void shutDown();
240     void maybeShutDown();
241
242     // IPC message handlers.
243     void updateBackForwardItem(const BackForwardListItemState&);
244     void didDestroyFrame(uint64_t);
245     void didDestroyUserGestureToken(uint64_t);
246
247     void shouldTerminate(bool& shouldTerminate);
248
249     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
250     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
251     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
252     void messagePortClosed(const WebCore::MessagePortIdentifier&);
253     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
254     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
255     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
256     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
257     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
258
259     // Plugins
260 #if ENABLE(NETSCAPE_PLUGIN_API)
261     void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins, std::optional<Vector<WebCore::SupportedPluginName>>&);
262 #endif // ENABLE(NETSCAPE_PLUGIN_API)
263 #if ENABLE(NETSCAPE_PLUGIN_API)
264     void getPluginProcessConnection(uint64_t pluginProcessToken, Ref<Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply>&&);
265 #endif
266     void getNetworkProcessConnection(Ref<Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply>&&);
267     void getStorageProcessConnection(PAL::SessionID initialSessionID, Ref<Messages::WebProcessProxy::GetStorageProcessConnection::DelayedReply>&&);
268
269     bool platformIsBeingDebugged() const;
270     bool shouldAllowNonValidInjectedCode() const;
271
272     static const HashSet<String>& platformPathsWithAssumedReadAccess();
273
274     void updateBackgroundResponsivenessTimer();
275
276     void processDidTerminateOrFailedToLaunch();
277
278     // IPC::Connection::Client
279     friend class WebConnectionToWebProcess;
280     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
281     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
282     void didClose(IPC::Connection&) override;
283     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
284
285     // ResponsivenessTimer::Client
286     void didBecomeUnresponsive() override;
287     void didBecomeResponsive() override;
288     void willChangeIsResponsive() override;
289     void didChangeIsResponsive() override;
290     bool mayBecomeUnresponsive() override;
291
292     // ProcessThrottlerClient
293     void sendProcessWillSuspendImminently() override;
294     void sendPrepareToSuspend() override;
295     void sendCancelPrepareToSuspend() override;
296     void sendProcessDidResume() override;
297     void didSetAssertionState(AssertionState) override;
298
299     // Implemented in generated WebProcessProxyMessageReceiver.cpp
300     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
301     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
302
303     bool canTerminateChildProcess();
304
305     void logDiagnosticMessageForResourceLimitTermination(const String& limitKey);
306
307     ResponsivenessTimer m_responsivenessTimer;
308     BackgroundProcessResponsivenessTimer m_backgroundResponsivenessTimer;
309     
310     RefPtr<WebConnectionToWebProcess> m_webConnection;
311     Ref<WebProcessPool> m_processPool;
312
313     bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it.
314     HashSet<String> m_localPathsWithAssumedReadAccess;
315
316     WebPageProxyMap m_pageMap;
317     HashMap<uint64_t, SuspendedPageProxy*> m_suspendedPageMap;
318     WebFrameProxyMap m_frameMap;
319     UserInitiatedActionMap m_userInitiatedActionMap;
320
321     HashSet<VisitedLinkStore*> m_visitedLinkStores;
322     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
323
324     int m_numberOfTimesSuddenTerminationWasDisabled;
325     ProcessThrottler m_throttler;
326     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
327 #if PLATFORM(IOS)
328     ForegroundWebProcessToken m_foregroundToken;
329     BackgroundWebProcessToken m_backgroundToken;
330 #endif
331
332     HashMap<String, uint64_t> m_pageURLRetainCountMap;
333
334     enum class NoOrMaybe { No, Maybe } m_isResponsive;
335     Vector<WTF::Function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
336
337     VisibleWebPageCounter m_visiblePageCounter;
338
339     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
340     Ref<WebsiteDataStore> m_websiteDataStore;
341
342     bool m_isUnderMemoryPressure { false };
343
344 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
345     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
346 #endif
347
348     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
349     HashMap<uint64_t, Function<void()>> m_messageBatchDeliveryCompletionHandlers;
350     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
351
352     bool m_hasCommittedAnyProvisionalLoads { false };
353     bool m_isInPrewarmedPool;
354
355 #if ENABLE(EXTRA_ZOOM_MODE)
356     ProcessThrottler::BackgroundActivityToken m_backgroundActivityTokenForFullscreenFormControls;
357 #endif
358 };
359
360 } // namespace WebKit