375 Commits

Author SHA1 Message Date
mutouyun
ce0773b3e6 refactor: improve name handling in shm_posix.cpp to match semaphore pattern
Check if name already starts with '/' before adding prefix, consistent
with the pattern used in semaphore_impl.h. This avoids duplicate prefix
when users provide names in the correct format.
2025-12-06 16:06:51 +08:00
木头云
2593213d9c Fix FreeBSD shm_unlink failure by adding '/' prefix in remove()
Problem: Tests fail on the second run on FreeBSD with ShmTest.RemoveByName failing.
After the first test run completes, subsequent runs fail because shared memory
objects are not properly removed.

Root cause: FreeBSD's shm_unlink() is stricter than Linux about POSIX compliance.
The remove(char const * name) function was calling shm_unlink() without the '/'
prefix, while acquire() was using '/'+name format. This inconsistency caused:
- Linux: Silently tolerates both /name and name formats
- FreeBSD: Strictly requires /name format, shm_unlink("name") fails

When shm_unlink() fails to remove the shared memory object:
1. First test run creates /remove_by_name_test_1
2. Test calls shm::remove("remove_by_name_test_1")
3. shm_unlink("remove_by_name_test_1") fails on FreeBSD (missing '/')
4. Shared memory object remains in the system
5. Second test run tries to reuse the same name -> conflict -> test fails

Solution:
1. Fix remove(char const * name) to prepend '/' to the name for consistency
   with acquire() function, ensuring POSIX compliance
2. Add error checking for all shm_unlink() calls to log failures with errno

This ensures proper cleanup on FreeBSD and maintains compatibility with Linux.

Changes:
- Modified remove(char const * name) to use '/'+name format
- Added error logging for all three shm_unlink() calls
- Now consistent with POSIX requirement: shared memory names must be /somename

Tested on FreeBSD 15: Multiple consecutive test runs now pass without failures.
2025-12-06 07:20:33 +00:00
木头云
37f16cea47 Fix mutex unlock timing to avoid interfering with other references
Problem: The previous fix unconditionally called pthread_mutex_unlock() at the
beginning of close(), which could interfere with other threads/processes that
still had valid references to the mutex. This caused test failures on FreeBSD
when running tests multiple times (ShmTest.RemoveByName would fail on the second run).

Root cause: Calling unlock() too early could affect the mutex state for other
references that are still using it, leading to unexpected behavior.

Solution: Move pthread_mutex_unlock() to only be called when we're about to
destroy the mutex (i.e., when we're the last reference: shm_->ref() <= 1 &&
self_ref <= 1). This ensures:
1. We don't interfere with other threads/processes using the mutex
2. We still unlock before destroying to avoid FreeBSD robust list issues
3. The unlock happens at the correct time - right before pthread_mutex_destroy()

This is the correct approach because:
- Only the last reference holder should clean up the mutex
- Unlocking should be paired with destroying for the final cleanup
- Other references should not be affected by one reference closing

Fixes the second-run test failure on FreeBSD while maintaining the segfault fix.
2025-12-06 06:53:29 +00:00
木头云
5517f48681 Fix FreeBSD segfault by unlocking mutex before destruction
Root cause: FreeBSD's robust mutex implementation (libthr) maintains a per-thread
robust list of mutexes. The error 'rb error 14' (EFAULT - Bad address) indicates
that the robust list contained a dangling pointer to a destroyed mutex.

When a mutex object is destroyed (via close() or clear()), if the mutex is still
in the current thread's robust list, FreeBSD's libthr may try to access it later
and encounter an invalid pointer, causing a segmentation fault.

This happened in MutexTest.TryLockExceptionSafety because:
1. The test called try_lock() which successfully acquired the lock
2. The test ended without calling unlock()
3. The mutex destructor called close()
4. close() called pthread_mutex_destroy() on a mutex that was:
   - Still locked by the current thread, OR
   - Still in the thread's robust list

Solution:
Call pthread_mutex_unlock() before pthread_mutex_destroy() in both close()
and clear() methods. This ensures:
1. The mutex is unlocked if we hold the lock
2. The mutex is removed from the thread's robust list
3. Subsequent pthread_mutex_destroy() is safe

We ignore errors from pthread_mutex_unlock() because:
- If we don't hold the lock, EPERM is expected and harmless
- If the mutex is already unlocked, this is a no-op
- Even if there's an error, we still want to proceed with cleanup

This fix is platform-agnostic and should not affect Linux/QNX behavior,
as both also use pthread robust mutexes with similar semantics.

Fixes the segfault in MutexTest.TryLockExceptionSafety on FreeBSD 15.
2025-12-06 06:35:02 +00:00
木头云
47fa303455 Fix segfault in EOWNERDEAD handling - remove incorrect ref count manipulation
Root cause: The previous code incorrectly called shm_->sub_ref() when handling
EOWNERDEAD, which could cause the shared memory to be freed prematurely while
the mutex pointer was still in use, leading to segmentation fault.

