Debian Codegraph @

src/Main/MultipleInstanceLock.cxx

raw symbols SCIP
1 // SPDX-FileCopyrightText: 2025 James Turner
2 // SPDX-License-Identifier: GPL-2.0-or-later
3
4 #include "config.h"
5
6 #include <cassert>
7 #include <cstdlib>
8
9
10 #include "MultipleInstanceLock.hxx"
11
12 #include <simgear/misc/sg_path.hxx>
13
14 #include <Main/globals.hxx>
15 #include <Main/sentryIntegration.hxx>
16
17 #include <GUI/MessageBox.hxx>
18
19 #if defined(SG_WINDOWS)
20 #define WIN32_LEAN_AND_MEAN // less crap :)
21 #include <Windows.h>
22 #else
23 #include <sys/file.h>
24 #include <unistd.h>
25 #endif
26
27 namespace {
28
29 #if defined(SG_WINDOWS)
30 static HANDLE static_fgMultipleInstanceMutex = nullptr;
31 static HANDLE static_fgLockReasonSharedMemory = nullptr;
32 #else
33 const std::string static_multiInstanceLockFile = "fgfs_exclusive.lock";
34 static int static_lockFileFd = -1;
35 #endif
36
37 enum LockStatus {
38 LockFailed = 0,
39 LockAlreadyLocked,
40 LockOk
41 };
42
43 #if defined(SG_WINDOWS)
44
45 void windowsCleanup()
46 {
47 if (static_fgLockReasonSharedMemory) {
48 CloseHandle(static_fgLockReasonSharedMemory);
49 static_fgLockReasonSharedMemory = nullptr;
50 }
51 }
52
53 std::string windowsReadLockReason()
54 {
55 if (!static_fgLockReasonSharedMemory) {
56 static_fgLockReasonSharedMemory = OpenFileMappingA(FILE_MAP_READ, false, "org.flightgear.fgfs.reason");
57 if (!static_fgLockReasonSharedMemory) {
58 SG_LOG(SG_IO, SG_WARN, "Failed to open shared memory file for lock reason");
59 return {};
60 }
61
62 std::atexit(windowsCleanup);
63 }
64
65 void* v = MapViewOfFile(static_fgLockReasonSharedMemory, FILE_MAP_READ, 0, 0, 0);
66 if (!v) {
67 SG_LOG(SG_IO, SG_ALERT, "Failed to mmap shared memory file for lock reason");
68 return {};
69 }
70
71 std::string buf{reinterpret_cast<char*>(v)}; // assumes null-terminated
72 SG_LOG(SG_IO, SG_INFO, "lock reason:" << buf);
73 UnmapViewOfFile(v);
74 return buf;
75 }
76
77
78 #endif
79
80 void writeLockReason(const std::string& s)
81
82 #if defined(SG_WINDOWS)
83 {
84 assert(s.length() < 1024);
85 if (!static_fgLockReasonSharedMemory) {
86 static_fgLockReasonSharedMemory = CreateFileMappingA(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, 0, 1024, "org.flightgear.fgfs.reason");
87 if (!static_fgLockReasonSharedMemory) {
88 SG_LOG(SG_IO, SG_ALERT, "Failed to create shared memory file for lock writing");
89 return;
90 }
91
92 std::atexit(windowsCleanup);
93 }
94
95 void* v = MapViewOfFile(static_fgLockReasonSharedMemory, FILE_MAP_WRITE, 0, 0, 0);
96 if (!v) {
97 SG_LOG(SG_IO, SG_ALERT, "Failed to mmap shared memory file for lock reason");
98 return;
99 }
100
101 memcpy(v, s.c_str(), s.length());
102 UnmapViewOfFile(v);
103 }
104 #else
105 {
106 // write our reason to the lock file
107 ::write(static_lockFileFd, s.data(), s.size());
108 }
109 #endif
110
111 LockStatus acquireLock()
112 {
113 #if defined(SG_WINDOWS)
114 if (!static_fgMultipleInstanceMutex) {
115 static_fgMultipleInstanceMutex = CreateMutexA(nullptr, FALSE, "org.flightgear.fgfs.exclusive");
116 if (!static_fgMultipleInstanceMutex) {
117 SG_LOG(SG_IO, SG_ALERT, "Failed to create exclusive-access mutex");
118 return LockFailed;
119 }
120
121 const auto err = GetLastError();
122 if (err && (err != ERROR_ALREADY_EXISTS)) {
123 SG_LOG(SG_IO, SG_ALERT, "Failed to create exclusive-access mutex: " << GetLastError());
124 return LockFailed;
125 }
126 }
127
128 // acquire the mutex, so that other processes can check the status.
129 const int result = WaitForSingleObject(static_fgMultipleInstanceMutex, 100);
130 if (result == WAIT_TIMEOUT) {
131 return LockAlreadyLocked;
132 }
133
134 if (result != WAIT_OBJECT_0) {
135 // failed, somehow
136 SG_LOG(SG_IO, SG_ALERT, "Failed to lock exclusive mutex:" << GetLastError());
137 return LockFailed;
138 }
139 #else
140 SGPath lockPath(globals->get_fg_home(), static_multiInstanceLockFile);
141 std::string ps = lockPath.utf8Str();
142 static_lockFileFd = ::open(ps.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);
143 if (static_lockFileFd < 0) {
144 SG_LOG(SG_IO, SG_ALERT, "Failed to create lock file (" << lockPath << "):" << simgear::strutils::error_string(errno));
145 return LockFailed;
146 }
147 int err = ::flock(static_lockFileFd, LOCK_EX | LOCK_NB);
148 if (err < 0) {
149 if (errno == EWOULDBLOCK) {
150 return LockAlreadyLocked;
151 }
152
153 SG_LOG(SG_IO, SG_ALERT, "Failed to lock file (" << lockPath << "):" << simgear::strutils::error_string(errno));
154 return LockFailed;
155 }
156 #endif
157 return LockOk;
158 }
159
160 void releaseLock(SGPath lockPath)
161 {
162 #if defined(SG_WINDOWS)
163 ReleaseMutex(static_fgMultipleInstanceMutex);
164 CloseHandle(static_fgMultipleInstanceMutex);
165 static_fgMultipleInstanceMutex = nullptr;
166 SG_LOG(SG_IO, SG_INFO, "Released lock");
167 #else
168 int err = ::flock(static_lockFileFd, LOCK_UN);
169 if (err < 0) {
170 SG_LOG(SG_IO, SG_ALERT, "Failed to unlock file:" << simgear::strutils::error_string(errno));
171 }
172
173 ::close(static_lockFileFd);
174 lockPath.remove();
175 #endif
176 }
177
178
179 std::optional<std::string> implIsLocked()
180 {
181 #if defined(SG_WINDOWS)
182 if (!static_fgMultipleInstanceMutex) {
183 static_fgMultipleInstanceMutex = OpenMutexA(SYNCHRONIZE, FALSE, "org.flightgear.fgfs.exclusive");
184 if (!static_fgMultipleInstanceMutex) {
185 // this is the common case: no other fgfs.exe has the lock
186 // the mutex does not exist. Simple, we are done
187 if (GetLastError() == ERROR_FILE_NOT_FOUND) {
188 return {};
189 }
190
191 flightgear::fatalMessageBoxThenExit("Multiple copies of Flightgear initializing",
192 "Unable to check if other copies of FlightGear are initializing. "
193 "Please report this error.");
194 }
195 }
196
197 // poll the named mutex
198 auto result = WaitForSingleObject(static_fgMultipleInstanceMutex, 0);
199 if (result == WAIT_OBJECT_0) {
200 // we acquired it, release it and we're done
201 // (there could be multiple read-only copies in this situation)
202 ReleaseMutex(static_fgMultipleInstanceMutex);
203 SG_LOG(SG_IO, SG_INFO, "isLocked: got the lock and released it");
204 return {};
205 }
206
207 // failed to acquire the mutex, so assume another FGFS.exe has it locked
208 return windowsReadLockReason();
209 #else
210 SGPath lockPath(globals->get_fg_home(), static_multiInstanceLockFile);
211 std::string ps = lockPath.utf8Str();
212 static_lockFileFd = ::open(ps.c_str(), O_RDONLY, 0644);
213 if (static_lockFileFd < 0) {
214 if (errno == ENOENT) {
215 return {}; // no such file, easy
216 }
217
218 SG_LOG(SG_IO, SG_ALERT, "Error opening lock file:" << simgear::strutils::error_string(errno));
219 return {};
220 }
221
222 int err = ::flock(static_lockFileFd, LOCK_EX | LOCK_NB);
223 if (err < 0) {
224 if (errno == EWOULDBLOCK) {
225 char buf[256];
226 int r = ::read(static_lockFileFd, buf, 256);
227 return std::string(buf, r);
228 }
229
230 SG_LOG(SG_IO, SG_ALERT, "Error querying lock file:" << simgear::strutils::error_string(errno));
231 return {};
232 }
233
234 // release it again, so any *other* waiting copies can also succeed
235 ::flock(static_lockFileFd, LOCK_UN);
236 return {};
237 #endif
238 }
239
240 } // namespace
241
242 namespace flightgear {
243
244 static std::unique_ptr<ExclusiveInstanceLock> static_theLock;
245
246 ExclusiveInstanceLock* ExclusiveInstanceLock::createInstance(const std::string& reason)
247 {
248 assert(static_theLock == nullptr);
249 const auto r = acquireLock();
250 if (r == LockFailed) {
251 fatalMessageBoxThenExit("Multiple copies of Flightgear initializing",
252 "Failed to initialise locking for data files.");
253 } else if (r == LockAlreadyLocked) {
254 fatalMessageBoxThenExit("Multiple copies of Flightgear initializing",
255 "Multiple copies of FlightGear are trying to initialise the same data files. "
256 "This means something has gone badly wrong: please report this error.");
257 }
258
259 static_theLock.reset(new ExclusiveInstanceLock(reason));
260 return static_theLock.get();
261 }
262
263 ExclusiveInstanceLock* ExclusiveInstanceLock::instance()
264 {
265 return static_theLock.get();
266 }
267
268 void ExclusiveInstanceLock::destroyInstance()
269 {
270 static_theLock.reset();
271 }
272
273 ExclusiveInstanceLock::ExclusiveInstanceLock(std::string reason)
274 : _reason(reason)
275 {
276 #if !defined(SG_WINDOWS)
277 _lockPath = SGPath(globals->get_fg_home(), static_multiInstanceLockFile);
278 #endif
279 writeLockReason(_reason);
280 addSentryBreadcrumb("created ExclusiveInstanceLock:" + reason, "info");
281 }
282
283 ExclusiveInstanceLock::~ExclusiveInstanceLock()
284 {
285 // depending on C++ destruction order, we can't access globals here,
286 // so we save the path at constructor time
287 releaseLock(_lockPath);
288 addSentryBreadcrumb("released ExclusiveInstanceLock", "info");
289 }
290
291 std::optional<std::string> ExclusiveInstanceLock::isLocked()
292 {
293 if (static_theLock) {
294 // we are the primary copy (the one holding the exclusive lock)
295 return {};
296 }
297
298 return implIsLocked();
299 }
300
301 void ExclusiveInstanceLock::updateReason(const std::string& reason)
302 {
303 assert(static_theLock.get() == this);
304 _reason = reason;
305 writeLockReason(_reason);
306 }
307
308 // if we do have Qt, this is defined in QtLauncher.cxx using QProgressDialog
309 #if !defined(HAVE_QT)
310 bool ExclusiveInstanceLock::showWaitDialog()
311 {
312 // rely on the fgIdleFunction state==1 code, to block startup until the primary copy is done
313 SG_LOG(SG_GUI, SG_INFO, "ExclusiveInstanceLock::showWaitDialog: no Qt support, will let splash screen block instead.");
314 return true;
315 }
316 #endif
317
318 } // namespace flightgear