Backed out changeset 5660a1cd0e25 (bug 1508468) for Windows MinGW bustages. CLOSED TREE

This commit is contained in:
Narcis Beleuzu 2018-11-20 21:39:10 +02:00
Родитель 4a2fc915af
Коммит 6d1ee7c9fd
13 изменённых файлов: 190 добавлений и 542 удалений

Просмотреть файл

@ -10,7 +10,6 @@
#include "mozilla/Attributes.h"
#include "mozilla/Types.h"
#include "mozilla/WindowsDllBlocklist.h"
#include "mozilla/WinHeaderOnlyUtils.h"
#define MOZ_LITERAL_UNICODE_STRING(s) \
{ \
@ -331,17 +330,14 @@ public:
, mLength(aLength)
, mTargetProcess(aTargetProcess)
, mPrevProt(0)
, mError(WindowsError::CreateSuccess())
{
if (!::VirtualProtectEx(aTargetProcess, aAddress, aLength, aProtFlags,
&mPrevProt)) {
mError = WindowsError::FromLastError();
}
::VirtualProtectEx(aTargetProcess, aAddress, aLength, aProtFlags,
&mPrevProt);
}
~AutoVirtualProtect()
{
if (!mError) {
if (!mPrevProt) {
return;
}
@ -351,12 +347,7 @@ public:
explicit operator bool() const
{
return !!mError;
}
WindowsError GetError() const
{
return mError;
return !!mPrevProt;
}
AutoVirtualProtect(const AutoVirtualProtect&) = delete;
@ -365,14 +356,13 @@ public:
AutoVirtualProtect& operator=(AutoVirtualProtect&&) = delete;
private:
void* mAddress;
size_t mLength;
HANDLE mTargetProcess;
DWORD mPrevProt;
WindowsError mError;
void* mAddress;
size_t mLength;
HANDLE mTargetProcess;
DWORD mPrevProt;
};
LauncherVoidResult
bool
InitializeDllBlocklistOOP(HANDLE aChildProcess)
{
mozilla::CrossProcessDllInterceptor intcpt(aChildProcess);
@ -381,7 +371,7 @@ InitializeDllBlocklistOOP(HANDLE aChildProcess)
"NtMapViewOfSection",
&patched_NtMapViewOfSection);
if (!ok) {
return LAUNCHER_ERROR_GENERIC();
return false;
}
// Because aChildProcess has just been created in a suspended state, its
@ -396,19 +386,19 @@ InitializeDllBlocklistOOP(HANDLE aChildProcess)
// safely make its ntdll calls.
mozilla::nt::PEHeaders ourExeImage(::GetModuleHandleW(nullptr));
if (!ourExeImage) {
return LAUNCHER_ERROR_FROM_WIN32(ERROR_BAD_EXE_FORMAT);
return false;
}
PIMAGE_IMPORT_DESCRIPTOR impDesc = ourExeImage.GetIATForModule("ntdll.dll");
if (!impDesc) {
return LAUNCHER_ERROR_FROM_WIN32(ERROR_INVALID_DATA);
return false;
}
// This is the pointer we need to write
auto firstIatThunk = ourExeImage.template
RVAToPtr<PIMAGE_THUNK_DATA>(impDesc->FirstThunk);
if (!firstIatThunk) {
return LAUNCHER_ERROR_FROM_WIN32(ERROR_INVALID_DATA);
return false;
}
// Find the length by iterating through the table until we find a null entry
@ -425,13 +415,13 @@ InitializeDllBlocklistOOP(HANDLE aChildProcess)
AutoVirtualProtect prot(firstIatThunk, iatLength, PAGE_READWRITE,
aChildProcess);
if (!prot) {
return LAUNCHER_ERROR_FROM_MOZ_WINDOWS_ERROR(prot.GetError());
return false;
}
ok = !!::WriteProcessMemory(aChildProcess, firstIatThunk, firstIatThunk,
iatLength, &bytesWritten);
if (!ok) {
return LAUNCHER_ERROR_FROM_LAST();
return false;
}
}
@ -439,11 +429,7 @@ InitializeDllBlocklistOOP(HANDLE aChildProcess)
uint32_t newFlags = eDllBlocklistInitFlagWasBootstrapped;
ok = !!::WriteProcessMemory(aChildProcess, &gBlocklistInitFlags, &newFlags,
sizeof(newFlags), &bytesWritten);
if (!ok) {
return LAUNCHER_ERROR_FROM_LAST();
}
return Ok();
return ok;
}
} // namespace mozilla

Просмотреть файл

@ -9,11 +9,9 @@
#include <windows.h>
#include "LauncherResult.h"
namespace mozilla {
LauncherVoidResult InitializeDllBlocklistOOP(HANDLE aChildProcess);
bool InitializeDllBlocklistOOP(HANDLE aChildProcess);
} // namespace mozilla

Просмотреть файл

@ -1,24 +0,0 @@
/* -*- 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/. */
#include "ErrorHandler.h"
namespace mozilla {
void
HandleLauncherError(const LauncherError& aError)
{
// This is a placeholder error handler. We'll add telemetry and a fallback
// error log in future revisions.
WindowsError::UniqueString msg = aError.mError.AsString();
if (!msg) {
return;
}
::MessageBoxW(nullptr, msg.get(), L"Firefox", MB_OK | MB_ICONERROR);
}
} // namespace mozilla

Просмотреть файл

