Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 8 additions & 13 deletions src/windows/ipc_sync_wrappers.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
* Copyright Andrey Semashev 2016.
* Copyright David Christle 2026.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
Expand Down Expand Up @@ -130,7 +131,8 @@ void interprocess_event::open(const wchar_t* name)
}

boost::atomic< interprocess_semaphore::is_semaphore_zero_count_t > interprocess_semaphore::is_semaphore_zero_count(&interprocess_semaphore::is_semaphore_zero_count_init);
interprocess_semaphore::nt_query_semaphore_t interprocess_semaphore::nt_query_semaphore = NULL;
// The dispatcher publishes this pointer; initialization can still run concurrently.
boost::atomic< interprocess_semaphore::nt_query_semaphore_t > interprocess_semaphore::nt_query_semaphore(NULL);

void interprocess_semaphore::create_or_open(const wchar_t* name, permissions const& perms)
{
Expand Down Expand Up @@ -193,7 +195,7 @@ bool interprocess_semaphore::is_semaphore_zero_count_init(boost::winapi::HANDLE_
nt_query_semaphore_t ntqs = (nt_query_semaphore_t)boost::winapi::get_proc_address(ntdll, "NtQuerySemaphore");
if (ntqs)
{
nt_query_semaphore = ntqs;
nt_query_semaphore.store(ntqs, boost::memory_order_relaxed);
impl = &interprocess_semaphore::is_semaphore_zero_count_nt_query_semaphore;
}
}
Expand All @@ -206,7 +208,7 @@ bool interprocess_semaphore::is_semaphore_zero_count_init(boost::winapi::HANDLE_
bool interprocess_semaphore::is_semaphore_zero_count_nt_query_semaphore(boost::winapi::HANDLE_ h)
{
semaphore_basic_information info = {};
NTSTATUS_ err = nt_query_semaphore
NTSTATUS_ err = nt_query_semaphore.load(boost::memory_order_relaxed)
(
h,
0u, // SemaphoreBasicInformation
Expand Down Expand Up @@ -372,6 +374,7 @@ bool interprocess_condition_variable::wait(interprocess_mutex::optional_unlock&
m_shared_state->m_waiters = waiters + 1;
const uint32_t generation = m_shared_state->m_generation;

semaphore_waiter waiter(*m_current_semaphore);
boost::winapi::HANDLE_ handles[2u] = { m_current_semaphore->m_semaphore.get_handle(), abort_handle };

interprocess_mutex* const mutex = lock.disengage();
Expand All @@ -383,15 +386,7 @@ bool interprocess_condition_variable::wait(interprocess_mutex::optional_unlock&
{
const boost::winapi::DWORD_ err = boost::winapi::GetLastError();

// Although highly unrealistic, it is possible that it took so long for the current thread to enter WaitForMultipleObjects that
// another thread has managed to destroy the semaphore. This can happen if the semaphore remains in a non-zero state
// for too long, which means that another process died while being blocked on the semaphore, and the semaphore was signalled,
// and the non-zero state timeout has passed. In this case the most logical behavior for the wait function is to return as
// if because of a wakeup.
if (err == ERROR_INVALID_HANDLE)
retval = boost::winapi::WAIT_OBJECT_0_;
else
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to block on an interprocess semaphore object", (err));
BOOST_LOG_THROW_DESCR_PARAMS(boost::log::system_error, "Failed to block on an interprocess semaphore object", (err));
}

// Have to unconditionally lock the mutex here
Expand Down Expand Up @@ -457,7 +452,7 @@ interprocess_condition_variable::semaphore_info* interprocess_condition_variable
mark_unused(info);
return &info;
}
else if (it->check_non_zero_timeout(now))
else if (it->m_local_waiters.load(boost::memory_order_acquire) == 0u && it->check_non_zero_timeout(now))
{
// The semaphore is non-zero for too long. A blocked process must have crashed. Close it.
m_semaphore_info_set.erase(m_semaphore_info_set.iterator_to(*it));
Expand Down
30 changes: 28 additions & 2 deletions src/windows/ipc_sync_wrappers.hpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/*
* Copyright Andrey Semashev 2016.
* Copyright David Christle 2026.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
Expand Down Expand Up @@ -139,7 +140,7 @@ class interprocess_semaphore
auto_handle m_sem;

static boost::atomic< is_semaphore_zero_count_t > is_semaphore_zero_count;
static nt_query_semaphore_t nt_query_semaphore;
static boost::atomic< nt_query_semaphore_t > nt_query_semaphore;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this is needed. The variable is used when is_semaphore_zero_count is is_semaphore_zero_count_nt_query_semaphore. It is set by is_semaphore_zero_count_init before the store to is_semaphore_zero_count with release semantics and loaded by is_semaphore_zero_count_nt_query_semaphore, which is called through the pointer loaded from is_semaphore_zero_count with acquire semantics. Concurrent stores to it in is_semaphore_zero_count_init are not an issue since the same value is stored.


public:
void create_or_open(const wchar_t* name, permissions const& perms = permissions());
Expand Down Expand Up @@ -392,14 +393,20 @@ class interprocess_condition_variable

//! The semaphore
interprocess_semaphore m_semaphore;
//! Number of local waiters that may still use the semaphore handle
boost::atomic< uint32_t > m_local_waiters;
//! Timestamp of the moment when the semaphore was checked for zero count and it was not zero. In milliseconds since epoch.
tick_count_clock::time_point m_last_check_for_zero;
//! The flag indicates that the semaphore has been checked for zero count and it was not zero
bool m_checked_for_zero;
//! The semaphore id
const uint32_t m_id;

explicit semaphore_info(uint32_t id) BOOST_NOEXCEPT : m_last_check_for_zero(0u), m_id(id)
explicit semaphore_info(uint32_t id) BOOST_NOEXCEPT :
m_local_waiters(0u),
m_last_check_for_zero(0u),
m_checked_for_zero(false),
m_id(id)
{
}

Expand All @@ -420,6 +427,25 @@ class interprocess_condition_variable
BOOST_DELETED_FUNCTION(semaphore_info& operator=(semaphore_info const&))
};

struct semaphore_waiter
{
explicit semaphore_waiter(semaphore_info& info) BOOST_NOEXCEPT : m_info(info)
{
m_info.m_local_waiters.fetch_add(1u, boost::memory_order_relaxed);
}

~semaphore_waiter() BOOST_NOEXCEPT
{
m_info.m_local_waiters.fetch_sub(1u, boost::memory_order_release);
}

BOOST_DELETED_FUNCTION(semaphore_waiter(semaphore_waiter const&))
BOOST_DELETED_FUNCTION(semaphore_waiter& operator=(semaphore_waiter const&))

private:
semaphore_info& m_info;
};

typedef boost::intrusive::list<
semaphore_info,
boost::intrusive::base_hook< semaphore_info_list_hook_t >,
Expand Down
9 changes: 8 additions & 1 deletion test/Jamfile.v2
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,14 @@ rule test_all
}
for file in [ glob run/*.cpp ]
{
all_rules += [ run $(file) ] ;
if [ path.basename $(file) ] = "util_ipc_windows_sync.cpp"
{
all_rules += [ run $(file) : : : <include>../src ] ;
}
else
{
all_rules += [ run $(file) ] ;
}
Comment on lines +97 to +104

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should not be needed. The test already checks if the target is Windows.

}

if ! [ os.environ BOOST_LOG_TEST_WITHOUT_EXAMPLES ]
Expand Down
225 changes: 225 additions & 0 deletions test/run/util_ipc_windows_sync.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
/*
* Copyright David Christle 2026.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*/

#include <boost/log/detail/config.hpp>

#if defined(BOOST_WINDOWS) && !defined(BOOST_LOG_WITHOUT_IPC)

#define BOOST_TEST_MODULE util_ipc_windows_sync
#include <boost/test/unit_test.hpp>
#include <windows.h>
#include <functional>
#include <string>
#include "windows/ipc_sync_wrappers.hpp"

namespace {

boost::winapi::ULONGLONG_ current_tick = 1u;
boost::winapi::HANDLE_ tracked_handle = NULL;
bool tracked_handle_closed = false;
bool retained_wait_in_progress = false;
bool fail_next_wait = false;
std::function< void(boost::winapi::HANDLE_) > before_wait;
std::function< void() > after_wait;

} // namespace

namespace boost {
namespace winapi {

ULONGLONG_ test_GetTickCount64()
{
return current_tick;
}

DWORD_ test_GetTickCount()
{
return static_cast< DWORD_ >(current_tick);
}

BOOL_ test_CloseHandle(HANDLE_ handle)
{
if (handle == tracked_handle)
tracked_handle_closed = true;
return CloseHandle(handle);
}

DWORD_ test_WaitForMultipleObjects(DWORD_ count, const HANDLE_* handles, BOOL_ all, DWORD_ timeout)
{
std::function< void(HANDLE_) > before;
before.swap(before_wait);
std::function< void() > after;
after.swap(after_wait);
if (before)
before(handles[0]);

if (fail_next_wait)
{
fail_next_wait = false;
SetLastError(ERROR_ACCESS_DENIED);
return WAIT_FAILED_;
}

// A closed handle may already name another object; never wait on it in the failing test.
if (before && retained_wait_in_progress && handles[0] == tracked_handle && tracked_handle_closed)
return WAIT_OBJECT_0_;

// A lost notification should fail the test instead of blocking the test executable.
const DWORD_ bounded_timeout = timeout < 5000u ? timeout : 5000u;
const DWORD_ result = WaitForMultipleObjects(count, handles, all, bounded_timeout);
BOOST_REQUIRE_MESSAGE(result != WAIT_TIMEOUT_, "Timed out waiting for an IPC test semaphore");
if (after)
after();
return result;
}

} // namespace winapi

BOOST_LOG_OPEN_NAMESPACE
namespace aux {
extern const char test_hex_char_table[2][16] = {
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'},
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}
};
} // namespace aux
BOOST_LOG_CLOSE_NAMESPACE
} // namespace boost

// Run the implementation with controlled wait scheduling and elapsed time.
#undef BOOST_LOG_WINDOWS_IPC_SYNC_WRAPPERS_HPP_INCLUDED_
#undef BOOST_LOG_WINDOWS_AUTO_HANDLE_HPP_INCLUDED_
#define interprocess_event test_interprocess_event
#define interprocess_semaphore test_interprocess_semaphore
#define interprocess_mutex test_interprocess_mutex
#define interprocess_condition_variable test_interprocess_condition_variable
#define tick_count_clock test_tick_count_clock
#define auto_handle test_auto_handle
#define g_hex_char_table test_hex_char_table
#define GetTickCount64 test_GetTickCount64
#define GetTickCount test_GetTickCount
#define CloseHandle test_CloseHandle
#define WaitForMultipleObjects test_WaitForMultipleObjects
#include "../../src/windows/ipc_sync_wrappers.cpp"
#undef WaitForMultipleObjects
#undef CloseHandle
#undef GetTickCount
#undef GetTickCount64
#undef g_hex_char_table
#undef auto_handle
#undef tick_count_clock
#undef interprocess_condition_variable
#undef interprocess_mutex
#undef interprocess_semaphore
#undef interprocess_event
Comment on lines +93 to +117

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, but I don't find this acceptable. The test must verify the component as it is compiled in the library, with no source modification or relying on implementation details. If this is not possible (even sometimes, if the problem is not deterministic) then that feature is untestable and no test is acceptable.


namespace ipc_aux = boost::log::ipc::aux;

struct condition_variable_fixture
{
ipc_aux::test_interprocess_mutex::shared_state mutex_state;
ipc_aux::test_interprocess_condition_variable::shared_state condition_state;
ipc_aux::test_interprocess_mutex mutex;
ipc_aux::test_interprocess_condition_variable condition;
ipc_aux::test_interprocess_event abort_event;
ipc_aux::test_interprocess_event continue_event;

condition_variable_fixture()
{
static unsigned int sequence = 0u;
const std::wstring name = L"Local\\boost_log_ipc_sync_" +
std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(++sequence);
mutex.create((name + L"_mutex").c_str(), &mutex_state);
condition.init(name.c_str(), &condition_state);
abort_event.create(NULL, true);
abort_event.set();
continue_event.create(NULL, true);
current_tick = 1u;
tracked_handle = NULL;
tracked_handle_closed = false;
retained_wait_in_progress = false;
fail_next_wait = false;
}

~condition_variable_fixture()
{
tracked_handle = NULL;
retained_wait_in_progress = false;
before_wait = std::function< void(boost::winapi::HANDLE_) >();
after_wait = std::function< void() >();
}

bool wait(boost::winapi::HANDLE_ abort_handle)
{
mutex.lock();
ipc_aux::test_interprocess_mutex::optional_unlock lock(mutex);
return condition.wait(lock, abort_handle);
}

void notify()
{
mutex.lock();
ipc_aux::test_interprocess_mutex::auto_unlock lock(mutex);
condition.notify_all();
}

void abandon_signalled_semaphore()
{
// Notification after cancellation leaves an unused semaphore credit.
after_wait = [this]() { notify(); };
BOOST_CHECK(!wait(abort_event.get_handle()));
}

void retire_stale_semaphores()
{
abandon_signalled_semaphore();
current_tick += 3000u;
abandon_signalled_semaphore();
}
};

BOOST_FIXTURE_TEST_CASE(retain_semaphore_until_wait_returns, condition_variable_fixture)
{
before_wait = [this](boost::winapi::HANDLE_ handle)
{
tracked_handle = handle;
retained_wait_in_progress = true;
notify();
// The original waiter is paused after unlocking and before the kernel wait.
retire_stale_semaphores();
};

BOOST_CHECK(wait(continue_event.get_handle()));
retained_wait_in_progress = false;
BOOST_CHECK(!tracked_handle_closed);
}

BOOST_FIXTURE_TEST_CASE(release_semaphore_after_cancelled_wait, condition_variable_fixture)
{
before_wait = [](boost::winapi::HANDLE_ handle) { tracked_handle = handle; };
abandon_signalled_semaphore();
retire_stale_semaphores();
BOOST_CHECK(tracked_handle_closed);
}

BOOST_FIXTURE_TEST_CASE(release_semaphore_after_failed_wait, condition_variable_fixture)
{
before_wait = [](boost::winapi::HANDLE_ handle) { tracked_handle = handle; };
fail_next_wait = true;
BOOST_CHECK_THROW(wait(continue_event.get_handle()), boost::log::system_error);
notify();
retire_stale_semaphores();
BOOST_CHECK(tracked_handle_closed);
}

#else

int main()
{
return 0;
}

#endif
Loading