Make synchronous IPC introduced in r237267 asynchronous
[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 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
54 #include "DisplayLink.h"
55 #endif
56
57 namespace API {
58 class Navigation;
59 class PageConfiguration;
60 }
61
62 namespace WebCore {
63 class ResourceRequest;
64 class URL;
65 struct PluginInfo;
66 struct SecurityOriginData;
67 }
68
69 namespace WebKit {
70
71 class NetworkProcessProxy;
72 class ObjCObjectGraph;
73 class PageClient;
74 class UserMediaCaptureManagerProxy;
75 class VisitedLinkStore;
76 class WebBackForwardListItem;
77 class WebFrameProxy;
78 class WebPageGroup;
79 class WebPageProxy;
80 class WebProcessPool;
81 class WebUserContentControllerProxy;
82 class WebsiteDataStore;
83 enum class WebsiteDataType;
84 struct WebNavigationDataStore;
85 struct WebPageCreationParameters;
86 struct WebsiteData;
87
88 #if PLATFORM(IOS_FAMILY)
89 enum ForegroundWebProcessCounterType { };
90 typedef RefCounter<ForegroundWebProcessCounterType> ForegroundWebProcessCounter;
91 typedef ForegroundWebProcessCounter::Token ForegroundWebProcessToken;
92 enum BackgroundWebProcessCounterType { };
93 typedef RefCounter<BackgroundWebProcessCounterType> BackgroundWebProcessCounter;
94 typedef BackgroundWebProcessCounter::Token BackgroundWebProcessToken;
95 #endif
96
97 class WebProcessProxy : public ChildProcessProxy, public ResponsivenessTimer::Client, public ThreadSafeRefCounted<WebProcessProxy>, public CanMakeWeakPtr<WebProcessProxy>, private ProcessThrottlerClient {
98 public:
99     typedef HashMap<uint64_t, RefPtr<WebFrameProxy>> WebFrameProxyMap;
100     typedef HashMap<uint64_t, WebPageProxy*> WebPageProxyMap;
101     typedef HashMap<uint64_t, RefPtr<API::UserInitiatedAction>> UserInitiatedActionMap;
102
103     enum class IsPrewarmed {
104         No,
105         Yes
106     };
107
108     static Ref<WebProcessProxy> create(WebProcessPool&, WebsiteDataStore&, IsPrewarmed);
109     ~WebProcessProxy();
110
111     WebConnection* webConnection() const { return m_webConnection.get(); }
112
113     WebProcessPool& processPool() const { ASSERT(m_processPool); return *m_processPool.get(); }
114
115     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2
116     WebsiteDataStore& websiteDataStore() const { return m_websiteDataStore.get(); }
117
118     static WebProcessProxy* processForIdentifier(WebCore::ProcessIdentifier);
119     static WebPageProxy* webPage(uint64_t pageID);
120     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
121     void addExistingWebPage(WebPageProxy&, uint64_t pageID);
122     void removeWebPage(WebPageProxy&, uint64_t pageID);
123
124     typename WebPageProxyMap::ValuesConstIteratorRange pages() const { return m_pageMap.values(); }
125     unsigned pageCount() const { return m_pageMap.size(); }
126     unsigned visiblePageCount() const { return m_visiblePageCounter.value(); }
127
128     void activePagesDomainsForTesting(CompletionHandler<void(Vector<String>&&)>&&); // This is what is reported to ActivityMonitor.
129
130     virtual bool isServiceWorkerProcess() const { return false; }
131
132     void addVisitedLinkStore(VisitedLinkStore&);
133     void addWebUserContentControllerProxy(WebUserContentControllerProxy&, WebPageCreationParameters&);
134     void didDestroyVisitedLinkStore(VisitedLinkStore&);
135     void didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy&);
136
137     RefPtr<API::UserInitiatedAction> userInitiatedActivity(uint64_t);
138
139     ResponsivenessTimer& responsivenessTimer() { return m_responsivenessTimer; }
140     bool isResponsive() const;
141
142     WebFrameProxy* webFrame(uint64_t) const;
143     bool canCreateFrame(uint64_t frameID) const;
144     void frameCreated(uint64_t, WebFrameProxy&);
145     void disconnectFramesFromPage(WebPageProxy*); // Including main frame.
146     size_t frameCountInPage(WebPageProxy*) const; // Including main frame.
147
148     VisibleWebPageToken visiblePageToken() const;
149
150     void updateTextCheckerState();
151
152     void willAcquireUniversalFileReadSandboxExtension() { m_mayHaveUniversalFileReadSandboxExtension = true; }
153     void assumeReadAccessToBaseURL(const String&);
154     bool hasAssumedReadAccessToURL(const WebCore::URL&) const;
155
156     bool checkURLReceivedFromWebProcess(const String&);
157     bool checkURLReceivedFromWebProcess(const WebCore::URL&);
158
159     static bool fullKeyboardAccessEnabled();
160
161     void didSaveToPageCache();
162     void releasePageCache();
163
164     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, CompletionHandler<void(WebsiteData)>&&);
165     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince, CompletionHandler<void()>&&);
166     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>&, CompletionHandler<void()>&&);
167     static void deleteWebsiteDataForTopPrivatelyControlledDomainsInAllPersistentDataStores(OptionSet<WebsiteDataType>, Vector<String>&& topPrivatelyControlledDomains, bool shouldNotifyPages, CompletionHandler<void (const HashSet<String>&)>&&);
168     static void topPrivatelyControlledDomainsWithWebsiteData(OptionSet<WebsiteDataType> dataTypes, bool shouldNotifyPage, CompletionHandler<void(HashSet<String>&&)>&&);
169     static void notifyPageStatisticsAndDataRecordsProcessed();
170     static void notifyPageStatisticsTelemetryFinished(API::Object* messageBody);
171
172     void enableSuddenTermination();
173     void disableSuddenTermination();
174     bool isSuddenTerminationEnabled() { return !m_numberOfTimesSuddenTerminationWasDisabled; }
175
176     void requestTermination(ProcessTerminationReason);
177
178     void stopResponsivenessTimer();
179
180     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
181     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
182
183 #if PLATFORM(COCOA)
184     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
185     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
186 #endif
187
188     void windowServerConnectionStateChanged();
189
190     void processReadyToSuspend();
191     void didCancelProcessSuspension();
192
193     void setIsHoldingLockedFiles(bool);
194
195     ProcessThrottler& throttler() { return m_throttler; }
196
197     void isResponsive(WTF::Function<void(bool isWebProcessResponsive)>&&);
198     void didReceiveMainThreadPing();
199     void didReceiveBackgroundResponsivenessPing();
200
201     void memoryPressureStatusChanged(bool isUnderMemoryPressure) { m_isUnderMemoryPressure = isUnderMemoryPressure; }
202     bool isUnderMemoryPressure() const { return m_isUnderMemoryPressure; }
203     void didExceedInactiveMemoryLimitWhileActive();
204
205     void processTerminated();
206
207     void didExceedCPULimit();
208     void didExceedActiveMemoryLimit();
209     void didExceedInactiveMemoryLimit();
210
211     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>&&);
212
213     void didCommitProvisionalLoad() { m_hasCommittedAnyProvisionalLoads = true; }
214     bool hasCommittedAnyProvisionalLoads() const { return m_hasCommittedAnyProvisionalLoads; }
215
216 #if PLATFORM(WATCHOS)
217     void takeBackgroundActivityTokenForFullscreenInput();
218     void releaseBackgroundActivityTokenForFullscreenInput();
219 #endif
220
221     bool isPrewarmed() const { return m_isPrewarmed; }
222     void markIsNoLongerInPrewarmedPool();
223
224 #if PLATFORM(COCOA)
225     Vector<String> mediaMIMETypes();
226     void cacheMediaMIMETypes(const Vector<String>&);
227 #endif
228
229 #if PLATFORM(MAC)
230     void requestHighPerformanceGPU();
231     void releaseHighPerformanceGPU();
232 #endif
233
234 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
235     void startDisplayLink(unsigned observerID, uint32_t displayID);
236     void stopDisplayLink(unsigned observerID, uint32_t displayID);
237 #endif
238
239     // Called when the web process has crashed or we know that it will terminate soon.
240     // Will potentially cause the WebProcessProxy object to be freed.
241     void shutDown();
242     void maybeShutDown();
243
244 protected:
245     static uint64_t generatePageID();
246     WebProcessProxy(WebProcessPool&, WebsiteDataStore&, IsPrewarmed);
247
248     // ChildProcessProxy
249     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
250     void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&) override;
251     void connectionWillOpen(IPC::Connection&) override;
252     void processWillShutDown(IPC::Connection&) override;
253
254     // ProcessLauncher::Client
255     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
256
257 #if PLATFORM(COCOA)
258     void cacheMediaMIMETypesInternal(const Vector<String>&);
259 #endif
260
261     bool isJITEnabled() const final;
262     
263 private:
264     // IPC message handlers.
265     void updateBackForwardItem(const BackForwardListItemState&);
266     void didDestroyFrame(uint64_t);
267     void didDestroyUserGestureToken(uint64_t);
268
269     void shouldTerminate(bool& shouldTerminate);
270
271     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
272     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
273     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
274     void messagePortClosed(const WebCore::MessagePortIdentifier&);
275     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
276     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
277     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
278     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
279     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
280
281     // Plugins
282 #if ENABLE(NETSCAPE_PLUGIN_API)
283     void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins, std::optional<Vector<WebCore::SupportedPluginIdentifier>>&);
284 #endif // ENABLE(NETSCAPE_PLUGIN_API)
285 #if ENABLE(NETSCAPE_PLUGIN_API)
286     void getPluginProcessConnection(uint64_t pluginProcessToken, Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply&&);
287 #endif
288     void getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
289
290     bool platformIsBeingDebugged() const;
291     bool shouldAllowNonValidInjectedCode() const;
292
293     static const HashSet<String>& platformPathsWithAssumedReadAccess();
294
295     void updateBackgroundResponsivenessTimer();
296
297     void processDidTerminateOrFailedToLaunch();
298
299     // IPC::Connection::Client
300     friend class WebConnectionToWebProcess;
301     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
302     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
303     void didClose(IPC::Connection&) override;
304     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
305
306     // ResponsivenessTimer::Client
307     void didBecomeUnresponsive() override;
308     void didBecomeResponsive() override;
309     void willChangeIsResponsive() override;
310     void didChangeIsResponsive() override;
311     bool mayBecomeUnresponsive() override;
312
313     // ProcessThrottlerClient
314     void sendProcessWillSuspendImminently() override;
315     void sendPrepareToSuspend() override;
316     void sendCancelPrepareToSuspend() override;
317     void sendProcessDidResume() override;
318     void didSetAssertionState(AssertionState) override;
319
320     // Implemented in generated WebProcessProxyMessageReceiver.cpp
321     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
322     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
323
324     bool canTerminateChildProcess();
325
326     void didCollectPrewarmInformation(const String& domain, const WebCore::PrewarmInformation&);
327
328     void logDiagnosticMessageForResourceLimitTermination(const String& limitKey);
329
330     enum class IsWeak { No, Yes };
331     template<typename T> class WeakOrStrongPtr {
332     public:
333         WeakOrStrongPtr(T& object, IsWeak isWeak)
334             : m_isWeak(isWeak)
335             , m_weakObject(makeWeakPtr(object))
336         {
337             updateStrongReference();
338         }
339
340         void setIsWeak(IsWeak isWeak)
341         {
342             m_isWeak = isWeak;
343             updateStrongReference();
344         }
345
346         T* get() const { return m_weakObject.get(); }
347         T* operator->() const { return m_weakObject.get(); }
348         T& operator*() const { return *m_weakObject; }
349         explicit operator bool() const { return !!m_weakObject; }
350
351     private:
352         void updateStrongReference()
353         {
354             m_strongObject = m_isWeak == IsWeak::Yes ? nullptr : m_weakObject.get();
355         }
356
357         IsWeak m_isWeak;
358         WeakPtr<T> m_weakObject;
359         RefPtr<T> m_strongObject;
360     };
361
362     ResponsivenessTimer m_responsivenessTimer;
363     BackgroundProcessResponsivenessTimer m_backgroundResponsivenessTimer;
364     
365     RefPtr<WebConnectionToWebProcess> m_webConnection;
366     WeakOrStrongPtr<WebProcessPool> m_processPool; // Pre-warmed processes do not hold a strong reference to their pool.
367
368     bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it.
369     HashSet<String> m_localPathsWithAssumedReadAccess;
370
371     WebPageProxyMap m_pageMap;
372     WebFrameProxyMap m_frameMap;
373     UserInitiatedActionMap m_userInitiatedActionMap;
374
375     HashSet<VisitedLinkStore*> m_visitedLinkStores;
376     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
377
378     int m_numberOfTimesSuddenTerminationWasDisabled;
379     ProcessThrottler m_throttler;
380     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
381 #if PLATFORM(IOS_FAMILY)
382     ForegroundWebProcessToken m_foregroundToken;
383     BackgroundWebProcessToken m_backgroundToken;
384 #endif
385
386     HashMap<String, uint64_t> m_pageURLRetainCountMap;
387
388     enum class NoOrMaybe { No, Maybe } m_isResponsive;
389     Vector<WTF::Function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
390
391     VisibleWebPageCounter m_visiblePageCounter;
392
393     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
394     Ref<WebsiteDataStore> m_websiteDataStore;
395
396     bool m_isUnderMemoryPressure { false };
397
398 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
399     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
400 #endif
401
402     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
403     HashMap<uint64_t, Function<void()>> m_messageBatchDeliveryCompletionHandlers;
404     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
405
406     bool m_hasCommittedAnyProvisionalLoads { false };
407     bool m_isPrewarmed;
408
409 #if PLATFORM(WATCHOS)
410     ProcessThrottler::BackgroundActivityToken m_backgroundActivityTokenForFullscreenFormControls;
411 #endif
412
413 #if PLATFORM(MAC) && ENABLE(WEBPROCESS_WINDOWSERVER_BLOCKING)
414     Vector<std::unique_ptr<DisplayLink>> m_displayLinks;
415 #endif
416 };
417
418 } // namespace WebKit