Unreviewed, rolling out r243008.
[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 protected:
297     static uint64_t generatePageID();
298     WebProcessProxy(WebProcessPool&, WebsiteDataStore&, IsPrewarmed);
299
300     // AuxiliaryProcessProxy
301     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
302     void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&) override;
303     void connectionWillOpen(IPC::Connection&) override;
304     void processWillShutDown(IPC::Connection&) override;
305
306     // ProcessLauncher::Client
307     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
308
309 #if PLATFORM(COCOA)
310     void cacheMediaMIMETypesInternal(const Vector<String>&);
311 #endif
312
313     bool isJITEnabled() const final;
314
315 private:
316     // IPC message handlers.
317     void updateBackForwardItem(const BackForwardListItemState&);
318     void didDestroyFrame(uint64_t);
319     void didDestroyUserGestureToken(uint64_t);
320
321     bool canBeAddedToWebProcessCache() const;
322     void shouldTerminate(CompletionHandler<void(bool)>&&);
323
324     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
325     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
326     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
327     void messagePortClosed(const WebCore::MessagePortIdentifier&);
328     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
329     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
330     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
331     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
332     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
333
334     bool hasProvisionalPageWithID(uint64_t pageID) const;
335     bool isAllowedToUpdateBackForwardItem(WebBackForwardListItem&) const;
336
337     // Plugins
338 #if ENABLE(NETSCAPE_PLUGIN_API)
339     void getPlugins(bool refresh, CompletionHandler<void(Vector<WebCore::PluginInfo>&& plugins, Vector<WebCore::PluginInfo>&& applicationPlugins, Optional<Vector<WebCore::SupportedPluginIdentifier>>&&)>&&);
340 #endif // ENABLE(NETSCAPE_PLUGIN_API)
341 #if ENABLE(NETSCAPE_PLUGIN_API)
342     void getPluginProcessConnection(uint64_t pluginProcessToken, Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply&&);
343 #endif
344     void getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
345
346     bool platformIsBeingDebugged() const;
347     bool shouldAllowNonValidInjectedCode() const;
348
349     static const HashSet<String>& platformPathsWithAssumedReadAccess();
350
351     void updateBackgroundResponsivenessTimer();
352
353     void processDidTerminateOrFailedToLaunch();
354
355     // IPC::Connection::Client
356     friend class WebConnectionToWebProcess;
357     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
358     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
359     void didClose(IPC::Connection&) override;
360     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
361
362     // ResponsivenessTimer::Client
363     void didBecomeUnresponsive() override;
364     void didBecomeResponsive() override;
365     void willChangeIsResponsive() override;
366     void didChangeIsResponsive() override;
367     bool mayBecomeUnresponsive() override;
368
369     // Implemented in generated WebProcessProxyMessageReceiver.cpp
370     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
371     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
372
373     bool canTerminateAuxiliaryProcess();
374
375     void didCollectPrewarmInformation(const WebCore::RegistrableDomain&, const WebCore::PrewarmInformation&);
376
377     void logDiagnosticMessageForResourceLimitTermination(const String& limitKey);
378
379     enum class IsWeak { No, Yes };
380     template<typename T> class WeakOrStrongPtr {
381     public:
382         WeakOrStrongPtr(T& object, IsWeak isWeak)
383             : m_isWeak(isWeak)
384             , m_weakObject(makeWeakPtr(object))
385         {
386             updateStrongReference();
387         }
388
389         void setIsWeak(IsWeak isWeak)
390         {
391             m_isWeak = isWeak;
392             updateStrongReference();
393         }
394
395         T* get() const { return m_weakObject.get(); }
396         T* operator->() const { return m_weakObject.get(); }
397         T& operator*() const { return *m_weakObject; }
398         explicit operator bool() const { return !!m_weakObject; }
399
400     private:
401         void updateStrongReference()
402         {
403             m_strongObject = m_isWeak == IsWeak::Yes ? nullptr : m_weakObject.get();
404         }
405
406         IsWeak m_isWeak;
407         WeakPtr<T> m_weakObject;
408         RefPtr<T> m_strongObject;
409     };
410
411     ResponsivenessTimer m_responsivenessTimer;
412     BackgroundProcessResponsivenessTimer m_backgroundResponsivenessTimer;
413     
414     RefPtr<WebConnectionToWebProcess> m_webConnection;
415     WeakOrStrongPtr<WebProcessPool> m_processPool; // Pre-warmed and cached processes do not hold a strong reference to their pool.
416
417     bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it.
418     HashSet<String> m_localPathsWithAssumedReadAccess;
419
420     WebPageProxyMap m_pageMap;
421     WebFrameProxyMap m_frameMap;
422     HashSet<ProvisionalPageProxy*> m_provisionalPages;
423     UserInitiatedActionMap m_userInitiatedActionMap;
424
425     HashSet<VisitedLinkStore*> m_visitedLinkStores;
426     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
427
428     int m_numberOfTimesSuddenTerminationWasDisabled;
429     ProcessThrottler m_throttler;
430     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
431 #if PLATFORM(IOS_FAMILY)
432     ForegroundWebProcessToken m_foregroundToken;
433     BackgroundWebProcessToken m_backgroundToken;
434 #endif
435
436     HashMap<String, uint64_t> m_pageURLRetainCountMap;
437
438     Optional<WebCore::RegistrableDomain> m_registrableDomain;
439     bool m_isInProcessCache { false };
440
441     enum class NoOrMaybe { No, Maybe } m_isResponsive;
442     Vector<CompletionHandler<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
443
444     VisibleWebPageCounter m_visiblePageCounter;
445
446     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
447     Ref<WebsiteDataStore> m_websiteDataStore;
448
449     bool m_isUnderMemoryPressure { false };
450
451 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
452     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
453 #endif
454
455     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
456     HashMap<uint64_t, Function<void()>> m_messageBatchDeliveryCompletionHandlers;
457     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
458
459     unsigned m_suspendedPageCount { 0 };
460     bool m_hasCommittedAnyProvisionalLoads { false };
461     bool m_isPrewarmed;
462
463 #if PLATFORM(WATCHOS)
464     ProcessThrottler::BackgroundActivityToken m_backgroundActivityTokenForFullscreenFormControls;
465 #endif
466
467 #if PLATFORM(IOS_FAMILY)
468     bool m_keyboardIsAttached { false };
469 #endif
470
471 #if PLATFORM(COCOA)
472     MediaCaptureSandboxExtensions m_mediaCaptureSandboxExtensions { SandboxExtensionType::None };
473 #endif
474 };
475
476 } // namespace WebKit