File: AuxiliaryProcessProxy.h

package info (click to toggle)
webkit2gtk 2.48.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 429,764 kB
  • sloc: cpp: 3,697,587; javascript: 194,444; ansic: 169,997; python: 46,499; asm: 19,295; ruby: 18,528; perl: 16,602; xml: 4,650; yacc: 2,360; sh: 2,098; java: 1,993; lex: 1,327; pascal: 366; makefile: 298
file content (399 lines) | stat: -rw-r--r-- 16,416 bytes parent folder | download | duplicates (7)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
/*
 * Copyright (C) 2012-2022 Apple Inc. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 * THE POSSIBILITY OF SUCH DAMAGE.
 */

#pragma once

#include "Connection.h"
#include "MessageReceiverMap.h"
#include "ProcessLauncher.h"
#include "ProcessThrottler.h"
#include "ResponsivenessTimer.h"
#include <WebCore/ProcessIdentifier.h>
#include <memory>
#include <wtf/CheckedRef.h>
#include <wtf/Forward.h>
#include <wtf/HashMap.h>
#include <wtf/ProcessID.h>
#include <wtf/Seconds.h>
#include <wtf/SystemTracing.h>
#include <wtf/TZoneMalloc.h>
#include <wtf/ThreadSafeRefCounted.h>
#include <wtf/UniqueRef.h>
#include <wtf/VectorHash.h>

namespace WebCore {
class SharedBuffer;
}