@ -1,48 +0,0 @@
/* -*- 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/. */
#ifndef mozilla_ErrorHandler_h
#define mozilla_ErrorHandler_h
#include "mozilla/Assertions.h"
#include "LauncherResult.h"
namespace mozilla {
/**
* All launcher process error handling should live in the implementation of
* this function.
*/
void HandleLauncherError(const LauncherError& aError);
// This function is simply a convenience overload that automatically unwraps
// the LauncherError from the provided LauncherResult and then forwards it to
// the main implementation.
template <typename T>
inline void
HandleLauncherError(const LauncherResult<T>& aResult)
{
MOZ_ASSERT(aResult.isErr());
if (aResult.isOk()) {
return;
}
HandleLauncherError(aResult.unwrapErr());
}
// This function is simply a convenience overload that unwraps the provided
// GenericErrorResult<LauncherError> and forwards it to the main implementation.
inline void
HandleLauncherError(const GenericErrorResult<LauncherError>& aResult)
{
LauncherVoidResult r(aResult);
HandleLauncherError(r);
}
} // namespace mozilla
#endif // mozilla_ErrorHandler_h

Просмотреть файл

@ -12,8 +12,6 @@
#include "mozilla/RefPtr.h"
#include "nsWindowsHelpers.h"
#include "LauncherResult.h"
// For _bstr_t and _variant_t
#include <comdef.h>
#include <comutil.h>
@ -25,36 +23,34 @@
#include <shlobj.h>
#include <shobjidl.h>
static mozilla::LauncherResult<TOKEN_ELEVATION_TYPE>
static mozilla::Maybe<TOKEN_ELEVATION_TYPE>
GetElevationType(const nsAutoHandle& aToken)
{
DWORD retLen;
TOKEN_ELEVATION_TYPE elevationType;
if (!::GetTokenInformation(aToken.get(), TokenElevationType, &elevationType,
sizeof(elevationType), &retLen)) {
return LAUNCHER_ERROR_FROM_LAST();
return mozilla::Nothing();
}
return elevationType;
return mozilla::Some(elevationType);
}
static mozilla::LauncherResult<bool>
static mozilla::Maybe<bool>
IsHighIntegrity(const nsAutoHandle& aToken)
{
DWORD reqdLen;
if (!::GetTokenInformation(aToken.get(), TokenIntegrityLevel, nullptr, 0,
&reqdLen)) {
DWORD err = ::GetLastError();
if (err != ERROR_INSUFFICIENT_BUFFER) {
return LAUNCHER_ERROR_FROM_WIN32(err);
}
&reqdLen) &&
::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return mozilla::Nothing();
}
auto buf = mozilla::MakeUnique<char[]>(reqdLen);
if (!::GetTokenInformation(aToken.get(), TokenIntegrityLevel, buf.get(),
reqdLen, &reqdLen)) {
return LAUNCHER_ERROR_FROM_LAST();
return mozilla::Nothing();
}
auto tokenLabel = reinterpret_cast<PTOKEN_MANDATORY_LABEL>(buf.get());
@ -62,17 +58,18 @@ IsHighIntegrity(const nsAutoHandle& aToken)
DWORD subAuthCount = *::GetSidSubAuthorityCount(tokenLabel->Label.Sid);
DWORD integrityLevel = *::GetSidSubAuthority(tokenLabel->Label.Sid,
subAuthCount - 1);
return integrityLevel > SECURITY_MANDATORY_MEDIUM_RID;
return mozilla::Some(integrityLevel > SECURITY_MANDATORY_MEDIUM_RID);
}
static mozilla::LauncherResult<HANDLE>
static nsReturnRef<HANDLE>
GetMediumIntegrityToken(const nsAutoHandle& aProcessToken)
{
nsAutoHandle empty;
HANDLE rawResult;
if (!::DuplicateTokenEx(aProcessToken.get(), 0, nullptr,
SecurityImpersonation, TokenPrimary, &rawResult)) {
return LAUNCHER_ERROR_FROM_LAST();
return empty.out();
}
nsAutoHandle result(rawResult);
@ -81,7 +78,7 @@ GetMediumIntegrityToken(const nsAutoHandle& aProcessToken)
DWORD mediumIlSidSize = sizeof(mediumIlSid);
if (!::CreateWellKnownSid(WinMediumLabelSid, nullptr, mediumIlSid,
&mediumIlSidSize)) {
return LAUNCHER_ERROR_FROM_LAST();
return empty.out();
}
TOKEN_MANDATORY_LABEL integrityLevel = {};
@ -90,10 +87,10 @@ GetMediumIntegrityToken(const nsAutoHandle& aProcessToken)
if (!::SetTokenInformation(rawResult, TokenIntegrityLevel, &integrityLevel,
sizeof(integrityLevel))) {
return LAUNCHER_ERROR_FROM_LAST();
return empty.out();
}
return result.disown();
return result.out();
}
namespace mozilla {
@ -106,13 +103,13 @@ namespace mozilla {
// those of the session.
// See https://blogs.msdn.microsoft.com/oldnewthing/20131118-00/?p=2643
LauncherVoidResult
bool
LaunchUnelevated(int aArgc, wchar_t* aArgv[])
{
// We require a single-threaded apartment to talk to Explorer.
mscom::STARegion sta;
if (!sta.IsValid()) {
return LAUNCHER_ERROR_FROM_HRESULT(sta.GetHResult());
return false;
}
// NB: Explorer is a local server, not an inproc server
@ -121,7 +118,7 @@ LaunchUnelevated(int aArgc, wchar_t* aArgv[])
CLSCTX_LOCAL_SERVER, IID_IShellWindows,
getter_AddRefs(shellWindows));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
// 1. Find the shell view for the desktop.
@ -132,26 +129,26 @@ LaunchUnelevated(int aArgc, wchar_t* aArgv[])
hr = shellWindows->FindWindowSW(&loc, &empty, SWC_DESKTOP, &hwnd,
SWFO_NEEDDISPATCH, getter_AddRefs(dispDesktop));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
RefPtr<IServiceProvider> servProv;
hr = dispDesktop->QueryInterface(IID_IServiceProvider, getter_AddRefs(servProv));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
RefPtr<IShellBrowser> browser;
hr = servProv->QueryService(SID_STopLevelBrowser, IID_IShellBrowser,
getter_AddRefs(browser));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
RefPtr<IShellView> activeShellView;
hr = browser->QueryActiveShellView(getter_AddRefs(activeShellView));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
// 2. Get the automation object for the desktop.
@ -159,27 +156,27 @@ LaunchUnelevated(int aArgc, wchar_t* aArgv[])
hr = activeShellView->GetItemObject(SVGIO_BACKGROUND, IID_IDispatch,
getter_AddRefs(dispView));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
RefPtr<IShellFolderViewDual> folderView;
hr = dispView->QueryInterface(IID_IShellFolderViewDual,
getter_AddRefs(folderView));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
// 3. Get the interface to IShellDispatch2
RefPtr<IDispatch> dispShell;
hr = folderView->get_Application(getter_AddRefs(dispShell));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
RefPtr<IShellDispatch2> shellDisp;
hr = dispShell->QueryInterface(IID_IShellDispatch2, getter_AddRefs(shellDisp));
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
return false;
}
// 4. Now call IShellDispatch2::ShellExecute to ask Explorer to re-launch us.
@ -187,7 +184,7 @@ LaunchUnelevated(int aArgc, wchar_t* aArgv[])
// Omit argv[0] because ShellExecute doesn't need it in params
UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(aArgc - 1, aArgv + 1));
if (!cmdLine) {
return LAUNCHER_ERROR_GENERIC();
return false;
}
_bstr_t exe(aArgv[0]);
@ -196,14 +193,10 @@ LaunchUnelevated(int aArgc, wchar_t* aArgv[])
_variant_t directory;
_variant_t showCmd(SW_SHOWNORMAL);
hr = shellDisp->ShellExecute(exe, args, operation, directory, showCmd);
if (FAILED(hr)) {
return LAUNCHER_ERROR_FROM_HRESULT(hr);
}
return Ok();
return SUCCEEDED(hr);
}
LauncherResult<ElevationState>
Maybe<ElevationState>
GetElevationState(mozilla::LauncherFlags aFlags, nsAutoHandle& aOutMediumIlToken)
{
aOutMediumIlToken.reset();
@ -212,40 +205,34 @@ GetElevationState(mozilla::LauncherFlags aFlags, nsAutoHandle& aOutMediumIlToken
TOKEN_ADJUST_DEFAULT | TOKEN_ASSIGN_PRIMARY;
HANDLE rawToken;
if (!::OpenProcessToken(::GetCurrentProcess(), tokenFlags, &rawToken)) {
return LAUNCHER_ERROR_FROM_LAST();
return Nothing();
}
nsAutoHandle token(rawToken);
LauncherResult<TOKEN_ELEVATION_TYPE> elevationType = GetElevationType(token);
if (elevationType.isErr()) {
return LAUNCHER_ERROR_FROM_RESULT(elevationType);
Maybe<TOKEN_ELEVATION_TYPE> elevationType = GetElevationType(token);
if (!elevationType) {
return Nothing();
}
switch (elevationType.unwrap()) {
switch (elevationType.value()) {
case TokenElevationTypeLimited:
return ElevationState::eNormalUser;
return Some(ElevationState::eNormalUser);
case TokenElevationTypeFull:
// If we want to start a non-elevated browser process and wait on it,
// we're going to need a medium IL token.
if ((aFlags & (mozilla::LauncherFlags::eWaitForBrowser |
mozilla::LauncherFlags::eNoDeelevate)) ==
mozilla::LauncherFlags::eWaitForBrowser) {
LauncherResult<HANDLE> tokenResult =
GetMediumIntegrityToken(token);
if (tokenResult.isOk()) {
aOutMediumIlToken.own(tokenResult.unwrap());
} else {
return LAUNCHER_ERROR_FROM_RESULT(tokenResult);
}
aOutMediumIlToken = GetMediumIntegrityToken(token);
}
return ElevationState::eElevated;
return Some(ElevationState::eElevated);
case TokenElevationTypeDefault:
break;
default:
MOZ_ASSERT_UNREACHABLE("Was a new value added to the enumeration?");
return LAUNCHER_ERROR_GENERIC();
return Nothing();
}
// In this case, UAC is disabled. We do not yet know whether or not we are
@ -253,26 +240,20 @@ GetElevationState(mozilla::LauncherFlags aFlags, nsAutoHandle& aOutMediumIlToken
// ourselves in a non-elevated state via Explorer, as we would just end up in
// an infinite loop of launcher processes re-launching themselves.
LauncherResult<bool> isHighIntegrity = IsHighIntegrity(token);
if (isHighIntegrity.isErr()) {
return LAUNCHER_ERROR_FROM_RESULT(isHighIntegrity);
Maybe<bool> isHighIntegrity = IsHighIntegrity(token);
if (!isHighIntegrity) {
return Nothing();
}
if (!isHighIntegrity.unwrap()) {
return ElevationState::eNormalUser;
if (!isHighIntegrity.value()) {
return Some(ElevationState::eNormalUser);
}
if (!(aFlags & mozilla::LauncherFlags::eNoDeelevate)) {
LauncherResult<HANDLE> tokenResult =
GetMediumIntegrityToken(token);
if (tokenResult.isOk()) {
aOutMediumIlToken.own(tokenResult.unwrap());
} else {
return LAUNCHER_ERROR_FROM_RESULT(tokenResult);
}
aOutMediumIlToken = GetMediumIntegrityToken(token);
}
return ElevationState::eHighIntegrityNoUAC;
return Some(ElevationState::eHighIntegrityNoUAC);
}
} // namespace mozilla

Просмотреть файл

@ -8,7 +8,6 @@
#define mozilla_LaunchUnelevated_h
#include "LauncherProcessWin.h"
#include "LauncherResult.h"
#include "mozilla/Maybe.h"
#include "nsWindowsHelpers.h"
@ -21,10 +20,10 @@ enum class ElevationState
eHighIntegrityNoUAC = (1 << 1),
};
LauncherResult<ElevationState>
mozilla::Maybe<ElevationState>
GetElevationState(LauncherFlags aFlags, nsAutoHandle& aOutMediumIlToken);
LauncherVoidResult LaunchUnelevated(int aArgc, wchar_t* aArgv[]);
bool LaunchUnelevated(int aArgc, wchar_t* aArgv[]);
} // namespace mozilla

Просмотреть файл

@ -25,8 +25,6 @@
#include <processthreadsapi.h>
#include "DllBlocklistWin.h"
#include "ErrorHandler.h"
#include "LauncherResult.h"
#include "LaunchUnelevated.h"
#include "ProcThreadAttributes.h"
@ -36,7 +34,7 @@
*
* @return true if browser startup should proceed, otherwise false.
*/
static mozilla::LauncherVoidResult
static bool
PostCreationSetup(HANDLE aChildProcess, HANDLE aChildMainThread,
const bool aIsSafeMode)
{
@ -44,7 +42,7 @@ PostCreationSetup(HANDLE aChildProcess, HANDLE aChildMainThread,
// it is able to execute before ASAN itself has even initialized.
// Also, the AArch64 build doesn't yet have a working interceptor.
#if defined(MOZ_ASAN) || defined(_M_ARM64)
return Ok();
return true;
#else
return mozilla::InitializeDllBlocklistOOP(aChildProcess);
#endif // defined(MOZ_ASAN) || defined(_M_ARM64)
@ -72,6 +70,27 @@ SetMitigationPolicies(mozilla::ProcThreadAttributes& aAttrs, const bool aIsSafeM
}
}
static void
ShowError(DWORD aError = ::GetLastError())
{
if (aError == ERROR_SUCCESS) {
return;
}
LPWSTR rawMsgBuf = nullptr;
DWORD result = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
aError, 0, reinterpret_cast<LPWSTR>(&rawMsgBuf),
0, nullptr);
if (!result) {
return;
}
::MessageBoxW(nullptr, rawMsgBuf, L"Firefox", MB_OK | MB_ICONERROR);
::LocalFree(rawMsgBuf);
}
static mozilla::LauncherFlags
ProcessCmdLine(int& aArgc, wchar_t* aArgv[])
{
@ -147,42 +166,53 @@ MaybeBreakForBrowserDebugging()
#if defined(MOZ_LAUNCHER_PROCESS)
static mozilla::LauncherResult<bool>
static bool
IsSameBinaryAsParentProcess()
{
mozilla::LauncherResult<DWORD> parentPid = mozilla::nt::GetParentProcessId();
if (parentPid.isErr()) {
return LAUNCHER_ERROR_FROM_RESULT(parentPid);
mozilla::Maybe<DWORD> parentPid = mozilla::nt::GetParentProcessId();
if (!parentPid) {
// If NtQueryInformationProcess failed (in GetParentProcessId()),
// we should not behave as the launcher process because it will also
// likely to fail in child processes.
MOZ_CRASH("NtQueryInformationProcess failed");
}
nsAutoHandle parentProcess(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
FALSE, parentPid.unwrap()));
FALSE, parentPid.value()));
if (!parentProcess.get()) {
return LAUNCHER_ERROR_FROM_LAST();
// If OpenProcess failed, the parent process may not be present,
// may be already terminated, etc. So we will have to behave as the
// launcher proces in this case.
return false;
}
WCHAR parentExe[MAX_PATH + 1] = {};
DWORD parentExeLen = mozilla::ArrayLength(parentExe);
if (!::QueryFullProcessImageNameW(parentProcess.get(), PROCESS_NAME_NATIVE,
parentExe, &parentExeLen)) {
return LAUNCHER_ERROR_FROM_LAST();
// If QueryFullProcessImageNameW failed, we should not behave as the
// launcher process for the same reason as NtQueryInformationProcess.
MOZ_CRASH("QueryFullProcessImageNameW failed");
}
WCHAR ourExe[MAX_PATH + 1] = {};
DWORD ourExeOk = ::GetModuleFileNameW(nullptr, ourExe,
mozilla::ArrayLength(ourExe));
if (!ourExeOk || ourExeOk == mozilla::ArrayLength(ourExe)) {
return LAUNCHER_ERROR_FROM_LAST();
// If GetModuleFileNameW failed, we should not behave as the launcher
// process for the same reason as NtQueryInformationProcess.
MOZ_CRASH("GetModuleFileNameW failed");
}
mozilla::WindowsErrorResult<bool> isSame =
mozilla::Maybe<bool> isSame =
mozilla::DoPathsPointToIdenticalFile(parentExe, ourExe,
mozilla::PathType::eNtPath);
if (isSame.isErr()) {
return LAUNCHER_ERROR_FROM_MOZ_WINDOWS_ERROR(isSame.unwrapErr());
mozilla::eNtPath);
if (!isSame) {
// If DoPathsPointToIdenticalFile failed, we should not behave as the
// launcher process for the same reason as NtQueryInformationProcess.
MOZ_CRASH("DoPathsPointToIdenticalFile failed");
}
return isSame.unwrap();
return isSame.value();
}
#endif // defined(MOZ_LAUNCHER_PROCESS)
@ -198,12 +228,7 @@ RunAsLauncherProcess(int& argc, wchar_t** argv)
bool result = false;
#if defined(MOZ_LAUNCHER_PROCESS)
LauncherResult<bool> isSame = IsSameBinaryAsParentProcess();
if (isSame.isOk()) {
result = !isSame.unwrap();
} else {
HandleLauncherError(isSame.unwrapErr());
}
result = !IsSameBinaryAsParentProcess();
#endif // defined(MOZ_LAUNCHER_PROCESS)
if (mozilla::EnvHasValue("MOZ_LAUNCHER_PROCESS")) {
@ -243,45 +268,37 @@ LauncherMain(int argc, wchar_t* argv[])
}
if (!SetArgv0ToFullBinaryPath(argv)) {
HandleLauncherError(LAUNCHER_ERROR_GENERIC());
ShowError();
return 1;
}
LauncherFlags flags = ProcessCmdLine(argc, argv);
nsAutoHandle mediumIlToken;
LauncherResult<ElevationState> elevationState = GetElevationState(flags, mediumIlToken);
if (elevationState.isErr()) {
HandleLauncherError(elevationState);
Maybe<ElevationState> elevationState = GetElevationState(flags, mediumIlToken);
if (!elevationState) {
return 1;
}
// If we're elevated, we should relaunch ourselves as a normal user.
// Note that we only call LaunchUnelevated when we don't need to wait for the
// browser process.
if (elevationState.unwrap() == ElevationState::eElevated &&
if (elevationState.value() == ElevationState::eElevated &&
!(flags & (LauncherFlags::eWaitForBrowser | LauncherFlags::eNoDeelevate)) &&
!mediumIlToken.get()) {
LauncherVoidResult launchedUnelevated = LaunchUnelevated(argc, argv);
bool failed = launchedUnelevated.isErr();
if (failed) {
HandleLauncherError(launchedUnelevated);
}
return failed;
return !LaunchUnelevated(argc, argv);
}
// Now proceed with setting up the parameters for process creation
UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(argc, argv));
if (!cmdLine) {
HandleLauncherError(LAUNCHER_ERROR_GENERIC());
return 1;
}
const Maybe<bool> isSafeMode = IsSafeModeRequested(argc, argv,
SafeModeFlag::NoKeyPressCheck);
if (!isSafeMode) {
HandleLauncherError(LAUNCHER_ERROR_FROM_WIN32(ERROR_INVALID_PARAMETER));
ShowError(ERROR_INVALID_PARAMETER);
return 1;
}
@ -299,15 +316,15 @@ LauncherMain(int argc, wchar_t* argv[])
DWORD creationFlags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;
STARTUPINFOEXW siex;
LauncherResult<bool> attrsOk = attrs.AssignTo(siex);
if (attrsOk.isErr()) {
HandleLauncherError(attrsOk);
Maybe<bool> attrsOk = attrs.AssignTo(siex);
if (!attrsOk) {
ShowError();
return 1;
}
BOOL inheritHandles = FALSE;
if (attrsOk.unwrap()) {
if (attrsOk.value()) {
creationFlags |= EXTENDED_STARTUPINFO_PRESENT;
if (attrs.HasInheritableHandles()) {
@ -337,23 +354,16 @@ LauncherMain(int argc, wchar_t* argv[])
}
if (!createOk) {
HandleLauncherError(LAUNCHER_ERROR_FROM_LAST());
ShowError();
return 1;
}
nsAutoHandle process(pi.hProcess);
nsAutoHandle mainThread(pi.hThread);
LauncherVoidResult setupResult =
PostCreationSetup(process.get(), mainThread.get(), isSafeMode.value());
if (setupResult.isErr()) {
HandleLauncherError(setupResult);
::TerminateProcess(process.get(), 1);
return 1;
}
if (::ResumeThread(mainThread.get()) == static_cast<DWORD>(-1)) {
HandleLauncherError(LAUNCHER_ERROR_FROM_LAST());
if (!PostCreationSetup(process.get(), mainThread.get(), isSafeMode.value()) ||
::ResumeThread(mainThread.get()) == static_cast<DWORD>(-1)) {
ShowError();
::TerminateProcess(process.get(), 1);
return 1;
}

Просмотреть файл

@ -1,64 +0,0 @@
/* -*- 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/. */
#ifndef mozilla_LauncherResult_h
#define mozilla_LauncherResult_h
#include "mozilla/Result.h"
#include "mozilla/WinHeaderOnlyUtils.h"
namespace mozilla {
struct LauncherError
{
LauncherError(const char* aFile, int aLine, WindowsError aWin32Error)
: mFile(aFile)
, mLine(aLine)
, mError(aWin32Error)
{}
const char* mFile;
int mLine;
WindowsError mError;
};
template <typename T>
using LauncherResult = Result<T, LauncherError>;
using LauncherVoidResult = Result<Ok, LauncherError>;
} // namespace mozilla
#define LAUNCHER_ERROR_GENERIC() \
::mozilla::Err(::mozilla::LauncherError(__FILE__, __LINE__, \
::mozilla::WindowsError::CreateGeneric()))
#define LAUNCHER_ERROR_FROM_WIN32(err) \
::mozilla::Err(::mozilla::LauncherError(__FILE__, __LINE__, \
::mozilla::WindowsError::FromWin32Error(err)))
#define LAUNCHER_ERROR_FROM_LAST() \
::mozilla::Err(::mozilla::LauncherError(__FILE__, __LINE__, \
::mozilla::WindowsError::FromWin32Error(::GetLastError())))
#define LAUNCHER_ERROR_FROM_NTSTATUS(ntstatus) \
::mozilla::Err(::mozilla::LauncherError(__FILE__, __LINE__, \
::mozilla::WindowsError::FromNtStatus(ntstatus)))
#define LAUNCHER_ERROR_FROM_HRESULT(hresult) \
::mozilla::Err(::mozilla::LauncherError(__FILE__, __LINE__, \
::mozilla::WindowsError::FromHResult(hresult)))
// This macro enables moving of a mozilla::LauncherError from a
// mozilla::LauncherResult<Foo> into a mozilla::LauncherResult<Bar>
#define LAUNCHER_ERROR_FROM_RESULT(result) \
::mozilla::Err(result.unwrapErr())
// This macro wraps the supplied WindowsError with a LauncherError
#define LAUNCHER_ERROR_FROM_MOZ_WINDOWS_ERROR(err) \
::mozilla::Err(::mozilla::LauncherError(__FILE__, __LINE__, err))
#endif // mozilla_LauncherResult_h

Просмотреть файл

@ -18,8 +18,7 @@
#include "mozilla/ArrayUtils.h"
#include "mozilla/Attributes.h"
#include "LauncherResult.h"
#include "mozilla/Maybe.h"
extern "C" {
@ -569,7 +568,7 @@ RtlGetProcessHeap()
return peb->Reserved4[1];
}
inline LauncherResult<DWORD>
inline Maybe<DWORD>
GetParentProcessId()
{
struct PROCESS_BASIC_INFORMATION
@ -582,18 +581,17 @@ GetParentProcessId()
ULONG_PTR InheritedFromUniqueProcessId;
};
const HANDLE kCurrentProcess = reinterpret_cast<HANDLE>(-1);
ULONG returnLength;
PROCESS_BASIC_INFORMATION pbi = {};
NTSTATUS status = ::NtQueryInformationProcess(kCurrentProcess,
NTSTATUS status = ::NtQueryInformationProcess(::GetCurrentProcess(),
ProcessBasicInformation,
&pbi, sizeof(pbi),
&returnLength);
if (!NT_SUCCESS(status)) {
return LAUNCHER_ERROR_FROM_NTSTATUS(status);
return Nothing();
}
return static_cast<DWORD>(pbi.InheritedFromUniqueProcessId & 0xFFFFFFFF);
return Some(static_cast<DWORD>(pbi.InheritedFromUniqueProcessId & 0xFFFFFFFF));
}
} // namespace nt

Просмотреть файл

@ -86,12 +86,14 @@ public:
}
/**
* @return false if the STARTUPINFOEXW::lpAttributeList was set to null
* as expected based on the state of |this|;
* true if the STARTUPINFOEXW::lpAttributeList was set to
* non-null;
* @return Some(false) if the STARTUPINFOEXW::lpAttributeList was set to null
* as expected based on the state of |this|;
* Some(true) if the STARTUPINFOEXW::lpAttributeList was set to
* non-null;
* Nothing() if something went wrong in the assignment and we should
* not proceed.
*/
LauncherResult<bool> AssignTo(STARTUPINFOEXW& aSiex)
Maybe<bool> AssignTo(STARTUPINFOEXW& aSiex)
{
ZeroMemory(&aSiex, sizeof(STARTUPINFOEXW));
@ -109,16 +111,14 @@ public:
}
if (!numAttributes) {
return false;
return Some(false);
}
SIZE_T listSize = 0;
if (!::InitializeProcThreadAttributeList(nullptr, numAttributes, 0,
&listSize)) {
DWORD err = ::GetLastError();
if (err != ERROR_INSUFFICIENT_BUFFER) {
return LAUNCHER_ERROR_FROM_WIN32(err);
}
&listSize) &&
::GetLastError() != ERROR_INSUFFICIENT_BUFFER) {
return Nothing();
}
auto buf = MakeUnique<char[]>(listSize);
@ -128,7 +128,7 @@ public:
if (!::InitializeProcThreadAttributeList(tmpList, numAttributes, 0,
&listSize)) {
return LAUNCHER_ERROR_FROM_LAST();
return Nothing();
}
// Transfer buf to a ProcThreadAttributeListPtr - now that the list is
@ -144,7 +144,7 @@ public:
&mMitigationPolicies,
sizeof(mMitigationPolicies), nullptr,
nullptr)) {
return LAUNCHER_ERROR_FROM_LAST();
return Nothing();
}
}
@ -154,14 +154,14 @@ public:
mInheritableHandles.begin(),
mInheritableHandles.length() * sizeof(HANDLE),
nullptr, nullptr)) {
return LAUNCHER_ERROR_FROM_LAST();
return Nothing();
}
}
mAttrList = std::move(attrList);
aSiex.lpAttributeList = mAttrList.get();
aSiex.StartupInfo.cb = sizeof(STARTUPINFOEXW);
return true;
return Some(true);
}
private:

