wasm_interface.cpp 45.1 KB
Newer Older
B
Bart Wyatt 已提交
1 2
#include <eosio/chain/wasm_interface.hpp>
#include <eosio/chain/apply_context.hpp>
3
#include <eosio/chain/chain_controller.hpp>
4
#include <eosio/chain/producer_schedule.hpp>
5
#include <eosio/chain/asset.hpp>
6
#include <eosio/chain/exceptions.hpp>
D
Daniel Larimer 已提交
7
#include <boost/core/ignore_unused.hpp>
8
#include <boost/multiprecision/cpp_bin_float.hpp>
9 10
#include <eosio/chain/wasm_interface_private.hpp>
#include <fc/exception/exception.hpp>
11 12
#include <fc/crypto/sha256.hpp>
#include <fc/utf8.hpp>
D
Daniel Larimer 已提交
13 14 15

#include <Runtime/Runtime.h>
#include "IR/Module.h"
16 17 18 19
#include "Platform/Platform.h"
#include "WAST/WAST.h"
#include "IR/Operators.h"
#include "IR/Validate.h"
20
#include "IR/Types.h"
21 22 23
#include "Runtime/Runtime.h"
#include "Runtime/Linker.h"
#include "Runtime/Intrinsics.h"
D
Daniel Larimer 已提交
24

25 26 27
#include <boost/asio.hpp>
#include <boost/bind.hpp>

28
#include <mutex>
29 30
#include <thread>
#include <condition_variable>
B
Bucky Kittinger 已提交
31
#include <iostream>
32

33 34
using namespace IR;
using namespace Runtime;
35
using boost::asio::io_service;
D
Daniel Larimer 已提交
36

37
#if 0
B
Brian Johnson 已提交
38 39 40 41 42 43 44 45
   // account.h/hpp expected account API balance interchange format
   // must match account.hpp account_balance definition
   PACKED_STRUCT(
   struct account_balance
   {
      /**
      * Name of the account who's balance this is
      */
46
      eosio::chain::account_name account;
B
Brian Johnson 已提交
47 48 49 50

      /**
      * Balance for this account
      */
51
      eosio::chain::asset eos_balance;
B
Brian Johnson 已提交
52 53 54 55

      /**
      * Staked balance for this account
      */
56
      eosio::chain::asset staked_balance;
B
Brian Johnson 已提交
57 58 59 60

      /**
      * Unstaking balance for this account
      */
61
      eosio::chain::asset unstaking_balance;
B
Brian Johnson 已提交
62 63 64 65

      /**
      * Time at which last unstaking occurred for this account
      */
66
      eosio::chain::time last_unstaking_time;
B
Brian Johnson 已提交
67
   })
68
#endif
B
Brian Johnson 已提交
69

70
namespace eosio { namespace chain {
71
   using namespace contracts;
72

73 74 75
   /**
    * Integration with the WASM Linker to resolve our intrinsics
    */
D
Daniel Larimer 已提交
76
   struct root_resolver : Runtime::Resolver
77
   {
78 79
      bool resolve(const string& mod_name,
                   const string& export_name,
D
Daniel Larimer 已提交
80 81
                   ObjectType type,
                   ObjectInstance*& out) override
82
      {
83 84 85
         // Try to resolve an intrinsic first.
         if(IntrinsicResolver::singleton.resolve(mod_name,export_name,type, out)) {
            return true;
86
         }
87 88

         FC_ASSERT( !"unresolvable", "${module}.${export}", ("module",mod_name)("export",export_name) );
89
         return false;
90
      }
D
Daniel Larimer 已提交
91
   };
M
Matias Romeo 已提交
92

93 94 95 96 97 98 99 100
   /**
    *  Implementation class for the wasm cache
    *  it is responsible for compiling and storing instances of wasm code for use
    *
    */
   struct wasm_cache_impl {
      wasm_cache_impl()
      {
101
         Runtime::init();
102
      }
M
Matias Romeo 已提交
103

104 105 106 107 108 109 110 111
      /**
       * this must wait for all work to be done otherwise it may destroy memory
       * referenced by other threads
       *
       * Expectations on wasm_cache dictate that all available code has been
       * returned before this can be destroyed
       */
      ~wasm_cache_impl() {
112
         freeUnreferencedObjects({});
113
      }
M
Matias Romeo 已提交
114

115 116 117 118 119 120 121 122 123 124 125 126 127
      /**
       * internal tracking structure which deduplicates memory images
       * and tracks available vs in-use entries.
       *
       * The instances array has two sections, "available" instances
       * are in the front of the vector and anything at an index of
       * available_instances or greater is considered "in use"
       *
       * instances are stored as pointers so that their positions
       * in the array can be moved without invaliding references to
       * the instance handed out to other threads
       */
      struct code_info {
128 129 130 131
         code_info( size_t mem_end, vector<char>&& mem_image )
         :mem_end(mem_end),mem_image(std::forward<vector<char>>(mem_image))
         {}

132 133 134 135 136 137 138 139 140 141
         // a clean image of the memory used to sanitize things on checkin
         size_t mem_start           = 0;
         size_t mem_end             = 1<<16;
         vector<char> mem_image;

         // all existing instances of this code
         vector<unique_ptr<wasm_cache::entry>> instances;
         size_t available_instances = 0;
      };

142 143 144
      using optional_info_ref = optional<std::reference_wrapper<code_info>>;
      using optional_entry_ref = optional<std::reference_wrapper<wasm_cache::entry>>;

145 146 147 148 149 150 151 152
      /**
       * Convenience method for running code with the _cache_lock and releaseint that lock
       * when the code completes
       *
       * @param f - lambda to execute
       * @return - varies depending on the signature of the lambda
       */
      template<typename F>
153 154
      auto with_lock(std::mutex &l, F f) {
         std::lock_guard<std::mutex> lock(l);
155 156 157 158 159 160 161 162 163
         return f();
      };

