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