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
|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "gtest/gtest.h"
#include "mozilla/_ipdltest/IPDLUnitTest.h"
#include "mozilla/ipc/NodeController.h"
#include "mozilla/ipc/ProtocolUtils.h"
#include "mozilla/ipc/ProcessChild.h"
#include "mozilla/ipc/ProcessUtils.h"
#include "mozilla/SpinEventLoopUntil.h"
#include "nsDebugImpl.h"
#include "nsThreadManager.h"
#ifdef MOZ_WIDGET_ANDROID
# include "nsIAppShell.h"
# include "nsServiceManagerUtils.h"
# include "nsWidgetsCID.h"
#endif
namespace mozilla::_ipdltest {
MOZ_RUNINIT static std::unordered_map<std::string_view,
ipc::IToplevelProtocol* (*)()>
sAllocChildActorRegistry;
const char* RegisterAllocChildActor(const char* aName,
ipc::IToplevelProtocol* (*aFunc)()) {
sAllocChildActorRegistry[aName] = aFunc;
return aName;
}
already_AddRefed<IPDLUnitTestParent> IPDLUnitTestParent::CreateCrossProcess() {
#ifdef MOZ_WIDGET_ANDROID
// Force-initialize the appshell on android, as android child process
// launching depends on widget component initialization.
nsCOMPtr<nsIAppShell> _appShell = do_GetService(NS_APPSHELL_CID);
#endif
RefPtr<IPDLUnitTestParent> parent = new IPDLUnitTestParent();
parent->mSubprocess =
new ipc::GeckoChildProcessHost(GeckoProcessType_IPDLUnitTest);
geckoargs::ChildProcessArgs extraArgs;
auto prefSerializer = MakeUnique<ipc::SharedPreferenceSerializer>();
if (!prefSerializer->SerializeToSharedMemory(GeckoProcessType_IPDLUnitTest,
/* remoteType */ ""_ns)) {
ADD_FAILURE()
<< "SharedPreferenceSerializer::SerializeToSharedMemory failed";
return nullptr;
}
prefSerializer->AddSharedPrefCmdLineArgs(*parent->mSubprocess, extraArgs);
if (!parent->mSubprocess->SyncLaunch(std::move(extraArgs))) {
ADD_FAILURE() << "Subprocess launch failed";
return nullptr;
}
if (!parent->mSubprocess->TakeInitialEndpoint().Bind(parent.get())) {
ADD_FAILURE() << "Opening the parent actor failed";
return nullptr;
}
EXPECT_TRUE(parent->CanSend());
return parent.forget();
}
already_AddRefed<IPDLUnitTestParent> IPDLUnitTestParent::CreateCrossThread() {
RefPtr<IPDLUnitTestParent> parent = new IPDLUnitTestParent();
RefPtr<IPDLUnitTestChild> child = new IPDLUnitTestChild();
nsresult rv =
NS_NewNamedThread("IPDL UnitTest", getter_AddRefs(parent->mOtherThread));
if (NS_FAILED(rv)) {
ADD_FAILURE() << "Failed to create IPDLUnitTest thread";
return nullptr;
}
if (!parent->Open(child, parent->mOtherThread)) {
ADD_FAILURE() << "Opening the actor failed";
return nullptr;
}
EXPECT_TRUE(parent->CanSend());
return parent.forget();
}
IPDLUnitTestParent::~IPDLUnitTestParent() {
if (mSubprocess) {
mSubprocess->Destroy();
mSubprocess = nullptr;
}
if (mOtherThread) {
mOtherThread->Shutdown();
}
}
bool IPDLUnitTestParent::Start(const char* aName,
ipc::IToplevelProtocol* aActor) {
nsID channelId = nsID::GenerateUUID();
auto [parentPort, childPort] =
ipc::NodeController::GetSingleton()->CreatePortPair();
if (!SendStart(nsDependentCString(aName), std::move(childPort), channelId)) {
ADD_FAILURE() << "IPDLUnitTestParent::SendStart failed";
return false;
}
if (!aActor->Open(std::move(parentPort), channelId,
OtherEndpointProcInfo())) {
ADD_FAILURE() << "Unable to open parent actor";
return false;
}
return true;
}
ipc::IPCResult IPDLUnitTestParent::RecvReport(const TestPartResult& aReport) {
if (!aReport.failed()) {
return IPC_OK();
}
// Report the failure
ADD_FAILURE_AT(aReport.filename().get(), aReport.lineNumber())
<< "[child " << OtherPid() << "] " << aReport.summary();
// If the failure was fatal, kill the child process to avoid hangs.
if (aReport.fatal()) {
KillHard();
}
return IPC_OK();
}
ipc::IPCResult IPDLUnitTestParent::RecvComplete() {
mComplete = true;
Close();
return IPC_OK();
}
void IPDLUnitTestParent::KillHard() {
if (mCalledKillHard) {
return;
}
mCalledKillHard = true;
// We can't effectively kill a same-process situation, but we can trigger
// shutdown early to avoid hanging.
if (mOtherThread) {
Close();
nsCOMPtr<nsIThread> otherThread = mOtherThread.forget();
otherThread->Shutdown();
}
if (mSubprocess) {
ProcessHandle handle = mSubprocess->GetChildProcessHandle();
if (!base::KillProcess(handle, base::PROCESS_END_KILLED_BY_USER)) {
NS_WARNING("failed to kill subprocess!");
}
mSubprocess->SetAlreadyDead();
}
}
ipc::IPCResult IPDLUnitTestChild::RecvStart(const nsCString& aName,
ipc::ScopedPort aPort,
const nsID& aMessageChannelId) {
auto* allocChildActor =
sAllocChildActorRegistry[std::string_view{aName.get()}];
if (!allocChildActor) {
ADD_FAILURE() << "No AllocChildActor for name " << aName.get()
<< " registered!";
return IPC_FAIL(this, "No AllocChildActor registered!");
}
// Store references to the node & port to watch for test completion.
RefPtr<ipc::NodeController> controller = aPort.Controller();
mojo::core::ports::PortRef port = aPort.Port();
RefPtr<IToplevelProtocol> child = allocChildActor();
if (!child->Open(std::move(aPort), aMessageChannelId,
OtherEndpointProcInfo())) {
ADD_FAILURE() << "Unable to open child actor";
return IPC_FAIL(this, "Unable to open child actor");
}
// Wait for the port which was created for this actor to be fully torn down.
SpinEventLoopUntil("IPDLUnitTestChild::RecvStart"_ns,
[&] { return controller->GetStatus(port).isNothing(); });
// Tear down the test actor to end the test.
SendComplete();
return IPC_OK();
}
void IPDLUnitTestChild::ActorDestroy(ActorDestroyReason aWhy) {
if (!XRE_IsParentProcess()) {
XRE_ShutdownChildProcess();
}
}
void IPDLTestHelper::TestWrapper(bool aCrossProcess) {
// Create the host and start the test actor with it.
RefPtr<IPDLUnitTestParent> host =
aCrossProcess ? IPDLUnitTestParent::CreateCrossProcess()
: IPDLUnitTestParent::CreateCrossThread();
ASSERT_TRUE(host);
if (!host->Start(GetName(), GetActor())) {
FAIL();
}
// XXX: Consider adding a test timeout?
// Run the test body. This will send the initial messages to our actor, which
// will eventually clean itself up.
TestBody();
// Spin the event loop until the test wrapper host has fully shut down.
SpinEventLoopUntil("IPDLTestHelper::TestWrapper"_ns,
[&] { return !host->CanSend(); });
EXPECT_TRUE(host->ReportedComplete())
<< "child process exited without signalling completion";
}
// Listener registered within the IPDLUnitTest process used to relay GTest
// failures to the parent process, so that the are marked as failing the overall
// gtest.
class IPDLChildProcessTestListener : public testing::EmptyTestEventListener {
public:
explicit IPDLChildProcessTestListener(IPDLUnitTestChild* aActor)
: mActor(aActor) {}
virtual void OnTestPartResult(
const testing::TestPartResult& aTestPartResult) override {
mActor->SendReport(TestPartResult(
aTestPartResult.failed(), aTestPartResult.fatally_failed(),
nsDependentCString(aTestPartResult.file_name()),
aTestPartResult.line_number(),
nsDependentCString(aTestPartResult.summary()),
nsDependentCString(aTestPartResult.message())));
}
RefPtr<IPDLUnitTestChild> mActor;
};
// ProcessChild instance used to run the IPDLUnitTest process.
class IPDLUnitTestProcessChild : public ipc::ProcessChild {
public:
using ipc::ProcessChild::ProcessChild;
bool Init(int aArgc, char* aArgv[]) override {
nsDebugImpl::SetMultiprocessMode("IPDLUnitTest");
if (!ProcessChild::InitPrefs(aArgc, aArgv)) {
MOZ_CRASH("InitPrefs failed");
return false;
}
if (NS_WARN_IF(NS_FAILED(nsThreadManager::get().Init()))) {
MOZ_CRASH("nsThreadManager initialization failed");
return false;
}
RefPtr<IPDLUnitTestChild> child = new IPDLUnitTestChild();
if (!TakeInitialEndpoint().Bind(child.get())) {
MOZ_CRASH("Bind of IPDLUnitTestChild failed");
return false;
}
// Register a listener to forward test results from the child process to the
// parent process to be handled there.
mListener = new IPDLChildProcessTestListener(child);
testing::UnitTest::GetInstance()->listeners().Append(mListener);
if (NS_FAILED(NS_InitMinimalXPCOM())) {
MOZ_CRASH("NS_InitMinimalXPCOM failed");
return false;
}
ipc::SetThisProcessName("IPDLUnitTest");
return true;
}
void CleanUp() override {
// Clean up the test listener we registered to get a clean shutdown.
if (mListener) {
testing::UnitTest::GetInstance()->listeners().Release(mListener);
delete mListener;
}
NS_ShutdownXPCOM(nullptr);
}
IPDLChildProcessTestListener* mListener = nullptr;
};
// Defined in nsEmbedFunctions.cpp
extern UniquePtr<ipc::ProcessChild> (*gMakeIPDLUnitTestProcessChild)(
IPC::Channel::ChannelHandle, base::ProcessId, const nsID&);
// Initialize gMakeIPDLUnitTestProcessChild in a static constructor.
MOZ_RUNINIT int _childProcessEntryPointStaticConstructor = ([] {
gMakeIPDLUnitTestProcessChild =
[](IPC::Channel::ChannelHandle aClientChannel, base::ProcessId aParentPid,
const nsID& aMessageChannelId) -> UniquePtr<ipc::ProcessChild> {
return MakeUnique<IPDLUnitTestProcessChild>(std::move(aClientChannel),
aParentPid, aMessageChannelId);
};
return 0;
})();
} // namespace mozilla::_ipdltest
|