      /**
       * Fetch the tracking struct given a code_id if it exists
       *
       * @param code_id
       * @return
       */
164
      optional_info_ref fetch_info(const digest_type& code_id) {
165
         return with_lock(_cache_lock, [&,this](){
166 167
            auto iter = _cache.find(code_id);
            if (iter != _cache.end()) {
168
               return optional_info_ref(iter->second);
169 170
            }

171
            return optional_info_ref();
172 173
         });
      }
M
Matias Romeo 已提交
174

175 176 177 178 179
      /**
       * Opportunistically fetch an available instance of the code;
       * @param code_id - the id of the code to fetch
       * @return - reference to the entry when one is available
       */
180
      optional_entry_ref try_fetch_entry(const digest_type& code_id) {
181
         return with_lock(_cache_lock, [&,this](){
182 183
            auto iter = _cache.find(code_id);
            if (iter != _cache.end() && iter->second.available_instances > 0) {
184
               auto &ptr = iter->second.instances.at(--(iter->second.available_instances));
185
               return optional_entry_ref(*ptr);
186 187
            }

188
            return optional_entry_ref();
189
         });
D
Daniel Larimer 已提交
190
      }
M
Matias Romeo 已提交
191

192 193 194 195 196 197 198 199 200 201 202 203
      /**
       * Fetch a copy of the code, this is guaranteed to return an entry IF the code is compilable.
       * In order to do that in safe way this code may cause the calling thread to sleep while a new
       * version of the code is compiled and inserted into the cache
       *
       * @param code_id - the id of the code to fetch
       * @param wasm_binary - the binary for the wasm
       * @param wasm_binary_size - the size of the binary
       * @return reference to a usable cache entry
       */
      wasm_cache::entry& fetch_entry(const digest_type& code_id, const char* wasm_binary, size_t wasm_binary_size) {
         std::condition_variable condition;
204
         optional_entry_ref result;
205 206 207 208
         std::exception_ptr error;

         // compilation is not thread safe, so we dispatch it to a io_service running on a single thread to
         // queue up and synchronize compilations
209
         with_lock(_compile_lock, [&,this](){
210 211 212 213 214 215
            // check to see if someone returned what we need before making a new one
            auto pending_result = try_fetch_entry(code_id);
            std::exception_ptr pending_error;

            if (!pending_result) {
               // time to compile a brand new (maybe first) copy of this code
216 217
               Module* module = new Module();
               ModuleInstance* instance = nullptr;
218
               size_t mem_end = 0;
219 220 221 222
               vector<char> mem_image;

               try {
                  Serialization::MemoryInputStream stream((const U8 *) wasm_binary, wasm_binary_size);
223 224
                  #warning TODO: restore checktime injection?
                  WASM::serialize(stream, *module);
225 226

                  root_resolver resolver;
227 228
                  LinkResult link_result = linkModule(*module, resolver);
                  instance = instantiateModule(*module, std::move(link_result.resolvedImports));
229 230
                  FC_ASSERT(instance != nullptr);

231
                  MemoryInstance* current_memory = Runtime::getDefaultMemory(instance);
232

233 234 235 236 237 238
                  if(current_memory) {
                     char *mem_ptr = &memoryRef<char>(current_memory, 0);
                     const auto allocated_memory = Runtime::getDefaultMemorySize(instance);
                     for (uint64_t i = 0; i < allocated_memory; ++i) {
                        if (mem_ptr[i])
                           mem_end = i + 1;
239
                     }
240 241
                     mem_image.resize(mem_end);
                     memcpy(mem_image.data(), mem_ptr, mem_end);
242
                  }
243
                  
244 245 246 247 248 249
               } catch (...) {
                  pending_error = std::current_exception();
               }

               if (pending_error == nullptr) {
                  // grab the lock and put this in the cache as unavailble
250
                  with_lock(_cache_lock, [&,this]() {
251
                     // find or create a new entry
252
                     auto iter = _cache.emplace(code_id, code_info(mem_end, std::move(mem_image))).first;
253

254 255
                     iter->second.instances.emplace_back(std::make_unique<wasm_cache::entry>(instance, module));
                     pending_result = optional_entry_ref(*iter->second.instances.back().get());
256 257 258 259
                  });
               }
            }

260 261 262 263 264
           if (pending_error != nullptr) {
              error = pending_error;
           } else {
              result = pending_result;
           }
265

266 267
         });

268

269 270 271 272
         try {
            if (error != nullptr) {
               std::rethrow_exception(error);
            } else {
273
               return (*result).get();
274 275
            }
         } FC_RETHROW_EXCEPTIONS(error, "error compiling WASM for code with hash: ${code_id}", ("code_id", code_id));
D
Daniel Larimer 已提交
276
      }
277

278 279 280 281 282 283 284 285 286
      /**
       * return an entry to the cache.  The entry is presumed to come back in a "dirty" state and must be
       * sanitized before returning to the "available" state.  This sanitization is done asynchronously so
       * as not to delay the current executing thread.
       *
       * @param code_id - the code Id associated with the instance
       * @param entry - the entry to return
       */
      void return_entry(const digest_type& code_id, wasm_cache::entry& entry) {
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311
        // sanitize by reseting the memory that may now be dirty
        auto& info = (*fetch_info(code_id)).get();
        if(getDefaultMemory(entry.instance)) {
           char* memstart = &memoryRef<char>( getDefaultMemory(entry.instance), 0 );
           memset( memstart + info.mem_end, 0, ((1<<16) - info.mem_end) );
           memcpy( memstart, info.mem_image.data(), info.mem_end);
        }
        resetGlobalInstances(entry.instance);

        // under a lock, put this entry back in the available instances side of the instances vector
        with_lock(_cache_lock, [&,this](){
           // walk the vector and find this entry
           auto iter = info.instances.begin();
           while (iter->get() != &entry) {
              ++iter;
           }

           FC_ASSERT(iter != info.instances.end(), "Checking in a WASM enty that was not created properly!");

           auto first_unavailable = (info.instances.begin() + info.available_instances);
           if (iter != first_unavailable) {
              std::swap(iter, first_unavailable);
           }
           info.available_instances++;
        });
D
Daniel Larimer 已提交
312
      }
313

314 315 316
      // mapping of digest to an entry for the code
      map<digest_type, code_info> _cache;
      std::mutex _cache_lock;
B
Brian Johnson 已提交
317

318 319
      // compilation lock
      std::mutex _compile_lock;
320
   };
B
Brian Johnson 已提交
321

322 323 324
   wasm_cache::wasm_cache()
      :_my( new wasm_cache_impl() ) {
   }
325

326 327
   wasm_cache::~wasm_cache() = default;

328
   wasm_cache::entry &wasm_cache::checkout( const digest_type& code_id, const char* wasm_binary, size_t wasm_binary_size ) {
329
      // see if there is an available entry in the cache
330
      auto result = _my->try_fetch_entry(code_id);
331
      if (result) {
332
         return (*result).get();
D
Daniel Larimer 已提交
333
      }
334 335 336 337 338
      return _my->fetch_entry(code_id, wasm_binary, wasm_binary_size);
   }


