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