Regression(PSON): Assertion hit under WebPageProxy::didNavigateWithNavigationData()
[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, public ThreadSafeRefCounted<WebProcessProxy>, 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 IsPrewarmed {
101         No,
102         Yes
103     };
104
105     static Ref<WebProcessProxy> create(WebProcessPool&, WebsiteDataStore&, IsPrewarmed);
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 updateTextCheckerState();
146
147     void willAcquireUniversalFileReadSandboxExtension() { m_mayHaveUniversalFileReadSandboxExtension = true; }
148     void assumeReadAccessToBaseURL(const String&);
149     bool hasAssumedReadAccessToURL(const WebCore::URL&) const;
150
151     bool checkURLReceivedFromWebProcess(const String&);
152     bool checkURLReceivedFromWebProcess(const WebCore::URL&);
153
154     static bool fullKeyboardAccessEnabled();
155
156     void didSaveToPageCache();
157     void releasePageCache();
158
159     void fetchWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, CompletionHandler<void(WebsiteData)>&&);
160     void deleteWebsiteData(PAL::SessionID, OptionSet<WebsiteDataType>, WallTime modifiedSince, CompletionHandler<void()>&&);
161     void deleteWebsiteDataForOrigins(PAL::SessionID, OptionSet<WebsiteDataType>, const Vector<WebCore::SecurityOriginData>&, CompletionHandler<void()>&&);
162     static void deleteWebsiteDataForTopPrivatelyControlledDomainsInAllPersistentDataStores(OptionSet<WebsiteDataType>, Vector<String>&& topPrivatelyControlledDomains, bool shouldNotifyPages, CompletionHandler<void (const HashSet<String>&)>&&);
163     static void topPrivatelyControlledDomainsWithWebsiteData(OptionSet<WebsiteDataType> dataTypes, bool shouldNotifyPage, CompletionHandler<void(HashSet<String>&&)>&&);
164     static void notifyPageStatisticsAndDataRecordsProcessed();
165     static void notifyPageStatisticsTelemetryFinished(API::Object* messageBody);
166
167     void enableSuddenTermination();
168     void disableSuddenTermination();
169     bool isSuddenTerminationEnabled() { return !m_numberOfTimesSuddenTerminationWasDisabled; }
170
171     void requestTermination(ProcessTerminationReason);
172
173     void stopResponsivenessTimer();
174
175     RefPtr<API::Object> transformHandlesToObjects(API::Object*);
176     static RefPtr<API::Object> transformObjectsToHandles(API::Object*);
177
178 #if PLATFORM(COCOA)
179     RefPtr<ObjCObjectGraph> transformHandlesToObjects(ObjCObjectGraph&);
180     static RefPtr<ObjCObjectGraph> transformObjectsToHandles(ObjCObjectGraph&);
181 #endif
182
183     void windowServerConnectionStateChanged();
184
185     void processReadyToSuspend();
186     void didCancelProcessSuspension();
187
188     void setIsHoldingLockedFiles(bool);
189
190     ProcessThrottler& throttler() { return m_throttler; }
191
192     void isResponsive(WTF::Function<void(bool isWebProcessResponsive)>&&);
193     void didReceiveMainThreadPing();
194     void didReceiveBackgroundResponsivenessPing();
195
196     void memoryPressureStatusChanged(bool isUnderMemoryPressure) { m_isUnderMemoryPressure = isUnderMemoryPressure; }
197     bool isUnderMemoryPressure() const { return m_isUnderMemoryPressure; }
198     void didExceedInactiveMemoryLimitWhileActive();
199
200     void processTerminated();
201
202     void didExceedCPULimit();
203     void didExceedActiveMemoryLimit();
204     void didExceedInactiveMemoryLimit();
205
206     void checkProcessLocalPortForActivity(const WebCore::MessagePortIdentifier&, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>&&);
207
208     void didCommitProvisionalLoad() { m_hasCommittedAnyProvisionalLoads = true; }
209     bool hasCommittedAnyProvisionalLoads() const { return m_hasCommittedAnyProvisionalLoads; }
210
211     void suspendWebPageProxy(WebPageProxy&, API::Navigation&, uint64_t mainFrameID);
212     void suspendedPageWasDestroyed(SuspendedPageProxy&);
213
214 #if PLATFORM(WATCHOS)
215     void takeBackgroundActivityTokenForFullscreenInput();
216     void releaseBackgroundActivityTokenForFullscreenInput();
217 #endif
218
219     bool isPrewarmed() const { return m_isPrewarmed; }
220     void markIsNoLongerInPrewarmedPool();
221
222 #if PLATFORM(COCOA)
223     Vector<String> mediaMIMETypes();
224     void cacheMediaMIMETypes(const Vector<String>&);
225 #endif
226
227 #if PLATFORM(MAC)
228     void requestHighPerformanceGPU();
229     void releaseHighPerformanceGPU();
230 #endif
231
232     // Called when the web process has crashed or we know that it will terminate soon.
233     // Will potentially cause the WebProcessProxy object to be freed.
234     void shutDown();
235
236 protected:
237     static uint64_t generatePageID();
238     WebProcessProxy(WebProcessPool&, WebsiteDataStore&, IsPrewarmed);
239
240     // ChildProcessProxy
241     void getLaunchOptions(ProcessLauncher::LaunchOptions&) override;
242     void connectionWillOpen(IPC::Connection&) override;
243     void processWillShutDown(IPC::Connection&) override;
244
245     // ProcessLauncher::Client
246     void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier) override;
247
248 #if PLATFORM(COCOA)
249     void cacheMediaMIMETypesInternal(const Vector<String>&);
250 #endif
251
252 private:
253     void maybeShutDown();
254
255     // IPC message handlers.
256     void updateBackForwardItem(const BackForwardListItemState&);
257     void didDestroyFrame(uint64_t);
258     void didDestroyUserGestureToken(uint64_t);
259
260     void shouldTerminate(bool& shouldTerminate);
261
262     void createNewMessagePortChannel(const WebCore::MessagePortIdentifier& port1, const WebCore::MessagePortIdentifier& port2);
263     void entangleLocalPortInThisProcessToRemote(const WebCore::MessagePortIdentifier& local, const WebCore::MessagePortIdentifier& remote);
264     void messagePortDisentangled(const WebCore::MessagePortIdentifier&);
265     void messagePortClosed(const WebCore::MessagePortIdentifier&);
266     void takeAllMessagesForPort(const WebCore::MessagePortIdentifier&, uint64_t messagesCallbackIdentifier);
267     void postMessageToRemote(WebCore::MessageWithMessagePorts&&, const WebCore::MessagePortIdentifier&);
268     void checkRemotePortForActivity(const WebCore::MessagePortIdentifier, uint64_t callbackIdentifier);
269     void didDeliverMessagePortMessages(uint64_t messageBatchIdentifier);
270     void didCheckProcessLocalPortForActivity(uint64_t callbackIdentifier, bool isLocallyReachable);
271
272     // Plugins
273 #if ENABLE(NETSCAPE_PLUGIN_API)
274     void getPlugins(bool refresh, Vector<WebCore::PluginInfo>& plugins, Vector<WebCore::PluginInfo>& applicationPlugins, std::optional<Vector<WebCore::SupportedPluginIdentifier>>&);
275 #endif // ENABLE(NETSCAPE_PLUGIN_API)
276 #if ENABLE(NETSCAPE_PLUGIN_API)
277     void getPluginProcessConnection(uint64_t pluginProcessToken, Messages::WebProcessProxy::GetPluginProcessConnection::DelayedReply&&);
278 #endif
279     void getNetworkProcessConnection(Messages::WebProcessProxy::GetNetworkProcessConnection::DelayedReply&&);
280
281     bool platformIsBeingDebugged() const;
282     bool shouldAllowNonValidInjectedCode() const;
283
284     static const HashSet<String>& platformPathsWithAssumedReadAccess();
285
286     void updateBackgroundResponsivenessTimer();
287
288     void processDidTerminateOrFailedToLaunch();
289
290     // IPC::Connection::Client
291     friend class WebConnectionToWebProcess;
292     void didReceiveMessage(IPC::Connection&, IPC::Decoder&) override;
293     void didReceiveSyncMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&) override;
294     void didClose(IPC::Connection&) override;
295     void didReceiveInvalidMessage(IPC::Connection&, IPC::StringReference messageReceiverName, IPC::StringReference messageName) override;
296
297     // ResponsivenessTimer::Client
298     void didBecomeUnresponsive() override;
299     void didBecomeResponsive() override;
300     void willChangeIsResponsive() override;
301     void didChangeIsResponsive() override;
302     bool mayBecomeUnresponsive() override;
303
304     // ProcessThrottlerClient
305     void sendProcessWillSuspendImminently() override;
306     void sendPrepareToSuspend() override;
307     void sendCancelPrepareToSuspend() override;
308     void sendProcessDidResume() override;
309     void didSetAssertionState(AssertionState) override;
310
311     // Implemented in generated WebProcessProxyMessageReceiver.cpp
312     void didReceiveWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&);
313     void didReceiveSyncWebProcessProxyMessage(IPC::Connection&, IPC::Decoder&, std::unique_ptr<IPC::Encoder>&);
314
315     bool canTerminateChildProcess();
316
317     void didCollectPrewarmInformation(const String& domain, const WebCore::PrewarmInformation&);
318
319     void logDiagnosticMessageForResourceLimitTermination(const String& limitKey);
320
321     enum class IsWeak { No, Yes };
322     template<typename T> class WeakOrStrongPtr {
323     public:
324         WeakOrStrongPtr(T& object, IsWeak isWeak)
325             : m_isWeak(isWeak)
326             , m_weakObject(makeWeakPtr(object))
327         {
328             updateStrongReference();
329         }
330
331         void setIsWeak(IsWeak isWeak)
332         {
333             m_isWeak = isWeak;
334             updateStrongReference();
335         }
336
337         T* get() const { return m_weakObject.get(); }
338         T* operator->() const { return m_weakObject.get(); }
339         T& operator*() const { return *m_weakObject; }
340         explicit operator bool() const { return !!m_weakObject; }
341
342     private:
343         void updateStrongReference()
344         {
345             m_strongObject = m_isWeak == IsWeak::Yes ? nullptr : m_weakObject.get();
346         }
347
348         IsWeak m_isWeak;
349         WeakPtr<T> m_weakObject;
350         RefPtr<T> m_strongObject;
351     };
352
353     ResponsivenessTimer m_responsivenessTimer;
354     BackgroundProcessResponsivenessTimer m_backgroundResponsivenessTimer;
355     
356     RefPtr<WebConnectionToWebProcess> m_webConnection;
357     WeakOrStrongPtr<WebProcessPool> m_processPool; // Pre-warmed processes do not hold a strong reference to their pool.
358
359     bool m_mayHaveUniversalFileReadSandboxExtension; // True if a read extension for "/" was ever granted - we don't track whether WebProcess still has it.
360     HashSet<String> m_localPathsWithAssumedReadAccess;
361
362     WebPageProxyMap m_pageMap;
363     HashMap<uint64_t, SuspendedPageProxy*> m_suspendedPageMap;
364     WebFrameProxyMap m_frameMap;
365     UserInitiatedActionMap m_userInitiatedActionMap;
366
367     HashSet<VisitedLinkStore*> m_visitedLinkStores;
368     HashSet<WebUserContentControllerProxy*> m_webUserContentControllerProxies;
369
370     int m_numberOfTimesSuddenTerminationWasDisabled;
371     ProcessThrottler m_throttler;
372     ProcessThrottler::BackgroundActivityToken m_tokenForHoldingLockedFiles;
373 #if PLATFORM(IOS)
374     ForegroundWebProcessToken m_foregroundToken;
375     BackgroundWebProcessToken m_backgroundToken;
376 #endif
377
378     HashMap<String, uint64_t> m_pageURLRetainCountMap;
379
380     enum class NoOrMaybe { No, Maybe } m_isResponsive;
381     Vector<WTF::Function<void(bool webProcessIsResponsive)>> m_isResponsiveCallbacks;
382
383     VisibleWebPageCounter m_visiblePageCounter;
384
385     // FIXME: WebsiteDataStores should be made per-WebPageProxy throughout WebKit2. Get rid of this member.
386     Ref<WebsiteDataStore> m_websiteDataStore;
387
388     bool m_isUnderMemoryPressure { false };
389
390 #if PLATFORM(COCOA) && ENABLE(MEDIA_STREAM)
391     std::unique_ptr<UserMediaCaptureManagerProxy> m_userMediaCaptureManagerProxy;
392 #endif
393
394     HashSet<WebCore::MessagePortIdentifier> m_processEntangledPorts;
395     HashMap<uint64_t, Function<void()>> m_messageBatchDeliveryCompletionHandlers;
396     HashMap<uint64_t, CompletionHandler<void(WebCore::MessagePortChannelProvider::HasActivity)>> m_localPortActivityCompletionHandlers;
397
398     bool m_hasCommittedAnyProvisionalLoads { false };
399     bool m_isPrewarmed;
400
401 #if PLATFORM(WATCHOS)
402     ProcessThrottler::BackgroundActivityToken m_backgroundActivityTokenForFullscreenFormControls;
403 #endif
404 };
405
406 } // namespace WebKit