   void wasm_cache::checkin(const digest_type& code_id, entry& code ) {
339 340 341
      MemoryInstance* default_mem = Runtime::getDefaultMemory(code.instance);
      if(default_mem)
         Runtime::shrinkMemory(default_mem, Runtime::getMemoryNumPages(default_mem) - 1);
342
      _my->return_entry(code_id, code);
343
   }
344

345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362
   /**
    * RAII wrapper to make sure that the context is cleaned up on exception
    */
   struct scoped_context {
      template<typename ...Args>
      scoped_context(optional<wasm_context> &context, Args&... args)
      :context(context)
      {
         context = wasm_context{ args... };
      }

      ~scoped_context() {
         context.reset();
      }

      optional<wasm_context>& context;
   };

363
   void wasm_interface_impl::call(const string& entry_point, const vector<Value>& args, wasm_cache::entry& code, apply_context& context)
364
   try {
365
      FunctionInstance* call = asFunctionNullable(getInstanceExport(code.instance,entry_point) );
366 367 368 369
      if( !call ) {
         return;
      }

370
      FC_ASSERT( getFunctionType(call)->parameters.size() == args.size() );
371

372
      auto context_guard = scoped_context(current_context, code, context);
373
      runInstanceStartFunc(code.instance);
374 375 376 377 378 379 380 381 382 383 384 385
      Runtime::invokeFunction(call,args);
   } catch( const Runtime::Exception& e ) {
      FC_THROW_EXCEPTION(wasm_execution_error,
                         "cause: ${cause}\n${callstack}",
                         ("cause", string(describeExceptionCause(e.cause)))
                         ("callstack", e.callStack));
   } FC_CAPTURE_AND_RETHROW()

   wasm_interface::wasm_interface()
      :my( new wasm_interface_impl() ) {
   }

386 387 388 389 390 391 392 393
   wasm_interface& wasm_interface::get() {
      thread_local wasm_interface* single = nullptr;
      if( !single ) {
         single = new wasm_interface();
      }
      return *single;
   }

394
   void wasm_interface::apply( wasm_cache::entry& code, apply_context& context ) {
395 396 397
      vector<Value> args = {Value(uint64_t(context.act.account)),
                            Value(uint64_t(context.act.name))};
      my->call("apply", args, code, context);
398 399 400 401 402
   }

   void wasm_interface::error( wasm_cache::entry& code, apply_context& context ) {
      vector<Value> args = { /* */ };
      my->call("error", args, code, context);
403 404
   }

405
#if defined(assert)
406
   #undef assert
407 408
#endif

B
Bart Wyatt 已提交
409
class context_aware_api {
410
   public:
B
Bart Wyatt 已提交
411
      context_aware_api(wasm_interface& wasm)
412 413
      :context(intrinsics_accessor::get_context(wasm).context), code(intrinsics_accessor::get_context(wasm).code),
       sbrk_bytes(intrinsics_accessor::get_context(wasm).sbrk_bytes)
414 415
      {}

B
Bart Wyatt 已提交
416
   protected:
B
Bucky Kittinger 已提交
417
      apply_context&     context;
418 419
      wasm_cache::entry& code;
      uint32_t&          sbrk_bytes;
B
Bart Wyatt 已提交
420 421
};

B
Bucky Kittinger 已提交
422
class chain_api : public context_aware_api {
423 424
   public:
      using context_aware_api::context_aware_api;
425 426
   
      int32_t get_active_producers(array_ptr<chain::account_name> producers, size_t datalen) {
B
Bucky Kittinger 已提交
427
         auto active_prods = context.get_active_producers();
428
         size_t len = std::min(datalen, active_prods.size() * sizeof(chain::account_name));
B
Bucky Kittinger 已提交
429 430
         memcpy(producers, active_prods.data(), len);
         return active_prods.size() * sizeof(chain::account_name);
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
      }
};

class crypto_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

      void assert_sha256(array_ptr<char> data, size_t datalen, const fc::sha256& hash_val) {
         auto result = fc::sha256::hash( data, datalen );
         FC_ASSERT( result == hash_val, "hash miss match" );
      }

      void sha256(array_ptr<char> data, size_t datalen, fc::sha256& hash_val) {
         hash_val = fc::sha256::hash( data, datalen );
      }
};

class string_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

      void assert_is_utf8(array_ptr<const char> str, size_t datalen, null_terminated_ptr msg) {
         const bool test = fc::is_utf8(std::string( str, datalen ));

         FC_ASSERT( test, "assertion failed: ${s}", ("s",msg.value) );
      }
};
458

B
Bart Wyatt 已提交
459 460 461 462
class system_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

463
      void assert(bool condition, null_terminated_ptr str) {
B
Bart Wyatt 已提交
464 465 466 467
         std::string message( str );
         if( !condition ) edump((message));
         FC_ASSERT( condition, "assertion failed: ${s}", ("s",message));
      }
B
Bucky Kittinger 已提交
468
      
469 470
      fc::time_point_sec now() {
         return context.controller.head_block_time();
471 472 473
      } 
};

B
Bart Wyatt 已提交
474 475 476 477
class action_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

478 479
      int read_action(array_ptr<char> memory, size_t size) {
         FC_ASSERT(size > 0);
480
         int minlen = std::min<size_t>(context.act.data.size(), size);
481 482 483 484
         memcpy((void *)memory, context.act.data.data(), minlen);
         return minlen;
      }

B
Bart Wyatt 已提交
485 486
      int action_size() {
         return context.act.data.size();
487 488
      }

B
Bart Wyatt 已提交
489 490 491
      const name& current_receiver() {
         return context.receiver;
      }
492 493

      fc::time_point_sec publication_time() {
B
Bart Wyatt 已提交
494
         return context.trx_meta.published;
495 496 497
      }

      name current_sender() {
B
Bart Wyatt 已提交
498 499
         if (context.trx_meta.sender) {
            return *context.trx_meta.sender;
500 501 502 503
         } else {
            return name();
         }
      }
504
};
B
Brian Johnson 已提交
505

B
Bart Wyatt 已提交
506 507 508 509
class console_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

