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 template <class A> unmarshall & operator>>(unmarshall &u, A &x) {
219 unsigned n = u.grab<unsigned>();
222 x.emplace_back(u.grab<typename A::value_type>());
226 template <class A, class B> unmarshall &
227 operator>>(unmarshall &u, std::map<A,B> &x) {
228 unsigned n = u.grab<unsigned>();
231 x.emplace(u.grab<std::pair<A,B>>());
235 template <class A, class B> unmarshall &
236 operator>>(unmarshall &u, std::pair<A,B> &d) {
237 return u >> d.first >> d.second;
240 typedef std::function<int(unmarshall &, marshall &)> handler;
243 // Automatic marshalling wrappers for RPC handlers
247 // C++11 does neither of these two things for us:
248 // 1) Declare variables using a parameter pack expansion, like so
250 // 2) Call a function with a std::tuple of the arguments it expects
252 // We implement an 'invoke' function for functions of the RPC handler
253 // signature, i.e. int(R & r, const Args...)
255 // One thing we need in order to accomplish this is a way to cause the compiler
256 // to specialize 'invoke' with a parameter pack containing a list of indices
257 // for the elements of the tuple. This will allow us to call the underlying
258 // function with the exploded contents of the tuple. The empty type
259 // tuple_indices<size_t...> accomplishes this. It will be passed in to
260 // 'invoke' as a parameter which will be ignored, but its type will force the
261 // compiler to specialize 'invoke' appropriately.
263 // The following implementation of tuple_indices is redistributed under the MIT
264 // License as an insubstantial portion of the LLVM compiler infrastructure.
266 template <size_t...> struct tuple_indices {};
267 template <size_t S, class IntTuple, size_t E> struct make_indices_imp;
268 template <size_t S, size_t ...Indices, size_t E> struct make_indices_imp<S, tuple_indices<Indices...>, E> {
269 typedef typename make_indices_imp<S+1, tuple_indices<Indices..., S>, E>::type type;
271 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
272 typedef tuple_indices<Indices...> type;
274 template <size_t E, size_t S=0> struct make_tuple_indices {
275 typedef typename make_indices_imp<S, tuple_indices<>, E>::type type;
278 // This class encapsulates the default response to runtime unmarshalling
279 // failures. The templated wrappers below may optionally use a different
282 struct VerifyOnFailure {
283 static inline int unmarshall_args_failure() {
289 // Here's the implementation of 'invoke'. It could be more general, but this
292 // One for function pointers...
294 template <class F, class R, class args_type, size_t ...Indices>
295 typename std::enable_if<!std::is_member_function_pointer<F>::value, int>::type
296 invoke(F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
297 return f(r, std::move(std::get<Indices>(t))...);
300 // And one for pointers to member functions...
302 template <class F, class C, class R, class args_type, size_t ...Indices>
303 typename std::enable_if<std::is_member_function_pointer<F>::value, int>::type
304 invoke(F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
305 return (c->*f)(r, std::move(std::get<Indices>(t))...);
308 // The class marshalled_func_imp uses partial template specialization to
309 // implement the ::wrap static function. ::wrap takes a function pointer or a
310 // pointer to a member function and returns a handler * object which
311 // unmarshalls arguments, verifies successful unmarshalling, calls the supplied
312 // function, and marshalls the response.
314 template <class Functor, class Instance, class Signature,
315 class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
317 // Here we specialize on the Signature template parameter to obtain the list of
318 // argument types. Note that we do not assume that the Functor parameter has
319 // the same pattern as Signature; this allows us to ignore the distinctions
320 // between various types of callable objects at this level of abstraction.
322 template <class F, class C, class ErrorHandler, class R, class... Args>
323 struct marshalled_func_imp<F, C, int(R&, Args...), ErrorHandler> {
324 static inline handler *wrap(F f, C *c=nullptr) {
325 // This type definition corresponds to an empty struct with
326 // template parameters running from 0 up to (# args) - 1.
327 using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
328 // This type definition represents storage for f's unmarshalled
329 // arguments. std::decay is (most notably) stripping off const
331 using ArgsStorage = std::tuple<typename std::decay<Args>::type...>;
332 // Allocate a handler (i.e. std::function) to hold the lambda
333 // which will unmarshall RPCs and call f.
334 return new handler([=](unmarshall &u, marshall &m) -> int {
335 // Unmarshall each argument with the correct type and store the
336 // result in a tuple.
337 ArgsStorage t = {u.grab<typename std::decay<Args>::type>()...};
338 // Verify successful unmarshalling of the entire input stream.
340 return ErrorHandler::unmarshall_args_failure();
341 // Allocate space for the RPC response -- will be passed into the
342 // function as an lvalue reference.
344 // Perform the invocation. Note that Indices() calls the default
345 // constructor of the empty struct with the special template
347 int b = invoke(f, c, r, t, Indices());
348 // Marshall the response.
356 // More partial template specialization shenanigans to reduce the number of
357 // parameters which must be provided explicitly and to support a few common
358 // callable types. C++11 doesn't allow partial function template
359 // specialization, so we use classes (structs).
361 template <class Functor, class ErrorHandler=VerifyOnFailure,
362 class Signature=Functor> struct marshalled_func;
364 template <class F, class ErrorHandler, class... Args>
365 struct marshalled_func<F, ErrorHandler, int(*)(Args...)> :
366 public marshalled_func_imp<F, void, int(Args...), ErrorHandler> {};
368 template <class F, class ErrorHandler, class C, class... Args>
369 struct marshalled_func<F, ErrorHandler, int(C::*)(Args...)> :
370 public marshalled_func_imp<F, C, int(Args...), ErrorHandler> {};
372 template <class F, class ErrorHandler, class Signature>
373 struct marshalled_func<F, ErrorHandler, std::function<Signature>> :
374 public marshalled_func_imp<F, void, Signature, ErrorHandler> {};