summaryrefslogtreecommitdiffstats
path: root/browser/app/winlauncher/test
diff options
context:
space:
mode:
authorDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
committerDaniel Baumann <daniel.baumann@progress-linux.org>2024-04-28 14:29:10 +0000
commit2aa4a82499d4becd2284cdb482213d541b8804dd (patch)
treeb80bf8bf13c3766139fbacc530efd0dd9d54394c /browser/app/winlauncher/test
parentInitial commit. (diff)
downloadfirefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz
firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'browser/app/winlauncher/test')
-rw-r--r--browser/app/winlauncher/test/TestCrossProcessWin.cpp365
-rw-r--r--browser/app/winlauncher/test/TestSafeThreadLocal.cpp74
-rw-r--r--browser/app/winlauncher/test/TestSameBinary.cpp255
-rw-r--r--browser/app/winlauncher/test/moz.build30
4 files changed, 724 insertions, 0 deletions
diff --git a/browser/app/winlauncher/test/TestCrossProcessWin.cpp b/browser/app/winlauncher/test/TestCrossProcessWin.cpp
new file mode 100644
index 0000000000..0c5c57aaaa
--- /dev/null
+++ b/browser/app/winlauncher/test/TestCrossProcessWin.cpp
@@ -0,0 +1,365 @@
+/* -*- 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 https://mozilla.org/MPL/2.0/. */
+
+#define MOZ_USE_LAUNCHER_ERROR
+
+#include "freestanding/SharedSection.cpp"
+#include "mozilla/CmdLineAndEnvUtils.h"
+#include "mozilla/NativeNt.h"
+
+const wchar_t kChildArg[] = L"--child";
+const char kTestStrings[][6] = {
+ "a b c", "A B C", "a b c", "A B C", "X Y Z",
+};
+const wchar_t kTestStringsMerged[] =
+ L"a b c"
+ L"\0"
+ L"X Y Z"
+ L"\0";
+
+using namespace mozilla;
+using namespace mozilla::freestanding;
+
+template <typename T, int N>
+void PrintLauncherError(const LauncherResult<T>& aResult,
+ const char (&aMsg)[N]) {
+ const LauncherError& err = aResult.inspectErr();
+ printf("TEST-FAILED | TestCrossProcessWin | %s - %lx at %s:%d\n", aMsg,
+ err.mError.AsHResult(), err.mFile, err.mLine);
+}
+
+#define VERIFY_FUNCTION_RESOLVED(mod, exports, name) \
+ do { \
+ if (reinterpret_cast<FARPROC>(exports.m##name) != \
+ ::GetProcAddress(mod, #name)) { \
+ printf( \
+ "TEST-FAILED | TestCrossProcessWin | " \
+ "Kernel32ExportsSolver::" #name " did not match.\n"); \
+ return false; \
+ } \
+ } while (0)
+
+static bool VerifySharedSection(SharedSection& aSharedSection) {
+ LauncherResult<SharedSection::Layout*> resultView = aSharedSection.GetView();
+ if (resultView.isErr()) {
+ PrintLauncherError(resultView, "Failed to map a shared section");
+ return false;
+ }
+
+ SharedSection::Layout* view = resultView.unwrap();
+
+ // Use a local variable of RTL_RUN_ONCE to resolve Kernel32Exports every time
+ RTL_RUN_ONCE sRunEveryTime = RTL_RUN_ONCE_INIT;
+ view->mK32Exports.Resolve(sRunEveryTime);
+
+ HMODULE k32mod = ::GetModuleHandleW(L"kernel32.dll");
+ VERIFY_FUNCTION_RESOLVED(k32mod, view->mK32Exports, FlushInstructionCache);
+ VERIFY_FUNCTION_RESOLVED(k32mod, view->mK32Exports, GetModuleHandleW);
+ VERIFY_FUNCTION_RESOLVED(k32mod, view->mK32Exports, GetSystemInfo);
+ VERIFY_FUNCTION_RESOLVED(k32mod, view->mK32Exports, VirtualProtect);
+
+ bool matched = memcmp(view->mModulePathArray, kTestStringsMerged,
+ sizeof(kTestStringsMerged)) == 0;
+ if (!matched) {
+ // Print actual strings on error
+ for (const wchar_t* p = view->mModulePathArray; *p;) {
+ printf("%p: %ls\n", p, p);
+ while (*p) {
+ ++p;
+ }
+ ++p;
+ }
+ return false;
+ }
+
+ return true;
+}
+
+static bool TestAddString() {
+ wchar_t testBuffer[3] = {0};
+ UNICODE_STRING ustr;
+
+ // This makes |testBuffer| full.
+ ::RtlInitUnicodeString(&ustr, L"a");
+ if (!AddString(testBuffer, sizeof(testBuffer), ustr)) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "AddString failed.\n");
+ return false;
+ }
+
+ // Adding a string to a full buffer should fail.
+ ::RtlInitUnicodeString(&ustr, L"b");
+ if (AddString(testBuffer, sizeof(testBuffer), ustr)) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "AddString caused OOB memory access.\n");
+ return false;
+ }
+
+ bool matched = memcmp(testBuffer, L"a\0", sizeof(testBuffer)) == 0;
+ if (!matched) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "AddString wrote wrong values.\n");
+ return false;
+ }
+
+ return true;
+}
+
+class ChildProcess final {
+ nsAutoHandle mChildProcess;
+ nsAutoHandle mChildMainThread;
+ DWORD mProcessId;
+
+ public:
+ // The following variables are updated from the parent process via
+ // WriteProcessMemory while the process is suspended as a part of
+ // TestWithChildProcess().
+ //
+ // Having both a non-const and a const is important because a constant
+ // is separately placed in the .rdata section which is read-only, so
+ // the region's attribute needs to be changed before modifying data via
+ // WriteProcessMemory.
+ // The keyword "volatile" is needed for a constant, otherwise the compiler
+ // evaluates a constant as a literal without fetching data from memory.
+ static HMODULE sExecutableImageBase;
+ static volatile const DWORD sReadOnlyProcessId;
+
+ static int Main() {
+ if (sExecutableImageBase != ::GetModuleHandle(nullptr)) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "sExecutableImageBase is expected to be %p, but actually was %p.\n",
+ ::GetModuleHandle(nullptr), sExecutableImageBase);
+ return 1;
+ }
+
+ if (sReadOnlyProcessId != ::GetCurrentProcessId()) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "sReadOnlyProcessId is expected to be %lx, but actually was %lx.\n",
+ ::GetCurrentProcessId(), sReadOnlyProcessId);
+ return 1;
+ }
+
+ auto getDependentModulePaths =
+ reinterpret_cast<const wchar_t (*)()>(::GetProcAddress(
+ ::GetModuleHandleW(nullptr), "GetDependentModulePaths"));
+ if (!getDependentModulePaths) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "Failed to get a pointer to GetDependentModulePaths - %08lx.\n",
+ ::GetLastError());
+ return 1;
+ }
+
+#if !defined(DEBUG)
+ // GetDependentModulePaths does not allow a caller other than xul.dll.
+ // Skip on Debug build because it hits MOZ_ASSERT.
+ if (getDependentModulePaths()) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "GetDependentModulePaths should return zero if the caller is "
+ "not xul.dll.\n");
+ return 1;
+ }
+#endif // !defined(DEBUG)
+
+ if (!VerifySharedSection(gSharedSection)) {
+ return 1;
+ }
+
+ // Test a scenario to transfer a transferred section as a readonly handle
+ static HANDLE copiedHandle = nullptr;
+ nt::CrossExecTransferManager tansferToSelf(::GetCurrentProcess());
+ LauncherVoidResult result = gSharedSection.TransferHandle(
+ tansferToSelf, GENERIC_READ, &copiedHandle);
+ if (result.isErr()) {
+ PrintLauncherError(result, "SharedSection::TransferHandle(self) failed");
+ return 1;
+ }
+
+ gSharedSection.Reset(copiedHandle);
+
+ UNICODE_STRING ustr;
+ ::RtlInitUnicodeString(&ustr, L"test");
+ result = gSharedSection.AddDepenentModule(&ustr);
+ if (result.inspectErr() !=
+ WindowsError::FromWin32Error(ERROR_ACCESS_DENIED)) {
+ PrintLauncherError(result, "The readonly section was writable");
+ return 1;
+ }
+
+ if (!VerifySharedSection(gSharedSection)) {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ ChildProcess(const wchar_t* aExecutable, const wchar_t* aOption)
+ : mProcessId(0) {
+ const wchar_t* childArgv[] = {aExecutable, aOption};
+ auto cmdLine(
+ mozilla::MakeCommandLine(mozilla::ArrayLength(childArgv), childArgv));
+
+ STARTUPINFOW si = {sizeof(si)};
+ PROCESS_INFORMATION pi;
+ BOOL ok =
+ ::CreateProcessW(aExecutable, cmdLine.get(), nullptr, nullptr, FALSE,
+ CREATE_SUSPENDED, nullptr, nullptr, &si, &pi);
+ if (!ok) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "CreateProcessW falied - %08lx.\n",
+ GetLastError());
+ return;
+ }
+
+ mProcessId = pi.dwProcessId;
+
+ mChildProcess.own(pi.hProcess);
+ mChildMainThread.own(pi.hThread);
+ }
+
+ ~ChildProcess() { ::TerminateProcess(mChildProcess, 0); }
+
+ operator HANDLE() const { return mChildProcess; }
+ DWORD GetProcessId() const { return mProcessId; }
+
+ bool ResumeAndWaitUntilExit() {
+ if (::ResumeThread(mChildMainThread) == 0xffffffff) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "ResumeThread failed - %08lx\n",
+ GetLastError());
+ return false;
+ }
+
+ if (::WaitForSingleObject(mChildProcess, 60000) != WAIT_OBJECT_0) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "Unexpected result from WaitForSingleObject\n");
+ return false;
+ }
+
+ DWORD exitCode;
+ if (!::GetExitCodeProcess(mChildProcess, &exitCode)) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "GetExitCodeProcess failed - %08lx\n",
+ GetLastError());
+ return false;
+ }
+
+ return exitCode == 0;
+ }
+};
+
+HMODULE ChildProcess::sExecutableImageBase = 0;
+volatile const DWORD ChildProcess::sReadOnlyProcessId = 0;
+
+int wmain(int argc, wchar_t* argv[]) {
+ printf("Process: %-8lx Base: %p\n", ::GetCurrentProcessId(),
+ ::GetModuleHandle(nullptr));
+
+ if (argc == 2 && wcscmp(argv[1], kChildArg) == 0) {
+ return ChildProcess::Main();
+ }
+
+ ChildProcess childProcess(argv[0], kChildArg);
+ if (!childProcess) {
+ return 1;
+ }
+
+ if (!TestAddString()) {
+ return 1;
+ }
+
+ LauncherResult<HMODULE> remoteImageBase =
+ nt::GetProcessExeModule(childProcess);
+ if (remoteImageBase.isErr()) {
+ PrintLauncherError(remoteImageBase, "nt::GetProcessExeModule failed");
+ return 1;
+ }
+
+ nt::CrossExecTransferManager transferMgr(childProcess);
+ if (!transferMgr) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "CrossExecTransferManager instantiation failed.\n");
+ return 1;
+ }
+
+ LauncherVoidResult result =
+ transferMgr.Transfer(&ChildProcess::sExecutableImageBase,
+ &remoteImageBase.inspect(), sizeof(HMODULE));
+ if (result.isErr()) {
+ PrintLauncherError(result, "ChildProcess::WriteData(Imagebase) failed");
+ return 1;
+ }
+
+ DWORD childPid = childProcess.GetProcessId();
+
+ DWORD* readOnlyData = const_cast<DWORD*>(&ChildProcess::sReadOnlyProcessId);
+ result = transferMgr.Transfer(readOnlyData, &childPid, sizeof(DWORD));
+ if (result.isOk()) {
+ printf(
+ "TEST-UNEXPECTED | TestCrossProcessWin | "
+ "A constant was located in a writable section.");
+ return 1;
+ }
+
+ AutoVirtualProtect prot =
+ transferMgr.Protect(readOnlyData, sizeof(uint32_t), PAGE_READWRITE);
+ if (!prot) {
+ printf(
+ "TEST-FAILED | TestCrossProcessWin | "
+ "VirtualProtect failed - %08lx\n",
+ prot.GetError().AsHResult());
+ return 1;
+ }
+
+ result = transferMgr.Transfer(readOnlyData, &childPid, sizeof(DWORD));
+ if (result.isErr()) {
+ PrintLauncherError(result, "ChildProcess::WriteData(PID) failed");
+ return 1;
+ }
+
+ {
+ // Define a scope for |sharedSection| to resume the child process after
+ // the section is deleted in the parent process.
+ result = gSharedSection.Init(transferMgr.LocalPEHeaders());
+ if (result.isErr()) {
+ PrintLauncherError(result, "SharedSection::Init failed");
+ return 1;
+ }
+
+ for (const auto& testString : kTestStrings) {
+ nt::AllocatedUnicodeString ustr(testString);
+ result = gSharedSection.AddDepenentModule(ustr);
+ if (result.isErr()) {
+ PrintLauncherError(result, "SharedSection::AddDepenentModule failed");
+ return 1;
+ }
+ }
+
+ result = gSharedSection.TransferHandle(transferMgr,
+ GENERIC_READ | GENERIC_WRITE);
+ if (result.isErr()) {
+ PrintLauncherError(result, "SharedSection::TransferHandle failed");
+ return 1;
+ }
+ }
+
+ if (!childProcess.ResumeAndWaitUntilExit()) {
+ return 1;
+ }
+
+ return 0;
+}
diff --git a/browser/app/winlauncher/test/TestSafeThreadLocal.cpp b/browser/app/winlauncher/test/TestSafeThreadLocal.cpp
new file mode 100644
index 0000000000..5aa122e16e
--- /dev/null
+++ b/browser/app/winlauncher/test/TestSafeThreadLocal.cpp
@@ -0,0 +1,74 @@
+/* -*- 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 https://mozilla.org/MPL/2.0/. */
+
+#define MOZ_USE_LAUNCHER_ERROR
+
+#include "freestanding/SafeThreadLocal.h"
+
+#include "mozilla/NativeNt.h"
+#include "nsWindowsHelpers.h"
+
+#include <process.h>
+#include <stdio.h>
+
+// Need a non-inline function to bypass compiler optimization that the thread
+// local storage pointer is cached in a register before accessing a thread-local
+// variable.
+MOZ_NEVER_INLINE PVOID SwapThreadLocalStoragePointer(PVOID aNewValue) {
+ auto oldValue = mozilla::nt::RtlGetThreadLocalStoragePointer();
+ mozilla::nt::RtlSetThreadLocalStoragePointerForTestingOnly(aNewValue);
+ return oldValue;
+}
+
+static mozilla::freestanding::SafeThreadLocal<int*> gTheStorage;
+
+static unsigned int __stdcall TestNonMainThread(void* aArg) {
+ for (int i = 0; i < 100; ++i) {
+ gTheStorage.set(&i);
+ if (gTheStorage.get() != &i) {
+ printf(
+ "TEST-FAILED | TestSafeThreadLocal | "
+ "A value is not correctly stored in the thread-local storage.\n");
+ return 1;
+ }
+ }
+ return 0;
+}
+
+extern "C" int wmain(int argc, wchar_t* argv[]) {
+ int dummy = 0x1234;
+
+ auto origHead = SwapThreadLocalStoragePointer(nullptr);
+ // Setting gTheStorage when TLS is null.
+ gTheStorage.set(&dummy);
+ SwapThreadLocalStoragePointer(origHead);
+
+ nsAutoHandle handles[8];
+ for (auto& handle : handles) {
+ handle.own(reinterpret_cast<HANDLE>(
+ ::_beginthreadex(nullptr, 0, TestNonMainThread, nullptr, 0, nullptr)));
+ }
+
+ for (int i = 0; i < 100; ++i) {
+ if (gTheStorage.get() != &dummy) {
+ printf(
+ "TEST-FAILED | TestSafeThreadLocal | "
+ "A value is not correctly stored in the global scope.\n");
+ return 1;
+ }
+ }
+
+ for (auto& handle : handles) {
+ ::WaitForSingleObject(handle, INFINITE);
+
+ DWORD exitCode;
+ if (!::GetExitCodeThread(handle, &exitCode) || exitCode) {
+ return 1;
+ }
+ }
+
+ return 0;
+}
diff --git a/browser/app/winlauncher/test/TestSameBinary.cpp b/browser/app/winlauncher/test/TestSameBinary.cpp
new file mode 100644
index 0000000000..2cb45f546f
--- /dev/null
+++ b/browser/app/winlauncher/test/TestSameBinary.cpp
@@ -0,0 +1,255 @@
+/* -*- 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 https://mozilla.org/MPL/2.0/. */
+
+#define MOZ_USE_LAUNCHER_ERROR
+
+#include <stdio.h>
+#include <stdlib.h>
+
+#include <utility>
+
+#include "SameBinary.h"
+#include "mozilla/ArrayUtils.h"
+#include "mozilla/Assertions.h"
+#include "mozilla/CmdLineAndEnvUtils.h"
+#include "mozilla/NativeNt.h"
+#include "mozilla/Unused.h"
+#include "mozilla/Vector.h"
+#include "mozilla/WinHeaderOnlyUtils.h"
+#include "nsWindowsHelpers.h"
+
+#define EXPECT_SAMEBINARY_IS(expected, option, message) \
+ do { \
+ mozilla::LauncherResult<bool> isSame = \
+ mozilla::IsSameBinaryAsParentProcess(option); \
+ if (isSame.isErr()) { \
+ PrintLauncherError(isSame, \
+ "IsSameBinaryAsParentProcess returned error " \
+ "when we were expecting success."); \
+ return 1; \
+ } \
+ if (isSame.unwrap() != expected) { \
+ PrintErrorMsg(message); \
+ return 1; \
+ } \
+ } while (0)
+
+/**
+ * This test involves three processes:
+ * 1. The "Monitor" process, which is executed by |MonitorMain|. This process
+ * is responsible for integrating with the test harness, so it spawns the
+ * "Parent" process (2), and then waits for the other two processes to
+ * finish.
+ * 2. The "Parent" process, which is executed by |ParentMain|. This process
+ * creates the "Child" process (3) and then waits indefinitely.
+ * 3. The "Child" process, which is executed by |ChildMain| and carries out
+ * the actual test. It terminates the Parent process during its execution,
+ * using the Child PID as the Parent process's exit code. This serves as a
+ * hacky yet effective way to signal to the Monitor process which PID it
+ * should wait on to ensure that the Child process has exited.
+ */
+
+static const char kMsgStart[] = "TEST-FAILED | SameBinary | ";
+
+inline void PrintErrorMsg(const char* aMsg) {
+ printf("%s%s\n", kMsgStart, aMsg);
+}
+
+inline void PrintWinError(const char* aMsg) {
+ mozilla::WindowsError err(mozilla::WindowsError::FromLastError());
+ printf("%s%s: %S\n", kMsgStart, aMsg, err.AsString().get());
+}
+
+template <typename T>
+inline void PrintLauncherError(const mozilla::LauncherResult<T>& aResult,
+ const char* aMsg = nullptr) {
+ const char* const kSep = aMsg ? ": " : "";
+ const char* msg = aMsg ? aMsg : "";
+ const mozilla::LauncherError& err = aResult.inspectErr();
+ printf("%s%s%s%S (%s:%d)\n", kMsgStart, msg, kSep,
+ err.mError.AsString().get(), err.mFile, err.mLine);
+}
+
+static int ChildMain(DWORD aExpectedParentPid) {
+ mozilla::LauncherResult<DWORD> parentPid = mozilla::nt::GetParentProcessId();
+ if (parentPid.isErr()) {
+ PrintLauncherError(parentPid);
+ return 1;
+ }
+
+ if (parentPid.inspect() != aExpectedParentPid) {
+ PrintErrorMsg("Unexpected mismatch of parent PIDs");
+ return 1;
+ }
+
+ const DWORD kAccess = PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_TERMINATE;
+ nsAutoHandle parentProcess(
+ ::OpenProcess(kAccess, FALSE, parentPid.inspect()));
+ if (!parentProcess) {
+ PrintWinError("Unexpectedly failed to call OpenProcess on parent");
+ return 1;
+ }
+
+ EXPECT_SAMEBINARY_IS(
+ true, mozilla::ImageFileCompareOption::Default,
+ "IsSameBinaryAsParentProcess returned incorrect result for identical "
+ "binaries");
+ EXPECT_SAMEBINARY_IS(
+ true, mozilla::ImageFileCompareOption::CompareNtPathsOnly,
+ "IsSameBinaryAsParentProcess(CompareNtPathsOnly) returned incorrect "
+ "result for identical binaries");
+
+ // Total hack, but who cares? We'll set the parent's exit code as our PID
+ // so that the monitor process knows who to wait for!
+ if (!::TerminateProcess(parentProcess.get(), ::GetCurrentProcessId())) {
+ PrintWinError("Unexpected failure in TerminateProcess");
+ return 1;
+ }
+
+ // Close our handle to the parent process so that no references are held.
+ ::CloseHandle(parentProcess.disown());
+
+ // Querying a pid on a terminated process may still succeed some time after
+ // that process has been terminated. For the purposes of this test, we'll poll
+ // the OS until we cannot succesfully open the parentPid anymore.
+ const uint32_t kMaxAttempts = 100;
+ uint32_t curAttempt = 0;
+ while (HANDLE p = ::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE,
+ parentPid.inspect())) {
+ ::CloseHandle(p);
+ ::Sleep(100);
+ ++curAttempt;
+ if (curAttempt >= kMaxAttempts) {
+ PrintErrorMsg(
+ "Exhausted retry attempts waiting for parent pid to become invalid");
+ return 1;
+ }
+ }
+
+ EXPECT_SAMEBINARY_IS(
+ false, mozilla::ImageFileCompareOption::Default,
+ "IsSameBinaryAsParentProcess returned incorrect result for dead parent "
+ "process");
+ EXPECT_SAMEBINARY_IS(
+ false, mozilla::ImageFileCompareOption::CompareNtPathsOnly,
+ "IsSameBinaryAsParentProcess(CompareNtPathsOnly) returned incorrect "
+ "result for dead parent process");
+
+ return 0;
+}
+
+static nsReturnRef<HANDLE> CreateSelfProcess(int argc, wchar_t* argv[]) {
+ nsAutoHandle empty;
+
+ DWORD myPid = ::GetCurrentProcessId();
+
+ wchar_t strPid[11] = {};
+#if defined(__MINGW32__)
+ _ultow(myPid, strPid, 16);
+#else
+ if (_ultow_s(myPid, strPid, 16)) {
+ PrintErrorMsg("_ultow_s failed");
+ return empty.out();
+ }
+#endif // defined(__MINGW32__)
+
+ wchar_t* extraArgs[] = {strPid};
+
+ auto cmdLine = mozilla::MakeCommandLine(
+ argc, argv, mozilla::ArrayLength(extraArgs), extraArgs);
+ if (!cmdLine) {
+ PrintErrorMsg("MakeCommandLine failed");
+ return empty.out();
+ }
+
+ STARTUPINFOW si = {sizeof(si)};
+ PROCESS_INFORMATION pi;
+ BOOL ok =
+ ::CreateProcessW(argv[0], cmdLine.get(), nullptr, nullptr, FALSE,
+ CREATE_UNICODE_ENVIRONMENT, nullptr, nullptr, &si, &pi);
+ if (!ok) {
+ PrintWinError("CreateProcess failed");
+ return empty.out();
+ }
+
+ nsAutoHandle proc(pi.hProcess);
+ nsAutoHandle thd(pi.hThread);
+
+ return proc.out();
+}
+
+static int ParentMain(int argc, wchar_t* argv[]) {
+ nsAutoHandle childProc(CreateSelfProcess(argc, argv));
+ if (!childProc) {
+ return 1;
+ }
+
+ if (::WaitForSingleObject(childProc.get(), INFINITE) != WAIT_OBJECT_0) {
+ PrintWinError(
+ "Unexpected result from WaitForSingleObject on child process");
+ return 1;
+ }
+
+ MOZ_ASSERT_UNREACHABLE("This process should be terminated by now");
+ return 0;
+}
+
+static int MonitorMain(int argc, wchar_t* argv[]) {
+ // In this process, "parent" means the process that will be running
+ // ParentMain, which is our child process (confusing, I know...)
+ nsAutoHandle parentProc(CreateSelfProcess(argc, argv));
+ if (!parentProc) {
+ return 1;
+ }
+
+ if (::WaitForSingleObject(parentProc.get(), 60000) != WAIT_OBJECT_0) {
+ PrintWinError("Unexpected result from WaitForSingleObject on parent");
+ return 1;
+ }
+
+ DWORD childPid;
+ if (!::GetExitCodeProcess(parentProc.get(), &childPid)) {
+ PrintWinError("GetExitCodeProcess failed");
+ return 1;
+ }
+
+ nsAutoHandle childProc(::OpenProcess(SYNCHRONIZE, FALSE, childPid));
+ if (!childProc) {
+ // Nothing to wait on anymore, which is OK.
+ return 0;
+ }
+
+ // We want no more references to parentProc
+ ::CloseHandle(parentProc.disown());
+
+ if (::WaitForSingleObject(childProc.get(), 60000) != WAIT_OBJECT_0) {
+ PrintWinError("Unexpected result from WaitForSingleObject on child");
+ return 1;
+ }
+
+ return 0;
+}
+
+extern "C" int wmain(int argc, wchar_t* argv[]) {
+ if (argc == 3) {
+ return ChildMain(wcstoul(argv[2], nullptr, 16));
+ }
+
+ if (!mozilla::SetArgv0ToFullBinaryPath(argv)) {
+ return 1;
+ }
+
+ if (argc == 1) {
+ return MonitorMain(argc, argv);
+ }
+
+ if (argc == 2) {
+ return ParentMain(argc, argv);
+ }
+
+ PrintErrorMsg("Unexpected argc");
+ return 1;
+}
diff --git a/browser/app/winlauncher/test/moz.build b/browser/app/winlauncher/test/moz.build
new file mode 100644
index 0000000000..a8503ddf55
--- /dev/null
+++ b/browser/app/winlauncher/test/moz.build
@@ -0,0 +1,30 @@
+# -*- Mode: python; indent-tabs-mode: nil; tab-width: 40 -*-
+# vim: set filetype=python:
+# 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/.
+
+DisableStlWrapping()
+
+GeckoCppUnitTests(
+ [
+ "TestCrossProcessWin",
+ "TestSafeThreadLocal",
+ "TestSameBinary",
+ ],
+ linkage=None,
+)
+
+LOCAL_INCLUDES += [
+ "/browser/app/winlauncher",
+]
+
+OS_LIBS += [
+ "ntdll",
+]
+
+if CONFIG["CC_TYPE"] in ("gcc", "clang"):
+ # This allows us to use wmain as the entry point on mingw
+ LDFLAGS += [
+ "-municode",
+ ]