510 511
      void prints(null_terminated_ptr str) {
         context.console_append<const char*>(str);
B
Bart Wyatt 已提交
512 513 514
      }

      void prints_l(array_ptr<const char> str, size_t str_len ) {
515
         context.console_append(string(str, str_len));
B
Bart Wyatt 已提交
516 517 518
      }

      void printi(uint64_t val) {
519
         context.console_append(val);
B
Bart Wyatt 已提交
520 521 522 523
      }

      void printi128(const unsigned __int128& val) {
         fc::uint128_t v(val>>64, uint64_t(val) );
524
         context.console_append(fc::variant(v).get_string());
B
Bart Wyatt 已提交
525 526 527
      }

      void printd( wasm_double val ) {
528
         context.console_append(val.str());
B
Bart Wyatt 已提交
529 530 531
      }

      void printn(const name& value) {
532
         context.console_append(value.to_string());
B
Bart Wyatt 已提交
533 534 535
      }

      void printhex(array_ptr<const char> data, size_t data_len ) {
536
         context.console_append(fc::to_hex(data, data_len));
B
Bart Wyatt 已提交
537 538 539
      }
};

540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
template<typename ObjectType>
class db_api : public context_aware_api {
   using KeyType = typename ObjectType::key_type;
   static constexpr int KeyCount = ObjectType::number_of_keys;
   using KeyArrayType = KeyType[KeyCount];
   using ContextMethodType = int(apply_context::*)(const table_id_object&, const KeyType*, const char*, size_t);

   private:
      int call(ContextMethodType method, const scope_name& scope, const name& table, array_ptr<const char> data, size_t data_len) {
         const auto& t_id = context.find_or_create_table(scope, context.receiver, table);
         FC_ASSERT(data_len >= KeyCount * sizeof(KeyType), "Data is not long enough to contain keys");
         const KeyType* keys = reinterpret_cast<const KeyType *>((const char *)data);

         const char* record_data =  ((const char*)data) + sizeof(KeyArrayType);
         size_t record_len = data_len - sizeof(KeyArrayType);
B
Bucky Kittinger 已提交
555
         return (context.*(method))(t_id, keys, record_data, record_len); 
556 557 558 559 560 561
      }

   public:
      using context_aware_api::context_aware_api;

      int store(const scope_name& scope, const name& table, array_ptr<const char> data, size_t data_len) {
562 563 564
         auto res = call(&apply_context::store_record<ObjectType>, scope, table, data, data_len);
         return res;

565 566 567 568 569
      }

      int update(const scope_name& scope, const name& table, array_ptr<const char> data, size_t data_len) {
         return call(&apply_context::update_record<ObjectType>, scope, table, data, data_len);
      }
B
Bucky Kittinger 已提交
570
      
571 572 573 574 575 576
      int remove(const scope_name& scope, const name& table, const KeyArrayType &keys) {
         const auto& t_id = context.find_or_create_table(scope, context.receiver, table);
         return context.remove_record<ObjectType>(t_id, keys);
      }
};

B
Bucky Kittinger 已提交
577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592
template<>
class db_api<keystr_value_object> : public context_aware_api {
   using KeyType = std::string;
   static constexpr int KeyCount = 1;
   using KeyArrayType = KeyType[KeyCount];
   using ContextMethodType = int(apply_context::*)(const table_id_object&, const KeyType*, const char*, size_t);

   private:
      int call(ContextMethodType method, const scope_name& scope, const name& table, 
            array_ptr<const char> key, size_t key_len, array_ptr<const char> data, size_t data_len) {
         const auto& t_id = context.find_or_create_table(scope, context.receiver, table);
         //FC_ASSERT(data_len >= KeyCount * sizeof(KeyType), "Data is not long enough to contain keys");
         const KeyType keys((const char*)key, key_len); // = std::string(reinterpret_cast<const KeyType *>((const char *)data);

         const char* record_data =  ((const char*)data); // + sizeof(KeyArrayType);
         size_t record_len = data_len; // - sizeof(KeyArrayType);
B
Bucky Kittinger 已提交
593
         return (context.*(method))(t_id, &keys, record_data, record_len);
B
Bucky Kittinger 已提交
594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617
      }

   public:
      using context_aware_api::context_aware_api;

      int store_str(const scope_name& scope, const name& table, 
            array_ptr<const char> &key, uint32_t key_len, array_ptr<const char> data, size_t data_len) {
         auto res = call(&apply_context::store_record<keystr_value_object>, scope, table, key, key_len, data, data_len);
         return res;

      }

      int update_str(const scope_name& scope, const name& table, 
            array_ptr<const char> &key, uint32_t key_len, array_ptr<const char> data, size_t data_len) {
         return call(&apply_context::update_record<keystr_value_object>, scope, table, key, key_len, data, data_len);
      }
      
      int remove_str(const scope_name& scope, const name& table, array_ptr<const char> &key, uint32_t key_len) {
         const auto& t_id = context.find_or_create_table(scope, context.receiver, table);
         const KeyArrayType k = {std::string(key, key_len)};
         return context.remove_record<keystr_value_object>(t_id, k);
      }
};

618 619 620 621 622 623 624 625 626 627 628
template<typename IndexType, typename Scope>
class db_index_api : public context_aware_api {
   using KeyType = typename IndexType::value_type::key_type;
   static constexpr int KeyCount = IndexType::value_type::number_of_keys;
   using KeyArrayType = KeyType[KeyCount];
   using ContextMethodType = int(apply_context::*)(const table_id_object&, KeyType*, char*, size_t);


   int call(ContextMethodType method, const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
      auto maybe_t_id = context.find_table(scope, context.receiver, table);
      if (maybe_t_id == nullptr) {
B
Bucky Kittinger 已提交
629
         return 0;
630 631 632 633 634 635 636 637 638
      }

      const auto& t_id = *maybe_t_id;
      FC_ASSERT(data_len >= KeyCount * sizeof(KeyType), "Data is not long enough to contain keys");
      KeyType* keys = reinterpret_cast<KeyType *>((char *)data);

      char* record_data =  ((char*)data) + sizeof(KeyArrayType);
      size_t record_len = data_len - sizeof(KeyArrayType);

639
      auto res = (context.*(method))(t_id, keys, record_data, record_len);
B
Bucky Kittinger 已提交
640
      if (res != 0) {
641 642 643
         res += sizeof(KeyArrayType);
      }
      return res;
644 645 646 647 648 649
   }

