9 using proc_t = uint32_t;
10 using status_t = int32_t;
12 struct request_header {
13 request_header(int x=0, proc_t p=0, unsigned c=0, unsigned s=0, int xi=0) :
14 xid(x), proc(p), clt_nonce(c), srv_nonce(s), xid_rep(xi) {}
17 unsigned int clt_nonce;
18 unsigned int srv_nonce;
23 reply_header(int x=0, int r=0): xid(x), ret(r) {}
28 template<class T> inline T hton(T t);
30 constexpr union { uint32_t i; uint8_t is_little_endian; } endianness{1};
32 template<> inline uint8_t hton(uint8_t t) { return t; }
33 template<> inline int8_t hton(int8_t t) { return t; }
34 template<> inline uint16_t hton(uint16_t t) { return htons(t); }
35 template<> inline int16_t hton(int16_t t) { return (int16_t)htons((uint16_t)t); }
36 template<> inline uint32_t hton(uint32_t t) { return htonl(t); }
37 template<> inline int32_t hton(int32_t t) { return (int32_t)htonl((uint32_t)t); }
38 template<> inline uint64_t hton(uint64_t t) {
39 if (!endianness.is_little_endian)
41 return (uint64_t)htonl((uint32_t)(t >> 32)) | ((uint64_t)htonl((uint32_t)t) << 32);
43 template<> inline int64_t hton(int64_t t) { return (int64_t)hton((uint64_t)t); }
44 template<> inline request_header hton(request_header h) { return {hton(h.xid), hton(h.proc), hton(h.clt_nonce), hton(h.srv_nonce), hton(h.xid_rep)}; }
45 template<> inline reply_header hton(reply_header h) { return {hton(h.xid), hton(h.ret)}; }
47 template <class T> inline T ntoh(T t) { return hton(t); }
51 //size of initial buffer allocation
52 #define DEFAULT_RPC_SZ 1024
53 #define RPC_HEADER_SZ (max(sizeof(request_header), sizeof(reply_header)) + sizeof(rpc_sz_t))
55 struct pass { template <typename... Args> inline pass(Args&&...) {} };
59 char *buf_; // Base of the raw bytes buffer (dynamically readjusted)
60 size_t capacity_; // Capacity of the buffer
61 size_t index_; // Read/write head position
63 inline void reserve(size_t n) {
64 if((index_+n) > capacity_){
65 capacity_ += max(capacity_, n);
66 VERIFY (buf_ != NULL);
67 buf_ = (char *)realloc(buf_, capacity_);
72 template <typename... Args>
73 marshall(const Args&... args) {
74 buf_ = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
76 capacity_ = DEFAULT_RPC_SZ;
77 index_ = RPC_HEADER_SZ;
78 (void)pass{(*this << args)...};
86 size_t size() { return index_;}
87 char *cstr() { return buf_;}
88 const char *cstr() const { return buf_;}
90 void rawbyte(uint8_t x) {
92 buf_[index_++] = (int8_t)x;
95 void rawbytes(const char *p, size_t n) {
97 memcpy(buf_+index_, p, n);
101 // Return the current content (excluding header) as a string
102 string get_content() {
103 return string(buf_+RPC_HEADER_SZ,index_-RPC_HEADER_SZ);
106 // Return the current content (excluding header) as a string
108 return get_content();
111 void pack_req_header(const request_header &h);
112 void pack_reply_header(const reply_header &h);
114 void take_buf(char **b, size_t *s) {
123 marshall& operator<<(marshall &, bool);
124 marshall& operator<<(marshall &, uint32_t);
125 marshall& operator<<(marshall &, int32_t);
126 marshall& operator<<(marshall &, uint8_t);
127 marshall& operator<<(marshall &, int8_t);
128 marshall& operator<<(marshall &, uint16_t);
129 marshall& operator<<(marshall &, int16_t);
130 marshall& operator<<(marshall &, uint64_t);
131 marshall& operator<<(marshall &, const string &);
133 template <class A> typename enable_if<is_iterable<A>::value, marshall>::type &
134 operator<<(marshall &m, const A &x) {
135 m << (unsigned int) x.size();
136 for (const auto &a : x)
141 template <class A, class B> marshall &
142 operator<<(marshall &m, const pair<A,B> &d) {
143 return m << d.first << d.second;
147 using enum_type_t = typename enable_if<is_enum<E>::value, typename underlying_type<E>::type>::type;
148 template<typename E> constexpr inline enum_type_t<E> from_enum(E e) noexcept { return (enum_type_t<E>)e; }
149 template<typename E> constexpr inline E to_enum(enum_type_t<E> value) noexcept { return (E)value; }
151 template <class E> typename enable_if<is_enum<E>::value, marshall>::type &
152 operator<<(marshall &m, E e) {
153 return m << from_enum(e);
158 unmarshall& operator>>(unmarshall &, bool &);
159 unmarshall& operator>>(unmarshall &, uint8_t &);
160 unmarshall& operator>>(unmarshall &, int8_t &);
161 unmarshall& operator>>(unmarshall &, uint16_t &);
162 unmarshall& operator>>(unmarshall &, int16_t &);
163 unmarshall& operator>>(unmarshall &, uint32_t &);
164 unmarshall& operator>>(unmarshall &, int32_t &);
165 unmarshall& operator>>(unmarshall &, size_t &);
166 unmarshall& operator>>(unmarshall &, uint64_t &);
167 unmarshall& operator>>(unmarshall &, int64_t &);
168 unmarshall& operator>>(unmarshall &, string &);
169 template <class E> typename enable_if<is_enum<E>::value, unmarshall>::type &
170 operator>>(unmarshall &u, E &e);
179 inline bool ensure(size_t n);
181 unmarshall(): buf_(NULL),sz_(0),index_(0),ok_(false) {}
182 unmarshall(char *b, size_t sz): buf_(b),sz_(sz),index_(),ok_(true) {}
183 unmarshall(const string &s) : buf_(NULL),sz_(0),index_(0),ok_(false)
185 //take the content which does not exclude a RPC header from a string
189 if (buf_) free(buf_);
192 //take contents from another unmarshall object
193 void take_in(unmarshall &another);
195 //take the content which does not exclude a RPC header from a string
196 void take_content(const string &s) {
197 sz_ = s.size()+RPC_HEADER_SZ;
198 buf_ = (char *)realloc(buf_,sz_);
200 index_ = RPC_HEADER_SZ;
201 memcpy(buf_+index_, s.data(), s.size());
205 bool ok() const { return ok_; }
206 char *cstr() { return buf_;}
207 bool okdone() const { return ok_ && index_ == sz_; }
210 void rawbytes(string &s, size_t n);
211 template <class T> void rawbytes(T &t);
213 size_t ind() { return index_;}
214 size_t size() { return sz_;}
215 void take_buf(char **b, size_t *sz) {
222 void unpack_req_header(request_header *h) {
223 //the first 4-byte is for channel to fill size of pdu
224 index_ = sizeof(rpc_sz_t);
225 *this >> h->xid >> h->proc >> h->clt_nonce >> h->srv_nonce >> h->xid_rep;
226 index_ = RPC_HEADER_SZ;
229 void unpack_reply_header(reply_header *h) {
230 //the first 4-byte is for channel to fill size of pdu
231 index_ = sizeof(rpc_sz_t);
232 *this >> h->xid >> h->ret;
233 index_ = RPC_HEADER_SZ;
244 template <class A> typename enable_if<is_iterable<A>::value, unmarshall>::type &
245 operator>>(unmarshall &u, A &x) {
246 unsigned n = u.grab<unsigned>();
249 x.emplace_back(u.grab<typename A::value_type>());
253 template <class A, class B> unmarshall &
254 operator>>(unmarshall &u, map<A,B> &x) {
255 unsigned n = u.grab<unsigned>();
258 x.emplace(u.grab<pair<A,B>>());
262 template <class A, class B> unmarshall &
263 operator>>(unmarshall &u, pair<A,B> &d) {
264 return u >> d.first >> d.second;
267 template <class E> typename enable_if<is_enum<E>::value, unmarshall>::type &
268 operator>>(unmarshall &u, E &e) {
269 e = to_enum<E>(u.grab<enum_type_t<E>>());
273 typedef function<int(unmarshall &, marshall &)> handler;
276 // Automatic marshalling wrappers for RPC handlers
280 // C++11 does neither of these two things for us:
281 // 1) Declare variables using a parameter pack expansion, like so
283 // 2) Call a function with a tuple of the arguments it expects
285 // We implement an 'invoke' function for functions of the RPC handler
286 // signature, i.e. int(R & r, const Args...)
288 // One thing we need in order to accomplish this is a way to cause the compiler
289 // to specialize 'invoke' with a parameter pack containing a list of indices
290 // for the elements of the tuple. This will allow us to call the underlying
291 // function with the exploded contents of the tuple. The empty type
292 // tuple_indices<size_t...> accomplishes this. It will be passed in to
293 // 'invoke' as a parameter which will be ignored, but its type will force the
294 // compiler to specialize 'invoke' appropriately.
296 // The following implementation of tuple_indices is redistributed under the MIT
297 // License as an insubstantial portion of the LLVM compiler infrastructure.
299 template <size_t...> struct tuple_indices {};
300 template <size_t S, class IntTuple, size_t E> struct make_indices_imp;
301 template <size_t S, size_t ...Indices, size_t E> struct make_indices_imp<S, tuple_indices<Indices...>, E> {
302 typedef typename make_indices_imp<S+1, tuple_indices<Indices..., S>, E>::type type;
304 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
305 typedef tuple_indices<Indices...> type;
307 template <size_t E, size_t S=0> struct make_tuple_indices {
308 typedef typename make_indices_imp<S, tuple_indices<>, E>::type type;
311 // This class encapsulates the default response to runtime unmarshalling
312 // failures. The templated wrappers below may optionally use a different
315 struct VerifyOnFailure {
316 static inline int unmarshall_args_failure() {
322 // Here's the implementation of 'invoke'. It could be more general, but this
325 // One for function pointers...
327 template <class F, class R, class RV, class args_type, size_t ...Indices>
328 typename enable_if<!is_member_function_pointer<F>::value, RV>::type
329 invoke(RV, F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
330 return f(r, move(get<Indices>(t))...);
333 // And one for pointers to member functions...
335 template <class F, class C, class RV, class R, class args_type, size_t ...Indices>
336 typename enable_if<is_member_function_pointer<F>::value, RV>::type
337 invoke(RV, F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
338 return (c->*f)(r, move(get<Indices>(t))...);
341 // The class marshalled_func_imp uses partial template specialization to
342 // implement the ::wrap static function. ::wrap takes a function pointer or a
343 // pointer to a member function and returns a handler * object which
344 // unmarshalls arguments, verifies successful unmarshalling, calls the supplied
345 // function, and marshalls the response.
347 template <class Functor, class Instance, class Signature,
348 class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
350 // Here we specialize on the Signature template parameter to obtain the list of
351 // argument types. Note that we do not assume that the Functor parameter has
352 // the same pattern as Signature; this allows us to ignore the distinctions
353 // between various types of callable objects at this level of abstraction.
355 template <class F, class C, class ErrorHandler, class R, class RV, class... Args>
356 struct marshalled_func_imp<F, C, RV(R&, Args...), ErrorHandler> {
357 static inline handler *wrap(F f, C *c=nullptr) {
358 // This type definition corresponds to an empty struct with
359 // template parameters running from 0 up to (# args) - 1.
360 using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
361 // This type definition represents storage for f's unmarshalled
362 // arguments. decay is (most notably) stripping off const
364 using ArgsStorage = tuple<typename decay<Args>::type...>;
365 // Allocate a handler (i.e. function) to hold the lambda
366 // which will unmarshall RPCs and call f.
367 return new handler([=](unmarshall &u, marshall &m) -> RV {
368 // Unmarshall each argument with the correct type and store the
369 // result in a tuple.
370 ArgsStorage t = {u.grab<typename decay<Args>::type>()...};
371 // Verify successful unmarshalling of the entire input stream.
373 return (RV)ErrorHandler::unmarshall_args_failure();
374 // Allocate space for the RPC response -- will be passed into the
375 // function as an lvalue reference.
377 // Perform the invocation. Note that Indices() calls the default
378 // constructor of the empty struct with the special template
380 RV b = invoke(RV(), f, c, r, t, Indices());
381 // Marshall the response.
389 // More partial template specialization shenanigans to reduce the number of
390 // parameters which must be provided explicitly and to support a few common
391 // callable types. C++11 doesn't allow partial function template
392 // specialization, so we use classes (structs).
394 template <class Functor, class ErrorHandler=VerifyOnFailure,
395 class Signature=Functor> struct marshalled_func;
397 template <class F, class ErrorHandler, class RV, class... Args>
398 struct marshalled_func<F, ErrorHandler, RV(*)(Args...)> :
399 public marshalled_func_imp<F, void, RV(Args...), ErrorHandler> {};
401 template <class F, class ErrorHandler, class RV, class C, class... Args>
402 struct marshalled_func<F, ErrorHandler, RV(C::*)(Args...)> :
403 public marshalled_func_imp<F, C, RV(Args...), ErrorHandler> {};
405 template <class F, class ErrorHandler, class Signature>
406 struct marshalled_func<F, ErrorHandler, function<Signature>> :
407 public marshalled_func_imp<F, void, Signature, ErrorHandler> {};
409 template <class ...Args, size_t ...Indices> unmarshall &
410 tuple_unmarshall_imp(unmarshall & u, tuple<Args &...> t, tuple_indices<Indices...>) {
411 (void)pass{(u >> get<Indices>(t))...};
415 template <class... Args> unmarshall &
416 operator>>(unmarshall & u, tuple<Args &...> && t) {
417 using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
418 return tuple_unmarshall_imp(u, t, Indices());
421 template <class ...Args, size_t ...Indices> marshall &
422 tuple_marshall_imp(marshall & m, tuple<Args...> & t, tuple_indices<Indices...>) {
423 (void)pass{(m << get<Indices>(t))...};
427 template <class... Args> marshall &
428 operator<<(marshall & m, tuple<Args...> && t) {
429 using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
430 return tuple_marshall_imp(m, t, Indices());
433 // for structs or classes containing a MEMBERS declaration
434 #define MARSHALLABLE(_c_) \
435 inline unmarshall & operator>>(unmarshall &u, _c_ &a) { return u >> a._tuple_(); } \
436 inline marshall & operator<<(marshall &m, _c_ a) { return m << a._tuple_(); }