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