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

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

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

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

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

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

@ -25,8 +25,6 @@
#include <processthreadsapi.h> #include <processthreadsapi.h>
#include "DllBlocklistWin.h" #include "DllBlocklistWin.h"
#include "ErrorHandler.h"
#include "LauncherResult.h"
#include "LaunchUnelevated.h" #include "LaunchUnelevated.h"
#include "ProcThreadAttributes.h" #include "ProcThreadAttributes.h"
@ -36,7 +34,7 @@
* *
* @return true if browser startup should proceed, otherwise false. * @return true if browser startup should proceed, otherwise false.
*/ */
static mozilla::LauncherVoidResult static bool
PostCreationSetup(HANDLE aChildProcess, HANDLE aChildMainThread, PostCreationSetup(HANDLE aChildProcess, HANDLE aChildMainThread,
const bool aIsSafeMode) const bool aIsSafeMode)
{ {
@ -44,7 +42,7 @@ PostCreationSetup(HANDLE aChildProcess, HANDLE aChildMainThread,
// it is able to execute before ASAN itself has even initialized. // it is able to execute before ASAN itself has even initialized.
// Also, the AArch64 build doesn't yet have a working interceptor. // Also, the AArch64 build doesn't yet have a working interceptor.
#if defined(MOZ_ASAN) || defined(_M_ARM64) #if defined(MOZ_ASAN) || defined(_M_ARM64)
return Ok(); return true;
#else #else
return mozilla::InitializeDllBlocklistOOP(aChildProcess); return mozilla::InitializeDllBlocklistOOP(aChildProcess);
#endif // defined(MOZ_ASAN) || defined(_M_ARM64) #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 static mozilla::LauncherFlags
ProcessCmdLine(int& aArgc, wchar_t* aArgv[]) ProcessCmdLine(int& aArgc, wchar_t* aArgv[])
{ {
@ -147,42 +166,53 @@ MaybeBreakForBrowserDebugging()
#if defined(MOZ_LAUNCHER_PROCESS) #if defined(MOZ_LAUNCHER_PROCESS)
static mozilla::LauncherResult<bool> static bool
IsSameBinaryAsParentProcess() IsSameBinaryAsParentProcess()
{ {
mozilla::LauncherResult<DWORD> parentPid = mozilla::nt::GetParentProcessId(); mozilla::Maybe<DWORD> parentPid = mozilla::nt::GetParentProcessId();
if (parentPid.isErr()) { if (!parentPid) {
return LAUNCHER_ERROR_FROM_RESULT(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, nsAutoHandle parentProcess(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,
FALSE, parentPid.unwrap())); FALSE, parentPid.value()));
if (!parentProcess.get()) { 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] = {}; WCHAR parentExe[MAX_PATH + 1] = {};
DWORD parentExeLen = mozilla::ArrayLength(parentExe); DWORD parentExeLen = mozilla::ArrayLength(parentExe);
if (!::QueryFullProcessImageNameW(parentProcess.get(), PROCESS_NAME_NATIVE, if (!::QueryFullProcessImageNameW(parentProcess.get(), PROCESS_NAME_NATIVE,
parentExe, &parentExeLen)) { 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] = {}; WCHAR ourExe[MAX_PATH + 1] = {};
DWORD ourExeOk = ::GetModuleFileNameW(nullptr, ourExe, DWORD ourExeOk = ::GetModuleFileNameW(nullptr, ourExe,
mozilla::ArrayLength(ourExe)); mozilla::ArrayLength(ourExe));
if (!ourExeOk || ourExeOk == 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::DoPathsPointToIdenticalFile(parentExe, ourExe,
mozilla::PathType::eNtPath); mozilla::eNtPath);
if (isSame.isErr()) { if (!isSame) {
return LAUNCHER_ERROR_FROM_MOZ_WINDOWS_ERROR(isSame.unwrapErr()); // If DoPathsPointToIdenticalFile failed, we should not behave as the
// launcher process for the same reason as NtQueryInformationProcess.
MOZ_CRASH("DoPathsPointToIdenticalFile failed");
} }
return isSame.value();
return isSame.unwrap();
} }
#endif // defined(MOZ_LAUNCHER_PROCESS) #endif // defined(MOZ_LAUNCHER_PROCESS)
@ -198,12 +228,7 @@ RunAsLauncherProcess(int& argc, wchar_t** argv)
bool result = false; bool result = false;
#if defined(MOZ_LAUNCHER_PROCESS) #if defined(MOZ_LAUNCHER_PROCESS)
LauncherResult<bool> isSame = IsSameBinaryAsParentProcess(); result = !IsSameBinaryAsParentProcess();
if (isSame.isOk()) {
result = !isSame.unwrap();
} else {
HandleLauncherError(isSame.unwrapErr());
}
#endif // defined(MOZ_LAUNCHER_PROCESS) #endif // defined(MOZ_LAUNCHER_PROCESS)
if (mozilla::EnvHasValue("MOZ_LAUNCHER_PROCESS")) { if (mozilla::EnvHasValue("MOZ_LAUNCHER_PROCESS")) {
@ -243,45 +268,37 @@ LauncherMain(int argc, wchar_t* argv[])
} }
if (!SetArgv0ToFullBinaryPath(argv)) { if (!SetArgv0ToFullBinaryPath(argv)) {
HandleLauncherError(LAUNCHER_ERROR_GENERIC()); ShowError();
return 1; return 1;
} }
LauncherFlags flags = ProcessCmdLine(argc, argv); LauncherFlags flags = ProcessCmdLine(argc, argv);
nsAutoHandle mediumIlToken; nsAutoHandle mediumIlToken;
LauncherResult<ElevationState> elevationState = GetElevationState(flags, mediumIlToken); Maybe<ElevationState> elevationState = GetElevationState(flags, mediumIlToken);
if (elevationState.isErr()) { if (!elevationState) {
HandleLauncherError(elevationState);
return 1; return 1;
} }
// If we're elevated, we should relaunch ourselves as a normal user. // 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 // Note that we only call LaunchUnelevated when we don't need to wait for the
// browser process. // browser process.
if (elevationState.unwrap() == ElevationState::eElevated && if (elevationState.value() == ElevationState::eElevated &&
!(flags & (LauncherFlags::eWaitForBrowser | LauncherFlags::eNoDeelevate)) && !(flags & (LauncherFlags::eWaitForBrowser | LauncherFlags::eNoDeelevate)) &&
!mediumIlToken.get()) { !mediumIlToken.get()) {
LauncherVoidResult launchedUnelevated = LaunchUnelevated(argc, argv); return !LaunchUnelevated(argc, argv);
bool failed = launchedUnelevated.isErr();
if (failed) {
HandleLauncherError(launchedUnelevated);
}
return failed;
} }
// Now proceed with setting up the parameters for process creation // Now proceed with setting up the parameters for process creation
UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(argc, argv)); UniquePtr<wchar_t[]> cmdLine(MakeCommandLine(argc, argv));
if (!cmdLine) { if (!cmdLine) {
HandleLauncherError(LAUNCHER_ERROR_GENERIC());
return 1; return 1;
} }
const Maybe<bool> isSafeMode = IsSafeModeRequested(argc, argv, const Maybe<bool> isSafeMode = IsSafeModeRequested(argc, argv,
SafeModeFlag::NoKeyPressCheck); SafeModeFlag::NoKeyPressCheck);
if (!isSafeMode) { if (!isSafeMode) {
HandleLauncherError(LAUNCHER_ERROR_FROM_WIN32(ERROR_INVALID_PARAMETER)); ShowError(ERROR_INVALID_PARAMETER);
return 1; return 1;
} }
@ -299,15 +316,15 @@ LauncherMain(int argc, wchar_t* argv[])
DWORD creationFlags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT; DWORD creationFlags = CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT;
STARTUPINFOEXW siex; STARTUPINFOEXW siex;
LauncherResult<bool> attrsOk = attrs.AssignTo(siex); Maybe<bool> attrsOk = attrs.AssignTo(siex);
if (attrsOk.isErr()) { if (!attrsOk) {
HandleLauncherError(attrsOk); ShowError();
return 1; return 1;
} }
BOOL inheritHandles = FALSE; BOOL inheritHandles = FALSE;
if (attrsOk.unwrap()) { if (attrsOk.value()) {
creationFlags |= EXTENDED_STARTUPINFO_PRESENT; creationFlags |= EXTENDED_STARTUPINFO_PRESENT;
if (attrs.HasInheritableHandles()) { if (attrs.HasInheritableHandles()) {
@ -337,23 +354,16 @@ LauncherMain(int argc, wchar_t* argv[])
} }
if (!createOk) { if (!createOk) {
HandleLauncherError(LAUNCHER_ERROR_FROM_LAST()); ShowError();
return 1; return 1;
} }
nsAutoHandle process(pi.hProcess); nsAutoHandle process(pi.hProcess);
nsAutoHandle mainThread(pi.hThread); nsAutoHandle mainThread(pi.hThread);
LauncherVoidResult setupResult = if (!PostCreationSetup(process.get(), mainThread.get(), isSafeMode.value()) ||
PostCreationSetup(process.get(), mainThread.get(), isSafeMode.value()); ::ResumeThread(mainThread.get()) == static_cast<DWORD>(-1)) {
if (setupResult.isErr()) { ShowError();
HandleLauncherError(setupResult);
::TerminateProcess(process.get(), 1);
return 1;
}
if (::ResumeThread(mainThread.get()) == static_cast<DWORD>(-1)) {
HandleLauncherError(LAUNCHER_ERROR_FROM_LAST());
::TerminateProcess(process.get(), 1); ::TerminateProcess(process.get(), 1);
return 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/ArrayUtils.h"
#include "mozilla/Attributes.h" #include "mozilla/Attributes.h"
#include "mozilla/Maybe.h"
#include "LauncherResult.h"
extern "C" { extern "C" {
@ -569,7 +568,7 @@ RtlGetProcessHeap()
return peb->Reserved4[1]; return peb->Reserved4[1];
} }
inline LauncherResult<DWORD> inline Maybe<DWORD>
GetParentProcessId() GetParentProcessId()
{ {
struct PROCESS_BASIC_INFORMATION struct PROCESS_BASIC_INFORMATION
@ -582,18 +581,17 @@ GetParentProcessId()
ULONG_PTR InheritedFromUniqueProcessId; ULONG_PTR InheritedFromUniqueProcessId;
}; };
const HANDLE kCurrentProcess = reinterpret_cast<HANDLE>(-1);
ULONG returnLength; ULONG returnLength;
PROCESS_BASIC_INFORMATION pbi = {}; PROCESS_BASIC_INFORMATION pbi = {};
NTSTATUS status = ::NtQueryInformationProcess(kCurrentProcess, NTSTATUS status = ::NtQueryInformationProcess(::GetCurrentProcess(),
ProcessBasicInformation, ProcessBasicInformation,
&pbi, sizeof(pbi), &pbi, sizeof(pbi),
&returnLength); &returnLength);
if (!NT_SUCCESS(status)) { 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 } // namespace nt

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

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

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

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

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

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

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

@ -8,16 +8,9 @@
#define mozilla_WinHeaderOnlyUtils_h #define mozilla_WinHeaderOnlyUtils_h
#include <windows.h> #include <windows.h>
#include <winerror.h>
#include <winternl.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/Maybe.h"
#include "mozilla/Result.h"
#include "mozilla/UniquePtr.h"
#include "mozilla/WindowsVersion.h" #include "mozilla/WindowsVersion.h"
#include "nsWindowsHelpers.h" #include "nsWindowsHelpers.h"
@ -41,159 +34,6 @@ typedef struct _FILE_ID_INFO
namespace mozilla { 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, // How long to wait for a created process to become available for input,
// to prevent that process's windows being forced to the background. // to prevent that process's windows being forced to the background.
// This is used across update, restart, and the launcher. // 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, eNtPath,
eDosPath, eDosPath,
}; };
@ -255,14 +94,13 @@ public:
return; return;
} }
nsAutoHandle file; nsAutoHandle file(INVALID_HANDLE_VALUE);
switch (aPathType) { switch (aPathType) {
default: default:
MOZ_ASSERT_UNREACHABLE("Unhandled PathType");
return; return;
case PathType::eNtPath: { case eNtPath:
{
UNICODE_STRING unicodeString; UNICODE_STRING unicodeString;
::RtlInitUnicodeString(&unicodeString, aPath); ::RtlInitUnicodeString(&unicodeString, aPath);
OBJECT_ATTRIBUTES objectAttributes; OBJECT_ATTRIBUTES objectAttributes;
@ -277,31 +115,23 @@ public:
FILE_SHARE_DELETE, FILE_SHARE_DELETE,
FILE_SYNCHRONOUS_IO_NONALERT | FILE_SYNCHRONOUS_IO_NONALERT |
FILE_OPEN_FOR_BACKUP_INTENT); FILE_OPEN_FOR_BACKUP_INTENT);
// We don't need to check |ntHandle| for INVALID_HANDLE_VALUE here, if (!NT_SUCCESS(status) || ntHandle == INVALID_HANDLE_VALUE) {
// as that value is set by the Win32 layer.
if (!NT_SUCCESS(status)) {
mError = Some(WindowsError::FromNtStatus(status));
return; return;
} }
file.own(ntHandle); file.own(ntHandle);
} }
break; break;
case PathType::eDosPath: { case eDosPath:
file.own(::CreateFileW(aPath, 0, FILE_SHARE_READ | file.own(::CreateFileW(aPath, 0, FILE_SHARE_READ |
FILE_SHARE_WRITE | FILE_SHARE_DELETE, FILE_SHARE_WRITE | FILE_SHARE_DELETE,
nullptr, OPEN_EXISTING, nullptr, OPEN_EXISTING,
FILE_FLAG_BACKUP_SEMANTICS, nullptr)); FILE_FLAG_BACKUP_SEMANTICS, nullptr));
if (file == INVALID_HANDLE_VALUE) { if (file == INVALID_HANDLE_VALUE) {
mError = Some(WindowsError::FromLastError());
return; return;
} }
break; break;
} }
}
GetId(file); GetId(file);
} }
@ -314,7 +144,6 @@ public:
FileUniqueId(const FileUniqueId& aOther) FileUniqueId(const FileUniqueId& aOther)
: mId(aOther.mId) : mId(aOther.mId)
, mError(aOther.mError)
{ {
} }
@ -323,18 +152,12 @@ public:
explicit operator bool() const explicit operator bool() const
{ {
FILE_ID_INFO zeros = {}; FILE_ID_INFO zeros = {};
return !mError && memcmp(&mId, &zeros, sizeof(FILE_ID_INFO)); return memcmp(&mId, &zeros, sizeof(FILE_ID_INFO));
}
Maybe<WindowsError> GetError() const
{
return mError;
} }
FileUniqueId& operator=(const FileUniqueId& aOther) FileUniqueId& operator=(const FileUniqueId& aOther)
{ {
mId = aOther.mId; mId = aOther.mId;
mError = aOther.mError;
return *this; return *this;
} }
@ -343,8 +166,7 @@ public:
bool operator==(const FileUniqueId& aOther) const bool operator==(const FileUniqueId& aOther) const
{ {
return !mError && !aOther.mError && return !memcmp(&mId, &aOther.mId, sizeof(FILE_ID_INFO));
!memcmp(&mId, &aOther.mId, sizeof(FILE_ID_INFO));
} }
bool operator!=(const FileUniqueId& aOther) const bool operator!=(const FileUniqueId& aOther) const
@ -365,7 +187,6 @@ private:
BY_HANDLE_FILE_INFORMATION info = {}; BY_HANDLE_FILE_INFORMATION info = {};
if (!::GetFileInformationByHandle(aFile.get(), &info)) { if (!::GetFileInformationByHandle(aFile.get(), &info)) {
mError = Some(WindowsError::FromLastError());
return; return;
} }
@ -378,27 +199,24 @@ private:
private: private:
FILE_ID_INFO mId; FILE_ID_INFO mId;
Maybe<WindowsError> mError;
}; };
inline WindowsErrorResult<bool> inline Maybe<bool>
DoPathsPointToIdenticalFile(const wchar_t* aPath1, const wchar_t* aPath2, DoPathsPointToIdenticalFile(const wchar_t* aPath1, const wchar_t* aPath2,
PathType aPathType1 = PathType::eDosPath, PathType aPathType1 = eDosPath,
PathType aPathType2 = PathType::eDosPath) PathType aPathType2 = eDosPath)
{ {
FileUniqueId id1(aPath1, aPathType1); FileUniqueId id1(aPath1, aPathType1);
if (!id1) { if (!id1) {
Maybe<WindowsError> error = id1.GetError(); return Nothing();
return Err(error.valueOr(WindowsError::CreateGeneric()));
} }
FileUniqueId id2(aPath2, aPathType2); FileUniqueId id2(aPath2, aPathType2);
if (!id2) { if (!id2) {
Maybe<WindowsError> error = id2.GetError(); return Nothing();
return Err(error.valueOr(WindowsError::CreateGeneric()));
} }
return id1 == id2; return Some(id1 == id2);
} }
} // namespace mozilla } // namespace mozilla