   public:
      using context_aware_api::context_aware_api;

      int load(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
650 651
         auto res = call(&apply_context::load_record<IndexType, Scope>, scope, code, table, data, data_len);
         return res;
652 653 654
      }

      int front(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
B
Bucky Kittinger 已提交
655
         auto res = call(&apply_context::front_record<IndexType, Scope>, scope, code, table, data, data_len);
B
Bucky Kittinger 已提交
656
         return res;
657 658 659
      }

      int back(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
B
Bucky Kittinger 已提交
660
         auto res = call(&apply_context::back_record<IndexType, Scope>, scope, code, table, data, data_len);
B
Bucky Kittinger 已提交
661
         return res;
662 663 664
      }

      int next(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
B
Bucky Kittinger 已提交
665
         auto res = call(&apply_context::next_record<IndexType, Scope>, scope, code, table, data, data_len);
B
Bucky Kittinger 已提交
666
         return res;
667 668 669
      }

      int previous(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
B
Bucky Kittinger 已提交
670
         auto res = call(&apply_context::previous_record<IndexType, Scope>, scope, code, table, data, data_len);
B
Bucky Kittinger 已提交
671
         return res;
672 673 674
      }

      int lower_bound(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
B
Bucky Kittinger 已提交
675
         auto res = call(&apply_context::lower_bound_record<IndexType, Scope>, scope, code, table, data, data_len);
B
Bucky Kittinger 已提交
676
         return res;
677 678 679
      }

      int upper_bound(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
B
Bucky Kittinger 已提交
680
         auto res = call(&apply_context::upper_bound_record<IndexType, Scope>, scope, code, table, data, data_len);
B
Bucky Kittinger 已提交
681
         return res;
682 683 684 685
      }

};

B
Bucky Kittinger 已提交
686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
template<>
class db_index_api<keystr_value_index, by_scope_primary> : public context_aware_api {
   using KeyType = std::string;
   static constexpr int KeyCount = 1;
   using KeyArrayType = KeyType[KeyCount];
   using ContextMethodType = int(apply_context::*)(const table_id_object&, KeyType*, char*, size_t);


   int call(ContextMethodType method, const scope_name& scope, const account_name& code, const name& table, 
         array_ptr<char> &key, uint32_t key_len, array_ptr<char> data, size_t data_len) {
      auto maybe_t_id = context.find_table(scope, context.receiver, table);
      if (maybe_t_id == nullptr) {
         return 0;
      }

      const auto& t_id = *maybe_t_id;
      //FC_ASSERT(data_len >= KeyCount * sizeof(KeyType), "Data is not long enough to contain keys");
      KeyType keys((const char*)key, key_len); // = reinterpret_cast<KeyType *>((char *)data);

      char* record_data =  ((char*)data); // + sizeof(KeyArrayType);
      size_t record_len = data_len; // - sizeof(KeyArrayType);

      return (context.*(method))(t_id, &keys, record_data, record_len); // + sizeof(KeyArrayType);
   }

   public:
      using context_aware_api::context_aware_api;

      int load_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         auto res = call(&apply_context::load_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
         return res;
      }

      int front_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::front_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
      }

      int back_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::back_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
      }

      int next_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::next_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
      }

      int previous_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::previous_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
      }

      int lower_bound_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::lower_bound_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
      }

      int upper_bound_str(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> key, size_t key_len, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::upper_bound_record<keystr_value_index, by_scope_primary>, scope, code, table, key, key_len, data, data_len);
      }

};

745
class memory_api : public context_aware_api {
746
   public:
B
Bucky Kittinger 已提交
747
      using context_aware_api::context_aware_api;
748
     
749 750 751 752 753 754 755 756
      char* memcpy( array_ptr<char> dest, array_ptr<const char> src, size_t length) {
         return (char *)::memcpy(dest, src, length);
      }

      int memcmp( array_ptr<const char> dest, array_ptr<const char> src, size_t length) {
         return ::memcmp(dest, src, length);
      }

B
Bucky Kittinger 已提交
757
      char* memset( array_ptr<char> dest, int value, size_t length ) {
B
Bucky Kittinger 已提交
758
         return (char *)::memset( dest, value, length );
B
Bucky Kittinger 已提交
759 760 761
      }

      uint32_t sbrk(int num_bytes) {
762 763 764
         // sbrk should only allow for memory to grow
         if (num_bytes < 0)
            throw eosio::chain::page_memory_error();
B
Bucky Kittinger 已提交
765
         // TODO: omitted checktime function from previous version of sbrk, may need to be put back in at some point
766 767 768
         constexpr uint32_t NBPPL2  = IR::numBytesPerPageLog2;
         constexpr uint32_t MAX_MEM = 1024 * 1024;

769 770 771 772 773 774 775
         MemoryInstance*  default_mem    = Runtime::getDefaultMemory(code.instance);
         if(!default_mem)
            throw eosio::chain::page_memory_error();

         const uint32_t         num_pages      = Runtime::getMemoryNumPages(default_mem);
         const uint32_t         min_bytes      = (num_pages << NBPPL2) > UINT32_MAX ? UINT32_MAX : num_pages << NBPPL2;
         const uint32_t         prev_num_bytes = sbrk_bytes; //_num_bytes;
776
         
B
Bucky Kittinger 已提交
777 778 779
         // round the absolute value of num_bytes to an alignment boundary
         num_bytes = (num_bytes + 7) & ~7;

780
         if ((num_bytes > 0) && (prev_num_bytes > (MAX_MEM - num_bytes)))  // test if allocating too much memory (overflowed)
B
Bucky Kittinger 已提交
781 782 783 784 785
            throw eosio::chain::page_memory_error();
         else if ((num_bytes < 0) && (prev_num_bytes < (min_bytes - num_bytes))) // test for underflow
            throw eosio::chain::page_memory_error(); 

         // update the number of bytes allocated, and compute the number of pages needed
786 787
         sbrk_bytes += num_bytes;
         const uint32_t num_desired_pages = (sbrk_bytes + IR::numBytesPerPage - 1) >> NBPPL2;
B
Bucky Kittinger 已提交
788 789 790 791 792 793 794 795

         // grow or shrink the memory to the desired number of pages
         if (num_desired_pages > num_pages)
            Runtime::growMemory(default_mem, num_desired_pages - num_pages);
         else if (num_desired_pages < num_pages)
            Runtime::shrinkMemory(default_mem, num_pages - num_desired_pages);

         return prev_num_bytes;
796
      }
797 798
};

