mirror of
https://github.com/bitcoin/bitcoin.git
synced 2026-01-19 14:53:43 +01:00
a4f929696490 Merge bitcoin-core/libmultiprocess#224: doc: fix typos f4344ae87da0 Merge bitcoin-core/libmultiprocess#222: test, ci: Fix threadsanitizer errors in mptest 1434642b3804 doc: fix typos 73d22ba2e930 test: Fix tsan race in thread busy test b74e1bba014d ci: Use tsan-instrumented cap'n proto in sanitizers job c332774409ad test: Fix failing exception check in new thread busy test ca3c05d56709 test: Use KJ_LOG instead of std::cout for logging 7eb1da120ab6 ci: Use tsan-instrumented libcxx in sanitizers job ec86e4336e98 Merge bitcoin-core/libmultiprocess#220: Add log levels and advertise them to users via logging callback 515ce93ad349 Logging: Pass LogData struct to logging callback 213574ccc43d Logging: reclassify remaining log messages e4de0412b430 Logging: Break out expensive log messages and classify them as Trace 408874a78fdc Logging: Use new logging macros 67b092d835cd Logging: Disable logging if messsage level is less than the requested level d0a1ba7ebf21 Logging: add log levels to mirror Core's 463a8296d188 Logging: Disable moving or copying Logger 83a2e10c0b03 Logging: Add an EventLoop constructor to allow for user-specified log options 58cf47a7fc8c Merge bitcoin-core/libmultiprocess#221: test default PassField impl handles output parameters db03a663f514 Merge bitcoin-core/libmultiprocess#214: Fix crash on simultaneous IPC calls using the same thread afcc40b0f1e8 Merge bitcoin-core/libmultiprocess#213: util+doc: Clearer errors when attempting to run examples + polished docs 6db669628387 test In|Out parameter 29cf2ada75ea test default PassField impl handles output parameters 1238170f68e8 test: simultaneous IPC calls using same thread eb069ab75d83 Fix crash on simultaneous IPC calls using the same thread ec03a9639ab5 doc: Precision and typos 2b4348193551 doc: Where possible, remove links to ryanofsky/bitcoin/ 286fe469c9c9 util: Add helpful error message when failing to execute file 47d79db8a552 Merge bitcoin-core/libmultiprocess#201: bug: fix mptest hang, ProxyClient<Thread> deadlock in disconnect handler f15ae9c9b9fb Merge bitcoin-core/libmultiprocess#211: Add .gitignore 4a269b21b8c8 bug: fix ProxyClient<Thread> deadlock if disconnected as IPC call is returning 85df96482c49 Use try_emplace in SetThread instead of threads.find ca9b380ea91a Use std::optional in ConnThreads to allow shortening locks 9b0799113557 doc: describe ThreadContext struct and synchronization requirements d60db601ed9b proxy-io.h: add Waiter::m_mutex thread safety annotations 4e365b019a9f ci: Use -Wthread-safety not -Wthread-safety-analysis 15d7bafbb001 Add .gitignore fe1cd8c76131 Merge bitcoin-core/libmultiprocess#208: ci: Test minimum cmake version in olddeps job b713a0b7bfbc Merge bitcoin-core/libmultiprocess#207: ci: output CMake version in CI script 0f580397c913 ci: Test minimum cmake version in olddeps job d603dcc0eef0 ci: output CMake version in CI script git-subtree-dir: src/ipc/libmultiprocess git-subtree-split: a4f92969649018ca70f949a09148bccfeaecd99a
244 lines
8.0 KiB
C++
244 lines
8.0 KiB
C++
// Copyright (c) The Bitcoin Core developers
|
|
// Distributed under the MIT software license, see the accompanying
|
|
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
|
|
|
|
#ifndef MP_UTIL_H
|
|
#define MP_UTIL_H
|
|
|
|
#include <capnp/schema.h>
|
|
#include <cassert>
|
|
#include <cstddef>
|
|
#include <cstring>
|
|
#include <functional>
|
|
#include <kj/string-tree.h>
|
|
#include <mutex>
|
|
#include <string>
|
|
#include <tuple>
|
|
#include <type_traits>
|
|
#include <utility>
|
|
#include <variant>
|
|
#include <vector>
|
|
|
|
namespace mp {
|
|
|
|
//! Generic utility functions used by capnp code.
|
|
|
|
//! Type holding a list of types.
|
|
//!
|
|
//! Example:
|
|
//! TypeList<int, bool, void>
|
|
template <typename... Types>
|
|
struct TypeList
|
|
{
|
|
static constexpr size_t size = sizeof...(Types);
|
|
};
|
|
|
|
//! Construct a template class value by deducing template arguments from the
|
|
//! types of constructor arguments, so they don't need to be specified manually.
|
|
//!
|
|
//! Uses of this can go away with class template deduction in C++17
|
|
//! (https://en.cppreference.com/w/cpp/language/class_template_argument_deduction)
|
|
//!
|
|
//! Example:
|
|
//! Make<std::pair>(5, true) // Constructs std::pair<int, bool>(5, true);
|
|
template <template <typename...> class Class, typename... Types, typename... Args>
|
|
Class<Types..., std::remove_reference_t<Args>...> Make(Args&&... args)
|
|
{
|
|
return Class<Types..., std::remove_reference_t<Args>...>{std::forward<Args>(args)...};
|
|
}
|
|
|
|
//! Type helper splitting a TypeList into two halves at position index.
|
|
//!
|
|
//! Example:
|
|
//! is_same<TypeList<int, double>, Split<2, TypeList<int, double, float, bool>>::First>
|
|
//! is_same<TypeList<float, bool>, Split<2, TypeList<int, double, float, bool>>::Second>
|
|
template <std::size_t index, typename List, typename _First = TypeList<>, bool done = index == 0>
|
|
struct Split;
|
|
|
|
//! Specialization of above (base case)
|
|
template <typename _Second, typename _First>
|
|
struct Split<0, _Second, _First, true>
|
|
{
|
|
using First = _First;
|
|
using Second = _Second;
|
|
};
|
|
|
|
//! Specialization of above (recursive case)
|
|
template <std::size_t index, typename Type, typename... _Second, typename... _First>
|
|
struct Split<index, TypeList<Type, _Second...>, TypeList<_First...>, false>
|
|
{
|
|
using _Next = Split<index - 1, TypeList<_Second...>, TypeList<_First..., Type>>;
|
|
using First = typename _Next::First;
|
|
using Second = typename _Next::Second;
|
|
};
|
|
|
|
//! Type helper giving return type of a callable type.
|
|
template <typename Callable>
|
|
using ResultOf = decltype(std::declval<Callable>()());
|
|
|
|
//! Substitutue for std::remove_cvref_t
|
|
template <typename T>
|
|
using RemoveCvRef = std::remove_cv_t<std::remove_reference_t<T>>;
|
|
|
|
//! Type helper abbreviating std::decay.
|
|
template <typename T>
|
|
using Decay = std::decay_t<T>;
|
|
|
|
//! SFINAE helper, see using Require below.
|
|
template <typename SfinaeExpr, typename Result_>
|
|
struct _Require
|
|
{
|
|
using Result = Result_;
|
|
};
|
|
|
|
//! SFINAE helper, basically the same as to C++17's void_t, but allowing types other than void to be returned.
|
|
template <typename SfinaeExpr, typename Result = void>
|
|
using Require = typename _Require<SfinaeExpr, Result>::Result;
|
|
|
|
//! Function parameter type for prioritizing overloaded function calls that
|
|
//! would otherwise be ambiguous.
|
|
//!
|
|
//! Example:
|
|
//! auto foo(Priority<1>) -> std::enable_if<>;
|
|
//! auto foo(Priority<0>) -> void;
|
|
//!
|
|
//! foo(Priority<1>()); // Calls higher priority overload if enabled.
|
|
template <int priority>
|
|
struct Priority : Priority<priority - 1>
|
|
{
|
|
};
|
|
|
|
//! Specialization of above (base case)
|
|
template <>
|
|
struct Priority<0>
|
|
{
|
|
};
|
|
|
|
//! Return capnp type name with filename prefix removed.
|
|
template <typename T>
|
|
const char* TypeName()
|
|
{
|
|
// DisplayName string looks like
|
|
// "interfaces/capnp/common.capnp:ChainNotifications.resendWalletTransactions$Results"
|
|
// This discards the part of the string before the first ':' character.
|
|
// Another alternative would be to use the displayNamePrefixLength field,
|
|
// but this discards everything before the last '.' character, throwing away
|
|
// the object name, which is useful.
|
|
const char* display_name = ::capnp::Schema::from<T>().getProto().getDisplayName().cStr();
|
|
const char* short_name = strchr(display_name, ':');
|
|
return short_name ? short_name + 1 : display_name;
|
|
}
|
|
|
|
//! Convenient wrapper around std::variant<T*, T>
|
|
template <typename T>
|
|
struct PtrOrValue {
|
|
std::variant<T*, T> data;
|
|
|
|
template <typename... Args>
|
|
PtrOrValue(T* ptr, Args&&... args) : data(ptr ? ptr : std::variant<T*, T>{std::in_place_type<T>, std::forward<Args>(args)...}) {}
|
|
|
|
T& operator*() { return data.index() ? std::get<T>(data) : *std::get<T*>(data); }
|
|
T* operator->() { return &**this; }
|
|
T& operator*() const { return data.index() ? std::get<T>(data) : *std::get<T*>(data); }
|
|
T* operator->() const { return &**this; }
|
|
};
|
|
|
|
// Annotated mutex and lock class (https://clang.llvm.org/docs/ThreadSafetyAnalysis.html)
|
|
#if defined(__clang__) && (!defined(SWIG))
|
|
#define MP_TSA(x) __attribute__((x))
|
|
#else
|
|
#define MP_TSA(x) // no-op
|
|
#endif
|
|
|
|
#define MP_CAPABILITY(x) MP_TSA(capability(x))
|
|
#define MP_SCOPED_CAPABILITY MP_TSA(scoped_lockable)
|
|
#define MP_REQUIRES(x) MP_TSA(requires_capability(x))
|
|
#define MP_ACQUIRE(...) MP_TSA(acquire_capability(__VA_ARGS__))
|
|
#define MP_RELEASE(...) MP_TSA(release_capability(__VA_ARGS__))
|
|
#define MP_ASSERT_CAPABILITY(x) MP_TSA(assert_capability(x))
|
|
#define MP_GUARDED_BY(x) MP_TSA(guarded_by(x))
|
|
#define MP_NO_TSA MP_TSA(no_thread_safety_analysis)
|
|
|
|
class MP_CAPABILITY("mutex") Mutex {
|
|
public:
|
|
void lock() MP_ACQUIRE() { m_mutex.lock(); }
|
|
void unlock() MP_RELEASE() { m_mutex.unlock(); }
|
|
|
|
std::mutex m_mutex;
|
|
};
|
|
|
|
class MP_SCOPED_CAPABILITY Lock {
|
|
public:
|
|
explicit Lock(Mutex& m) MP_ACQUIRE(m) : m_lock(m.m_mutex) {}
|
|
~Lock() MP_RELEASE() = default;
|
|
void unlock() MP_RELEASE() { m_lock.unlock(); }
|
|
void lock() MP_ACQUIRE() { m_lock.lock(); }
|
|
void assert_locked(Mutex& mutex) MP_ASSERT_CAPABILITY() MP_ASSERT_CAPABILITY(mutex)
|
|
{
|
|
assert(m_lock.mutex() == &mutex.m_mutex);
|
|
assert(m_lock);
|
|
}
|
|
|
|
std::unique_lock<std::mutex> m_lock;
|
|
};
|
|
|
|
template<typename T>
|
|
struct GuardedRef
|
|
{
|
|
Mutex& mutex;
|
|
T& ref MP_GUARDED_BY(mutex);
|
|
};
|
|
|
|
// CTAD for Clang 16: GuardedRef{mutex, x} -> GuardedRef<decltype(x)>
|
|
template <class U>
|
|
GuardedRef(Mutex&, U&) -> GuardedRef<U>;
|
|
|
|
//! Analog to std::lock_guard that unlocks instead of locks.
|
|
template <typename Lock>
|
|
struct UnlockGuard
|
|
{
|
|
UnlockGuard(Lock& lock) : m_lock(lock) { m_lock.unlock(); }
|
|
~UnlockGuard() { m_lock.lock(); }
|
|
Lock& m_lock;
|
|
};
|
|
|
|
template <typename Lock, typename Callback>
|
|
void Unlock(Lock& lock, Callback&& callback)
|
|
{
|
|
const UnlockGuard<Lock> unlock(lock);
|
|
callback();
|
|
}
|
|
|
|
//! Format current thread name as "{exe_name}-{$pid}/{thread_name}-{$tid}".
|
|
std::string ThreadName(const char* exe_name);
|
|
|
|
//! Escape binary string for use in log so it doesn't trigger unicode decode
|
|
//! errors in python unit tests.
|
|
std::string LogEscape(const kj::StringTree& string, size_t max_size);
|
|
|
|
//! Callback type used by SpawnProcess below.
|
|
using FdToArgsFn = std::function<std::vector<std::string>(int fd)>;
|
|
|
|
//! Spawn a new process that communicates with the current process over a socket
|
|
//! pair. Returns pid through an output argument, and file descriptor for the
|
|
//! local side of the socket. Invokes fd_to_args callback with the remote file
|
|
//! descriptor number which returns the command line arguments that should be
|
|
//! used to execute the process, and which should have the remote file
|
|
//! descriptor embedded in whatever format the child process expects.
|
|
int SpawnProcess(int& pid, FdToArgsFn&& fd_to_args);
|
|
|
|
//! Call execvp with vector args.
|
|
void ExecProcess(const std::vector<std::string>& args);
|
|
|
|
//! Wait for a process to exit and return its exit code.
|
|
int WaitProcess(int pid);
|
|
|
|
inline char* CharCast(char* c) { return c; }
|
|
inline char* CharCast(unsigned char* c) { return (char*)c; }
|
|
inline const char* CharCast(const char* c) { return c; }
|
|
inline const char* CharCast(const unsigned char* c) { return (const char*)c; }
|
|
|
|
} // namespace mp
|
|
|
|
#endif // MP_UTIL_H
|