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