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