799 800 801 802
class transaction_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

803 804 805 806 807 808 809 810 811 812
      int read_transaction( array_ptr<char> data, size_t data_len ) {
         bytes trx = context.get_packed_transaction();
         if (data_len >= trx.size()) {
            memcpy(data, trx.data(), trx.size());
         }
         return trx.size();
      }

      int transaction_size() {
         return context.get_packed_transaction().size();
813 814 815 816 817 818 819 820 821
      }

      int expiration() {
        return context.trx_meta.trx.expiration.sec_since_epoch();
      }

      int tapos_block_num() {
        return context.trx_meta.trx.ref_block_num;
      }
822
      int tapos_block_prefix() {
823 824 825
        return context.trx_meta.trx.ref_block_prefix;
      }

826 827 828 829 830 831 832 833 834 835 836
      void send_inline( array_ptr<char> data, size_t data_len ) {
         // TODO: use global properties object for dynamic configuration of this default_max_gen_trx_size
         FC_ASSERT( data_len < config::default_max_inline_action_size, "inline action too big" );

         action act;
         fc::raw::unpack<action>(data, data_len, act);
         context.execute_inline(std::move(act));
      }


      void send_deferred( uint32_t sender_id, const fc::time_point_sec& execute_after, array_ptr<char> data, size_t data_len ) {
837 838 839
         try {
            // TODO: use global properties object for dynamic configuration of this default_max_gen_trx_size
            FC_ASSERT(data_len < config::default_max_gen_trx_size, "generated transaction too big");
840

841 842 843 844 845 846 847
            deferred_transaction dtrx;
            fc::raw::unpack<transaction>(data, data_len, dtrx);
            dtrx.sender = context.receiver;
            dtrx.sender_id = sender_id;
            dtrx.execute_after = execute_after;
            context.execute_deferred(std::move(dtrx));
         } FC_CAPTURE_AND_RETHROW((fc::to_hex(data, data_len)));
848 849 850 851
      }

};

852 853 854
class compiler_builtins : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;
855 856 857
      void __break_point() {
         __asm("int3\n");
      }
858
      void __ashlti3(__int128& ret, uint64_t low, uint64_t high, uint32_t shift) {
859 860 861 862 863
         fc::uint128_t i(high, low);
         i <<= shift;
         ret = (unsigned __int128)i;
      }

864
      void __ashrti3(__int128& ret, uint64_t low, uint64_t high, uint32_t shift) {
B
oops  
Bucky Kittinger 已提交
865 866 867 868 869
         // retain the signedness
         ret = high;
         ret <<= 64;
         ret |= low;
         ret >>= shift;
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884
      }

      void __lshlti3(__int128& ret, uint64_t low, uint64_t high, uint32_t shift) {
         fc::uint128_t i(high, low);
         i <<= shift;
         ret = (unsigned __int128)i;
      }

      void __lshrti3(__int128& ret, uint64_t low, uint64_t high, uint32_t shift) {
         fc::uint128_t i(high, low);
         i >>= shift;
         ret = (unsigned __int128)i;
      }
      
      void __divti3(__int128& ret, uint64_t la, uint64_t ha, uint64_t lb, uint64_t hb) {
B
oops  
Bucky Kittinger 已提交
885 886
         __int128 lhs = ha;
         __int128 rhs = hb;
887
         
B
oops  
Bucky Kittinger 已提交
888 889
         lhs <<= 64;
         lhs |=  la;
890

B
oops  
Bucky Kittinger 已提交
891 892
         rhs <<= 64;
         rhs |=  lb;
893

B
oops  
Bucky Kittinger 已提交
894
         FC_ASSERT(rhs != 0, "divide by zero");    
895

B
oops  
Bucky Kittinger 已提交
896
         lhs /= rhs; 
897

B
oops  
Bucky Kittinger 已提交
898
         ret = lhs;
899 900
      } 

B
oops  
Bucky Kittinger 已提交
901 902 903 904 905 906 907 908 909
      void __udivti3(unsigned __int128& ret, uint64_t la, uint64_t ha, uint64_t lb, uint64_t hb) {
         unsigned __int128 lhs = ha;
         unsigned __int128 rhs = hb;
         
         lhs <<= 64;
         lhs |=  la;

         rhs <<= 64;
         rhs |=  lb;
910

B
oops  
Bucky Kittinger 已提交
911
         FC_ASSERT(rhs != 0, "divide by zero");    
912

B
oops  
Bucky Kittinger 已提交
913 914 915 916 917 918 919
         lhs /= rhs; 
         ret = lhs;
      }

      void __multi3(__int128& ret, uint64_t la, uint64_t ha, uint64_t lb, uint64_t hb) {
         __int128 lhs = ha;
         __int128 rhs = hb;
920

B
oops  
Bucky Kittinger 已提交
921 922
         lhs <<= 64;
         lhs |=  la;
923

B
oops  
Bucky Kittinger 已提交
924 925
         rhs <<= 64;
         rhs |=  lb;
926

B
oops  
Bucky Kittinger 已提交
927 928
         lhs *= rhs; 
         ret = lhs;
929
      } 
930 931

      void __modti3(__int128& ret, uint64_t la, uint64_t ha, uint64_t lb, uint64_t hb) {
B
oops  
Bucky Kittinger 已提交
932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957
         __int128 lhs = ha;
         __int128 rhs = hb;

         lhs <<= 64;
         lhs |=  la;
   
         rhs <<= 64;
         rhs |=  lb;
         
         FC_ASSERT(rhs != 0, "divide by zero");

         lhs %= rhs;
         ret = lhs;
      }

      void __umodti3(unsigned __int128& ret, uint64_t la, uint64_t ha, uint64_t lb, uint64_t hb) {
         unsigned __int128 lhs = ha;
         unsigned __int128 rhs = hb;

         lhs <<= 64;
         lhs |=  la;
   
         rhs <<= 64;
         rhs |=  lb;
         
         FC_ASSERT(rhs != 0, "divide by zero");
958

B
oops  
Bucky Kittinger 已提交
959 960
         lhs %= rhs;
         ret = lhs;
961 962
      }

B
Bucky Kittinger 已提交
963
      static constexpr uint32_t SHIFT_WIDTH = (sizeof(uint64_t)*8)-1;