namespace WebKit {

class ExtensionCapabilityGrant;
class ProcessThrottler;
class ProcessAssertion;
class SandboxExtensionHandle;

struct AuxiliaryProcessCreationParameters;

enum class ProcessThrottleState : uint8_t;

enum class ShouldTakeUIBackgroundAssertion : bool { No, Yes };
enum class AlwaysRunsAtBackgroundPriority : bool { No, Yes };

using ExtensionCapabilityGrantMap = HashMap<String, ExtensionCapabilityGrant>;

class AuxiliaryProcessProxy
    : public ThreadSafeRefCounted<AuxiliaryProcessProxy, WTF::DestructionThread::MainRunLoop>
    , public ResponsivenessTimer::Client
    , private ProcessLauncher::Client
    , public IPC::Connection::Client {
    WTF_MAKE_NONCOPYABLE(AuxiliaryProcessProxy);
    WTF_MAKE_TZONE_ALLOCATED(AuxiliaryProcessProxy);
    WTF_OVERRIDE_DELETE_FOR_CHECKED_PTR(AuxiliaryProcessProxy);
protected:
    AuxiliaryProcessProxy(ShouldTakeUIBackgroundAssertion, AlwaysRunsAtBackgroundPriority = AlwaysRunsAtBackgroundPriority::No, Seconds responsivenessTimeout = ResponsivenessTimer::defaultResponsivenessTimeout);

public:
    USING_CAN_MAKE_WEAKPTR(ResponsivenessTimer::Client);

    // ProcessLauncher::Client
    uint32_t checkedPtrCount() const final { return IPC::Connection::Client::checkedPtrCount(); }
    uint32_t checkedPtrCountWithoutThreadCheck() const final { return IPC::Connection::Client::checkedPtrCountWithoutThreadCheck(); }
    void incrementCheckedPtrCount() const final { IPC::Connection::Client::incrementCheckedPtrCount(); }
    void decrementCheckedPtrCount() const final { IPC::Connection::Client::decrementCheckedPtrCount(); }

    virtual ~AuxiliaryProcessProxy();

    static AuxiliaryProcessCreationParameters auxiliaryProcessParameters();

    enum class Type : uint8_t {
        GraphicsProcessing,
        Network,
#if ENABLE(MODEL_PROCESS)
        Model,
#endif
        WebContent,
    };
    virtual Type type() const = 0;

    void connect();
    virtual void terminate();

    ProcessThrottler& throttler() { return m_throttler; }
    const ProcessThrottler& throttler() const { return m_throttler; }
    Ref<ProcessThrottler> protectedThrottler() { return m_throttler; }
    Ref<const ProcessThrottler> protectedThrottler() const { return m_throttler; }

    template<typename T> bool send(T&& message, uint64_t destinationID, OptionSet<IPC::SendOption> sendOptions = { });

    template<typename T> using SendSyncResult = IPC::Connection::SendSyncResult<T>;
    template<typename T> SendSyncResult<T> sendSync(T&& message, uint64_t destinationID, IPC::Timeout = 1_s, OptionSet<IPC::SendSyncOption> sendSyncOptions = { });

    enum class ShouldStartProcessThrottlerActivity : bool { No, Yes };
    using AsyncReplyID = IPC::Connection::AsyncReplyID;
    template<typename T, typename C> std::optional<AsyncReplyID> sendWithAsyncReply(T&&, C&&, uint64_t destinationID = 0, OptionSet<IPC::SendOption> = { }, ShouldStartProcessThrottlerActivity = ShouldStartProcessThrottlerActivity::Yes);

    template<typename T, typename C, typename RawValue>
    std::optional<AsyncReplyID> sendWithAsyncReply(T&& message, C&& completionHandler, const ObjectIdentifierGenericBase<RawValue>& destinationID, OptionSet<IPC::SendOption> sendOptions = { }, ShouldStartProcessThrottlerActivity shouldStartProcessThrottlerActivity = ShouldStartProcessThrottlerActivity::Yes)
    {
        return sendWithAsyncReply(std::forward<T>(message), std::forward<C>(completionHandler), destinationID.toUInt64(), sendOptions, shouldStartProcessThrottlerActivity);
    }

    template<typename T, typename RawValue>
    bool send(T&& message, const ObjectIdentifierGenericBase<RawValue>& destinationID, OptionSet<IPC::SendOption> sendOptions = { })
    {
        return send<T>(std::forward<T>(message), destinationID.toUInt64(), sendOptions);
    }

    template<typename T, typename RawValue>
    SendSyncResult<T> sendSync(T&& message, const ObjectIdentifierGenericBase<RawValue>& destinationID, IPC::Timeout timeout = 1_s, OptionSet<IPC::SendSyncOption> sendSyncOptions = { })
    {
        return sendSync<T>(std::forward<T>(message), destinationID.toUInt64(), timeout, sendSyncOptions);
    }

    IPC::Connection& connection() const
    {
        RELEASE_ASSERT(m_connection);
        return *m_connection;
    }

    Ref<IPC::Connection> protectedConnection() const { return connection(); }

    bool hasConnection() const
    {
        return !!m_connection;
    }
    
    bool hasConnection(const IPC::Connection& connection) const
    {
        return m_connection == &connection;
    }
    static AuxiliaryProcessProxy* fromConnection(const IPC::Connection&);

    void addMessageReceiver(IPC::ReceiverName, IPC::MessageReceiver&);
    void addMessageReceiver(IPC::ReceiverName, uint64_t destinationID, IPC::MessageReceiver&);
    void removeMessageReceiver(IPC::ReceiverName, uint64_t destinationID);
    void removeMessageReceiver(IPC::ReceiverName);
    
    template<typename RawValue>
    void addMessageReceiver(IPC::ReceiverName messageReceiverName, const ObjectIdentifierGenericBase<RawValue>& destinationID, IPC::MessageReceiver& receiver)
    {
        addMessageReceiver(messageReceiverName, destinationID.toUInt64(), receiver);
    }
    
    template<typename RawValue>
    void removeMessageReceiver(IPC::ReceiverName messageReceiverName, const ObjectIdentifierGenericBase<RawValue>& destinationID)
    {
        removeMessageReceiver(messageReceiverName, destinationID.toUInt64());
    }

    enum class State {
        Launching,
        Running,
        Terminated,
    };
    inline State state() const;

    String stateString() const;
    bool isLaunching() const { return state() == State::Launching; }
    bool wasTerminated() const;

    ProcessID processID() const { return m_processLauncher ? m_processLauncher->processID() : 0; }

    bool canSendMessage() const { return state() != State::Terminated;}
    bool sendMessage(UniqueRef<IPC::Encoder>&&, OptionSet<IPC::SendOption>, std::optional<IPC::Connection::AsyncReplyHandler> = std::nullopt, ShouldStartProcessThrottlerActivity = ShouldStartProcessThrottlerActivity::Yes);
    bool sendMessageAfterResuming(Vector<uint8_t>&& coalescingKey, UniqueRef<IPC::Encoder>&&);

    void replyToPendingMessages();

    void shutDownProcess();

    WebCore::ProcessIdentifier coreProcessIdentifier() const { return m_processIdentifier; }

    void setProcessSuppressionEnabled(bool);
    bool platformIsBeingDebugged() const;

#if PLATFORM(MAC) && USE(RUNNINGBOARD)
    bool runningBoardThrottlingEnabled();
    void setRunningBoardThrottlingEnabled();
#endif

    enum class UseLazyStop : bool { No, Yes };
    void startResponsivenessTimer(UseLazyStop = UseLazyStop::No);
    void stopResponsivenessTimer();

    void checkForResponsiveness(CompletionHandler<void()>&& = nullptr, UseLazyStop = UseLazyStop::No);

    ResponsivenessTimer& responsivenessTimer() const { return m_responsivenessTimer.get(); }
    Ref<ResponsivenessTimer> protectedResponsivenessTimer() const { return m_responsivenessTimer; }

    void ref() const final { ThreadSafeRefCounted::ref(); }
    void deref() const final { ThreadSafeRefCounted::deref(); }

    bool operator==(const AuxiliaryProcessProxy& other) const { return (this == &other); }

    std::optional<SandboxExtensionHandle> createMobileGestaltSandboxExtensionIfNeeded() const;

#if USE(RUNNINGBOARD)
    void wakeUpTemporarilyForIPC();
#endif

#if USE(EXTENSIONKIT)
    std::optional<ExtensionProcess> extensionProcess() const;
    LaunchGrant* launchGrant() const;
#endif

#if ENABLE(EXTENSION_CAPABILITIES)
    ExtensionCapabilityGrantMap& extensionCapabilityGrants() { return m_extensionCapabilityGrants; }
#endif

#if PLATFORM(COCOA)
    struct TaskInfo {
        ProcessID pid;
        ProcessThrottleState state;
        Seconds totalUserCPUTime;
        Seconds totalSystemCPUTime;
        size_t physicalFootprint;
    };

    std::optional<TaskInfo> taskInfo() const;
#endif

#if ENABLE(CFPREFS_DIRECT_MODE)
    void notifyPreferencesChanged(const String& domain, const String& key, const std::optional<String>& encodedValue);
#endif

    enum ResumeReason : bool { ForegroundActivity, BackgroundActivity };
    virtual void sendPrepareToSuspend(IsSuspensionImminent, double remainingRunTime, CompletionHandler<void()>&&) = 0;
    virtual void sendProcessDidResume(ResumeReason) = 0;
    virtual void didChangeThrottleState(ProcessThrottleState);
    virtual ASCIILiteral clientName() const = 0;
    virtual String environmentIdentifier() const { return emptyString(); }
    virtual void prepareToDropLastAssertion(CompletionHandler<void()>&& completionHandler) { completionHandler(); }
    virtual void didDropLastAssertion() { }

protected:
    // ProcessLauncher::Client
    void didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier&&) override;

