Debian Codegraph @

modules/lsp-runtime-lib/src/main/ipc/SharedMutex.cpp

raw
1 /*
2 * Copyright (C) 2025 Linux Studio Plugins Project <https://lsp-plug.in/>
3 * (C) 2025 Vladimir Sadovnikov <[email protected]>
4 *
5 * This file is part of lsp-runtime-lib
6 * Created on: 24 апр. 2024 г.
7 *
8 * lsp-runtime-lib is free software: you can redistribute it and/or modify
9 * it under the terms of the GNU Lesser General Public License as published by
10 * the Free Software Foundation, either version 3 of the License, or
11 * any later version.
12 *
13 * lsp-runtime-lib is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU Lesser General Public License for more details.
17 *
18 * You should have received a copy of the GNU Lesser General Public License
19 * along with lsp-runtime-lib. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22 #include <lsp-plug.in/common/atomic.h>
23 #include <lsp-plug.in/common/debug.h>
24 #include <lsp-plug.in/io/Path.h>
25 #include <lsp-plug.in/ipc/SharedMutex.h>
26 #include <lsp-plug.in/ipc/Thread.h>
27 #include <lsp-plug.in/runtime/system.h>
28
29 #ifdef PLATFORM_WINDOWS
30 #include <windows.h>
31 #include <synchapi.h>
32 #else
33 #include <errno.h>
34 #include <fcntl.h>
35 #include <pthread.h>
36 #include <sys/file.h>
37 #include <sys/mman.h>
38 #include <sys/stat.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 #endif /* PLATFORM_WINDOWS */
42
43 namespace lsp
44 {
45 namespace ipc
46 {
47 #ifdef LSP_ROBUST_MUTEX_SUPPORTED
48 static constexpr uint64_t SHMUTEX_INIT_FLAG = __IF_LEBE(0x786574756D5F6873ULL, 0x73685F6D75746578ULL); // "sh_mutex"
49
50 typedef struct shared_mutex_t
51 {
52 volatile uint64_t init_flag; // Should contain SHMUTEX_INIT_FLAG if mutex has been initialized
53 uatomic_t spin_lock; // Failover if system does not support flock() on shared memory
54 uatomic_t padding; // Padding, not used, should be zero
55 pthread_mutex_t mutex; // Shared mutex data
56 } shared_mutex_t;
57 #endif /* LSP_ROBUST_MUTEX_SUPPORTED */
58
59 SharedMutex::SharedMutex()
60 {
61 #ifdef PLATFORM_WINDOWS
62 hLock = NULL;
63 #else
64 hFD = -1;
65
66 #ifdef LSP_ROBUST_MUTEX_SUPPORTED
67 hLock = NULL;
68 #endif /* LSP_ROBUST_MUTEX_SUPPORTED */
69 #endif /* PLATFORM_WINDOWS */
70
71 atomic_store(&nOwner, INVALID_THREAD_ID);
72 }
73
74 SharedMutex::~SharedMutex()
75 {
76 close();
77 }
78
79 inline bool SharedMutex::is_opened() const
80 {
81 #if defined(PLATFORM_WINDOWS) || defined(LSP_ROBUST_MUTEX_SUPPORTED)
82 return hLock != NULL;
83 #else
84 return hFD >= 0;
85 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
86 }
87
88 status_t SharedMutex::open(const char *name)
89 {
90 if (is_opened())
91 return STATUS_OPENED;
92
93 LSPString tmp;
94 #ifdef PLATFORM_WINDOWS
95 if (!tmp.set_utf8(name))
96 return STATUS_NO_MEM;
97 #else
98 if (!tmp.append(FILE_SEPARATOR_C))
99 return STATUS_NO_MEM;
100 if (!tmp.append_utf8(name))
101 return STATUS_NO_MEM;
102 #endif /* PLATFORM_WINDOWS */
103 return open_internal(&tmp);
104 }
105
106 status_t SharedMutex::open(const LSPString *name)
107 {
108 if (is_opened())
109 return STATUS_OPENED;
110
111 #ifdef PLATFORM_WINDOWS
112 return open_internal(name);
113 #else
114 LSPString tmp;
115
116 if (!tmp.append(FILE_SEPARATOR_C))
117 return STATUS_NO_MEM;
118 if (!tmp.append(name))
119 return STATUS_NO_MEM;
120
121 return open_internal(&tmp);
122 #endif /* PLATFORM_WINDOWS */
123 }
124
125 #ifndef PLATFORM_WINDOWS
126 status_t SharedMutex::lock_descriptor(int fd, int flags)
127 {
128 while (true)
129 {
130 if (flock(fd, flags) == 0)
131 return STATUS_OK;
132
133 const int error = errno;
134 if (error == ENOTSUP)
135 return STATUS_NOT_SUPPORTED;
136
137 switch (error)
138 {
139 case EAGAIN: return STATUS_RETRY;
140 case EBADF: return STATUS_IO_ERROR;
141 case EINTR: break;
142 case EINVAL: return STATUS_INVALID_VALUE;
143 case ENOLCK: return STATUS_NO_MEM;
144 default: return STATUS_IO_ERROR;
145 }
146 }
147 }
148
149 #ifdef LSP_ROBUST_MUTEX_SUPPORTED
150 status_t SharedMutex::lock_memory(int fd, shared_mutex_t *mutex)
151 {
152 status_t res = lock_descriptor(fd, LOCK_EX);
153 if ((res == STATUS_OK) || (res == STATUS_NOT_SUPPORTED))
154 {
155 // Try to acquire spin-lock instead of flock
156 while (atomic_swap(&mutex->spin_lock, 1) != 0)
157 ipc::Thread::yield();
158
159 res = STATUS_OK;
160 }
161
162 return res;
163 }
164
165 status_t SharedMutex::unlock_memory(int fd, shared_mutex_t *mutex)
166 {
167 status_t res = lock_descriptor(fd, LOCK_UN);
168 if ((res == STATUS_OK) || (res == STATUS_NOT_SUPPORTED))
169 {
170 // Release spin lock
171 atomic_swap(&mutex->spin_lock, 0);
172 res = STATUS_OK;
173 }
174
175 return res;
176 }
177 #endif /* LSP_ROBUST_MUTEX_SUPPORTED */
178
179 #endif /* PLATFORM_WINDOWS */
180
181 status_t SharedMutex::open_internal(const LSPString *name)
182 {
183 #if defined(PLATFORM_WINDOWS)
184 const WCHAR *path = name->get_utf16();
185 if (path == NULL)
186 return STATUS_NO_MEM;
187
188 hLock = CreateMutexW(NULL, FALSE, path);
189 return (hLock != NULL) ? STATUS_OK : STATUS_IO_ERROR;
190 #elif defined(LSP_ROBUST_MUTEX_SUPPORTED)
191 int error;
192 const char *path = (name != NULL) ? name->get_native() : NULL;
193 if (path == NULL)
194 return STATUS_NO_MEM;
195
196 static constexpr int open_mode =
197 S_IRUSR | S_IWUSR |
198 S_IRGRP | S_IWGRP |
199 S_IROTH | S_IWOTH;
200
201 // Create shared memory segment
202 int fd = shm_open(path, O_RDWR | O_CREAT, open_mode);
203 if (fd < 0)
204 {
205 error = errno;
206 switch (error)
207 {
208 case EACCES: return STATUS_PERMISSION_DENIED;
209 case EEXIST: return STATUS_ALREADY_EXISTS;
210 case EINVAL: return STATUS_INVALID_VALUE;
211 case EMFILE: return STATUS_OVERFLOW;
212 case ENFILE: return STATUS_OVERFLOW;
213 case ENAMETOOLONG: return STATUS_TOO_BIG;
214 case ENOENT: return STATUS_NOT_FOUND;
215 case ENOMEM: return STATUS_NO_MEM;
216 default: return STATUS_IO_ERROR;
217 }
218 }
219 lsp_finally {
220 if (fd >= 0)
221 ::close(fd);
222 };
223
224 // Reserve memory for the mutex
225 if (ftruncate(fd, sizeof(shared_mutex_t)) != 0)
226 {
227 error = errno;
228 switch (error)
229 {
230 case EACCES: return STATUS_PERMISSION_DENIED;
231 case EFAULT: return STATUS_UNKNOWN_ERR;
232 case EFBIG: return STATUS_TOO_BIG;
233 case EINVAL: return STATUS_INVALID_VALUE;
234 case EINTR: return STATUS_INTERRUPTED;
235 case EIO: return STATUS_IO_ERROR;
236 case EISDIR: return STATUS_IS_DIRECTORY;
237 case EPERM: return STATUS_PERMISSION_DENIED;
238 case EROFS: return STATUS_READONLY;
239 case ETXTBSY: return STATUS_PERMISSION_DENIED;
240 case EBADF: return STATUS_IO_ERROR;
241 default: return STATUS_IO_ERROR;
242 }
243 }
244
245 // Map the mutex memory
246 shared_mutex_t *shmutex = static_cast<shared_mutex_t *>(mmap(0, sizeof(shared_mutex_t), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0));
247 if (shmutex == MAP_FAILED)
248 {
249 error = errno;
250 switch (error)
251 {
252 case EACCES: return STATUS_PERMISSION_DENIED;
253 case EAGAIN: return STATUS_RETRY;
254 case EPERM: return STATUS_PERMISSION_DENIED;
255 case EFBIG: return STATUS_TOO_BIG;
256 case EEXIST: return STATUS_ALREADY_EXISTS;
257 case ENOMEM: return STATUS_NO_MEM;
258 case EOVERFLOW: return STATUS_OVERFLOW;
259 default: return STATUS_IO_ERROR;
260 }
261 }
262 lsp_finally {
263 if (shmutex != NULL)
264 munmap(shmutex, sizeof(shared_mutex_t));
265 };
266
267 // Ensure that mutex is initialized
268 if (shmutex->init_flag != SHMUTEX_INIT_FLAG)
269 {
270 // Lock the shared memory segment to initialize mutex atomically
271 status_t lock_res = lock_memory(fd, shmutex);
272 if (lock_res != STATUS_OK)
273 return lock_res;
274
275 // Unlock file descriptor on exit out of the scope
276 bool need_unlock = true;
277 lsp_finally {
278 if (need_unlock)
279 unlock_memory(fd, shmutex);
280 };
281
282 if (shmutex->init_flag != SHMUTEX_INIT_FLAG)
283 {
284 // Mutex is not initialized, initialize it
285 pthread_mutexattr_t attr;
286 if ((error = pthread_mutexattr_init(&attr)) != 0)
287 return STATUS_UNKNOWN_ERR;
288
289 if ((error = pthread_mutexattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)) != 0)
290 {
291 switch (error)
292 {
293 case EINVAL: return STATUS_INVALID_VALUE;
294 case ENOTSUP: return STATUS_NOT_IMPLEMENTED;
295 default: return STATUS_UNKNOWN_ERR;
296 }
297 }
298 if ((error = pthread_mutexattr_setrobust(&attr, PTHREAD_MUTEX_ROBUST)) != 0)
299 return STATUS_UNKNOWN_ERR;
300 if ((error = pthread_mutex_init(&shmutex->mutex, &attr)) != 0)
301 return STATUS_UNKNOWN_ERR;
302
303 // Mark the mutex being initialized
304 shmutex->init_flag = SHMUTEX_INIT_FLAG;
305 }
306
307 // Unlock memory
308 need_unlock = false;
309 lock_res = unlock_memory(fd, shmutex);
310 if (lock_res != STATUS_OK)
311 return lock_res;
312 }
313
314 // Now we have shared mutex and file descriptor, store them
315 hFD = fd;
316 hLock = release_ptr(shmutex);
317
318 fd = -1;
319
320 return STATUS_OK;
321 #else
322 // Open lock file
323 io::Path tmp;
324 status_t res = system::get_system_temporary_dir(&tmp);
325 if (res != STATUS_OK)
326 return res;
327
328 // Use separate directory to not to confuse with another applications' files
329 if ((res = tmp.append_child("shmutex")) != STATUS_OK)
330 return res;
331
332 if ((res = tmp.mkdir()) != STATUS_OK)
333 {
334 if (res != STATUS_ALREADY_EXISTS)
335 return res;
336 }
337
338 // Try to open or create file
339 if ((res = tmp.append(name)) != STATUS_OK)
340 return res;
341
342 int fd = ::open(tmp.as_native(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
343 if (fd < 0)
344 {
345 int code = errno;
346 status_t res = STATUS_IO_ERROR;
347
348 switch (code)
349 {
350 case EPERM: case EACCES: res = STATUS_PERMISSION_DENIED; break;
351 case EEXIST: res = STATUS_ALREADY_EXISTS; break;
352 case EINVAL: res = STATUS_INVALID_VALUE; break;
353 case EISDIR: res = STATUS_IS_DIRECTORY; break;
354 case ENAMETOOLONG: res = STATUS_OVERFLOW; break;
355 case ENOENT: res = STATUS_NOT_FOUND; break;
356 case ENOMEM: res = STATUS_NO_MEM; break;
357 case ENOTDIR: res = STATUS_NOT_DIRECTORY; break;
358 case EROFS: res = STATUS_READONLY; break;
359 default: break;
360 }
361
362 return res;
363 }
364 lsp_finally {
365 if (fd >= 0)
366 ::close(fd);
367 };
368
369 // Now we have shared mutex and file descriptor, store them
370 hFD = fd;
371 fd = -1;
372
373 return STATUS_OK;
374 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
375 }
376
377 status_t SharedMutex::close()
378 {
379 if (!is_opened())
380 return STATUS_OK;
381
382 status_t res = STATUS_OK;
383
384 #ifdef PLATFORM_WINDOWS
385 // Release lock if it is set
386 if (atomic_swap(&nOwner, INVALID_THREAD_ID) != INVALID_THREAD_ID)
387 {
388 if (!ReleaseMutex(hLock))
389 res = update_status(res, STATUS_IO_ERROR);
390 }
391
392 if (!CloseHandle(hLock))
393 res = update_status(res, STATUS_IO_ERROR);
394 hLock = NULL;
395 #elif defined(LSP_ROBUST_MUTEX_SUPPORTED)
396 // Release lock if it is set
397 if (atomic_swap(&nOwner, INVALID_THREAD_ID) != INVALID_THREAD_ID)
398 {
399 int error = pthread_mutex_unlock(&hLock->mutex);
400 if (error != 0)
401 res = update_status(res, STATUS_IO_ERROR);
402 }
403
404 // Unmap memory
405 munmap(hLock, sizeof(shared_mutex_t));
406 hLock = NULL;
407
408 // Close file descriptor
409 if (hFD >= 0)
410 {
411 ::close(hFD);
412 hFD = -1;
413 }
414 #else
415 // Release lock if it is set
416 if (atomic_swap(&nOwner, INVALID_THREAD_ID) != INVALID_THREAD_ID)
417 lock_descriptor(hFD, LOCK_UN);
418
419 // Close file descriptor
420 ::close(hFD);
421 hFD = -1;
422 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
423
424 return res;
425 }
426
427 status_t SharedMutex::lock()
428 {
429 if (!is_opened())
430 return STATUS_CLOSED;
431
432 // Check that we don't lock the mutex again
433 const thread_id_t tid = Thread::current_thread_id();
434 if (atomic_load(&nOwner) == tid)
435 return STATUS_LOCKED;
436
437 #if defined(PLATFORM_WINDOWS)
438 DWORD res = WaitForSingleObject(hLock, INFINITE);
439 switch (res)
440 {
441 case WAIT_OBJECT_0:
442 case WAIT_ABANDONED:
443 atomic_store(&nOwner, tid);
444 return STATUS_OK;
445 case WAIT_TIMEOUT:
446 return STATUS_TIMED_OUT;
447 case WAIT_FAILED:
448 return STATUS_UNKNOWN_ERR;
449 default:
450 break;
451 }
452
453 return STATUS_UNKNOWN_ERR;
454 #elif defined(LSP_ROBUST_MUTEX_SUPPORTED)
455 int error = pthread_mutex_lock(&hLock->mutex);
456 switch (error)
457 {
458 case 0: break;
459 case EDEADLK: return STATUS_BAD_STATE;
460 case EBUSY: return STATUS_LOCKED;
461 case EOWNERDEAD:
462 {
463 pthread_mutex_consistent(&hLock->mutex);
464 break;
465 }
466 default: return STATUS_UNKNOWN_ERR;
467 }
468
469 atomic_store(&nOwner, tid);
470
471 return STATUS_OK;
472 #else
473 status_t res = lock_descriptor(hFD, LOCK_EX);
474 if (res != STATUS_OK)
475 return res;
476
477 // Now we need to spin to ensure that our thread owns the lock
478 while (true)
479 {
480 if (atomic_cas(&nOwner, INVALID_THREAD_ID, tid))
481 return STATUS_OK;
482
483 // Wait for a while
484 ipc::Thread::sleep(1);
485 }
486
487 return res;
488 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
489 }
490
491 status_t SharedMutex::lock(system::time_millis_t delay)
492 {
493 if (!is_opened())
494 return STATUS_CLOSED;
495
496 // Check that we don't lock the mutex again
497 const thread_id_t tid = Thread::current_thread_id();
498 if (atomic_load(&nOwner) == tid)
499 return STATUS_LOCKED;
500
501 #ifdef PLATFORM_WINDOWS
502 DWORD res = WaitForSingleObject(hLock, delay);
503 switch (res)
504 {
505 case WAIT_OBJECT_0:
506 case WAIT_ABANDONED:
507 atomic_store(&nOwner, tid);
508 return STATUS_OK;
509 case WAIT_TIMEOUT:
510 return STATUS_TIMED_OUT;
511 case WAIT_FAILED:
512 return STATUS_UNKNOWN_ERR;
513 default:
514 break;
515 }
516
517 return STATUS_UNKNOWN_ERR;
518 #elif defined(LSP_ROBUST_MUTEX_SUPPORTED)
519 // sem_timedwait() is the same as sem_wait(), except that abs_timeout specifies a limit on the
520 // amount of time that the call should block if the decrement cannot be immediately performed.
521 // The abs_timeout argument points to a structure that specifies an absolute timeout in seconds
522 // and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC).
523 struct timespec timeout;
524 clock_gettime(CLOCK_REALTIME, &timeout);
525
526 timeout.tv_sec += delay / 1000;
527 timeout.tv_nsec += (delay % 1000) * 1000000;
528 if (timeout.tv_nsec >= 1000000000)
529 {
530 timeout.tv_sec += 1;
531 timeout.tv_nsec -= 1000000000;
532 }
533
534 int error = pthread_mutex_timedlock(&hLock->mutex, &timeout);
535 switch (error)
536 {
537 case 0: break;
538 case EDEADLK: return STATUS_BAD_STATE;
539 case EBUSY:
540 return STATUS_LOCKED;
541 case ETIMEDOUT: return STATUS_TIMED_OUT;
542 case EOWNERDEAD:
543 {
544 pthread_mutex_consistent(&hLock->mutex);
545 break;
546 }
547 default: return STATUS_UNKNOWN_ERR;
548 }
549
550 atomic_store(&nOwner, tid);
551
552 return STATUS_OK;
553 #else
554 // Since we can not lock file without using signals, we need to simulate the timed wait with a loop
555 const system::time_millis_t deadline = system::get_time_millis() + delay;
556 while (true)
557 {
558 status_t res = lock_descriptor(hFD, LOCK_EX | LOCK_NB);
559 if (res == STATUS_OK)
560 break;
561
562 // Check that we didn't reach deadline
563 const system::time_millis_t ctime = system::get_time_millis();
564 if (ctime >= deadline)
565 return STATUS_TIMED_OUT;
566
567 // Wait for a while
568 ipc::Thread::yield();
569 }
570
571 // Now we need to spin to ensure that our thread owns the lock
572 while (true)
573 {
574 if (atomic_cas(&nOwner, 0, tid))
575 return STATUS_OK;
576
577 // Check that we didn't reach deadline
578 const system::time_millis_t ctime = system::get_time_millis();
579 if (ctime >= deadline)
580 {
581 lock_descriptor(hFD, LOCK_UN);
582 return STATUS_TIMED_OUT;
583 }
584
585 // Wait for a while
586 ipc::Thread::sleep(1);
587 }
588 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
589 }
590
591 status_t SharedMutex::try_lock()
592 {
593 if (!is_opened())
594 return STATUS_CLOSED;
595
596 // Check that we don't lock the mutex again
597 const thread_id_t tid = Thread::current_thread_id();
598 if (atomic_load(&nOwner) == tid)
599 return STATUS_LOCKED;
600
601 #ifdef PLATFORM_WINDOWS
602 DWORD res = WaitForSingleObject(hLock, 0);
603 switch (res)
604 {
605 case WAIT_OBJECT_0:
606 case WAIT_ABANDONED:
607 atomic_store(&nOwner, tid);
608 return STATUS_OK;
609 case WAIT_TIMEOUT:
610 return STATUS_RETRY;
611 case WAIT_FAILED:
612 return STATUS_UNKNOWN_ERR;
613 default:
614 break;
615 }
616
617 return STATUS_UNKNOWN_ERR;
618 #elif defined(LSP_ROBUST_MUTEX_SUPPORTED)
619 int error = pthread_mutex_trylock(&hLock->mutex);
620 switch (error)
621 {
622 case 0: break;
623 case EDEADLK: return STATUS_BAD_STATE;
624 case EBUSY: return STATUS_RETRY;
625 case EOWNERDEAD:
626 {
627 pthread_mutex_consistent(&hLock->mutex);
628 break;
629 }
630 default: return STATUS_UNKNOWN_ERR;
631 }
632
633 atomic_store(&nOwner, tid);
634
635 return STATUS_OK;
636 #else
637 status_t res = lock_descriptor(hFD, LOCK_EX | LOCK_NB);
638 if (res != STATUS_OK)
639 return res;
640
641 // Now we need to lock the spin
642 if (atomic_cas(&nOwner, INVALID_THREAD_ID, tid))
643 return STATUS_OK;
644
645 // Unlock descriptor
646 lock_descriptor(hFD, LOCK_UN);
647 return STATUS_RETRY;
648 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
649 }
650
651 status_t SharedMutex::unlock()
652 {
653 if (!is_opened())
654 return STATUS_CLOSED;
655
656 // Check that we own the lock the mutex
657 const thread_id_t tid = Thread::current_thread_id();
658 if (atomic_load(&nOwner) != tid)
659 return STATUS_BAD_STATE;
660
661 #ifdef PLATFORM_WINDOWS
662 if (!ReleaseMutex(hLock))
663 return STATUS_UNKNOWN_ERR;
664 #elif defined(LSP_ROBUST_MUTEX_SUPPORTED)
665 int error = pthread_mutex_unlock(&hLock->mutex);
666 switch (error)
667 {
668 case 0: break;
669 case EDEADLK: return STATUS_BAD_STATE;
670 case EBUSY: return STATUS_RETRY;
671 case EPERM: return STATUS_PERMISSION_DENIED;
672 default: return STATUS_UNKNOWN_ERR;
673 }
674 #else
675 status_t res = lock_descriptor(hFD, LOCK_UN);
676 if (res != STATUS_OK)
677 return res;
678 #endif /* PLATFORM_WINDOWS, LSP_ROBUST_MUTEX_SUPPORTED */
679
680 atomic_store(&nOwner, INVALID_THREAD_ID);
681 return STATUS_OK;
682 }
683
684 } /* namespace ipc */
685 } /* namespace lsp */
686
687