964 965 966 967 968 969 970 971 972 973 974 975 976 977
};

/*
class account_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;
      bool account_balance_get(array_ptr<const char> balance, uint32_t len) {
         const uint32_t account_balance_size = sizeof(account_balance);
         auto mem = Runtime::getDefaultMemory(code.instance);
         FC_ASSERT(len == account_balance_size, "passed in len ${len} is not equal to the size of an account_balance struct == ${real_len}", ("len",len)("real_len",account_balance_size));
         account_balance& total_balance = memoryRef<account_balance>(mem, balance);
      }
};
*/
978

979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041
class math_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;
      

      void diveq_i128(unsigned __int128* self, const unsigned __int128* other) {
         fc::uint128_t s(*self);
         const fc::uint128_t o(*other);
         FC_ASSERT( o != 0, "divide by zero" );
         
         s = s/o;
         *self = (unsigned __int128)s;
      }

      void multeq_i128(unsigned __int128* self, const unsigned __int128* other) {
         fc::uint128_t s(*self);
         const fc::uint128_t o(*other);
         s *= o;
         *self = (unsigned __int128)s;
      }

      uint64_t double_add(uint64_t a, uint64_t b) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         DOUBLE c = DOUBLE(*reinterpret_cast<double *>(&a))
                  + DOUBLE(*reinterpret_cast<double *>(&b));
         double res = c.convert_to<double>();
         return *reinterpret_cast<uint64_t *>(&res);
      }

      uint64_t double_mult(uint64_t a, uint64_t b) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         DOUBLE c = DOUBLE(*reinterpret_cast<double *>(&a))
                  * DOUBLE(*reinterpret_cast<double *>(&b));
         double res = c.convert_to<double>();
         return *reinterpret_cast<uint64_t *>(&res);
      }

      uint64_t double_div(uint64_t a, uint64_t b) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         DOUBLE divisor = DOUBLE(*reinterpret_cast<double *>(&b));
         FC_ASSERT(divisor != 0, "divide by zero");
         DOUBLE c = DOUBLE(*reinterpret_cast<double *>(&a)) / divisor;
         double res = c.convert_to<double>();
         return *reinterpret_cast<uint64_t *>(&res);
      }

      uint32_t double_eq(uint64_t a, uint64_t b) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         return DOUBLE(*reinterpret_cast<double *>(&a)) == DOUBLE(*reinterpret_cast<double *>(&b));
      }

      uint32_t double_lt(uint64_t a, uint64_t b) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         return DOUBLE(*reinterpret_cast<double *>(&a)) < DOUBLE(*reinterpret_cast<double *>(&b));
      }

      uint32_t double_gt(uint64_t a, uint64_t b) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         return DOUBLE(*reinterpret_cast<double *>(&a)) > DOUBLE(*reinterpret_cast<double *>(&b));
      }

      uint64_t double_to_i64(uint64_t n) {
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
B
Bucky Kittinger 已提交
1042
         return DOUBLE(*reinterpret_cast<double *>(&n)).convert_to<int64_t>();
1043 1044
      }

B
Bucky Kittinger 已提交
1045
      uint64_t i64_to_double(int64_t n) {
1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064
         using DOUBLE = boost::multiprecision::cpp_bin_float_50;
         double res = DOUBLE(n).convert_to<double>();
         return *reinterpret_cast<uint64_t *>(&res);
      }
};

REGISTER_INTRINSICS(math_api,
   (diveq_i128,    void(int, int)            )
   (multeq_i128,   void(int, int)            )
   (double_add,    int64_t(int64_t, int64_t) )
   (double_mult,   int64_t(int64_t, int64_t) )
   (double_div,    int64_t(int64_t, int64_t) )
   (double_eq,     int32_t(int64_t, int64_t) )
   (double_lt,     int32_t(int64_t, int64_t) )
   (double_gt,     int32_t(int64_t, int64_t) )
   (double_to_i64, int64_t(int64_t)          )
   (i64_to_double, int64_t(int64_t)          )
);

1065
REGISTER_INTRINSICS(chain_api,
B
Bucky Kittinger 已提交
1066
   (get_active_producers,     int(int, int)  )
1067 1068
);

1069
REGISTER_INTRINSICS(compiler_builtins,
1070
   (__break_point, void()                            )
1071 1072 1073 1074 1075
   (__ashlti3,     void(int, int64_t, int64_t, int)  )
   (__ashrti3,     void(int, int64_t, int64_t, int)  )
   (__lshlti3,     void(int, int64_t, int64_t, int)  )
   (__lshrti3,     void(int, int64_t, int64_t, int)  )
   (__divti3,      void(int, int64_t, int64_t, int64_t, int64_t) )
B
oops  
Bucky Kittinger 已提交
1076 1077 1078
   (__udivti3,      void(int, int64_t, int64_t, int64_t, int64_t) )
   (__modti3,      void(int, int64_t, int64_t, int64_t, int64_t) )
   (__umodti3,      void(int, int64_t, int64_t, int64_t, int64_t) )
1079
   (__multi3,      void(int, int64_t, int64_t, int64_t, int64_t) )
1080 1081 1082 1083
);

REGISTER_INTRINSICS(string_api,
   (assert_is_utf8,  void(int, int, int))
1084 1085
);

B
Bart Wyatt 已提交
1086
REGISTER_INTRINSICS(system_api,
1087 1088
   (assert,              void(int, int)           )
   (now,                 int()                    )
B
Bart Wyatt 已提交
1089 1090
);

1091 1092 1093 1094 1095 1096
/*
REGISTER_INTRINSICS(account_api,
   (account_balance_get,   int(int, int32_t)   )
);
*/

B
Bart Wyatt 已提交
1097 1098 1099 1100
REGISTER_INTRINSICS(action_api,
   (read_action,            int(int, int)  )
   (action_size,            int()          )
   (current_receiver,   int64_t()          )
1101 1102
   (publication_time,   int32_t()          )
   (current_sender,     int64_t()          )
B
Bart Wyatt 已提交
1103 1104 1105
);

REGISTER_INTRINSICS(apply_context,
1106 1107
   (require_write_lock,    void(int64_t)   )
   (require_read_lock,     void(int64_t, int64_t)   )
B
Bart Wyatt 已提交
1108
   (require_recipient,     void(int64_t)   )
1109
   (require_authorization, void(int64_t), "require_auth", void(apply_context::*)(const account_name&)const)
B
Bart Wyatt 已提交
1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121
);

