13 #include "lang/verify.h"
15 using proc_t = uint32_t;
16 using status_t = int32_t;
18 struct request_header {
19 request_header(int x=0, proc_t p=0, unsigned c=0, unsigned s=0, int xi=0) :
20 xid(x), proc(p), clt_nonce(c), srv_nonce(s), xid_rep(xi) {}
23 unsigned int clt_nonce;
24 unsigned int srv_nonce;
29 reply_header(int x=0, int r=0): xid(x), ret(r) {}
34 template<class T> inline T hton(T t);
36 constexpr union { uint32_t i; uint8_t is_little_endian; } endianness{1};
38 template<> inline uint8_t hton(uint8_t t) { return t; }
39 template<> inline int8_t hton(int8_t t) { return t; }
40 template<> inline uint16_t hton(uint16_t t) { return htons(t); }
41 template<> inline int16_t hton(int16_t t) { return (int16_t)htons((uint16_t)t); }
42 template<> inline uint32_t hton(uint32_t t) { return htonl(t); }
43 template<> inline int32_t hton(int32_t t) { return (int32_t)htonl((uint32_t)t); }
44 template<> inline uint64_t hton(uint64_t t) {
45 if (!endianness.is_little_endian)
47 return (uint64_t)htonl((uint32_t)(t >> 32)) | ((uint64_t)htonl((uint32_t)t) << 32);
49 template<> inline int64_t hton(int64_t t) { return (int64_t)hton((uint64_t)t); }
50 template<> inline request_header hton(request_header h) { return {hton(h.xid), hton(h.proc), hton(h.clt_nonce), hton(h.srv_nonce), hton(h.xid_rep)}; }
51 template<> inline reply_header hton(reply_header h) { return {hton(h.xid), hton(h.ret)}; }
53 template <class T> inline T ntoh(T t) { return hton(t); }
57 //size of initial buffer allocation
58 #define DEFAULT_RPC_SZ 1024
59 #define RPC_HEADER_SZ (std::max(sizeof(request_header), sizeof(reply_header)) + sizeof(rpc_sz_t))
63 char *buf_; // Base of the raw bytes buffer (dynamically readjusted)
64 size_t capacity_; // Capacity of the buffer
65 size_t index_; // Read/write head position
67 inline void reserve(size_t n) {
68 if((index_+n) > capacity_){
69 capacity_ += std::max(capacity_, n);
70 VERIFY (buf_ != NULL);
71 buf_ = (char *)realloc(buf_, capacity_);
76 struct pass { template <typename... Args> inline pass(Args&&...) {} };
78 template <typename... Args>
80 marshall(const Args&... args) {
81 buf_ = (char *) malloc(sizeof(char)*DEFAULT_RPC_SZ);
83 capacity_ = DEFAULT_RPC_SZ;
84 index_ = RPC_HEADER_SZ;
85 (void)pass{(*this << args)...};
93 size_t size() { return index_;}
94 char *cstr() { return buf_;}
95 const char *cstr() const { return buf_;}
97 void rawbyte(uint8_t x) {
99 buf_[index_++] = (int8_t)x;
102 void rawbytes(const char *p, size_t n) {
104 memcpy(buf_+index_, p, n);
108 // Return the current content (excluding header) as a string
109 std::string get_content() {
110 return std::string(buf_+RPC_HEADER_SZ,index_-RPC_HEADER_SZ);
113 // Return the current content (excluding header) as a string
115 return get_content();
118 void pack_req_header(const request_header &h);
119 void pack_reply_header(const reply_header &h);
121 void take_buf(char **b, size_t *s) {
130 marshall& operator<<(marshall &, bool);
131 marshall& operator<<(marshall &, uint32_t);
132 marshall& operator<<(marshall &, int32_t);
133 marshall& operator<<(marshall &, uint8_t);
134 marshall& operator<<(marshall &, int8_t);
135 marshall& operator<<(marshall &, uint16_t);
136 marshall& operator<<(marshall &, int16_t);
137 marshall& operator<<(marshall &, uint64_t);
138 marshall& operator<<(marshall &, const std::string &);
140 template <class A, typename I=void>
141 struct is_enumerable : std::false_type {};
143 template<class A> struct is_enumerable<A,
144 decltype(std::declval<A&>().cbegin(), std::declval<A&>().cend(), void())
145 > : std::true_type {};
147 template <class A> typename std::enable_if<is_enumerable<A>::value, marshall>::type &
148 operator<<(marshall &m, const A &x) {
149 m << (unsigned int) x.size();
150 for (const auto &a : x)
155 template <class A, class B> marshall &
156 operator<<(marshall &m, const std::pair<A,B> &d) {
157 return m << d.first << d.second;
161 using enum_type_t = typename std::enable_if<std::is_enum<E>::value, typename std::underlying_type<E>::type>::type;
162 template<typename E> constexpr inline enum_type_t<E> from_enum(E e) noexcept { return (enum_type_t<E>)e; }
163 template<typename E> constexpr inline E to_enum(enum_type_t<E> value) noexcept { return (E)value; }
165 template <class E> typename std::enable_if<std::is_enum<E>::value, marshall>::type &
166 operator<<(marshall &m, E e) {
167 return m << from_enum(e);
172 unmarshall& operator>>(unmarshall &, bool &);
173 unmarshall& operator>>(unmarshall &, uint8_t &);
174 unmarshall& operator>>(unmarshall &, int8_t &);
175 unmarshall& operator>>(unmarshall &, uint16_t &);
176 unmarshall& operator>>(unmarshall &, int16_t &);
177 unmarshall& operator>>(unmarshall &, uint32_t &);
178 unmarshall& operator>>(unmarshall &, int32_t &);
179 unmarshall& operator>>(unmarshall &, size_t &);
180 unmarshall& operator>>(unmarshall &, uint64_t &);
181 unmarshall& operator>>(unmarshall &, int64_t &);
182 unmarshall& operator>>(unmarshall &, std::string &);
183 template <class E> typename std::enable_if<std::is_enum<E>::value, unmarshall>::type &
184 operator>>(unmarshall &u, E &e);
193 inline bool ensure(size_t n);
195 unmarshall(): buf_(NULL),sz_(0),index_(0),ok_(false) {}
196 unmarshall(char *b, size_t sz): buf_(b),sz_(sz),index_(),ok_(true) {}
197 unmarshall(const std::string &s) : buf_(NULL),sz_(0),index_(0),ok_(false)
199 //take the content which does not exclude a RPC header from a string
203 if (buf_) free(buf_);
206 //take contents from another unmarshall object
207 void take_in(unmarshall &another);
209 //take the content which does not exclude a RPC header from a string
210 void take_content(const std::string &s) {
211 sz_ = s.size()+RPC_HEADER_SZ;
212 buf_ = (char *)realloc(buf_,sz_);
214 index_ = RPC_HEADER_SZ;
215 memcpy(buf_+index_, s.data(), s.size());
219 bool ok() const { return ok_; }
220 char *cstr() { return buf_;}
221 bool okdone() const { return ok_ && index_ == sz_; }
224 void rawbytes(std::string &s, size_t n);
225 template <class T> void rawbytes(T &t);
227 size_t ind() { return index_;}
228 size_t size() { return sz_;}
229 void take_buf(char **b, size_t *sz) {
236 void unpack_req_header(request_header *h) {
237 //the first 4-byte is for channel to fill size of pdu
238 index_ = sizeof(rpc_sz_t);
239 *this >> h->xid >> h->proc >> h->clt_nonce >> h->srv_nonce >> h->xid_rep;
240 index_ = RPC_HEADER_SZ;
243 void unpack_reply_header(reply_header *h) {
244 //the first 4-byte is for channel to fill size of pdu
245 index_ = sizeof(rpc_sz_t);
246 *this >> h->xid >> h->ret;
247 index_ = RPC_HEADER_SZ;
258 template <class A> typename std::enable_if<is_enumerable<A>::value, unmarshall>::type &
259 operator>>(unmarshall &u, A &x) {
260 unsigned n = u.grab<unsigned>();
263 x.emplace_back(u.grab<typename A::value_type>());
267 template <class A, class B> unmarshall &
268 operator>>(unmarshall &u, std::map<A,B> &x) {
269 unsigned n = u.grab<unsigned>();
272 x.emplace(u.grab<std::pair<A,B>>());
276 template <class A, class B> unmarshall &
277 operator>>(unmarshall &u, std::pair<A,B> &d) {
278 return u >> d.first >> d.second;
281 template <class E> typename std::enable_if<std::is_enum<E>::value, unmarshall>::type &
282 operator>>(unmarshall &u, E &e) {
283 e = to_enum<E>(u.grab<enum_type_t<E>>());
287 typedef std::function<int(unmarshall &, marshall &)> handler;
290 // Automatic marshalling wrappers for RPC handlers
294 // C++11 does neither of these two things for us:
295 // 1) Declare variables using a parameter pack expansion, like so
297 // 2) Call a function with a std::tuple of the arguments it expects
299 // We implement an 'invoke' function for functions of the RPC handler
300 // signature, i.e. int(R & r, const Args...)
302 // One thing we need in order to accomplish this is a way to cause the compiler
303 // to specialize 'invoke' with a parameter pack containing a list of indices
304 // for the elements of the tuple. This will allow us to call the underlying
305 // function with the exploded contents of the tuple. The empty type
306 // tuple_indices<size_t...> accomplishes this. It will be passed in to
307 // 'invoke' as a parameter which will be ignored, but its type will force the
308 // compiler to specialize 'invoke' appropriately.
310 // The following implementation of tuple_indices is redistributed under the MIT
311 // License as an insubstantial portion of the LLVM compiler infrastructure.
313 template <size_t...> struct tuple_indices {};
314 template <size_t S, class IntTuple, size_t E> struct make_indices_imp;
315 template <size_t S, size_t ...Indices, size_t E> struct make_indices_imp<S, tuple_indices<Indices...>, E> {
316 typedef typename make_indices_imp<S+1, tuple_indices<Indices..., S>, E>::type type;
318 template <size_t E, size_t ...Indices> struct make_indices_imp<E, tuple_indices<Indices...>, E> {
319 typedef tuple_indices<Indices...> type;
321 template <size_t E, size_t S=0> struct make_tuple_indices {
322 typedef typename make_indices_imp<S, tuple_indices<>, E>::type type;
325 // This class encapsulates the default response to runtime unmarshalling
326 // failures. The templated wrappers below may optionally use a different
329 struct VerifyOnFailure {
330 static inline int unmarshall_args_failure() {
336 // Here's the implementation of 'invoke'. It could be more general, but this
339 // One for function pointers...
341 template <class F, class R, class RV, class args_type, size_t ...Indices>
342 typename std::enable_if<!std::is_member_function_pointer<F>::value, RV>::type
343 invoke(RV, F f, void *, R & r, args_type & t, tuple_indices<Indices...>) {
344 return f(r, std::move(std::get<Indices>(t))...);
347 // And one for pointers to member functions...
349 template <class F, class C, class RV, class R, class args_type, size_t ...Indices>
350 typename std::enable_if<std::is_member_function_pointer<F>::value, RV>::type
351 invoke(RV, F f, C *c, R & r, args_type & t, tuple_indices<Indices...>) {
352 return (c->*f)(r, std::move(std::get<Indices>(t))...);
355 // The class marshalled_func_imp uses partial template specialization to
356 // implement the ::wrap static function. ::wrap takes a function pointer or a
357 // pointer to a member function and returns a handler * object which
358 // unmarshalls arguments, verifies successful unmarshalling, calls the supplied
359 // function, and marshalls the response.
361 template <class Functor, class Instance, class Signature,
362 class ErrorHandler=VerifyOnFailure> struct marshalled_func_imp;
364 // Here we specialize on the Signature template parameter to obtain the list of
365 // argument types. Note that we do not assume that the Functor parameter has
366 // the same pattern as Signature; this allows us to ignore the distinctions
367 // between various types of callable objects at this level of abstraction.
369 template <class F, class C, class ErrorHandler, class R, class RV, class... Args>
370 struct marshalled_func_imp<F, C, RV(R&, Args...), ErrorHandler> {
371 static inline handler *wrap(F f, C *c=nullptr) {
372 // This type definition corresponds to an empty struct with
373 // template parameters running from 0 up to (# args) - 1.
374 using Indices = typename make_tuple_indices<sizeof...(Args)>::type;
375 // This type definition represents storage for f's unmarshalled
376 // arguments. std::decay is (most notably) stripping off const
378 using ArgsStorage = std::tuple<typename std::decay<Args>::type...>;
379 // Allocate a handler (i.e. std::function) to hold the lambda
380 // which will unmarshall RPCs and call f.
381 return new handler([=](unmarshall &u, marshall &m) -> RV {
382 // Unmarshall each argument with the correct type and store the
383 // result in a tuple.
384 ArgsStorage t = {u.grab<typename std::decay<Args>::type>()...};
385 // Verify successful unmarshalling of the entire input stream.
387 return (RV)ErrorHandler::unmarshall_args_failure();
388 // Allocate space for the RPC response -- will be passed into the
389 // function as an lvalue reference.
391 // Perform the invocation. Note that Indices() calls the default
392 // constructor of the empty struct with the special template
394 RV b = invoke(RV(), f, c, r, t, Indices());
395 // Marshall the response.
403 // More partial template specialization shenanigans to reduce the number of
404 // parameters which must be provided explicitly and to support a few common
405 // callable types. C++11 doesn't allow partial function template
406 // specialization, so we use classes (structs).
408 template <class Functor, class ErrorHandler=VerifyOnFailure,
409 class Signature=Functor> struct marshalled_func;
411 template <class F, class ErrorHandler, class RV, class... Args>
412 struct marshalled_func<F, ErrorHandler, RV(*)(Args...)> :
413 public marshalled_func_imp<F, void, RV(Args...), ErrorHandler> {};
415 template <class F, class ErrorHandler, class RV, class C, class... Args>
416 struct marshalled_func<F, ErrorHandler, RV(C::*)(Args...)> :
417 public marshalled_func_imp<F, C, RV(Args...), ErrorHandler> {};
419 template <class F, class ErrorHandler, class Signature>
420 struct marshalled_func<F, ErrorHandler, std::function<Signature>> :
421 public marshalled_func_imp<F, void, Signature, ErrorHandler> {};