More clean-ups and cool template stuff
[invirt/third/libt4.git] / rpc / marshall.h
1 #ifndef marshall_h
2 #define marshall_h
3
4 #include <iostream>
5 #include <sstream>
6 #include <string>
7 #include <vector>
8 #include <map>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <cstddef>
12 #include <inttypes.h>
13 #include "lang/verify.h"
14
15 using proc_t = uint32_t;
16 using status_t = int32_t;
17
18 struct request_header {
19     request_header(int x=0, proc_t p=0, unsigned c=0, unsigned s=0, int xi=0) :
20         xid(x), proc(p), clt_nonce(c), srv_nonce(s), xid_rep(xi) {}
21     int xid;
22     proc_t proc;
23     unsigned int clt_nonce;
24     unsigned int srv_nonce;
25     int xid_rep;
26 };
27
28 struct reply_header {
29     reply_header(int x=0, int r=0): xid(x), ret(r) {}
30     int xid;
31     int ret;
32 };
33
34 template<class T> inline T hton(T t);
35
36 constexpr union { uint32_t i; uint8_t is_little_endian; } endianness{1};
37
38 template<> inline uint8_t hton(uint8_t t) { return t; }
39 template<> inline int8_t hton(int8_t t) { return t; }
40 template<> inline uint16_t hton(uint16_t t) { return htons(t); }
41 template<> inline int16_t hton(int16_t t) { return (int16_t)htons((uint16_t)t); }
42 template<> inline uint32_t hton(uint32_t t) { return htonl(t); }
43 template<> inline int32_t hton(int32_t t) { return (int32_t)htonl((uint32_t)t); }
44 template<> inline uint64_t hton(uint64_t t) {
45     if (!endianness.is_little_endian)
46         return t;
47     return (uint64_t)htonl((uint32_t)(t >> 32)) | ((uint64_t)htonl((uint32_t)t) << 32);
48 }
49 template<> inline int64_t hton(int64_t t) { return (int64_t)hton((uint64_t)t); }
50 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)}; }
51 template<> inline reply_header hton(reply_header h) { return {hton(h.xid), hton(h.ret)}; }
52
53 template <class T> inline T ntoh(T t) { return hton(t); }
54
55 typedef int rpc_sz_t;
56
57 //size of initial buffer allocation
58 #define DEFAULT_RPC_SZ 1024
59 #define RPC_HEADER_SZ (std::max(sizeof(request_header), sizeof(reply_header)) + sizeof(rpc_sz_t))
60
61 class marshall {
62     private:
63         char *buf_;     // Base of the raw bytes buffer (dynamically readjusted)
64         size_t capacity_;  // Capacity of the buffer
65         size_t index_;     // Read/write head position
66
67         inline void reserve(size_t n) {
68             if((index_+n) > capacity_){
69                 capacity_ += std::max(capacity_, n);
70                 VERIFY (buf_ != NULL);
71                 buf_ = (char *)realloc(buf_, capacity_);
72                 VERIFY(buf_);
73             }
74         }
75     public:
76         struct pass { template <typename... Args> inline pass(Args&&...) {} };
77
78         template <typename... Args>
79
80         marshall(const Args&... args) {
81             buf_ = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
82             VERIFY(buf_);
83             capacity_ = DEFAULT_RPC_SZ;
84             index_ = RPC_HEADER_SZ;
85             (void)pass{(*this << args)...};
86         }
87
88         ~marshall() {
89             if (buf_)
90                 free(buf_);
91         }
92
93         size_t size() { return index_;}
94         char *cstr() { return buf_;}
95         const char *cstr() const { return buf_;}
96
97         void rawbyte(uint8_t x) {
98             reserve(1);
99             buf_[index_++] = (int8_t)x;
100         }
101
102         void rawbytes(const char *p, size_t n) {
103             reserve(n);
104             memcpy(buf_+index_, p, n);
105             index_ += n;
106         }
107
108         // Return the current content (excluding header) as a string
109         std::string get_content() {
110             return std::string(buf_+RPC_HEADER_SZ,index_-RPC_HEADER_SZ);
111         }
112
113         // Return the current content (excluding header) as a string
114         std::string str() {
115             return get_content();
116         }
117
118         void pack_req_header(const request_header &h);
119         void pack_reply_header(const reply_header &h);
120
121         void take_buf(char **b, size_t *s) {
122             *b = buf_;
123             *s = index_;
124             buf_ = NULL;
125             index_ = 0;
126             return;
127         }
128 };
129
130 marshall& operator<<(marshall &, bool);
131 marshall& operator<<(marshall &, uint32_t);
132 marshall& operator<<(marshall &, int32_t);
133 marshall& operator<<(marshall &, uint8_t);
134 marshall& operator<<(marshall &, int8_t);
135 marshall& operator<<(marshall &, uint16_t);
136 marshall& operator<<(marshall &, int16_t);
137 marshall& operator<<(marshall &, uint64_t);
138 marshall& operator<<(marshall &, const std::string &);
139
140 template <class A, typename I=void>
141 struct is_enumerable : std::false_type {};
142
143 template<class A> struct is_enumerable<A,
144     decltype(std::declval<A&>().cbegin(), std::declval<A&>().cend(), void())
145 > : std::true_type {};
146
147 template <class A> typename std::enable_if<is_enumerable<A>::value, marshall>::type &
148 operator<<(marshall &m, const A &x) {
149     m << (unsigned int) x.size();
150     for (const auto &a : x)
151         m << a;
152     return m;
153 }
154
155 template <class A, class B> marshall &
156 operator<<(marshall &m, const std::pair<A,B> &d) {
157     return m << d.first << d.second;
158 }
159
160 template<typename E>
161 using enum_type_t = typename std::enable_if<std::is_enum<E>::value, typename std::underlying_type<E>::type>::type;
162 template<typename E> constexpr inline enum_type_t<E> from_enum(E e) noexcept { return (enum_type_t<E>)e; }
163 template<typename E> constexpr inline E to_enum(enum_type_t<E> value) noexcept { return (E)value; }
164
165 template <class E> typename std::enable_if<std::is_enum<E>::value, marshall>::type &
166 operator<<(marshall &m, E e) {
167     return m << from_enum(e);
168 }
169
170 class unmarshall;
171
172 unmarshall& operator>>(unmarshall &, bool &);
173 unmarshall& operator>>(unmarshall &, uint8_t &);
174 unmarshall& operator>>(unmarshall &, int8_t &);
175 unmarshall& operator>>(unmarshall &, uint16_t &);
176 unmarshall& operator>>(unmarshall &, int16_t &);
177 unmarshall& operator>>(unmarshall &, uint32_t &);
178 unmarshall& operator>>(unmarshall &, int32_t &);
179 unmarshall& operator>>(unmarshall &, size_t &);
180 unmarshall& operator>>(unmarshall &, uint64_t &);
181 unmarshall& operator>>(unmarshall &, int64_t &);
182 unmarshall& operator>>(unmarshall &, std::string &);
183 template <class E> typename std::enable_if<std::is_enum<E>::value, unmarshall>::type &
184 operator>>(unmarshall &u, E &e);
185
186 class unmarshall {
187     private:
188         char *buf_;
189         size_t sz_;
190         size_t index_;
191         bool ok_;
192
193         inline bool ensure(size_t n);
194     public:
195         unmarshall(): buf_(NULL),sz_(0),index_(0),ok_(false) {}
196         unmarshall(char *b, size_t sz): buf_(b),sz_(sz),index_(),ok_(true) {}
197         unmarshall(const std::string &s) : buf_(NULL),sz_(0),index_(0),ok_(false)
198         {
199             //take the content which does not exclude a RPC header from a string
200             take_content(s);
201         }
202         ~unmarshall() {
203             if (buf_) free(buf_);
204         }
205
206         //take contents from another unmarshall object
207         void take_in(unmarshall &another);
208
209         //take the content which does not exclude a RPC header from a string
210         void take_content(const std::string &s) {
211             sz_ = s.size()+RPC_HEADER_SZ;
212             buf_ = (char *)realloc(buf_,sz_);
213             VERIFY(buf_);
214             index_ = RPC_HEADER_SZ;
215             memcpy(buf_+index_, s.data(), s.size());
216             ok_ = true;
217         }
218
219         bool ok() const { return ok_; }
220         char *cstr() { return buf_;}
221         bool okdone() const { return ok_ && index_ == sz_; }
222
223         uint8_t rawbyte();
224         void rawbytes(std::string &s, size_t n);
225         template <class T> void rawbytes(T &t);
226
227         size_t ind() { return index_;}
228         size_t size() { return sz_;}
229         void take_buf(char **b, size_t *sz) {
230             *b = buf_;
231             *sz = sz_;
232             sz_ = index_ = 0;
233             buf_ = NULL;
234         }
235
236         void unpack_req_header(request_header *h) {
237             //the first 4-byte is for channel to fill size of pdu
238             index_ = sizeof(rpc_sz_t);
239             *this >> h->xid >> h->proc >> h->clt_nonce >> h->srv_nonce >> h->xid_rep;
240             index_ = RPC_HEADER_SZ;
241         }
242
243         void unpack_reply_header(reply_header *h) {
244             //the first 4-byte is for channel to fill size of pdu
245             index_ = sizeof(rpc_sz_t);
246             *this >> h->xid >> h->ret;
247             index_ = RPC_HEADER_SZ;
248         }
249
250         template <class A>
251         inline A grab() {
252             A a;
253             *this >> a;
254             return a;
255         }
256 };
257
258 template <class A> typename std::enable_if<is_enumerable<A>::value, unmarshall>::type &
259 operator>>(unmarshall &u, A &x) {
260     unsigned n = u.grab<unsigned>();
261     x.clear();
262     while (n--)
263         x.emplace_back(u.grab<typename A::value_type>());
264     return u;
265 }
266
267 template <class A, class B> unmarshall &
268 operator>>(unmarshall &u, std::map<A,B> &x) {
269     unsigned n = u.grab<unsigned>();
270     x.clear();
271     while (n--)
272         x.emplace(u.grab<std::pair<A,B>>());
273     return u;
274 }
275
276 template <class A, class B> unmarshall &
277 operator>>(unmarshall &u, std::pair<A,B> &d) {
278     return u >> d.first >> d.second;
279 }
280
281 template <class E> typename std::enable_if<std::is_enum<E>::value, unmarshall>::type &
282 operator>>(unmarshall &u, E &e) {
283     e = to_enum<E>(u.grab<enum_type_t<E>>());
284     return u;
285 }
286
287 typedef std::function<int(unmarshall &, marshall &)> handler;
288
289 //
290 // Automatic marshalling wrappers for RPC handlers
291 //
292
293 // PAI 2013/09/19
294 // C++11 does neither of these two things for us:
295 // 1) Declare variables using a parameter pack expansion, like so
296 //      Args ...args;
297 // 2) Call a function with a std::tuple of the arguments it expects
298 //
299 // We implement an 'invoke' function for functions of the RPC handler
300 // signature, i.e. int(R & r, const Args...)
301 //
302 // One thing we need in order to accomplish this is a way to cause the compiler
303 // to specialize 'invoke' with a parameter pack containing a list of indices
304 // for the elements of the tuple.  This will allow us to call the underlying
305 // function with the exploded contents of the tuple.  The empty type
306 // tuple_indices<size_t...> accomplishes this.  It will be passed in to
307 // 'invoke' as a parameter which will be ignored, but its type will force the
308 // compiler to specialize 'invoke' appropriately.
309
310 // The following implementation of tuple_indices is redistributed under the MIT
311 // License as an insubstantial portion of the LLVM compiler infrastructure.
312
313 template <size_t...> struct tuple_indices {};
314 template <size_t S, class IntTuple, size_t E> struct make_indices_imp;
315 template <size_t S, size_t ...Indices, size_t E> struct make_indices_imp<S, tuple_indices<Indices...>, E> {
316     typedef typename make_indices_imp<S+1, tuple_indices<Indices..., S>, E>::type type;
317 };
318 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
319     typedef tuple_indices<Indices...> type;
320 };
321 template <size_t E, size_t S=0> struct make_tuple_indices {
322     typedef typename make_indices_imp<S, tuple_indices<>, E>::type type;
323 };
324
325 // This class encapsulates the default response to runtime unmarshalling
326 // failures.  The templated wrappers below may optionally use a different
327 // class.
328
329 struct VerifyOnFailure {
330     static inline int unmarshall_args_failure() {
331         VERIFY(0);
332         return 0;
333     }
334 };
335
336 // Here's the implementation of 'invoke'.  It could be more general, but this
337 // meets our needs.
338
339 // One for function pointers...
340
341 template <class F, class R, class RV, class args_type, size_t ...Indices>
342 typename std::enable_if<!std::is_member_function_pointer<F>::value, RV>::type
343 invoke(RV, F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
344     return f(r, std::move(std::get<Indices>(t))...);
345 }
346
347 // And one for pointers to member functions...
348
349 template <class F, class C, class RV, class R, class args_type, size_t ...Indices>
350 typename std::enable_if<std::is_member_function_pointer<F>::value, RV>::type
351 invoke(RV, F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
352     return (c->*f)(r, std::move(std::get<Indices>(t))...);
353 }
354
355 // The class marshalled_func_imp uses partial template specialization to
356 // implement the ::wrap static function.  ::wrap takes a function pointer or a
357 // pointer to a member function and returns a handler * object which
358 // unmarshalls arguments, verifies successful unmarshalling, calls the supplied
359 // function, and marshalls the response.
360
361 template <class Functor, class Instance, class Signature,
362           class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
363
364 // Here we specialize on the Signature template parameter to obtain the list of
365 // argument types.  Note that we do not assume that the Functor parameter has
366 // the same pattern as Signature; this allows us to ignore the distinctions
367 // between various types of callable objects at this level of abstraction.
368
369 template <class F, class C, class ErrorHandler, class R, class RV, class... Args>
370 struct marshalled_func_imp<F, C, RV(R&, Args...), ErrorHandler> {
371     static inline handler *wrap(F f, C *c=nullptr) {
372         // This type definition corresponds to an empty struct with
373         // template parameters running from 0 up to (# args) - 1.
374         using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
375         // This type definition represents storage for f's unmarshalled
376         // arguments.  std::decay is (most notably) stripping off const
377         // qualifiers.
378         using ArgsStorage = std::tuple<typename std::decay<Args>::type...>;
379         // Allocate a handler (i.e. std::function) to hold the lambda
380         // which will unmarshall RPCs and call f.
381         return new handler([=](unmarshall &u, marshall &m) -> RV {
382             // Unmarshall each argument with the correct type and store the
383             // result in a tuple.
384             ArgsStorage t = {u.grab<typename std::decay<Args>::type>()...};
385             // Verify successful unmarshalling of the entire input stream.
386             if (!u.okdone())
387                 return (RV)ErrorHandler::unmarshall_args_failure();
388             // Allocate space for the RPC response -- will be passed into the
389             // function as an lvalue reference.
390             R r;
391             // Perform the invocation.  Note that Indices() calls the default
392             // constructor of the empty struct with the special template
393             // parameters.
394             RV b = invoke(RV(), f, c, r, t, Indices());
395             // Marshall the response.
396             m << r;
397             // Make like a tree.
398             return b;
399         });
400     }
401 };
402
403 // More partial template specialization shenanigans to reduce the number of
404 // parameters which must be provided explicitly and to support a few common
405 // callable types.  C++11 doesn't allow partial function template
406 // specialization, so we use classes (structs).
407
408 template <class Functor, class ErrorHandler=VerifyOnFailure,
409     class Signature=Functor> struct marshalled_func;
410
411 template <class F, class ErrorHandler, class RV, class... Args>
412 struct marshalled_func<F, ErrorHandler, RV(*)(Args...)> :
413     public marshalled_func_imp<F, void, RV(Args...), ErrorHandler> {};
414
415 template <class F, class ErrorHandler, class RV, class C, class... Args>
416 struct marshalled_func<F, ErrorHandler, RV(C::*)(Args...)> :
417     public marshalled_func_imp<F, C, RV(Args...), ErrorHandler> {};
418
419 template <class F, class ErrorHandler, class Signature>
420 struct marshalled_func<F, ErrorHandler, std::function<Signature>> :
421     public marshalled_func_imp<F, void, Signature, ErrorHandler> {};
422
423 #endif