6c18e8666ade10c487b6f667656be657917d30c2
[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 SuspendedPageProxy;
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)
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 class WebProcessProxy : public ChildProcessProxy, public ResponsivenessTimer::Client, private ProcessThrottlerClient {
95 public:
96     typedef HashMap<uint64_t, RefPtr<WebFrameProxy>> WebFrameProxyMap;
97     typedef HashMap<uint64_t, WebPageProxy*> WebPageProxyMap;
98     typedef HashMap<uint64_t, RefPtr<API::UserInitiatedAction>> UserInitiatedActionMap;
99
100     enum class IsInPrewarmedPool {
101         No,
102         Yes
103     };
104
105     static Ref<WebProcessProxy> create(WebProcessPool&, WebsiteDataStore&, IsInPrewarmedPool);
106     ~WebProcessProxy();
107
108     WebConnection* webConnection() const { return m_webConnection.get(); }
109
110     WebProcessPool& processPool() { ASSERT(m_processPool); return *m_processPool.get(); }
111
112     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2
113     WebsiteDataStore& websiteDataStore() const { return m_websiteDataStore.get(); }
114
115     static WebProcessProxy* processForIdentifier(WebCore::ProcessIdentifier);
116     static WebPageProxy* webPage(uint64_t pageID);
117     Ref<WebPageProxy> createWebPage(PageClient&, Ref<API::PageConfiguration>&&);
118     void addExistingWebPage(WebPageProxy&, uint64_t pageID);
119     void removeWebPage(WebPageProxy&, uint64_t pageID);
120
121     typename WebPageProxyMap::ValuesConstIteratorRange pages() const { return m_pageMap.values(); }
122     unsigned pageCount() const { return m_pageMap.size(); }
123     unsigned visiblePageCount() const { return m_visiblePageCounter.value(); }
124
125     virtual bool isServiceWorkerProcess() const { return false; }
126
127     void addVisitedLinkStore(VisitedLinkStore&);
128     void addWebUserContentControllerProxy(WebUserContentControllerProxy&, WebPageCreationParameters&);
129     void didDestroyVisitedLinkStore(VisitedLinkStore&);
130     void didDestroyWebUserContentControllerProxy(WebUserContentControllerProxy&);
131
132     RefPtr<API::UserInitiatedAction> userInitiatedActivity(uint64_t);
133
134     ResponsivenessTimer& responsivenessTimer() { return m_responsivenessTimer; }
135     bool isResponsive() const;
136
137     WebFrameProxy* webFrame(uint64_t) const;
138     bool canCreateFrame(uint64_t frameID) const;
139     void frameCreated(uint64_t, WebFrameProxy&);
140     void disconnectFramesFromPage(WebPageProxy*); // Including main frame.
141     size_t frameCountInPage(WebPageProxy*) const; // Including main frame.
142
143     VisibleWebPageToken visiblePageToken() const;
144
145     void testIncomingSyncIPCMessageWhileWaitingForSyncReply(bool& handled);
146
147     void updateTextCheckerState();
148
149     void willAcquireUniversalFileReadSandboxExtension() { m_mayHaveUniversalFileReadSandboxExtension = true; }
150     void assumeReadAccessToBaseURL(const String&);
151     bool hasAssumedReadAccessToURL(const WebCore::URL&) const;
152
153     bool checkURLReceivedFromWebProcess(const String&);
154     bool checkURLReceivedFromWebProcess(const WebCore::URL&);
155
156     static bool fullKeyboardAccessEnabled();
157
158     void didSaveToPageCache();
159     void releasePageCache();
160
161     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, CompletionHandler<void(WebsiteData)>&&);
162     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince, CompletionHandler<void()>&&);
163     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>&, CompletionHandler<void()>&&);
164     static void deleteWebsiteDataForTopPrivatelyControlledDomainsInAllPersistentDataStores(OptionSet<WebsiteDataType>, Vector<String>&& topPrivatelyControlledDomains, bool shouldNotifyPages, CompletionHandler<void (const HashSet<String>&)>&&);
165     static void topPrivatelyControlledDomainsWithWebsiteData(OptionSet<WebsiteDataType> dataTypes, bool shouldNotifyPage, CompletionHandler<void(HashSet<String>&&)>&&);
166     static void notifyPageStatisticsAndDataRecordsProcessed();
167     static void notifyPageStatisticsTelemetryFinished(API::Object* messageBody);
168
169     void enableSuddenTermination();
170     void disableSuddenTermination();
171     bool isSuddenTerminationEnabled() { return !m_numberOfTimesSuddenTerminationWasDisabled; }
172
173     void requestTermination(ProcessTerminationReason);
174
175     void stopResponsivenessTimer();
176
177     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
178     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
179
180 #if PLATFORM(COCOA)
181     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
182     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
183 #endif
184
185     void windowServerConnectionStateChanged();
186
187     void processReadyToSuspend();
188     void didCancelProcessSuspension();
189
190     void setIsHoldingLockedFiles(bool);
191
192     ProcessThrottler& throttler() { return m_throttler; }
193
194     void isResponsive(WTF::Function<void(bool isWebProcessResponsive)>&&);
195     void didReceiveMainThreadPing();
196     void didReceiveBackgroundResponsivenessPing();
197
198     void memoryPressureStatusChanged(bool isUnderMemoryPressure) { m_isUnderMemoryPressure = isUnderMemoryPressure; }
199     bool isUnderMemoryPressure() const { return m_isUnderMemoryPressure; }
200     void didExceedInactiveMemoryLimitWhileActive();
201
202     void processTerminated();
203
204     void didExceedCPULimit();
205     void didExceedActiveMemoryLimit();
206     void didExceedInactiveMemoryLimit();
207
208     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>&&);
209
210     void didCommitProvisionalLoad() { m_hasCommittedAnyProvisionalLoads = true; }
211     bool hasCommittedAnyProvisionalLoads() const { return m_hasCommittedAnyProvisionalLoads; }
212
213     void suspendWebPageProxy(WebPageProxy&, API::Navigation&);
214     void suspendedPageWasDestroyed(SuspendedPageProxy&);
215
216 #if PLATFORM(WATCHOS)
217     void takeBackgroundActivityTokenForFullscreenInput();
218     void releaseBackgroundActivityTokenForFullscreenInput();
219 #endif
220
221     bool isInPrewarmedPool() const { return m_isInPrewarmedPool; }
222     void markIsNoLongerInPrewarmedPool();
223
224 #if PLATFORM(COCOA)
225     Vector<String> mediaMIMETypes();
226     void cacheMediaMIMETypes(const Vector<String>&);
227 #endif
228
229     // Called when the web process has crashed or we know that it will terminate soon.
230     // Will potentially cause the WebProcessProxy object to be freed.
231     void shutDown();
232
233 protected:
234     static uint64_t generatePageID();
235     WebProcessProxy(WebProcessPool&, WebsiteDataStore&, IsInPrewarmedPool);
236
237     // ChildProcessProxy
238     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
239     void connectionWillOpen(IPC::Connection&) override;
240     void processWillShutDown(IPC::Connection&) override;
241
242     // ProcessLauncher::Client
243     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
244
245 #if PLATFORM(COCOA)
246     void cacheMediaMIMETypesInternal(const Vector<String>&);
247 #endif
248
249 private:
250     void maybeShutDown();
251
252     // IPC message handlers.
253     void updateBackForwardItem(const BackForwardListItemState&);
254     void didDestroyFrame(uint64_t);
255     void didDestroyUserGestureToken(uint64_t);
256
257     void shouldTerminate(bool& shouldTerminate);
258
259     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
260     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
261     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
262     void messagePortClosed(const WebCore::MessagePortIdentifier&);
263     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
264     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
265     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
266     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
267     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
268
269     // Plugins
270 #if ENABLE(NETSCAPE_PLUGIN_API)
271     void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins, std::optional<Vector<WebCore::SupportedPluginIdentifier>>&);
272 #endif // ENABLE(NETSCAPE_PLUGIN_API)
273 #if ENABLE(NETSCAPE_PLUGIN_API)
274     void getPluginProcessConnection(uint64_t pluginProcessToken, Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply&&);
275 #endif
276     void getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
277     void getStorageProcessConnection(PAL::SessionID initialSessionID, Messages::WebProcessProxy::GetStorageProcessConnection::DelayedReply&&);
278
279     bool platformIsBeingDebugged() const;
280     bool shouldAllowNonValidInjectedCode() const;
281
282     static const HashSet<String>& platformPathsWithAssumedReadAccess();
283
284     void updateBackgroundResponsivenessTimer();
285
286     void processDidTerminateOrFailedToLaunch();
287
288     // IPC::Connection::Client
289     friend class WebConnectionToWebProcess;
290     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
291     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
292     void didClose(IPC::Connection&) override;
293     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
294
295     // ResponsivenessTimer::Client
296     void didBecomeUnresponsive() override;
297     void didBecomeResponsive() override;
298     void willChangeIsResponsive() override;
299     void didChangeIsResponsive() override;
300     bool mayBecomeUnresponsive() override;
301
302     // ProcessThrottlerClient
303     void sendProcessWillSuspendImminently() override;
304     void sendPrepareToSuspend() override;
305     void sendCancelPrepareToSuspend() override;
306     void sendProcessDidResume() override;
307     void didSetAssertionState(AssertionState) override;
308
309     // Implemented in generated WebProcessProxyMessageReceiver.cpp
310     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
311     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
312
313     bool canTerminateChildProcess();
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     HashMap<uint64_t, SuspendedPageProxy*> m_suspendedPageMap;
360     WebFrameProxyMap m_frameMap;
361     UserInitiatedActionMap m_userInitiatedActionMap;
362
363     HashSet<VisitedLinkStore*> m_visitedLinkStores;
364     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
365
366     int m_numberOfTimesSuddenTerminationWasDisabled;
367     ProcessThrottler m_throttler;
368     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
369 #if PLATFORM(IOS)
370     ForegroundWebProcessToken m_foregroundToken;
371     BackgroundWebProcessToken m_backgroundToken;
372 #endif
373
374     HashMap<String, uint64_t> m_pageURLRetainCountMap;
375
376     enum class NoOrMaybe { No, Maybe } m_isResponsive;
377     Vector<WTF::Function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
378
379     VisibleWebPageCounter m_visiblePageCounter;
380
381     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
382     Ref<WebsiteDataStore> m_websiteDataStore;
383
384     bool m_isUnderMemoryPressure { false };
385
386 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
387     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
388 #endif
389
390     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
391     HashMap<uint64_t, Function<void()>> m_messageBatchDeliveryCompletionHandlers;
392     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
393
394     bool m_hasCommittedAnyProvisionalLoads { false };
395     bool m_isInPrewarmedPool;
396
397 #if PLATFORM(WATCHOS)
398     ProcessThrottler::BackgroundActivityToken m_backgroundActivityTokenForFullscreenFormControls;
399 #endif
400 };
401
402 } // namespace WebKit