Fix: Remove the shm_->sub_ref() call. When EOWNERDEAD is returned, it means
we have successfully acquired the lock. We only need to call pthread_mutex_consistent()
to make the mutex usable again, then return success. The shared memory reference
count should not be modified in this path.

This fixes the segfault in MutexTest.TryLockExceptionSafety on FreeBSD 15.
2025-12-06 06:21:38 +00:00
木头云
a82e3faf63 Fix C++17 compilation error on FreeBSD GCC 13.3
Remove custom deduction guides for std::unique_ptr in C++17 mode.

Issue: FreeBSD GCC 13.3 correctly rejects adding deduction guides
to namespace std, which violates C++ standard [namespace.std]:
"The behavior of a C++ program is undefined if it adds declarations
or definitions to namespace std or to a namespace within namespace std."

Root cause: The code attempted to add custom deduction guides for
std::unique_ptr in namespace std when compiling in C++17 mode.
This is not allowed by the C++ standard.

Solution: Remove the custom deduction guides for C++17 and later,
as the C++17 standard library already provides deduction guides
for std::unique_ptr (added in C++17 via P0433R2).

The custom deduction guide wrappers in the else branch (for C++14
and earlier) are kept as they provide helper functions, not actual
deduction guides in namespace std.

Tested-on: FreeBSD 15 with GCC 13.3
Fixes: Compilation error 'deduction guide must be declared in the
same scope as template std::unique_ptr'
2025-12-06 06:13:58 +00:00
木头云
543672b39d Fix FreeBSD-specific issues in POSIX implementation
This commit addresses the test failures reported in issue #156
on FreeBSD platform.

1. Fix POSIX semaphore naming for FreeBSD compatibility
   - FreeBSD requires semaphore names to start with "/"
   - Add "_sem" suffix to avoid namespace conflicts with shm
   - Store semaphore name separately for proper cleanup
   - This fixes all 24 semaphore test failures

2. Fix robust mutex EOWNERDEAD handling
   - When pthread_mutex_lock returns EOWNERDEAD, the lock is
     already acquired by the calling thread
   - After calling pthread_mutex_consistent(), we should return
     success immediately, not unlock and retry
   - Previous behavior caused issues with FreeBSD's libthr robust
     mutex list management, leading to fatal errors
   - This fixes the random crashes in MutexTest

Technical details:
- EOWNERDEAD indicates the previous lock owner died while holding
  the lock, but the current thread has successfully acquired it
- pthread_mutex_consistent() restores the mutex to a consistent state
- The Linux implementation worked differently, but the new approach
  is more correct according to POSIX semantics and works on both
  Linux and FreeBSD

