1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4 * License, v. 2.0. If a copy of the MPL was not distributed with this
5 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "ProfileUnlockerWin.h"
16 * RAII class to obtain and manage a handle to a Restart Manager session.
17 * It opens a new handle upon construction and releases it upon destruction.
19 class MOZ_STACK_CLASS ScopedRestartManagerSession
{
21 explicit ScopedRestartManagerSession(ProfileUnlockerWin
& aUnlocker
)
22 : mError(ERROR_INVALID_HANDLE
),
23 mHandle((DWORD
)-1) // 0 is a valid restart manager handle
25 mUnlocker(aUnlocker
) {
26 mError
= mUnlocker
.StartSession(mHandle
);
29 ~ScopedRestartManagerSession() {
30 if (mError
== ERROR_SUCCESS
) {
31 mUnlocker
.EndSession(mHandle
);
36 * @return true if the handle is a valid Restart Ranager handle.
38 inline bool ok() { return mError
== ERROR_SUCCESS
; }
41 * @return the Restart Manager handle to pass to other Restart Manager APIs.
43 inline DWORD
handle() { return mHandle
; }
48 ProfileUnlockerWin
& mUnlocker
;
51 ProfileUnlockerWin::ProfileUnlockerWin(const nsAString
& aFileName
)
52 : mRmStartSession(nullptr),
53 mRmRegisterResources(nullptr),
55 mRmEndSession(nullptr),
56 mQueryFullProcessImageName(nullptr),
57 mFileName(aFileName
) {}
59 ProfileUnlockerWin::~ProfileUnlockerWin() {}
61 NS_IMPL_ISUPPORTS(ProfileUnlockerWin
, nsIProfileUnlocker
)
63 nsresult
ProfileUnlockerWin::Init() {
64 MOZ_ASSERT(!mRestartMgrModule
);
65 if (mFileName
.IsEmpty()) {
66 return NS_ERROR_ILLEGAL_VALUE
;
69 nsModuleHandle
module(::LoadLibraryW(L
"Rstrtmgr.dll"));
71 return NS_ERROR_NOT_AVAILABLE
;
73 mRmStartSession
= reinterpret_cast<RMSTARTSESSION
>(
74 ::GetProcAddress(module
, "RmStartSession"));
75 if (!mRmStartSession
) {
76 return NS_ERROR_UNEXPECTED
;
78 mRmRegisterResources
= reinterpret_cast<RMREGISTERRESOURCES
>(
79 ::GetProcAddress(module
, "RmRegisterResources"));
80 if (!mRmRegisterResources
) {
81 return NS_ERROR_UNEXPECTED
;
84 reinterpret_cast<RMGETLIST
>(::GetProcAddress(module
, "RmGetList"));
86 return NS_ERROR_UNEXPECTED
;
89 reinterpret_cast<RMENDSESSION
>(::GetProcAddress(module
, "RmEndSession"));
91 return NS_ERROR_UNEXPECTED
;
94 mQueryFullProcessImageName
=
95 reinterpret_cast<QUERYFULLPROCESSIMAGENAME
>(::GetProcAddress(
96 ::GetModuleHandleW(L
"kernel32.dll"), "QueryFullProcessImageNameW"));
97 if (!mQueryFullProcessImageName
) {
98 return NS_ERROR_NOT_AVAILABLE
;
101 mRestartMgrModule
.steal(module
);
106 ProfileUnlockerWin::StartSession(DWORD
& aHandle
) {
107 WCHAR sessionKey
[CCH_RM_SESSION_KEY
+ 1] = {0};
108 return mRmStartSession(&aHandle
, 0, sessionKey
);
111 void ProfileUnlockerWin::EndSession(DWORD aHandle
) { mRmEndSession(aHandle
); }
114 ProfileUnlockerWin::Unlock(uint32_t aSeverity
) {
115 if (!mRestartMgrModule
) {
116 return NS_ERROR_NOT_INITIALIZED
;
119 if (aSeverity
!= FORCE_QUIT
) {
120 return NS_ERROR_NOT_IMPLEMENTED
;
123 ScopedRestartManagerSession
session(*this);
125 return NS_ERROR_FAILURE
;
128 LPCWSTR resources
[] = {mFileName
.get()};
129 DWORD error
= mRmRegisterResources(session
.handle(), 1, resources
, 0, nullptr,
131 if (error
!= ERROR_SUCCESS
) {
132 return NS_ERROR_FAILURE
;
135 // Using a AutoTArray here because we expect the required size to be 1.
136 AutoTArray
<RM_PROCESS_INFO
, 1> info
;
138 UINT numEntriesNeeded
= 1;
139 error
= ERROR_MORE_DATA
;
140 DWORD reason
= RmRebootReasonNone
;
141 while (error
== ERROR_MORE_DATA
) {
142 info
.SetLength(numEntriesNeeded
);
143 numEntries
= numEntriesNeeded
;
144 error
= mRmGetList(session
.handle(), &numEntriesNeeded
, &numEntries
,
147 if (error
!= ERROR_SUCCESS
) {
148 return NS_ERROR_FAILURE
;
150 if (numEntries
== 0) {
151 // Nobody else is locking the file; the other process must have terminated
155 nsresult rv
= NS_ERROR_FAILURE
;
156 for (UINT i
= 0; i
< numEntries
; ++i
) {
157 rv
= TryToTerminate(info
[i
].Process
);
158 if (NS_SUCCEEDED(rv
)) {
163 // If nothing could be unlocked then we return the error code of the last
164 // failure that was returned.
168 nsresult
ProfileUnlockerWin::TryToTerminate(RM_UNIQUE_PROCESS
& aProcess
) {
169 // Subtle: If the target process terminated before this call to OpenProcess,
170 // this call will still succeed. This is because the restart manager session
171 // internally retains a handle to the target process. The rules for Windows
172 // PIDs state that the PID of a terminated process remains valid as long as
173 // at least one handle to that process remains open, so when we reach this
174 // point the PID is still valid and the process will open successfully.
175 DWORD accessRights
= PROCESS_QUERY_LIMITED_INFORMATION
| PROCESS_TERMINATE
;
176 nsAutoHandle
otherProcess(
177 ::OpenProcess(accessRights
, FALSE
, aProcess
.dwProcessId
));
179 return NS_ERROR_FAILURE
;
182 FILETIME creationTime
, exitTime
, kernelTime
, userTime
;
183 if (!::GetProcessTimes(otherProcess
, &creationTime
, &exitTime
, &kernelTime
,
185 return NS_ERROR_FAILURE
;
187 if (::CompareFileTime(&aProcess
.ProcessStartTime
, &creationTime
)) {
188 return NS_ERROR_NOT_AVAILABLE
;
191 WCHAR imageName
[MAX_PATH
];
192 DWORD imageNameLen
= MAX_PATH
;
193 if (!mQueryFullProcessImageName(otherProcess
, 0, imageName
, &imageNameLen
)) {
194 // The error codes for this function are not very descriptive. There are
195 // actually two failure cases here: Either the call failed because the
196 // process is no longer running, or it failed for some other reason. We
197 // need to know which case that is.
198 DWORD otherProcessExitCode
;
199 if (!::GetExitCodeProcess(otherProcess
, &otherProcessExitCode
) ||
200 otherProcessExitCode
== STILL_ACTIVE
) {
201 // The other process is still running.
202 return NS_ERROR_FAILURE
;
204 // The other process must have terminated. We should return NS_OK so that
205 // this process may proceed with startup.
208 nsCOMPtr
<nsIFile
> otherProcessImageName
;
209 if (NS_FAILED(NS_NewLocalFile(nsDependentString(imageName
, imageNameLen
),
211 getter_AddRefs(otherProcessImageName
)))) {
212 return NS_ERROR_FAILURE
;
214 nsAutoString otherProcessLeafName
;
215 if (NS_FAILED(otherProcessImageName
->GetLeafName(otherProcessLeafName
))) {
216 return NS_ERROR_FAILURE
;
219 imageNameLen
= MAX_PATH
;
220 if (!mQueryFullProcessImageName(::GetCurrentProcess(), 0, imageName
,
222 return NS_ERROR_FAILURE
;
224 nsCOMPtr
<nsIFile
> thisProcessImageName
;
225 if (NS_FAILED(NS_NewLocalFile(nsDependentString(imageName
, imageNameLen
),
226 false, getter_AddRefs(thisProcessImageName
)))) {
227 return NS_ERROR_FAILURE
;
229 nsAutoString thisProcessLeafName
;
230 if (NS_FAILED(thisProcessImageName
->GetLeafName(thisProcessLeafName
))) {
231 return NS_ERROR_FAILURE
;
234 // Make sure the image leaf names match
235 if (_wcsicmp(otherProcessLeafName
.get(), thisProcessLeafName
.get())) {
236 return NS_ERROR_NOT_AVAILABLE
;
239 // We know that another process holds the lock and that it shares the same
240 // image name as our process. Let's kill it.
241 // Subtle: TerminateProcess returning ERROR_ACCESS_DENIED is actually an
242 // indicator that the target process managed to shut down on its own. In that
243 // case we should return NS_OK since we may proceed with startup.
244 if (!::TerminateProcess(otherProcess
, 1) &&
245 ::GetLastError() != ERROR_ACCESS_DENIED
) {
246 return NS_ERROR_FAILURE
;
252 } // namespace mozilla