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 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518
|
/*
* 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.
*/
#include "config.h"
#include "AuxiliaryProcessProxy.h"
#include "AuxiliaryProcessCreationParameters.h"
#include "AuxiliaryProcessMessages.h"
#include "Logging.h"
#include "OverrideLanguages.h"
#include "UIProcessLogInitialization.h"
#include "WebPageProxy.h"
#include "WebProcessProxy.h"
#include <wtf/RunLoop.h>
#if PLATFORM(COCOA)
#include "SandboxUtilities.h"
#include <sys/sysctl.h>
#include <wtf/spi/darwin/SandboxSPI.h>
#endif
#if PLATFORM(IOS_FAMILY) && !PLATFORM(MACCATALYST)
#import <pal/spi/ios/MobileGestaltSPI.h>
#endif
namespace WebKit {
AuxiliaryProcessProxy::AuxiliaryProcessProxy(bool alwaysRunsAtBackgroundPriority, Seconds responsivenessTimeout)
: m_responsivenessTimer(*this, responsivenessTimeout)
, m_alwaysRunsAtBackgroundPriority(alwaysRunsAtBackgroundPriority)
#if USE(RUNNINGBOARD)
, m_timedActivityForIPC(3_s)
#endif
{
}
AuxiliaryProcessProxy::~AuxiliaryProcessProxy()
{
if (m_connection)
m_connection->invalidate();
if (m_processLauncher) {
m_processLauncher->invalidate();
m_processLauncher = nullptr;
}
replyToPendingMessages();
}
void AuxiliaryProcessProxy::populateOverrideLanguagesLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions) const
{
LOG(Language, "WebProcessProxy is getting launch options.");
auto overrideLanguages = WebKit::overrideLanguages();
if (overrideLanguages.isEmpty()) {
LOG(Language, "overrideLanguages() reports empty. Calling platformOverrideLanguages()");
overrideLanguages = platformOverrideLanguages();
}
if (!overrideLanguages.isEmpty()) {
StringBuilder languageString;
for (size_t i = 0; i < overrideLanguages.size(); ++i) {
if (i)
languageString.append(',');
languageString.append(overrideLanguages[i]);
}
LOG_WITH_STREAM(Language, stream << "Setting WebProcess's launch OverrideLanguages to " << languageString);
launchOptions.extraInitializationData.add<HashTranslatorASCIILiteral>("OverrideLanguages"_s, languageString.toString());
} else
LOG(Language, "overrideLanguages is still empty. Not setting WebProcess's launch OverrideLanguages.");
}
void AuxiliaryProcessProxy::getLaunchOptions(ProcessLauncher::LaunchOptions& launchOptions)
{
launchOptions.processIdentifier = m_processIdentifier;
if (const char* userDirectorySuffix = getenv("DIRHELPER_USER_DIR_SUFFIX")) {
if (auto userDirectorySuffixString = String::fromUTF8(userDirectorySuffix); !userDirectorySuffixString.isNull())
launchOptions.extraInitializationData.add<HashTranslatorASCIILiteral>("user-directory-suffix"_s, userDirectorySuffixString);
}
if (m_alwaysRunsAtBackgroundPriority)
launchOptions.extraInitializationData.add<HashTranslatorASCIILiteral>("always-runs-at-background-priority"_s, "true"_s);
#if ENABLE(DEVELOPER_MODE) && (PLATFORM(GTK) || PLATFORM(WPE))
const char* varname;
switch (launchOptions.processType) {
case ProcessLauncher::ProcessType::Web:
varname = "WEB_PROCESS_CMD_PREFIX";
break;
case ProcessLauncher::ProcessType::Network:
varname = "NETWORK_PROCESS_CMD_PREFIX";
break;
#if ENABLE(GPU_PROCESS)
case ProcessLauncher::ProcessType::GPU:
varname = "GPU_PROCESS_CMD_PREFIX";
break;
#endif
#if ENABLE(BUBBLEWRAP_SANDBOX)
case ProcessLauncher::ProcessType::DBusProxy:
ASSERT_NOT_REACHED();
break;
#endif
}
const char* processCmdPrefix = getenv(varname);
if (processCmdPrefix && *processCmdPrefix)
launchOptions.processCmdPrefix = String::fromUTF8(processCmdPrefix);
#endif // ENABLE(DEVELOPER_MODE) && (PLATFORM(GTK) || PLATFORM(WPE))
populateOverrideLanguagesLaunchOptions(launchOptions);
platformGetLaunchOptions(launchOptions);
}
void AuxiliaryProcessProxy::connect()
{
ASSERT(!m_processLauncher);
m_processStart = MonotonicTime::now();
ProcessLauncher::LaunchOptions launchOptions;
getLaunchOptions(launchOptions);
m_processLauncher = ProcessLauncher::create(this, WTFMove(launchOptions));
}
void AuxiliaryProcessProxy::terminate()
{
RELEASE_LOG(Process, "AuxiliaryProcessProxy::terminate: PID=%d", processID());
#if PLATFORM(COCOA)
if (m_connection && m_connection->kill())
return;
#endif
// FIXME: We should really merge process launching into IPC connection creation and get rid of the process launcher.
if (m_processLauncher)
m_processLauncher->terminateProcess();
}
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;
}
String AuxiliaryProcessProxy::stateString() const
{
auto currentState = state();
switch (currentState) {
case AuxiliaryProcessProxy::State::Launching:
return "Launching"_s;
case AuxiliaryProcessProxy::State::Running:
return "Running"_s;
case AuxiliaryProcessProxy::State::Terminated:
return "Terminated"_s;
default:
RELEASE_ASSERT_NOT_REACHED();
}
}
bool AuxiliaryProcessProxy::wasTerminated() const
{
switch (state()) {
case AuxiliaryProcessProxy::State::Launching:
return false;
case AuxiliaryProcessProxy::State::Terminated:
return true;
case AuxiliaryProcessProxy::State::Running:
break;
}
auto pid = processID();
if (!pid)
return true;
#if PLATFORM(COCOA)
// Use kill() with a signal of 0 to make sure there is indeed still a process with the given PID.
// This is needed because it sometimes takes a little bit of time for us to get notified that a process
// was terminated.
return kill(pid, 0) && errno == ESRCH;
#else
return false;
#endif
}
bool AuxiliaryProcessProxy::sendMessage(UniqueRef<IPC::Encoder>&& encoder, OptionSet<IPC::SendOption> sendOptions, std::optional<IPC::Connection::AsyncReplyHandler> asyncReplyHandler, ShouldStartProcessThrottlerActivity shouldStartProcessThrottlerActivity)
{
// FIXME: We should turn this into a RELEASE_ASSERT().
ASSERT(isMainRunLoop());
if (!isMainRunLoop()) {
callOnMainRunLoop([protectedThis = Ref { *this }, encoder = WTFMove(encoder), sendOptions, asyncReplyHandler = WTFMove(asyncReplyHandler), shouldStartProcessThrottlerActivity]() mutable {
protectedThis->sendMessage(WTFMove(encoder), sendOptions, WTFMove(asyncReplyHandler), shouldStartProcessThrottlerActivity);
});
return true;
}
if (asyncReplyHandler && canSendMessage() && shouldStartProcessThrottlerActivity == ShouldStartProcessThrottlerActivity::Yes) {
auto completionHandler = WTFMove(asyncReplyHandler->completionHandler);
asyncReplyHandler->completionHandler = [activity = throttler().backgroundActivity({ }), completionHandler = WTFMove(completionHandler)](IPC::Decoder* decoder) mutable {
completionHandler(decoder);
};
}
switch (state()) {
case State::Launching:
// If we're waiting for the child process to launch, we need to stash away the messages so we can send them once we have a connection.
m_pendingMessages.append({ WTFMove(encoder), sendOptions, WTFMove(asyncReplyHandler) });
return true;
case State::Running:
if (asyncReplyHandler) {
if (connection()->sendMessageWithAsyncReply(WTFMove(encoder), WTFMove(*asyncReplyHandler), sendOptions) == IPC::Error::NoError)
return true;
} else {
if (connection()->sendMessage(WTFMove(encoder), sendOptions) == IPC::Error::NoError)
return true;
}
break;
case State::Terminated:
break;
}
if (asyncReplyHandler && asyncReplyHandler->completionHandler) {
RunLoop::current().dispatch([completionHandler = WTFMove(asyncReplyHandler->completionHandler)]() mutable {
completionHandler(nullptr);
});
}
return false;
}
void AuxiliaryProcessProxy::addMessageReceiver(IPC::ReceiverName messageReceiverName, IPC::MessageReceiver& messageReceiver)
{
m_messageReceiverMap.addMessageReceiver(messageReceiverName, messageReceiver);
}
void AuxiliaryProcessProxy::addMessageReceiver(IPC::ReceiverName messageReceiverName, uint64_t destinationID, IPC::MessageReceiver& messageReceiver)
{
m_messageReceiverMap.addMessageReceiver(messageReceiverName, destinationID, messageReceiver);
}
void AuxiliaryProcessProxy::removeMessageReceiver(IPC::ReceiverName messageReceiverName, uint64_t destinationID)
{
m_messageReceiverMap.removeMessageReceiver(messageReceiverName, destinationID);
}
void AuxiliaryProcessProxy::removeMessageReceiver(IPC::ReceiverName messageReceiverName)
{
m_messageReceiverMap.removeMessageReceiver(messageReceiverName);
}
bool AuxiliaryProcessProxy::dispatchMessage(IPC::Connection& connection, IPC::Decoder& decoder)
{
return m_messageReceiverMap.dispatchMessage(connection, decoder);
}
bool AuxiliaryProcessProxy::dispatchSyncMessage(IPC::Connection& connection, IPC::Decoder& decoder, UniqueRef<IPC::Encoder>& replyEncoder)
{
return m_messageReceiverMap.dispatchSyncMessage(connection, decoder, replyEncoder);
}
void AuxiliaryProcessProxy::didFinishLaunching(ProcessLauncher*, IPC::Connection::Identifier connectionIdentifier)
{
ASSERT(!m_connection);
ASSERT(isMainRunLoop());
auto launchTime = MonotonicTime::now() - m_processStart;
if (launchTime > 1_s)
RELEASE_LOG_FAULT(Process, "%s process (%p) took %f seconds to launch", processName().characters(), this, launchTime.value());
if (!connectionIdentifier)
return;
#if PLATFORM(MAC) && USE(RUNNINGBOARD)
m_lifetimeActivity = throttler().foregroundActivity("Lifetime Activity"_s).moveToUniquePtr();
m_boostedJetsamAssertion = ProcessAssertion::create(xpc_connection_get_pid(connectionIdentifier.xpcConnection.get()), "Jetsam Boost"_s, ProcessAssertionType::BoostedJetsam);
#endif
m_connection = IPC::Connection::createServerConnection(connectionIdentifier);
connectionWillOpen(*m_connection);
m_connection->open(*this);
m_connection->setOutgoingMessageQueueIsGrowingLargeCallback([weakThis = WeakPtr { *this }] {
ensureOnMainRunLoop([weakThis] {
if (weakThis)
weakThis->outgoingMessageQueueIsGrowingLarge();
});
});
for (auto&& pendingMessage : std::exchange(m_pendingMessages, { })) {
if (!shouldSendPendingMessage(pendingMessage))
continue;
if (pendingMessage.asyncReplyHandler)
m_connection->sendMessageWithAsyncReply(WTFMove(pendingMessage.encoder), WTFMove(*pendingMessage.asyncReplyHandler), pendingMessage.sendOptions);
else
m_connection->sendMessage(WTFMove(pendingMessage.encoder), pendingMessage.sendOptions);
}
}
void AuxiliaryProcessProxy::outgoingMessageQueueIsGrowingLarge()
{
#if USE(RUNNINGBOARD)
wakeUpTemporarilyForIPC();
#endif
}
#if USE(RUNNINGBOARD)
void AuxiliaryProcessProxy::wakeUpTemporarilyForIPC()
{
// If we keep trying to send IPC to a suspended process, the outgoing message queue may grow large and result
// in increased memory usage. To avoid this, we wake up the process for a bit so we can drain the messages.
if (!ProcessThrottler::isValidBackgroundActivity(m_timedActivityForIPC.activity()))
m_timedActivityForIPC = throttler().backgroundActivity("IPC sending due to large outgoing queue"_s);
}
#endif
void AuxiliaryProcessProxy::replyToPendingMessages()
{
ASSERT(isMainRunLoop());
for (auto& pendingMessage : std::exchange(m_pendingMessages, { })) {
if (pendingMessage.asyncReplyHandler)
pendingMessage.asyncReplyHandler->completionHandler(nullptr);
}
}
void AuxiliaryProcessProxy::shutDownProcess()
{
switch (state()) {
case State::Launching:
m_processLauncher->invalidate();
m_processLauncher = nullptr;
break;
case State::Running:
platformStartConnectionTerminationWatchdog();
break;
case State::Terminated:
return;
}
if (!m_connection)
return;
processWillShutDown(*m_connection);
if (canSendMessage())
send(Messages::AuxiliaryProcess::ShutDown(), 0);
m_connection->invalidate();
m_connection = nullptr;
m_responsivenessTimer.invalidate();
}
void AuxiliaryProcessProxy::setProcessSuppressionEnabled(bool processSuppressionEnabled)
{
#if PLATFORM(COCOA)
if (state() != State::Running)
return;
connection()->send(Messages::AuxiliaryProcess::SetProcessSuppressionEnabled(processSuppressionEnabled), 0);
#else
UNUSED_PARAM(processSuppressionEnabled);
#endif
}
void AuxiliaryProcessProxy::connectionWillOpen(IPC::Connection&)
{
}
void AuxiliaryProcessProxy::logInvalidMessage(IPC::Connection& connection, IPC::MessageName messageName)
{
RELEASE_LOG_FAULT(IPC, "Received an invalid message '%" PUBLIC_LOG_STRING "' from the %" PUBLIC_LOG_STRING " process with PID %d", description(messageName), processName().characters(), processID());
}
bool AuxiliaryProcessProxy::platformIsBeingDebugged() const
{
#if PLATFORM(COCOA)
// If the UI process is sandboxed and lacks 'process-info-pidinfo', it cannot find out whether other processes are being debugged.
if (currentProcessIsSandboxed() && !!sandbox_check(getpid(), "process-info-pidinfo", SANDBOX_CHECK_NO_REPORT))
return false;
struct kinfo_proc info;
int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, processID() };
size_t size = sizeof(info);
if (sysctl(mib, std::size(mib), &info, &size, nullptr, 0) == -1)
return false;
return info.kp_proc.p_flag & P_TRACED;
#else
return false;
#endif
}
void AuxiliaryProcessProxy::stopResponsivenessTimer()
{
responsivenessTimer().stop();
}
void AuxiliaryProcessProxy::beginResponsivenessChecks()
{
m_didBeginResponsivenessChecks = true;
if (m_delayedResponsivenessCheck)
startResponsivenessTimer(*std::exchange(m_delayedResponsivenessCheck, std::nullopt));
}
void AuxiliaryProcessProxy::startResponsivenessTimer(UseLazyStop useLazyStop)
{
if (!m_didBeginResponsivenessChecks) {
if (!m_delayedResponsivenessCheck)
m_delayedResponsivenessCheck = useLazyStop;
return;
}
if (useLazyStop == UseLazyStop::Yes)
responsivenessTimer().startWithLazyStop();
else
responsivenessTimer().start();
}
bool AuxiliaryProcessProxy::mayBecomeUnresponsive()
{
return !(platformIsBeingDebugged() || throttler().isSuspended());
}
void AuxiliaryProcessProxy::didBecomeUnresponsive()
{
RELEASE_LOG_ERROR(Process, "AuxiliaryProcessProxy::didBecomeUnresponsive: %" PUBLIC_LOG_STRING " process with PID %d became unresponsive", processName().characters(), processID());
}
void AuxiliaryProcessProxy::checkForResponsiveness(CompletionHandler<void()>&& responsivenessHandler, UseLazyStop useLazyStop)
{
startResponsivenessTimer(useLazyStop);
sendWithAsyncReply(Messages::AuxiliaryProcess::MainThreadPing(), [weakThis = WeakPtr { *this }, responsivenessHandler = WTFMove(responsivenessHandler)]() mutable {
// Schedule an asynchronous task because our completion handler may have been called as a result of the AuxiliaryProcessProxy
// being in the middle of destruction.
RunLoop::main().dispatch([weakThis = WTFMove(weakThis), responsivenessHandler = WTFMove(responsivenessHandler)]() mutable {
if (weakThis)
weakThis->stopResponsivenessTimer();
if (responsivenessHandler)
responsivenessHandler();
});
});
}
AuxiliaryProcessCreationParameters AuxiliaryProcessProxy::auxiliaryProcessParameters()
{
AuxiliaryProcessCreationParameters parameters;
#if !LOG_DISABLED || !RELEASE_LOG_DISABLED
parameters.wtfLoggingChannels = UIProcess::wtfLogLevelString();
parameters.webCoreLoggingChannels = UIProcess::webCoreLogLevelString();
parameters.webKitLoggingChannels = UIProcess::webKitLogLevelString();
#endif
return parameters;
}
std::optional<SandboxExtensionHandle> AuxiliaryProcessProxy::createMobileGestaltSandboxExtensionIfNeeded() const
{
#if PLATFORM(IOS_FAMILY) && !PLATFORM(MACCATALYST)
if (_MGCacheValid())
return std::nullopt;
RELEASE_LOG_FAULT(Sandbox, "MobileGestalt cache is invalid! Creating a sandbox extension to repopulate cache in memory.");
return SandboxExtension::createHandleForMachLookup("com.apple.mobilegestalt.xpc"_s, std::nullopt);
#else
return std::nullopt;
#endif
}
#if !PLATFORM(COCOA)
Vector<String> AuxiliaryProcessProxy::platformOverrideLanguages() const
{
return { };
}
void AuxiliaryProcessProxy::platformStartConnectionTerminationWatchdog()
{
}
#endif
#if PLATFORM(MAC) && USE(RUNNINGBOARD)
void AuxiliaryProcessProxy::setRunningBoardThrottlingEnabled()
{
m_lifetimeActivity = nullptr;
}
bool AuxiliaryProcessProxy::runningBoardThrottlingEnabled()
{
return !m_lifetimeActivity;
}
#endif
} // namespace WebKit
|