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