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 A> marshall &
127 operator<<(marshall &m, const A &x) {
128 m << (unsigned int) x.size();
129 for (const auto &a : x)
134 template <class A, class B> marshall &
135 operator<<(marshall &m, const std::pair<A,B> &d) {
148 inline bool ensure(size_t n);
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)
154 //take the content which does not exclude a RPC header from a string
158 if (buf_) free(buf_);
161 //take contents from another unmarshall object
162 void take_in(unmarshall &another);
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_);
169 index_ = RPC_HEADER_SZ;
170 memcpy(buf_+index_, s.data(), s.size());
174 bool ok() const { return ok_; }
175 char *cstr() { return buf_;}
176 bool okdone() const { return ok_ && index_ == sz_; }
178 unsigned int rawbyte();
179 void rawbytes(std::string &s, size_t n);
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) {
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);
196 unpack((int *)&h->clt_nonce);
197 unpack((int *)&h->srv_nonce);
199 index_ = RPC_HEADER_SZ;
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);
207 index_ = RPC_HEADER_SZ;
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 &);
228 template <class A> unmarshall & operator>>(unmarshall &u, A &x) {
229 unsigned n = u.grab<unsigned>();
232 x.emplace_back(u.grab<typename A::value_type>());
236 template <class A, class B> unmarshall &
237 operator>>(unmarshall &u, std::map<A,B> &x) {
238 unsigned n = u.grab<unsigned>();
241 x.emplace(u.grab<std::pair<A,B>>());
245 template <class A, class B> unmarshall &
246 operator>>(unmarshall &u, std::pair<A,B> &d) {
247 return u >> d.first >> d.second;
250 typedef std::function<int(unmarshall &, marshall &)> handler;
253 // Automatic marshalling wrappers for RPC handlers
257 // C++11 does neither of these two things for us:
258 // 1) Declare variables using a parameter pack expansion, like so
260 // 2) Call a function with a std::tuple of the arguments it expects
262 // We implement an 'invoke' function for functions of the RPC handler
263 // signature, i.e. int(R & r, const Args...)
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.
273 // The following implementation of tuple_indices is redistributed under the MIT
274 // License as an insubstantial portion of the LLVM compiler infrastructure.
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;
281 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
282 typedef tuple_indices<Indices...> type;
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;
288 // This class encapsulates the default response to runtime unmarshalling
289 // failures. The templated wrappers below may optionally use a different
292 struct VerifyOnFailure {
293 static inline int unmarshall_args_failure() {
299 // Here's the implementation of 'invoke'. It could be more general, but this
302 // One for function pointers...
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))...);
310 // And one for pointers to member functions...
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))...);
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.
324 template <class Functor, class Instance, class Signature,
325 class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
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.
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
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.
350 return ErrorHandler::unmarshall_args_failure();
351 // Allocate space for the RPC response -- will be passed into the
352 // function as an lvalue reference.
354 // Perform the invocation. Note that Indices() calls the default
355 // constructor of the empty struct with the special template
357 int b = invoke(f, c, r, t, Indices());
358 // Marshall the response.
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).
371 template <class Functor, class ErrorHandler=VerifyOnFailure,
372 class Signature=Functor> struct marshalled_func;
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> {};
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> {};
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> {};