Bug 1942239 - Add option to explicitly enable incremental origin initialization in...
[gecko.git] / toolkit / xre / nsUpdateMutex.cpp
blob2bdc12ddf30cc856ecfd421a40e1a9ca39fb4d02
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim:set ts=2 sw=2 sts=2 et cindent: */
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 "nsUpdateMutex.h"
9 #include "mozilla/DebugOnly.h"
10 #include "mozilla/ScopeExit.h"
11 #include "mozilla/StaticMutex.h"
12 #include "nsIFile.h"
13 #include "nsProfileLock.h"
14 #include "nsXULAppAPI.h"
16 mozilla::StaticMutex UpdateMutexImpl::sInProcessMutex;
18 bool UpdateMutexImpl::TryLock() {
19 if (!sInProcessMutex.TryLock()) {
20 return false;
23 bool success = [&crossProcessLock = mCrossProcessLock]() {
24 nsCOMPtr<nsIFile> updRoot;
25 nsresult nsrv =
26 NS_GetSpecialDirectory(XRE_UPDATE_ROOT_DIR, getter_AddRefs(updRoot));
27 if (NS_FAILED(nsrv)) {
28 return false;
31 nsrv = updRoot->Create(nsIFile::DIRECTORY_TYPE, 0755);
32 if (NS_FAILED(nsrv) && nsrv != NS_ERROR_FILE_ALREADY_EXISTS) {
33 return false;
36 return NS_SUCCEEDED(crossProcessLock.Lock(updRoot, nullptr));
37 }();
39 if (!success) {
40 sInProcessMutex.Unlock();
43 return success;
46 void UpdateMutexImpl::Unlock() {
47 sInProcessMutex.AssertCurrentThreadOwns();
49 mozilla::DebugOnly<nsresult> nsrv = mCrossProcessLock.Unlock();
50 #ifdef DEBUG
51 if (!NS_SUCCEEDED(nsrv)) {
52 MOZ_CRASH_UNSAFE_PRINTF(
53 "failed to unlock the update mutex's nsProfileLock -- got 0x%08x",
54 static_cast<uint32_t>(nsrv.inspect()));
56 #endif
58 sInProcessMutex.Unlock();
61 NS_IMPL_ISUPPORTS(nsUpdateMutex, nsIUpdateMutex)
63 NS_IMETHODIMP nsUpdateMutex::IsLocked(bool* aResult) {
64 *aResult = mIsLocked;
65 return NS_OK;
68 NS_IMETHODIMP nsUpdateMutex::TryLock(bool* aResult) {
69 if (!mIsLocked) {
70 mIsLocked = mUpdateMutexImpl.TryLock();
72 *aResult = mIsLocked;
73 return NS_OK;
76 NS_IMETHODIMP nsUpdateMutex::Unlock() MOZ_NO_THREAD_SAFETY_ANALYSIS {
77 // Thread safety analysis cannot make sense out of a conditional release
78 if (mIsLocked) {
79 mUpdateMutexImpl.Unlock();
80 mIsLocked = false;
82 return NS_OK;