REGISTER_INTRINSICS(console_api,
   (prints,                void(int)       )
   (prints_l,              void(int, int)  )
   (printi,                void(int64_t)   )
   (printi128,             void(int)       )
   (printd,                void(int64_t)   )
   (printn,                void(int64_t)   )
   (printhex,              void(int, int)  )
);

1122 1123 1124
REGISTER_INTRINSICS(crypto_api,
   (assert_sha256,       void(int, int32_t, int)  )
   (sha256,              void(int, int32_t, int)  )
1125 1126 1127
);

REGISTER_INTRINSICS(transaction_api,
1128 1129 1130 1131 1132 1133
   (read_transaction,       int(int, int)            )
   (transaction_size,       int()                    )
   (expiration,             int()                    )
   (tapos_block_prefix,     int()                    )
   (tapos_block_num,        int()                    )
   (send_inline,           void(int, int)            )
1134 1135 1136
   (send_deferred,         void(int, int, int, int)  )
);

1137 1138 1139 1140
REGISTER_INTRINSICS(memory_api,
   (memcpy,                 int(int, int, int)   )
   (memcmp,                 int(int, int, int)   )
   (memset,                 int(int, int, int)   )
B
Bucky Kittinger 已提交
1141
   (sbrk,                   int(int)             )
1142 1143
);

1144

1145

1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
#define DB_METHOD_SEQ(SUFFIX) \
   (store,        int32_t(int64_t, int64_t, int, int),            "store_"#SUFFIX )\
   (update,       int32_t(int64_t, int64_t, int, int),            "update_"#SUFFIX )\
   (remove,       int32_t(int64_t, int64_t, int),                 "remove_"#SUFFIX )

#define DB_INDEX_METHOD_SEQ(SUFFIX)\
   (load,         int32_t(int64_t, int64_t, int64_t, int, int),   "load_"#SUFFIX )\
   (front,        int32_t(int64_t, int64_t, int64_t, int, int),   "front_"#SUFFIX )\
   (back,         int32_t(int64_t, int64_t, int64_t, int, int),   "back_"#SUFFIX )\
   (next,         int32_t(int64_t, int64_t, int64_t, int, int),   "next_"#SUFFIX )\
   (previous,     int32_t(int64_t, int64_t, int64_t, int, int),   "previous_"#SUFFIX )\
   (lower_bound,  int32_t(int64_t, int64_t, int64_t, int, int),   "lower_bound_"#SUFFIX )\
   (upper_bound,  int32_t(int64_t, int64_t, int64_t, int, int),   "upper_bound_"#SUFFIX )\

using db_api_key_value_object                                 = db_api<key_value_object>;
using db_api_keystr_value_object                              = db_api<keystr_value_object>;
using db_api_key128x128_value_object                          = db_api<key128x128_value_object>;
using db_api_key64x64x64_value_object                         = db_api<key64x64x64_value_object>;
using db_index_api_key_value_index_by_scope_primary           = db_index_api<key_value_index,by_scope_primary>;
using db_index_api_keystr_value_index_by_scope_primary        = db_index_api<keystr_value_index,by_scope_primary>;
using db_index_api_key128x128_value_index_by_scope_primary    = db_index_api<key128x128_value_index,by_scope_primary>;
using db_index_api_key128x128_value_index_by_scope_secondary  = db_index_api<key128x128_value_index,by_scope_secondary>;
using db_index_api_key64x64x64_value_index_by_scope_primary   = db_index_api<key64x64x64_value_index,by_scope_primary>;
using db_index_api_key64x64x64_value_index_by_scope_secondary = db_index_api<key64x64x64_value_index,by_scope_secondary>;
using db_index_api_key64x64x64_value_index_by_scope_tertiary  = db_index_api<key64x64x64_value_index,by_scope_tertiary>;

REGISTER_INTRINSICS(db_api_key_value_object,         DB_METHOD_SEQ(i64));
REGISTER_INTRINSICS(db_api_key128x128_value_object,  DB_METHOD_SEQ(i128i128));
REGISTER_INTRINSICS(db_api_key64x64x64_value_object, DB_METHOD_SEQ(i64i64i64));
B
Bucky Kittinger 已提交
1175 1176 1177 1178 1179
REGISTER_INTRINSICS(db_api_keystr_value_object,
   (store_str,                int32_t(int64_t, int64_t, int, int, int, int)  )
   (update_str,               int32_t(int64_t, int64_t, int, int, int, int)  )
   (remove_str,               int32_t(int64_t, int64_t, int, int)  ));

1180
REGISTER_INTRINSICS(db_index_api_key_value_index_by_scope_primary,           DB_INDEX_METHOD_SEQ(i64));
B
Bucky Kittinger 已提交
1181 1182 1183 1184 1185 1186 1187 1188
REGISTER_INTRINSICS(db_index_api_keystr_value_index_by_scope_primary,
   (load_str,            int32_t(int64_t, int64_t, int64_t, int, int, int, int)  )
   (front_str,           int32_t(int64_t, int64_t, int64_t, int, int, int, int)  )
   (back_str,            int32_t(int64_t, int64_t, int64_t, int, int, int, int)  )
   (next_str,            int32_t(int64_t, int64_t, int64_t, int, int, int, int)  )
   (previous_str,        int32_t(int64_t, int64_t, int64_t, int, int, int, int)  )
   (lower_bound_str,     int32_t(int64_t, int64_t, int64_t, int, int, int, int)  )
   (upper_bound_str,     int32_t(int64_t, int64_t, int64_t, int, int, int, int)  ));
1189 1190 1191
REGISTER_INTRINSICS(db_index_api_key128x128_value_index_by_scope_primary,    DB_INDEX_METHOD_SEQ(primary_i128i128));
REGISTER_INTRINSICS(db_index_api_key128x128_value_index_by_scope_secondary,  DB_INDEX_METHOD_SEQ(secondary_i128i128));
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_primary,   DB_INDEX_METHOD_SEQ(primary_i64i64i64));
1192
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_secondary, DB_INDEX_METHOD_SEQ(secondary_i64i64i64));
1193 1194
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_tertiary,  DB_INDEX_METHOD_SEQ(tertiary_i64i64i64));

B
Brian Johnson 已提交
1195

D
Daniel Larimer 已提交
1196
} } /// eosio::chain