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