13 #include "lang/verify.h"
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) {}
20 unsigned int clt_nonce;
21 unsigned int srv_nonce;
23 request_header hton() const {
25 htonl(xid), htonl(proc), htonl(clt_nonce), htonl(srv_nonce), htonl(xid_rep)
31 reply_header(int x=0, int r=0): xid(x), ret(r) {}
34 reply_header hton() const {
36 htonl(xid), htonl(ret)
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))
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
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_);
62 struct pass { template <typename... Args> inline pass(Args&&...) {} };
64 template <typename... Args>
66 marshall(const Args&... args) {
67 buf_ = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
69 capacity_ = DEFAULT_RPC_SZ;
70 index_ = RPC_HEADER_SZ;
71 (void)pass{(*this << args)...};
79 int size() { return index_;}
80 char *cstr() { return buf_;}
81 const char *cstr() const { return buf_;}
83 void rawbyte(unsigned char x) {
88 void rawbytes(const char *p, int n) {
90 memcpy(buf_+index_, p, n);
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);
99 // Return the current content (excluding header) as a string
101 return get_content();
104 void pack_req_header(const request_header &h);
105 void pack_reply_header(const reply_header &h);
107 void take_buf(char **b, int *s) {
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 &);
126 template <class C> marshall &
127 operator<<(marshall &m, std::vector<C> v)
129 m << (unsigned int) v.size();
130 for(unsigned i = 0; i < v.size(); i++)
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;
139 m << (unsigned int) d.size();
141 for (i = d.begin(); i != d.end(); i++) {
142 m << i->first << i->second;
147 template <class A> marshall &
148 operator<<(marshall &m, const std::list<A> &d) {
149 m << std::vector<A>(d.begin(), d.end());
153 template <class A, class B> marshall &
154 operator<<(marshall &m, const std::pair<A,B> &d) {
167 inline bool ensure(size_t n);
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)
173 //take the content which does not exclude a RPC header from a string
177 if (buf_) free(buf_);
180 //take contents from another unmarshall object
181 void take_in(unmarshall &another);
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_);
188 index_ = RPC_HEADER_SZ;
189 memcpy(buf_+index_, s.data(), s.size());
193 bool ok() const { return ok_; }
194 char *cstr() { return buf_;}
195 bool okdone() const { return ok_ && index_ == sz_; }
197 unsigned int rawbyte();
198 void rawbytes(std::string &s, size_t n);
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) {
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);
215 unpack((int *)&h->clt_nonce);
216 unpack((int *)&h->srv_nonce);
218 index_ = RPC_HEADER_SZ;
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);
226 index_ = RPC_HEADER_SZ;
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 &);
247 template <class C> unmarshall &
248 operator>>(unmarshall &u, std::vector<C> &v)
261 template <class A, class B> unmarshall &
262 operator>>(unmarshall &u, std::map<A,B> &d) {
275 template <class C> unmarshall &
276 operator>>(unmarshall &u, std::list<C> &l) {
288 template <class A, class B> unmarshall &
289 operator>>(unmarshall &u, std::pair<A,B> &d) {
290 return u >> d.first >> d.second;
293 typedef std::function<int(unmarshall &, marshall &)> handler;
296 // Automatic marshalling wrappers for RPC handlers
300 // C++11 does neither of these two things for us:
301 // 1) Declare variables using a parameter pack expansion, like so
303 // 2) Call a function with a std::tuple of the arguments it expects
305 // We implement an 'invoke' function for functions of the RPC handler
306 // signature, i.e. int(R & r, const Args...)
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.
316 // The following implementation of tuple_indices is redistributed under the MIT
317 // License as an insubstantial portion of the LLVM compiler infrastructure.
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;
324 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
325 typedef tuple_indices<Indices...> type;
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;
331 // This class encapsulates the default response to runtime unmarshalling
332 // failures. The templated wrappers below may optionally use a different
335 struct VerifyOnFailure {
336 static inline int unmarshall_args_failure() {
342 // Here's the implementation of 'invoke'. It could be more general, but this
345 // One for function pointers...
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))...);
353 // And one for pointers to member functions...
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))...);
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.
367 template <class Functor, class Instance, class Signature,
368 class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
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.
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
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.
393 return ErrorHandler::unmarshall_args_failure();
394 // Allocate space for the RPC response -- will be passed into the
395 // function as an lvalue reference.
397 // Perform the invocation. Note that Indices() calls the default
398 // constructor of the empty struct with the special template
400 int b = invoke(f, c, r, t, Indices());
401 // Marshall the response.
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).
414 template <class Functor, class ErrorHandler=VerifyOnFailure,
415 class Signature=Functor> struct marshalled_func;
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> {};
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> {};
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> {};