Split out marshall code into a new file
[invirt/third/libt4.git] / rpc / marshall.h
1 #ifndef marshall_h
2 #define marshall_h
3
4 #include "types.h"
5 #include <cstring>
6 #include <cstddef>
7 #include <cinttypes>
8
9 using proc_t = uint32_t;
10 using status_t = int32_t;
11
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) {}
15     int xid;
16     proc_t proc;
17     unsigned int clt_nonce;
18     unsigned int srv_nonce;
19     int xid_rep;
20 };
21
22 struct reply_header {
23     reply_header(int x=0, int r=0): xid(x), ret(r) {}
24     int xid;
25     int ret;
26 };
27
28 template<class T> inline T hton(T t);
29
30 constexpr union { uint32_t i; uint8_t is_little_endian; } endianness{1};
31
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)
40         return t;
41     return (uint64_t)htonl((uint32_t)(t >> 32)) | ((uint64_t)htonl((uint32_t)t) << 32);
42 }
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)}; }
46
47 template <class T> inline T ntoh(T t) { return hton(t); }
48
49 typedef int rpc_sz_t;
50
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))
54
55 struct pass { template <typename... Args> inline pass(Args&&...) {} };
56
57 class marshall {
58     private:
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
62
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_);
68                 VERIFY(buf_);
69             }
70         }
71     public:
72         template <typename... Args>
73         marshall(const Args&... args) {
74             buf_ = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
75             VERIFY(buf_);
76             capacity_ = DEFAULT_RPC_SZ;
77             index_ = RPC_HEADER_SZ;
78             (void)pass{(*this << args)...};
79         }
80
81         ~marshall() {
82             if (buf_)
83                 free(buf_);
84         }
85
86         size_t size() { return index_;}
87         char *cstr() { return buf_;}
88         const char *cstr() const { return buf_;}
89
90         void rawbyte(uint8_t x) {
91             reserve(1);
92             buf_[index_++] = (int8_t)x;
93         }
94
95         void rawbytes(const char *p, size_t n) {
96             reserve(n);
97             memcpy(buf_+index_, p, n);
98             index_ += n;
99         }
100
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);
104         }
105
106         // Return the current content (excluding header) as a string
107         string str() {
108             return get_content();
109         }
110
111         void pack_req_header(const request_header &h);
112         void pack_reply_header(const reply_header &h);
113
114         void take_buf(char **b, size_t *s) {
115             *b = buf_;
116             *s = index_;
117             buf_ = NULL;
118             index_ = 0;
119             return;
120         }
121 };
122
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 &);
132
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)
137         m << a;
138     return m;
139 }
140
141 template <class A, class B> marshall &
142 operator<<(marshall &m, const pair<A,B> &d) {
143     return m << d.first << d.second;
144 }
145
146 template<typename E>
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; }
150
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);
154 }
155
156 class unmarshall;
157
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);
171
172 class unmarshall {
173     private:
174         char *buf_;
175         size_t sz_;
176         size_t index_;
177         bool ok_;
178
179         inline bool ensure(size_t n);
180     public:
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)
184         {
185             //take the content which does not exclude a RPC header from a string
186             take_content(s);
187         }
188         ~unmarshall() {
189             if (buf_) free(buf_);
190         }
191
192         //take contents from another unmarshall object
193         void take_in(unmarshall &another);
194
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_);
199             VERIFY(buf_);
200             index_ = RPC_HEADER_SZ;
201             memcpy(buf_+index_, s.data(), s.size());
202             ok_ = true;
203         }
204
205         bool ok() const { return ok_; }
206         char *cstr() { return buf_;}
207         bool okdone() const { return ok_ && index_ == sz_; }
208
209         uint8_t rawbyte();
210         void rawbytes(string &s, size_t n);
211         template <class T> void rawbytes(T &t);
212
213         size_t ind() { return index_;}
214         size_t size() { return sz_;}
215         void take_buf(char **b, size_t *sz) {
216             *b = buf_;
217             *sz = sz_;
218             sz_ = index_ = 0;
219             buf_ = NULL;
220         }
221
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;
227         }
228
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;
234         }
235
236         template <class A>
237         inline A grab() {
238             A a;
239             *this >> a;
240             return a;
241         }
242 };
243
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>();
247     x.clear();
248     while (n--)
249         x.emplace_back(u.grab<typename A::value_type>());
250     return u;
251 }
252
253 template <class A, class B> unmarshall &
254 operator>>(unmarshall &u, map<A,B> &x) {
255     unsigned n = u.grab<unsigned>();
256     x.clear();
257     while (n--)
258         x.emplace(u.grab<pair<A,B>>());
259     return u;
260 }
261
262 template <class A, class B> unmarshall &
263 operator>>(unmarshall &u, pair<A,B> &d) {
264     return u >> d.first >> d.second;
265 }
266
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>>());
270     return u;
271 }
272
273 typedef function<int(unmarshall &, marshall &)> handler;
274
275 //
276 // Automatic marshalling wrappers for RPC handlers
277 //
278
279 // PAI 2013/09/19
280 // C++11 does neither of these two things for us:
281 // 1) Declare variables using a parameter pack expansion, like so
282 //      Args ...args;
283 // 2) Call a function with a tuple of the arguments it expects
284 //
285 // We implement an 'invoke' function for functions of the RPC handler
286 // signature, i.e. int(R & r, const Args...)
287 //
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.
295
296 // The following implementation of tuple_indices is redistributed under the MIT
297 // License as an insubstantial portion of the LLVM compiler infrastructure.
298
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;
303 };
304 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
305     typedef tuple_indices<Indices...> type;
306 };
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;
309 };
310
311 // This class encapsulates the default response to runtime unmarshalling
312 // failures.  The templated wrappers below may optionally use a different
313 // class.
314
315 struct VerifyOnFailure {
316     static inline int unmarshall_args_failure() {
317         VERIFY(0);
318         return 0;
319     }
320 };
321
322 // Here's the implementation of 'invoke'.  It could be more general, but this
323 // meets our needs.
324
325 // One for function pointers...
326
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))...);
331 }
332
333 // And one for pointers to member functions...
334
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))...);
339 }
340
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.
346
347 template <class Functor, class Instance, class Signature,
348           class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
349
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.
354
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
363         // qualifiers.
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.
372             if (!u.okdone())
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.
376             R r;
377             // Perform the invocation.  Note that Indices() calls the default
378             // constructor of the empty struct with the special template
379             // parameters.
380             RV b = invoke(RV(), f, c, r, t, Indices());
381             // Marshall the response.
382             m << r;
383             // Make like a tree.
384             return b;
385         });
386     }
387 };
388
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).
393
394 template <class Functor, class ErrorHandler=VerifyOnFailure,
395     class Signature=Functor> struct marshalled_func;
396
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> {};
400
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> {};
404
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> {};
408
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))...};
412     return u;
413 }
414
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());
419 }
420
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))...};
424     return m;
425 }
426
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());
431 }
432
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_(); }
437
438 #endif