LCOV - code coverage report
Current view: top level - src/ipc/libmultiprocess/include/mp - proxy.h (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 93.8 % 16 15
Test Date: 2026-11-25 06:45:13 Functions: 43.5 % 23 10
Branches: 21.8 % 78 17

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) The Bitcoin Core developers
       2                 :             : // Distributed under the MIT software license, see the accompanying
       3                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       4                 :             : 
       5                 :             : #ifndef MP_PROXY_H
       6                 :             : #define MP_PROXY_H
       7                 :             : 
       8                 :             : #include <mp/util.h>
       9                 :             : 
      10                 :             : #include <cassert>
      11                 :             : #include <functional>
      12                 :             : #include <list>
      13                 :             : #include <memory>
      14                 :             : #include <stddef.h>
      15                 :             : #include <tuple>
      16                 :             : #include <type_traits>
      17                 :             : #include <utility>
      18                 :             : #include <variant> // IWYU pragma: keep
      19                 :             : 
      20                 :             : namespace mp {
      21                 :             : class Connection;
      22                 :             : class EventLoop;
      23                 :             : //! Mapping from capnp interface type to proxy client implementation (specializations are generated by
      24                 :             : //! proxy-codegen.cpp).
      25                 :             : template <typename Interface> struct ProxyClient; // IWYU pragma: export
      26                 :             : //! Mapping from capnp interface type to proxy server implementation (specializations are generated by
      27                 :             : //! proxy-codegen.cpp).
      28                 :             : template <typename Interface> struct ProxyServer; // IWYU pragma: export
      29                 :             : //! Mapping from capnp method params type to method traits (specializations are generated by proxy-codegen.cpp).
      30                 :             : template <typename Params> struct ProxyMethod; // IWYU pragma: export
      31                 :             : //! Mapping from capnp struct type to struct traits (specializations are generated by proxy-codegen.cpp).
      32                 :             : template <typename Struct> struct ProxyStruct; // IWYU pragma: export
      33                 :             : //! Mapping from local c++ type to capnp type and traits (specializations are generated by proxy-codegen.cpp).
      34                 :             : template <typename Type> struct ProxyType; // IWYU pragma: export
      35                 :             : 
      36                 :             : using CleanupList = std::list<std::function<void()>>;
      37                 :             : using CleanupIt = typename CleanupList::iterator;
      38                 :             : 
      39                 :         110 : inline void CleanupRun(CleanupList& fns) {
      40         [ +  + ]:         191 :     while (!fns.empty()) {
      41                 :          81 :         auto fn = std::move(fns.front());
      42                 :          81 :         fns.pop_front();
      43         [ +  - ]:          81 :         fn();
      44                 :          81 :     }
      45                 :         110 : }
      46                 :             : 
      47                 :             : //! Event loop smart pointer automatically managing m_num_refs. Hold one
      48                 :             : //! reference to keep the loop running, once the last reference is released
      49                 :             : //! EventLoop::loop() will exit.
      50                 :             : //! If a lock pointer argument is passed, the specified lock will be used,
      51                 :             : //! otherwise EventLoop::m_mutex will be locked when needed.
      52                 :             : class EventLoopRef
      53                 :             : {
      54                 :             : public:
      55                 :             :     explicit EventLoopRef(EventLoop& loop, Lock* lock = nullptr);
      56                 :             :     EventLoopRef(EventLoopRef&& other) noexcept : m_loop(other.m_loop) { other.m_loop = nullptr; }
      57                 :             :     EventLoopRef(const EventLoopRef&) = delete;
      58                 :             :     EventLoopRef& operator=(const EventLoopRef&) = delete;
      59                 :             :     EventLoopRef& operator=(EventLoopRef&&) = delete;
      60         [ +  - ]:         339 :     ~EventLoopRef() { reset(); }
      61         [ -  + ]:        1194 :     EventLoop& operator*() const { assert(m_loop); return *m_loop; }
      62         [ -  + ]:        1016 :     EventLoop* operator->() const { assert(m_loop); return m_loop; }
      63                 :             :     void reset(bool relock=false);
      64                 :             : 
      65                 :             :     EventLoop* m_loop{nullptr};
      66                 :             :     Lock* m_lock{nullptr};
      67                 :             : };
      68                 :             : 
      69                 :             : //! Context data associated with proxy client and server classes.
      70                 :             : struct ProxyContext
      71                 :             : {
      72                 :             :     Connection* connection;
      73                 :             :     EventLoopRef loop;
      74                 :             :     CleanupList cleanup_fns;
      75                 :             : 
      76                 :             :     ProxyContext(Connection* connection);
      77                 :             : };
      78                 :             : 
      79                 :             : //! Base class for generated ProxyClient classes that implement a C++ interface
      80                 :             : //! and forward calls to a capnp interface.
      81                 :             : template <typename Interface_, typename Impl_>
      82                 :             : class ProxyClientBase : public Impl_
      83                 :             : {
      84                 :             : public:
      85                 :             :     using Interface = Interface_;
      86                 :             :     using Impl = Impl_;
      87                 :             :     using Sub = ProxyClient<Interface>;
      88                 :             :     using Super = ProxyClientBase<Interface, Impl>;
      89                 :             : 
      90                 :             :     //! Construct libmultiprocess client object wrapping Cap'n Proto client
      91                 :             :     //! object with a reference to the associated mp::Connection object.
      92                 :             :     //!
      93                 :             :     //! The destroy_connection option determines whether destroying this client
      94                 :             :     //! object closes the connection. It is set to true for the
      95                 :             :     //! ProxyClient<InitInterface> object returned by ConnectStream, to let IPC
      96                 :             :     //! clients close the connection by freeing the object. It is false for
      97                 :             :     //! other client objects so they can be destroyed without affecting the
      98                 :             :     //! connection.
      99                 :             :     ProxyClientBase(typename Interface::Client client, Connection* connection, bool destroy_connection);
     100                 :             :     ~ProxyClientBase() noexcept;
     101                 :             : 
     102                 :             :     // construct/destroy methods called during client construction/destruction
     103                 :             :     // that can optionally be defined in capnp interfaces to invoke code on the
     104                 :             :     // server when proxy client objects are created and destroyed.
     105                 :             :     //
     106                 :             :     // The construct() method is not generally very useful, but can be used to
     107                 :             :     // run custom code on the server automatically when a ProxyClient client is
     108                 :             :     // constructed. The only current use is adding a construct method to Init
     109                 :             :     // interfaces that is called automatically on construction, so client and
     110                 :             :     // server exchange ThreadMap references and set Connection::m_thread_map
     111                 :             :     // values as soon as the Init client is created.
     112                 :             :     //
     113                 :             :     //     construct @0 (threadMap: Proxy.ThreadMap) -> (threadMap: Proxy.ThreadMap);
     114                 :             :     //
     115                 :             :     // But construct() is not necessary for this, thread maps could be passed
     116                 :             :     // through a normal method that is just called explicitly rather than
     117                 :             :     // implicitly.
     118                 :             :     //
     119                 :             :     // The destroy() method is more generally useful than construct(), because
     120                 :             :     // it ensures that the server object will be destroyed synchronously before
     121                 :             :     // the client destructor returns, instead of asynchronously at some
     122                 :             :     // unpredictable time after the client object is already destroyed and
     123                 :             :     // client code has moved on. If the destroy method accepts a Context
     124                 :             :     // parameter like:
     125                 :             :     //
     126                 :             :     //     destroy @0 (context: Proxy.Context) -> ();
     127                 :             :     //
     128                 :             :     // then it will also ensure that the destructor runs on the same thread the
     129                 :             :     // client used to make other RPC calls, instead of running on the server
     130                 :             :     // EventLoop thread and possibly blocking it.
     131 [ +  + ][ -  +  :          69 :     static void construct(Super&) {}
             -  -  -  + ]
     132                 :             :     static void destroy(Super&) {}
     133                 :             : 
     134                 :             :     typename Interface::Client m_client;
     135                 :             :     ProxyContext m_context;
     136                 :             : };
     137                 :             : 
     138                 :             : //! Customizable (through template specialization) base class used in generated ProxyClient implementations from
     139                 :             : //! proxy-codegen.cpp.
     140                 :             : template <typename Interface, typename Impl>
     141                 :          25 : class ProxyClientCustom : public ProxyClientBase<Interface, Impl>
     142                 :             : {
     143   [ +  -  +  - ]:          25 :     using ProxyClientBase<Interface, Impl>::ProxyClientBase;
           [ +  -  +  -  
          -  -  -  -  -  
           -  -  - ][ -  
          -  -  -  -  -  
          -  -  +  -  +  
           - ][ #  #  #  
          #  #  #  #  #  
          #  #  #  #  #  
                      # ]
     144                 :             : };
     145                 :             : 
     146                 :             : //! Base class for generated ProxyServer classes that implement capnp server
     147                 :             : //! methods and forward calls to a wrapped c++ implementation class.
     148                 :             : template <typename Interface_, typename Impl_>
     149                 :             : struct ProxyServerBase : public virtual Interface_::Server
     150                 :             : {
     151                 :             : public:
     152                 :             :     using Interface = Interface_;
     153                 :             :     using Impl = Impl_;
     154                 :             : 
     155                 :             :     ProxyServerBase(std::shared_ptr<Impl> impl, Connection& connection);
     156                 :             :     virtual ~ProxyServerBase();
     157                 :             :     void invokeDestroy();
     158                 :             :     using Interface_::Server::thisCap;
     159                 :             : 
     160                 :             :     /**
     161                 :             :      * Implementation pointer that may or may not be owned and deleted when this
     162                 :             :      * capnp server goes out of scope. It is owned for servers created to wrap
     163                 :             :      * unique_ptr<Impl> method arguments, but unowned for servers created to
     164                 :             :      * wrap Impl& method arguments.
     165                 :             :      *
     166                 :             :      * In the case of Impl& arguments, custom code is required on other side of
     167                 :             :      * the connection to delete the capnp client & server objects since native
     168                 :             :      * code on that side of the connection will just be taking a plain reference
     169                 :             :      * rather than a pointer, so won't be able to do its own cleanup. Right now
     170                 :             :      * this is implemented with addCloseHook callbacks to delete clients at
     171                 :             :      * appropriate times depending on semantics of the particular method being
     172                 :             :      * wrapped. */
     173                 :             :     std::shared_ptr<Impl> m_impl;
     174                 :             :     ProxyContext m_context;
     175                 :             : };
     176                 :             : 
     177                 :             : //! Customizable (through template specialization) base class which ProxyServer
     178                 :             : //! classes produced by generated code will inherit from. The default
     179                 :             : //! specialization of this class just inherits from ProxyServerBase, but custom
     180                 :             : //! specializations can be defined to control ProxyServer behavior.
     181                 :             : //!
     182                 :             : //! Specifically, it can be useful to specialize this class to add additional
     183                 :             : //! state to ProxyServer classes, for example to cache state between IPC calls.
     184                 :             : //! If this is done, however, care should be taken to ensure that the extra
     185                 :             : //! state can be destroyed without blocking, because ProxyServer destructors are
     186                 :             : //! called from the EventLoop thread, and if they block, it could deadlock the
     187                 :             : //! program. One way to do avoid blocking is to clean up the state by pushing
     188                 :             : //! cleanup callbacks to the m_context.cleanup_fns list, which run after the server
     189                 :             : //! m_impl object is destroyed on the same thread destroying it (which will
     190                 :             : //! either be an IPC worker thread if the ProxyServer is being explicitly
     191                 :             : //! destroyed by a client calling a destroy() method with a Context argument and
     192                 :             : //! Context.thread value set, or the temporary EventLoop::m_async_thread used to
     193                 :             : //! run destructors without blocking the event loop when no-longer used server
     194                 :             : //! objects are garbage collected by Cap'n Proto.) Alternately, if cleanup needs
     195                 :             : //! to run before m_impl is destroyed, the specialization can override
     196                 :             : //! invokeDestroy and destructor methods to do that.
     197                 :             : template <typename Interface, typename Impl>
     198                 :             : struct ProxyServerCustom : public ProxyServerBase<Interface, Impl>
     199                 :             : {
     200                 :             :     using ProxyServerBase<Interface, Impl>::ProxyServerBase;
     201                 :             : };
     202                 :             : 
     203                 :             : //! Function traits class used to get method parameter and result types, used in
     204                 :             : //! generated ProxyClient and ProxyServer classes produced by gen.cpp to get C++
     205                 :             : //! method type information. The generated code accesses these traits via
     206                 :             : //! intermediate ProxyClientMethodTraits and ProxyServerMethodTraits classes,
     207                 :             : //! which it is possible to specialize to change the way method arguments and
     208                 :             : //! return values are handled.
     209                 :             : //!
     210                 :             : //! Fields of the trait class are:
     211                 :             : //!
     212                 :             : //! Params   - TypeList of C++ ClassName::methodName parameter types
     213                 :             : //! Result   - Return type of ClassName::method
     214                 :             : //! Param<N> - helper to access individual parameter types by index number.
     215                 :             : //! Fwd<N>   - helper to forward arguments by index number.
     216                 :             : //! Fields   - helper alias that appends Result type to the Params typelist if
     217                 :             : //!            it not void.
     218                 :             : template <class Fn>
     219                 :             : struct FunctionTraits;
     220                 :             : 
     221                 :             : //! Specialization of above extracting result and params types assuming the
     222                 :             : //! template argument is a pointer-to-method type,
     223                 :             : //! decltype(&ClassName::methodName)
     224                 :             : template <class _Class, class _Result, class... _Params>
     225                 :             : struct FunctionTraits<_Result (_Class::*const)(_Params...)>
     226                 :             : {
     227                 :             :     using Params = TypeList<_Params...>;
     228                 :             :     using Result = _Result;
     229                 :             :     template <size_t N>
     230                 :             :     using Param = typename std::tuple_element<N, std::tuple<_Params...>>::type;
     231                 :             :     using Fields =
     232                 :             :         std::conditional_t<std::is_same_v<void, Result>, Params, TypeList<_Params..., _Result>>;
     233                 :             : 
     234                 :             :     //! Enable perfect forwarding for clientInvoke calls. If parameter is a
     235                 :             :     //! value type or rvalue reference type, pass it as an rvalue-reference to
     236                 :             :     //! MakeClientParam and BuildField calls so it can be moved from, and if it
     237                 :             :     //! is an lvalue reference, pass it an lvalue reference so it won't be moved
     238                 :             :     //! from. This method does the same thing as std::forward except it takes a
     239                 :             :     //! parameter number instead of a type as a template argument, so generated
     240                 :             :     //! code calling this can be less repetitive and verbose.
     241                 :             :     template <size_t N>
     242                 :             :     static decltype(auto) Fwd(Param<N>& arg) { return static_cast<Param<N>&&>(arg); }
     243                 :             : };
     244                 :             : 
     245                 :             : //! Traits class for a proxy method, providing the same
     246                 :             : //! Params/Result/Param/Fields described in the FunctionTraits class above, plus
     247                 :             : //! an additional invoke() method that calls the C++ method which is being
     248                 :             : //! proxied, forwarding any arguments.
     249                 :             : //!
     250                 :             : //! The template argument should be the InterfaceName::MethodNameParams class
     251                 :             : //! (generated by Cap'n Proto) associated with the method.
     252                 :             : //!
     253                 :             : //! Note: The class definition here is just the fallback definition used when
     254                 :             : //! the other specialization below doesn't match. The fallback is only used for
     255                 :             : //! capnp methods which do not have corresponding C++ methods, which in practice
     256                 :             : //! is just the two special construct() and destroy() methods described in \ref
     257                 :             : //! ProxyClientBase. These methods don't have any C++ parameters or return
     258                 :             : //! types, so the trait information below reflects that.
     259                 :             : template <typename MethodParams, typename Enable = void>
     260                 :             : struct ProxyMethodTraits
     261                 :             : {
     262                 :             :     using Params = TypeList<>;
     263                 :             :     using Result = void;
     264                 :             :     using Fields = Params;
     265                 :             : 
     266                 :             :     template <typename ServerContext>
     267                 :             :     static void invoke(ServerContext&)
     268                 :             :     {
     269                 :             :     }
     270                 :             : };
     271                 :             : 
     272                 :             : //! Specialization of above for proxy methods that have a
     273                 :             : //! ProxyMethod<InterfaceName::MethodNameParams>::impl pointer-to-method
     274                 :             : //! constant defined by generated code. This includes all functions defined in
     275                 :             : //! the capnp interface except any construct() or destroy() methods, that are
     276                 :             : //! assumed not to correspond to real member functions in the C++ class, and
     277                 :             : //! will use the fallback traits definition above. The generated code this
     278                 :             : //! specialization relies on looks like:
     279                 :             : //!
     280                 :             : //! struct ProxyMethod<InterfaceName::MethodNameParams>
     281                 :             : //! {
     282                 :             : //!     static constexpr auto impl = &ClassName::methodName;
     283                 :             : //! };
     284                 :             : template <typename MethodParams>
     285                 :             : struct ProxyMethodTraits<MethodParams, Require<decltype(ProxyMethod<MethodParams>::impl)>>
     286                 :             :     : public FunctionTraits<decltype(ProxyMethod<MethodParams>::impl)>
     287                 :             : {
     288                 :             :     template <typename ServerContext, typename... Args>
     289                 :          31 :     static decltype(auto) invoke(ServerContext& server_context, Args&&... args)
     290                 :             :     {
     291   [ #  #  #  # ]:          31 :         return (server_context.proxy_server.m_impl.get()->*ProxyMethod<MethodParams>::impl)(std::forward<Args>(args)...);
         [ +  - ][ #  #  
          #  #  #  #  #  
                #  #  # ]
     292                 :             :     }
     293                 :             : };
     294                 :             : 
     295                 :             : //! Customizable (through template specialization) traits class used in generated ProxyClient implementations from
     296                 :             : //! proxy-codegen.cpp.
     297                 :             : template <typename MethodParams>
     298                 :             : struct ProxyClientMethodTraits : public ProxyMethodTraits<MethodParams>
     299                 :             : {
     300                 :             : };
     301                 :             : 
     302                 :             : //! Customizable (through template specialization) traits class used in generated ProxyServer implementations from
     303                 :             : //! proxy-codegen.cpp.
     304                 :             : template <typename MethodParams>
     305                 :             : struct ProxyServerMethodTraits : public ProxyMethodTraits<MethodParams>
     306                 :             : {
     307                 :             : };
     308                 :             : 
     309                 :             : static constexpr int FIELD_IN = 1;        //!< See Accessor::in.
     310                 :             : static constexpr int FIELD_OUT = 2;       //!< See Accessor::out.
     311                 :             : static constexpr int FIELD_OPTIONAL = 4;  //!< See Accessor::optional.
     312                 :             : static constexpr int FIELD_REQUESTED = 8; //!< See Accessor::requested.
     313                 :             : static constexpr int FIELD_BOXED = 16;    //!< See Accessor::boxed.
     314                 :             : 
     315                 :             : //! Accessor type holding flags that determine how to access a message field.
     316                 :             : template <typename Field, int flags>
     317                 :             : struct Accessor : public Field
     318                 :             : {
     319                 :             :     //! Field is present from the Cap'n Proto Params struct (client -> server).
     320                 :             :     static constexpr bool in = (flags & FIELD_IN) != 0;
     321                 :             :     //! Field is present from the Cap'n Proto Results struct (server -> client).
     322                 :             :     static constexpr bool out = (flags & FIELD_OUT) != 0;
     323                 :             :     //! Field has a companion has{Name} boolean field in the Cap'n Proto struct.
     324                 :             :     //! This is used to represent optional primitive values (e.g. C++
     325                 :             :     //! std::optional<int>) because Cap'n Proto doesn't allow primitive fields to
     326                 :             :     //! be unset.
     327                 :             :     static constexpr bool optional = (flags & FIELD_OPTIONAL) != 0;
     328                 :             :     //! Results field has a companion want{Name} boolean field in the Params
     329                 :             :     //! struct. Used for optional output parameters (e.g. C++ int*) and set to
     330                 :             :     //! true if the caller passed a non-null pointer and wants the result.
     331                 :             :     static constexpr bool requested = (flags & FIELD_REQUESTED) != 0;
     332                 :             :     //! Field is a Cap'n Proto pointer type (struct, list, text, data,
     333                 :             :     //! interface) as opposed to a primitive type (bool, int, float, enum).
     334                 :             :     static constexpr bool boxed = (flags & FIELD_BOXED) != 0;
     335                 :             : };
     336                 :             : 
     337                 :             : //! Wrapper around std::function for passing std::function objects between client and servers.
     338                 :             : template <typename Fn>
     339                 :             : class ProxyCallback;
     340                 :             : 
     341                 :             : //! Specialization of above to separate Result and Arg types.
     342                 :             : template <typename Result, typename... Args>
     343         [ #  # ]:           0 : class ProxyCallback<std::function<Result(Args...)>>
     344                 :             : {
     345                 :             : public:
     346                 :             :     virtual Result call(Args&&... args) = 0;
     347                 :             : };
     348                 :             : 
     349                 :             : } // namespace mp
     350                 :             : 
     351                 :             : #endif // MP_PROXY_H
        

Generated by: LCOV version 2.0-1