    bool dispatchMessage(IPC::Connection&, IPC::Decoder&);
    bool dispatchSyncMessage(IPC::Connection&, IPC::Decoder&, UniqueRef<IPC::Encoder>&);

    void logInvalidMessage(IPC::Connection&, IPC::MessageName);
    virtual ASCIILiteral processName() const = 0;

    virtual void getLaunchOptions(ProcessLauncher::LaunchOptions&);
    virtual void platformGetLaunchOptions(ProcessLauncher::LaunchOptions&) { }

    struct PendingMessage {
        UniqueRef<IPC::Encoder> encoder;
        OptionSet<IPC::SendOption> sendOptions;
        std::optional<IPC::Connection::AsyncReplyHandler> asyncReplyHandler;
    };

    virtual bool shouldSendPendingMessage(const PendingMessage&) { return true; }

    void beginResponsivenessChecks();

    // ResponsivenessTimer::Client.
    void didBecomeUnresponsive() override;
    void didBecomeResponsive() override { }
    void willChangeIsResponsive() override { }
    void didChangeIsResponsive() override { }
    bool mayBecomeUnresponsive() override;

#if HAVE(AUDIO_COMPONENT_SERVER_REGISTRATIONS)
    static RefPtr<WebCore::SharedBuffer> fetchAudioComponentServerRegistrations();
#endif

    struct InitializationActivityAndGrant {
        Ref<ProcessThrottler::ForegroundActivity> foregroundActivity;
#if USE(EXTENSIONKIT)
        RefPtr<LaunchGrant> launchGrant;
#endif
    };

    InitializationActivityAndGrant initializationActivityAndGrant();

private:
    virtual void connectionWillOpen(IPC::Connection&);
    virtual void processWillShutDown(IPC::Connection&) = 0;
    void outgoingMessageQueueIsGrowingLarge();

    void populateOverrideLanguagesLaunchOptions(ProcessLauncher::LaunchOptions&) const;
    Vector<String> platformOverrideLanguages() const;
    void platformStartConnectionTerminationWatchdog();

