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