Просмотреть файл

@ -10,7 +10,6 @@ FORCE_STATIC_LIB = True
UNIFIED_SOURCES += [
'DllBlocklistWin.cpp',
'ErrorHandler.cpp',
'LauncherProcessWin.cpp',
'LaunchUnelevated.cpp',
]

Просмотреть файл

@ -43,11 +43,6 @@ public:
return SUCCEEDED(mInitResult);
}
HRESULT GetHResult() const
{
return mInitResult;
}
private:
COMApartmentRegion(const COMApartmentRegion&) = delete;
COMApartmentRegion& operator=(const COMApartmentRegion&) = delete;

Просмотреть файл

@ -8,16 +8,9 @@
#define mozilla_WinHeaderOnlyUtils_h
#include <windows.h>
#include <winerror.h>
#include <winternl.h>
#include <ntstatus.h>
#include "mozilla/Assertions.h"
#include "mozilla/Attributes.h"
#include "mozilla/DynamicallyLinkedFunctionPtr.h"
#include "mozilla/Maybe.h"
#include "mozilla/Result.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/WindowsVersion.h"
#include "nsWindowsHelpers.h"
@ -41,159 +34,6 @@ typedef struct _FILE_ID_INFO
namespace mozilla {
class WindowsError final
{
private:
// HRESULT and NTSTATUS are both typedefs of LONG, so we cannot use
// overloading to properly differentiate between the two. Instead we'll use
// static functions to convert the various error types to HRESULTs before
// instantiating.
explicit WindowsError(HRESULT aHResult)
: mHResult(aHResult)
{
}
public:
using UniqueString = UniquePtr<WCHAR[], LocalFreeDeleter>;
static WindowsError FromNtStatus(NTSTATUS aNtStatus)
{
if (aNtStatus == STATUS_SUCCESS) {
// Special case: we don't want to set FACILITY_NT_BIT
// (HRESULT_FROM_NT does not handle this case, unlike HRESULT_FROM_WIN32)
return WindowsError(S_OK);
}
return WindowsError(HRESULT_FROM_NT(aNtStatus));
}
static WindowsError FromHResult(HRESULT aHResult)
{
return WindowsError(aHResult);
}
static WindowsError FromWin32Error(DWORD aWin32Err)
{
return WindowsError(HRESULT_FROM_WIN32(aWin32Err));
}
static WindowsError FromLastError()
{
return FromWin32Error(::GetLastError());
}
static WindowsError CreateSuccess()
{
return WindowsError(S_OK);
}
static WindowsError CreateGeneric()
{
return FromWin32Error(ERROR_UNIDENTIFIED_ERROR);
}
explicit operator bool() const
{
return SUCCEEDED(mHResult);
}
bool IsAvailableAsWin32Error() const
{
return IsAvailableAsNtStatus() ||
HRESULT_FACILITY(mHResult) == FACILITY_WIN32;
}
bool IsAvailableAsNtStatus() const
{
return mHResult == S_OK || (mHResult & FACILITY_NT_BIT);
}
bool IsAvailableAsHResult() const
{
return true;
}
UniqueString AsString() const
{
LPWSTR rawMsgBuf = nullptr;
DWORD result = ::FormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, nullptr,
mHResult, 0,
reinterpret_cast<LPWSTR>(&rawMsgBuf), 0,
nullptr);
if (!result) {
return nullptr;
}
return UniqueString(rawMsgBuf);
}
HRESULT AsHResult() const
{
return mHResult;
}
// Not all HRESULTs are convertible to Win32 Errors, so we use Maybe
Maybe<DWORD> AsWin32Error() const
{
if (mHResult == S_OK) {
return Some(static_cast<DWORD>(ERROR_SUCCESS));
}
if (HRESULT_FACILITY(mHResult) == FACILITY_WIN32) {
// This is the inverse of HRESULT_FROM_WIN32
return Some(static_cast<DWORD>(HRESULT_CODE(mHResult)));
}
// The NTSTATUS facility is a special case and thus does not utilize the
// HRESULT_FACILITY and HRESULT_CODE macros.
if (mHResult & FACILITY_NT_BIT) {
return Some(NtStatusToWin32Error(
static_cast<NTSTATUS>(mHResult & ~FACILITY_NT_BIT)));
}
return Nothing();
}
// Not all HRESULTs are convertible to NTSTATUS, so we use Maybe
Maybe<NTSTATUS> AsNtStatus() const
{
if (mHResult == S_OK) {
return Some(STATUS_SUCCESS);
}
// The NTSTATUS facility is a special case and thus does not utilize the
// HRESULT_FACILITY and HRESULT_CODE macros.
if (mHResult & FACILITY_NT_BIT) {
return Some(static_cast<NTSTATUS>(mHResult & ~FACILITY_NT_BIT));
}
return Nothing();
}
static DWORD NtStatusToWin32Error(NTSTATUS aNtStatus)
{
static const DynamicallyLinkedFunctionPtr<decltype(&RtlNtStatusToDosError)>
pRtlNtStatusToDosError(L"ntdll.dll", "RtlNtStatusToDosError");
MOZ_ASSERT(!!pRtlNtStatusToDosError);
if (!pRtlNtStatusToDosError) {
return ERROR_UNIDENTIFIED_ERROR;
}
return pRtlNtStatusToDosError(aNtStatus);
}
private:
// We store the error code as an HRESULT because they can encode both Win32
// error codes and NTSTATUS codes.
HRESULT mHResult;
};
template <typename T>
using WindowsErrorResult = Result<T, WindowsError>;
// How long to wait for a created process to become available for input,
// to prevent that process's windows being forced to the background.
// This is used across update, restart, and the launcher.
@ -239,8 +79,7 @@ WaitForInputIdle(HANDLE aProcess, DWORD aTimeoutMs = kWaitForInputIdleTimeoutMS)
}
}
enum class PathType
{
enum PathType {
eNtPath,
eDosPath,
};
@ -255,52 +94,43 @@ public:
return;
}
nsAutoHandle file;
nsAutoHandle file(INVALID_HANDLE_VALUE);
switch (aPathType) {
default:
MOZ_ASSERT_UNREACHABLE("Unhandled PathType");
return;
default:
return;
case PathType::eNtPath: {
UNICODE_STRING unicodeString;
::RtlInitUnicodeString(&unicodeString, aPath);
OBJECT_ATTRIBUTES objectAttributes;
InitializeObjectAttributes(&objectAttributes, &unicodeString,
OBJ_CASE_INSENSITIVE, nullptr, nullptr);
IO_STATUS_BLOCK ioStatus = {};
HANDLE ntHandle;
NTSTATUS status = ::NtOpenFile(&ntHandle, SYNCHRONIZE |
FILE_READ_ATTRIBUTES,
&objectAttributes, &ioStatus,
FILE_SHARE_READ | FILE_SHARE_WRITE |
FILE_SHARE_DELETE,
FILE_SYNCHRONOUS_IO_NONALERT |
FILE_OPEN_FOR_BACKUP_INTENT);
// We don't need to check |ntHandle| for INVALID_HANDLE_VALUE here,
// as that value is set by the Win32 layer.
if (!NT_SUCCESS(status)) {
mError = Some(WindowsError::FromNtStatus(status));
return;
}
file.own(ntHandle);
}
break;
case PathType::eDosPath: {
file.own(::CreateFileW(aPath, 0, FILE_SHARE_READ |
FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, nullptr));
if (file == INVALID_HANDLE_VALUE) {
mError = Some(WindowsError::FromLastError());
case eNtPath:
{
UNICODE_STRING unicodeString;
::RtlInitUnicodeString(&unicodeString, aPath);
OBJECT_ATTRIBUTES objectAttributes;
InitializeObjectAttributes(&objectAttributes, &unicodeString,
OBJ_CASE_INSENSITIVE, nullptr, nullptr);
IO_STATUS_BLOCK ioStatus = {};
HANDLE ntHandle;
NTSTATUS status = ::NtOpenFile(&ntHandle, SYNCHRONIZE |
FILE_READ_ATTRIBUTES,
&objectAttributes, &ioStatus,
FILE_SHARE_READ | FILE_SHARE_WRITE |
FILE_SHARE_DELETE,
FILE_SYNCHRONOUS_IO_NONALERT |
FILE_OPEN_FOR_BACKUP_INTENT);
if (!NT_SUCCESS(status) || ntHandle == INVALID_HANDLE_VALUE) {
return;
}
break;
file.own(ntHandle);
}
break;
case eDosPath:
file.own(::CreateFileW(aPath, 0, FILE_SHARE_READ |
FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, nullptr));
if (file == INVALID_HANDLE_VALUE) {
return;
}
break;
}
GetId(file);
@ -314,7 +144,6 @@ public:
FileUniqueId(const FileUniqueId& aOther)
: mId(aOther.mId)
, mError(aOther.mError)
{
}
@ -323,18 +152,12 @@ public:
explicit operator bool() const
{
FILE_ID_INFO zeros = {};
return !mError && memcmp(&mId, &zeros, sizeof(FILE_ID_INFO));
}
Maybe<WindowsError> GetError() const
{
return mError;
return memcmp(&mId, &zeros, sizeof(FILE_ID_INFO));
}
FileUniqueId& operator=(const FileUniqueId& aOther)
{
mId = aOther.mId;
mError = aOther.mError;
return *this;
}
@ -343,8 +166,7 @@ public:
bool operator==(const FileUniqueId& aOther) const
{
return !mError && !aOther.mError &&
!memcmp(&mId, &aOther.mId, sizeof(FILE_ID_INFO));
return !memcmp(&mId, &aOther.mId, sizeof(FILE_ID_INFO));
}
bool operator!=(const FileUniqueId& aOther) const
@ -365,7 +187,6 @@ private:
BY_HANDLE_FILE_INFORMATION info = {};
if (!::GetFileInformationByHandle(aFile.get(), &info)) {
mError = Some(WindowsError::FromLastError());
return;
}
@ -377,28 +198,25 @@ private:
}
private:
FILE_ID_INFO mId;
Maybe<WindowsError> mError;
FILE_ID_INFO mId;
};
inline WindowsErrorResult<bool>
inline Maybe<bool>
DoPathsPointToIdenticalFile(const wchar_t* aPath1, const wchar_t* aPath2,
PathType aPathType1 = PathType::eDosPath,
PathType aPathType2 = PathType::eDosPath)
PathType aPathType1 = eDosPath,
PathType aPathType2 = eDosPath)
{
FileUniqueId id1(aPath1, aPathType1);
if (!id1) {
Maybe<WindowsError> error = id1.GetError();
return Err(error.valueOr(WindowsError::CreateGeneric()));
return Nothing();
}
FileUniqueId id2(aPath2, aPathType2);
if (!id2) {
Maybe<WindowsError> error = id2.GetError();
return Err(error.valueOr(WindowsError::CreateGeneric()));
return Nothing();
}
return id1 == id2;
return Some(id1 == id2);
}
} // namespace mozilla