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