    // Connection::Client
    void requestRemoteProcessTermination() final;

    const Ref<ResponsivenessTimer> m_responsivenessTimer;
    Vector<PendingMessage> m_pendingMessages;
    RefPtr<ProcessLauncher> m_processLauncher;
    RefPtr<IPC::Connection> m_connection;
    IPC::MessageReceiverMap m_messageReceiverMap;
    bool m_alwaysRunsAtBackgroundPriority { false };
    bool m_didBeginResponsivenessChecks { false };
    bool m_isSuspended { false };
    const WebCore::ProcessIdentifier m_processIdentifier { WebCore::ProcessIdentifier::generate() };
    std::optional<UseLazyStop> m_delayedResponsivenessCheck;
    MonotonicTime m_processStart;
    ProcessThrottler m_throttler;
#if USE(RUNNINGBOARD)
    bool m_startedTerminationWatchdog { false };
#if PLATFORM(MAC)
    RefPtr<ProcessThrottler::ForegroundActivity> m_lifetimeActivity;
    RefPtr<ProcessAssertion> m_boostedJetsamAssertion;
#endif
#endif
#if ENABLE(EXTENSION_CAPABILITIES)
    ExtensionCapabilityGrantMap m_extensionCapabilityGrants;
#endif
    HashMap<Vector<uint8_t>, std::pair<unsigned, std::unique_ptr<IPC::Encoder>>> m_messagesToSendOnResume;
    unsigned m_messagesToSendOnResumeIndex { 0 };
};

template<typename T>
bool AuxiliaryProcessProxy::send(T&& message, uint64_t destinationID, OptionSet<IPC::SendOption> sendOptions)
{
    static_assert(!T::isSync, "Async message expected");

    if constexpr (T::deferSendingIfSuspended) {
        if (UNLIKELY(m_isSuspended)) {
            // encodeCoalescingKey must be called before arguments() below since arguments() takes ownership of the message's args tuple.
            auto coalescingKeyEncoder = makeUniqueRef<IPC::Encoder>(T::name(), destinationID);
            message.encodeCoalescingKey(coalescingKeyEncoder.get());
            Vector<uint8_t> coalescingKey { coalescingKeyEncoder->mutableSpan() };

            auto encoder = makeUniqueRef<IPC::Encoder>(T::name(), destinationID);
            encoder.get() << message.arguments();
            return sendMessageAfterResuming(WTFMove(coalescingKey), WTFMove(encoder));
        }
    }

    auto encoder = makeUniqueRef<IPC::Encoder>(T::name(), destinationID);
    encoder.get() << message.arguments();
    return sendMessage(WTFMove(encoder), sendOptions);
}

template<typename T>
AuxiliaryProcessProxy::SendSyncResult<T> AuxiliaryProcessProxy::sendSync(T&& message, uint64_t destinationID, IPC::Timeout timeout, OptionSet<IPC::SendSyncOption> sendSyncOptions)
{
    static_assert(T::isSync, "Sync message expected");

    RefPtr connection = m_connection;
    if (!connection)
        return { IPC::Error::InvalidConnection };

    TraceScope scope(SyncMessageStart, SyncMessageEnd);

    return connection->sendSync(std::forward<T>(message), destinationID, timeout, sendSyncOptions);
}

template<typename T, typename C>
std::optional<AuxiliaryProcessProxy::AsyncReplyID> AuxiliaryProcessProxy::sendWithAsyncReply(T&& message, C&& completionHandler, uint64_t destinationID, OptionSet<IPC::SendOption> sendOptions, ShouldStartProcessThrottlerActivity shouldStartProcessThrottlerActivity)
{
    static_assert(!T::isSync, "Async message expected");

    auto encoder = makeUniqueRef<IPC::Encoder>(T::name(), destinationID);
    encoder.get() << message.arguments();
    auto handler = IPC::Connection::makeAsyncReplyHandler<T>(std::forward<C>(completionHandler));
    auto replyID = handler.replyID;
    if (sendMessage(WTFMove(encoder), sendOptions, WTFMove(handler), shouldStartProcessThrottlerActivity))
        return replyID;
    return std::nullopt;
}

inline AuxiliaryProcessProxy::State AuxiliaryProcessProxy::state() const
{
    if (m_processLauncher && m_processLauncher->isLaunching())
        return AuxiliaryProcessProxy::State::Launching;

    if (!m_connection)
        return AuxiliaryProcessProxy::State::Terminated;

    return AuxiliaryProcessProxy::State::Running;
}

} // namespace WebKit