Fixes #156
2025-12-06 06:05:53 +00:00
木头云
006a46e09f
Merge pull request #158 from mutouyun/feature/issue-156
Add FreeBSD platform support (fixes #156)
2025-12-03 16:49:36 +08:00
木头云
c31ef988c1 fix(shm): remove redundant self-assignment in shm_win.cpp
- Remove useless 'ii->size_ = ii->size_;' statement at line 140
- The user-requested size is already set in acquire() function
- Simplify else branch to just a comment for clarity
- No functional change, just code cleanup
2025-11-30 11:06:04 +00:00
木头云
7726742157 feat(shm): implement reference counting for Windows shared memory
Problem:
- Reference counting tests fail on Windows (ReleaseMemory, ReferenceCount,
  SubtractReference, HandleRef, HandleSubRef)
- get_ref() and sub_ref() were stub implementations returning 0/doing nothing
- CreateFileMapping HANDLE lacks built-in reference counting mechanism

Solution:
- Implement reference counting using std::atomic<std::int32_t> stored at
  the end of shared memory (same strategy as POSIX version)
- Add calc_size() helper to allocate extra space for atomic counter
- Add acc_of() helper to access the atomic counter at the end of memory
- Modify acquire() to allocate calc_size(size) instead of size
- Modify get_mem() to initialize counter to 1 on first mapping
- Modify release() to decrement counter and return ref count before decrement
- Implement get_ref() to return current reference count
- Implement sub_ref() to atomically decrement reference count
- Convert file from Windows (CRLF) to Unix (LF) line endings for consistency

Key Implementation Details:
1. Reference counter stored at end of shared memory (aligned to info_t)
2. First get_mem() call: fetch_add(1) initializes counter to 1
3. release() returns ref count before decrement (for semantics compatibility)
4. Memory layout: [user data][padding][atomic<int32_t> counter]
5. Uses memory_order_acquire/release/acq_rel for proper synchronization

This makes Windows implementation match POSIX behavior and ensures all
reference counting tests pass on Windows platform.
2025-11-30 10:55:24 +00:00
木头云
b9dd75ccd9 fix(platform): rename linux/posix namespaces to avoid predefined macro conflict
Problem:
- 'linux' is a predefined macro on Linux platforms
- Using 'namespace linux' causes compilation errors
- Preprocessor replaces 'linux' with '1' before compilation

Solution:
- Rename 'namespace linux' to 'namespace linux_'
- Rename 'namespace posix' to 'namespace posix_'
- Update all 7 call sites accordingly:
  - linux/condition.h:  linux_::detail::make_timespec()
  - linux/mutex.h:      linux_::detail::make_timespec() (2 places)
  - posix/condition.h:  posix_::detail::make_timespec()
  - posix/mutex.h:      posix_::detail::make_timespec() (2 places)
  - posix/semaphore_impl.h: posix_::detail::make_timespec()

This prevents preprocessor macro expansion issues while maintaining
the ODR violation fix from the previous commit.
2025-11-30 07:07:14 +00:00
木头云
e66bd880e9 fix(platform): resolve ODR violation in make_timespec/calc_wait_time inline functions
Problem:
- Both linux/get_wait_time.h and posix/get_wait_time.h define inline functions
  make_timespec() and calc_wait_time() in namespace ipc::detail
- On Linux, semaphore uses posix implementation, but may include both headers
- This causes ODR (One Definition Rule) violation - undefined behavior
- Different inline function definitions with same name violates C++ standard
- Manifested as test failures in SemaphoreTest::WaitTimeout

Solution:
- Add platform-specific namespace layer between ipc and detail:
  - linux/get_wait_time.h: ipc::linux::detail::make_timespec()
  - posix/get_wait_time.h: ipc::posix::detail::make_timespec()
- Update all call sites to use fully qualified names:
  - linux/condition.h: linux::detail::make_timespec()
  - linux/mutex.h: linux::detail::make_timespec() (2 places)
  - posix/condition.h: posix::detail::make_timespec()
  - posix/mutex.h: posix::detail::make_timespec() (2 places)
  - posix/semaphore_impl.h: posix::detail::make_timespec()

This ensures each platform's implementation is uniquely named, preventing
ODR violations and ensuring correct function resolution at compile time.
2025-11-30 07:00:32 +00:00
木头云
91e4489a55 refactor(buffer): rename 'additional' parameter to 'mem_to_free' for clarity
Header changes (include/libipc/buffer.h):
- Rename: additional → mem_to_free (better semantic name)
- Add documentation comments explaining the parameter's purpose
- Clarifies that mem_to_free is passed to destructor instead of p
- Use case: when data pointer is offset into a larger allocation

Implementation changes (src/libipc/buffer.cpp):
- Update parameter name in constructor implementation
- No logic changes, just naming improvement

Test changes (test/test_buffer.cpp):
- Fix TEST_F(BufferTest, ConstructorWithMemToFree)
- Previous test caused crash: passed stack variable address to destructor
- New test correctly demonstrates the parameter's purpose:
  * Allocate 100-byte block
  * Use offset portion (bytes 25-75) as data
  * Destructor receives original block pointer for proper cleanup
- Prevents double-free and invalid free errors

Semantic explanation:
  buffer(data_ptr, size, destructor, mem_to_free)

  On destruction:
    destructor(mem_to_free ? mem_to_free : data_ptr, size)

  This allows:
    char* block = new char[100];
    char* data = block + 25;
    buffer buf(data, 50, my_free, block);  // Frees 'block', not 'data'
2025-11-30 05:09:56 +00:00
木头云
de76cf80d5 fix(buffer): remove const from char constructor to prevent UB
- Change: explicit buffer(char const & c) → explicit buffer(char & c)
- Remove dangerous const_cast in implementation
- Before: buffer(const_cast<char*>(&c), 1) [UB if c is truly const]
- After: buffer(&c, 1) [safe, requires non-const char]
- Prevents undefined behavior from modifying compile-time constants
- Constructor now correctly requires mutable char reference
- Aligns with buffer's mutable data semantics

The previous implementation with const_cast could lead to:
- Modifying string literals (undefined behavior)
- Modifying const variables (undefined behavior)
- Runtime crashes or data corruption

Example of prevented misuse:
  buffer buf('X');           // Now: compile error ✓
  char c = 'X';
  buffer buf(c);             // Now: works correctly ✓
  const char cc = 'Y';
  buffer buf(cc);            // Now: compile error ✓
2025-11-30 05:00:57 +00:00
木头云
0d53a3cdb1 Add FreeBSD platform support (fixes #156)
- Add IPC_OS_FREEBSD_ platform detection macro
- Enable FreeBSD to use POSIX pthread implementation (shared with QNX)
- Update all conditional compilation directives to include FreeBSD
- Update README to reflect FreeBSD platform support

FreeBSD uses the existing POSIX implementation which supports:
- Process-shared mutexes (PTHREAD_PROCESS_SHARED)
- Robust mutexes (PTHREAD_MUTEX_ROBUST)
- Timed lock operations
- POSIX shared memory

This is a minimal change that reuses the mature POSIX implementation
already proven by QNX platform support.
2025-11-29 10:55:54 +00:00
Craig Carnell
72c4b5abc4 mingw: use lower case windows.h 2025-11-17 09:56:49 +00:00
mutouyun
a1cdc9a711 In non-broadcast mode, connection tags are only used for counting. 2025-05-10 15:14:39 +08:00
yongke liu
87b1fa4abc Fixed issue 107 and 123, receiver check connection when pop msg failed, and call reconnect function when the connection check result is false 2025-05-09 17:10:07 +08:00
johnwongx
a6c7c8542f 修复连接槽满判断错误 2025-04-23 13:15:39 +08:00
Aengus.Jiang
06d4aec320 posix shm open 失败时如果文件不存在打印log #2 修改逻辑错误 2025-03-07 12:33:42 +08:00
Aengus.Jiang
d69093462a open的时候不存在共享内存,则返回false,没有必要报错 2025-03-07 11:36:57 +08:00
mutouyun
2673453e66 Try to fix permission issues under linux 2024-12-01 21:06:06 +08:00
mutouyun
84bb801b6e Try to fix a communication problem caused by different permissions under linux 2024-12-01 19:53:40 +08:00
mutouyun
5e5b347636 Complete the implementation of the clean interface and add unit tests 2024-12-01 19:06:50 +08:00
mutouyun
28fdf17279 Added cleanup interfaces for ipc chan 2024-12-01 17:49:34 +08:00
mutouyun
17dcde92bf Added clear_storage for quieue 2024-12-01 17:49:34 +08:00
mutouyun
ab90437e44 Added a cleanup interface for waiter. 2024-12-01 17:49:34 +08:00
mutouyun
e1f377d7f6 Added a cleanup interface for the synchronization facilities 2024-11-17 17:39:03 +08:00
mutouyun
29678f1d41 Added a cleanup interface for queue 2024-11-17 17:36:09 +08:00
mutouyun
5071fb5db6 Added a cleanup interface for shared memory handles 2024-11-17 17:35:29 +08:00
mutouyun
805490605e refactor: improve emplace construction for shm_data in mutex.h 2024-05-25 17:33:33 +08:00
abathur puppe
025311d5f6 fix emplace construction for shm_data. Previous required copy constructor 2024-05-25 17:32:31 +08:00
winsoft666
035d76d5aa Update CMakeLists.txt 2023-12-10 21:07:18 +08:00
winsoft666
144b2db9ca Add PACKAGE_VERSION 2023-12-10 21:07:18 +08:00
winsoft666
c4280efd5f Add cpp-ipc-targets 2023-12-10 21:07:18 +08:00
mutouyun
ac54be7083 reconnect cannot reconnect when you are out of authority 2023-10-28 16:44:16 +08:00
mutouyun
a3b0a968f8 回滚多余的修改 2023-10-28 16:44:16 +08:00
mutouyun
fafa5e85f7 Fixed memory access exception in multithreading. 2023-10-28 16:44:16 +08:00
mutouyun
c74f78ea08 统一字符串有效性判断 2023-10-28 16:44:16 +08:00
mutouyun
cf72d0293a The global sender could not be obtained due to different prefixes. 2023-10-28 16:44:16 +08:00
mutouyun
fab3f6fffe Add a user interface with a custom name prefix. 2023-10-28 16:44:16 +08:00
mutouyun
16b138d6af Check illegal parameter. 2023-10-28 16:44:16 +08:00
mutouyun
ec14e81ffd Identify the user group and add the appropriate prefix to the names. 2023-10-28 16:44:16 +08:00
mutouyun
22a253a72f Supplement similar demo under linux. 2023-10-28 16:44:16 +08:00
mutouyun
e229f78a15 Windows services can communicate with common processes. 2023-10-28 16:44:16 +08:00
mutouyun
7981a1cbc1 disable warning C4858 2023-10-28 16:44:16 +08:00
木头云
6111722534
fix: the receiver of channel will hang after disconnect 2023-05-14 14:11:54 +08:00
mutouyun
2a2b626210 补充遗漏的初始化 2023-02-25 16:30:11 +08:00
mutouyun
162011d4b4 修正全局变量初始化时序问题导致的内存访问异常 2023-02-25 16:30:11 +08:00
木头云
f25668c4c2
Update CMakeLists.txt 2022-01-08 23:23:45 +08:00