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