wasm_interface.cpp 31.4 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/exceptions.hpp>
D
Daniel Larimer 已提交
5
#include <boost/core/ignore_unused.hpp>
6 7
#include <eosio/chain/wasm_interface_private.hpp>
#include <fc/exception/exception.hpp>
8
#include <fc/utf8.hpp>
D
Daniel Larimer 已提交
9 10 11

#include <Runtime/Runtime.h>
#include "IR/Module.h"
12 13 14 15
#include "Platform/Platform.h"
#include "WAST/WAST.h"
#include "IR/Operators.h"
#include "IR/Validate.h"
16
#include "IR/Types.h"
17 18 19
#include "Runtime/Runtime.h"
#include "Runtime/Linker.h"
#include "Runtime/Intrinsics.h"
D
Daniel Larimer 已提交
20

21 22 23
#include <boost/asio.hpp>
#include <boost/bind.hpp>

24
#include <mutex>
25 26 27
#include <thread>
#include <condition_variable>

28

29

30 31
using namespace IR;
using namespace Runtime;
32
using boost::asio::io_service;
D
Daniel Larimer 已提交
33

34
#if 0
B
Brian Johnson 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
   // 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
      */
      account_name account;

      /**
      * Balance for this account
      */
      asset eos_balance;

      /**
      * Staked balance for this account
      */
      asset staked_balance;

      /**
      * Unstaking balance for this account
      */
      asset unstaking_balance;

      /**
      * Time at which last unstaking occurred for this account
      */
      time last_unstaking_time;
   })
65
#endif
B
Brian Johnson 已提交
66

67
namespace eosio { namespace chain {
68
   using namespace contracts;
69

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

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

90 91 92 93 94 95 96 97 98 99
   /**
    *  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()
      :_ios()
      ,_work(_ios)
      {
100 101
         Runtime::init();

102 103 104 105
         _utility_thread = std::thread([](io_service* ios){
            ios->run();
         }, &_ios);
      }
M
Matias Romeo 已提交
106

107 108 109 110 111 112 113 114 115 116
      /**
       * 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() {
         _work.reset();
         _ios.stop();
117 118
         _utility_thread.join();
         freeUnreferencedObjects({});
119
      }
M
Matias Romeo 已提交
120

121 122 123 124 125 126 127 128 129 130 131 132 133
      /**
       * 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 {
134 135 136 137
         code_info( size_t mem_end, vector<char>&& mem_image )
         :mem_end(mem_end),mem_image(std::forward<vector<char>>(mem_image))
         {}

138 139 140 141 142 143 144 145 146 147
         // 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;
      };

148 149 150
      using optional_info_ref = optional<std::reference_wrapper<code_info>>;
      using optional_entry_ref = optional<std::reference_wrapper<wasm_cache::entry>>;

151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169
      /**
       * 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>
      auto with_lock(F f) {
         std::lock_guard<std::mutex> lock(_cache_lock);
         return f();
      };

      /**
       * Fetch the tracking struct given a code_id if it exists
       *
       * @param code_id
       * @return
       */
170 171
      optional_info_ref fetch_info(const digest_type& code_id) {
         return with_lock([&,this](){
172 173
            auto iter = _cache.find(code_id);
            if (iter != _cache.end()) {
174
               return optional_info_ref(iter->second);
175 176
            }

177
            return optional_info_ref();
178 179
         });
      }
M
Matias Romeo 已提交
180

181 182 183 184 185
      /**
       * 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
       */
186 187
      optional_entry_ref try_fetch_entry(const digest_type& code_id) {
         return with_lock([&,this](){
188 189
            auto iter = _cache.find(code_id);
            if (iter != _cache.end() && iter->second.available_instances > 0) {
190
               auto &ptr = iter->second.instances.at(--(iter->second.available_instances));
191
               return optional_entry_ref(*ptr);
192 193
            }

194
            return optional_entry_ref();
195
         });
D
Daniel Larimer 已提交
196
      }
M
Matias Romeo 已提交
197

198 199 200 201 202 203 204 205 206 207 208 209
      /**
       * 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;
210
         optional_entry_ref result;
211 212 213 214
         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
215
         _ios.post([&,this](){
216 217 218 219 220 221
            // 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
222 223
               Module* module = new Module();
               ModuleInstance* instance = nullptr;
224
               size_t mem_end = 0;
225 226 227 228
               vector<char> mem_image;

               try {
                  Serialization::MemoryInputStream stream((const U8 *) wasm_binary, wasm_binary_size);
229 230
                  #warning TODO: restore checktime injection?
                  WASM::serialize(stream, *module);
231 232

                  root_resolver resolver;
233 234
                  LinkResult link_result = linkModule(*module, resolver);
                  instance = instantiateModule(*module, std::move(link_result.resolvedImports));
235 236
                  FC_ASSERT(instance != nullptr);

237
                  MemoryInstance* current_memory = Runtime::getDefaultMemory(instance);
238

239 240 241 242 243 244
                  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;
245
                     }
246 247
                     mem_image.resize(mem_end);
                     memcpy(mem_image.data(), mem_ptr, mem_end);
248
                  }
249
                  
250 251 252 253 254 255
               } catch (...) {
                  pending_error = std::current_exception();
               }

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

260 261
                     iter->second.instances.emplace_back(std::make_unique<wasm_cache::entry>(instance, module));
                     pending_result = optional_entry_ref(*iter->second.instances.back().get());
262 263 264 265 266 267 268 269 270 271 272 273
                  });
               }
            }

            // publish result under lock
            with_lock([&](){
               if (pending_error != nullptr) {
                  error = pending_error;
               } else {
                  result = pending_result;
               }
            });
274

275 276 277 278 279 280 281 282 283 284
            condition.notify_all();
         });

         // wait for the other thread to compile a copy for us
         {
            std::unique_lock<std::mutex> lock(_cache_lock);
            condition.wait(lock, [&]{
               return error != nullptr || result.valid();
            });
         }
285

286 287 288 289
         try {
            if (error != nullptr) {
               std::rethrow_exception(error);
            } else {
290
               return (*result).get();
291 292
            }
         } FC_RETHROW_EXCEPTIONS(error, "error compiling WASM for code with hash: ${code_id}", ("code_id", code_id));
D
Daniel Larimer 已提交
293
      }
294

295 296 297 298 299 300 301 302 303
      /**
       * 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) {
304
         _ios.post([&,code_id,this](){
305
            // sanitize by reseting the memory that may now be dirty
306
            auto& info = (*fetch_info(code_id)).get();
307 308 309 310 311
            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);
            }
312
            resetGlobalInstances(entry.instance);
313 314

            // under a lock, put this entry back in the available instances side of the instances vector
315
            with_lock([&,this](){
316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
               // 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 已提交
331
      }
332

333 334 335
      // mapping of digest to an entry for the code
      map<digest_type, code_info> _cache;
      std::mutex _cache_lock;
B
Brian Johnson 已提交
336

337 338 339 340 341
      // compilation and cleanup thread
      std::thread _utility_thread;
      io_service _ios;
      optional<io_service::work> _work;
   };
B
Brian Johnson 已提交
342

343 344 345
   wasm_cache::wasm_cache()
      :_my( new wasm_cache_impl() ) {
   }
346

347 348
   wasm_cache::~wasm_cache() = default;

349
   wasm_cache::entry &wasm_cache::checkout( const digest_type& code_id, const char* wasm_binary, size_t wasm_binary_size ) {
350
      // see if there is an available entry in the cache
351
      auto result = _my->try_fetch_entry(code_id);
352
      if (result) {
353
         return (*result).get();
D
Daniel Larimer 已提交
354
      }
355 356 357 358 359
      return _my->fetch_entry(code_id, wasm_binary, wasm_binary_size);
   }


   void wasm_cache::checkin(const digest_type& code_id, entry& code ) {
360 361 362
      MemoryInstance* default_mem = Runtime::getDefaultMemory(code.instance);
      if(default_mem)
         Runtime::shrinkMemory(default_mem, Runtime::getMemoryNumPages(default_mem) - 1);
363
      _my->return_entry(code_id, code);
364
   }
365

366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383
   /**
    * 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;
   };

384
   void wasm_interface_impl::call(const string& entry_point, const vector<Value>& args, wasm_cache::entry& code, apply_context& context)
385
   try {
386
      FunctionInstance* call = asFunctionNullable(getInstanceExport(code.instance,entry_point) );
387 388 389 390
      if( !call ) {
         return;
      }

391
      FC_ASSERT( getFunctionType(call)->parameters.size() == args.size() );
392

393
      auto context_guard = scoped_context(current_context, code, context);
394
      runInstanceStartFunc(code.instance);
395 396 397 398 399 400 401 402 403 404 405 406
      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() ) {
   }

407 408 409 410 411 412 413 414
   wasm_interface& wasm_interface::get() {
      thread_local wasm_interface* single = nullptr;
      if( !single ) {
         single = new wasm_interface();
      }
      return *single;
   }

415
   void wasm_interface::apply( wasm_cache::entry& code, apply_context& context ) {
B
Bart Wyatt 已提交
416
      if (context.act.account == config::system_account_name && context.act.name == N(setcode)) {
417 418
         my->call("init", {}, code, context);
      } else {
B
Bart Wyatt 已提交
419
         vector<Value> args = {Value(uint64_t(context.act.account)),
420 421 422
                               Value(uint64_t(context.act.name))};
         my->call("apply", args, code, context);
      }
423 424 425 426 427
   }

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

430
#if defined(assert)
431
   #undef assert
432 433
#endif

B
Bart Wyatt 已提交
434
class context_aware_api {
435
   public:
B
Bart Wyatt 已提交
436
      context_aware_api(wasm_interface& wasm)
437 438
      :context(intrinsics_accessor::get_context(wasm).context), code(intrinsics_accessor::get_context(wasm).code),
       sbrk_bytes(intrinsics_accessor::get_context(wasm).sbrk_bytes)
439 440
      {}

B
Bart Wyatt 已提交
441
   protected:
442
      uint32_t&          sbrk_bytes;
B
Bucky Kittinger 已提交
443
      wasm_cache::entry& code;
B
Bucky Kittinger 已提交
444
      apply_context&     context;
B
Bart Wyatt 已提交
445 446
};

447 448 449 450
class producer_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

451 452 453
      int get_active_producers(array_ptr<chain::account_name> producers, size_t datalen) {
         auto actual_num_prod = context.get_active_producers(producers, datalen / sizeof(chain::account_name));
         return actual_num_prod * sizeof(chain::account_name);
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481
      }
};

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) );
      }
};

B
Bart Wyatt 已提交
482 483 484 485
class system_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

486
      void assert(bool condition, null_terminated_ptr str) {
B
Bart Wyatt 已提交
487 488 489 490
         std::string message( str );
         if( !condition ) edump((message));
         FC_ASSERT( condition, "assertion failed: ${s}", ("s",message));
      }
491 492 493 494

      fc::time_point_sec now() {
         return context.controller.head_block_time();
      }
B
Bart Wyatt 已提交
495 496 497 498 499 500
};

class action_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

501 502
      int read_action(array_ptr<char> memory, size_t size) {
         FC_ASSERT(size > 0);
503
         int minlen = std::min<size_t>(context.act.data.size(), size);
504 505 506 507
         memcpy((void *)memory, context.act.data.data(), minlen);
         return minlen;
      }

B
Bart Wyatt 已提交
508 509
      int action_size() {
         return context.act.data.size();
510 511
      }

B
Bart Wyatt 已提交
512 513 514
      const name& current_receiver() {
         return context.receiver;
      }
515 516

      fc::time_point_sec publication_time() {
B
Bart Wyatt 已提交
517
         return context.trx_meta.published;
518 519 520
      }

      name current_sender() {
B
Bart Wyatt 已提交
521 522
         if (context.trx_meta.sender) {
            return *context.trx_meta.sender;
523 524 525 526
         } else {
            return name();
         }
      }
527
};
B
Brian Johnson 已提交
528

B
Bart Wyatt 已提交
529 530 531 532
class console_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

533 534
      void prints(null_terminated_ptr str) {
         context.console_append<const char*>(str);
B
Bart Wyatt 已提交
535 536 537
      }

      void prints_l(array_ptr<const char> str, size_t str_len ) {
538
         context.console_append(string(str, str_len));
B
Bart Wyatt 已提交
539 540 541
      }

      void printi(uint64_t val) {
542
         context.console_append(val);
B
Bart Wyatt 已提交
543 544 545 546
      }

      void printi128(const unsigned __int128& val) {
         fc::uint128_t v(val>>64, uint64_t(val) );
547
         context.console_append(fc::variant(v).get_string());
B
Bart Wyatt 已提交
548 549 550
      }

      void printd( wasm_double val ) {
551
         context.console_append(val.str());
B
Bart Wyatt 已提交
552 553 554
      }

      void printn(const name& value) {
555
         context.console_append(value.to_string());
B
Bart Wyatt 已提交
556 557 558
      }

      void printhex(array_ptr<const char> data, size_t data_len ) {
559
         context.console_append(fc::to_hex(data, data_len));
B
Bart Wyatt 已提交
560 561 562
      }
};

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577
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);
578
         return (context.*(method))(t_id, keys, record_data, record_len) + sizeof(KeyArrayType);
579 580 581 582 583 584
      }

   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) {
585 586 587 588
         auto res = call(&apply_context::store_record<ObjectType>, scope, table, data, data_len);
         //ilog("STORE [${scope},${code},${table}] => ${res} :: ${HEX}", ("scope",scope)("code",context.receiver)("table",table)("res",res)("HEX", fc::to_hex(data, data_len)));
         return res;

589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611
      }

      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);
      }

      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);
      }
};

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) {
612
         return -1;
613 614 615 616 617 618 619 620 621
      }

      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);

622 623 624 625 626
      auto res = (context.*(method))(t_id, keys, record_data, record_len);
      if (res != -1) {
         res += sizeof(KeyArrayType);
      }
      return res;
627 628 629 630 631 632
   }

   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) {
633 634 635
         auto res = call(&apply_context::load_record<IndexType, Scope>, scope, code, table, data, data_len);
         //ilog("LOAD [${scope},${code},${table}] => ${res} :: ${HEX}", ("scope",scope)("code",code)("table",table)("res",res)("HEX", fc::to_hex(data, data_len)));
         return res;
636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663
      }

      int front(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::front_record<IndexType, Scope>, scope, code, table, data, data_len);
      }

      int back(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::back_record<IndexType, Scope>, scope, code, table, data, data_len);
      }

      int next(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::next_record<IndexType, Scope>, scope, code, table, data, data_len);
      }

      int previous(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::previous_record<IndexType, Scope>, scope, code, table, data, data_len);
      }

      int lower_bound(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::lower_bound_record<IndexType, Scope>, scope, code, table, data, data_len);
      }

      int upper_bound(const scope_name& scope, const account_name& code, const name& table, array_ptr<char> data, size_t data_len) {
         return call(&apply_context::upper_bound_record<IndexType, Scope>, scope, code, table, data, data_len);
      }

};

664
class memory_api : public context_aware_api {
665
   public:
B
Bucky Kittinger 已提交
666
      using context_aware_api::context_aware_api;
667
     
668 669 670 671 672 673 674 675
      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 已提交
676
      char* memset( array_ptr<char> dest, int value, size_t length ) {
B
Bucky Kittinger 已提交
677
         return (char *)::memset( dest, value, length );
B
Bucky Kittinger 已提交
678 679 680
      }

      uint32_t sbrk(int num_bytes) {
B
Bucky Kittinger 已提交
681
         // TODO: omitted checktime function from previous version of sbrk, may need to be put back in at some point
682 683 684
         constexpr uint32_t NBPPL2  = IR::numBytesPerPageLog2;
         constexpr uint32_t MAX_MEM = 1024 * 1024;

685 686 687 688 689 690 691
         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;
692
         
B
Bucky Kittinger 已提交
693 694 695
         // round the absolute value of num_bytes to an alignment boundary
         num_bytes = (num_bytes + 7) & ~7;

696
         if ((num_bytes > 0) && (prev_num_bytes > (MAX_MEM - num_bytes)))  // test if allocating too much memory (overflowed)
B
Bucky Kittinger 已提交
697 698 699 700 701
            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
702 703
         sbrk_bytes += num_bytes;
         const uint32_t num_desired_pages = (sbrk_bytes + IR::numBytesPerPage - 1) >> NBPPL2;
B
Bucky Kittinger 已提交
704 705 706 707 708 709 710 711

         // 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;
712
      }
713 714
};

715 716 717 718 719 720 721 722 723 724 725 726 727 728 729
class transaction_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

      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 ) {
730 731 732
         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");
733

734 735 736 737 738 739 740
            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)));
741 742 743 744
      }

};

745
REGISTER_INTRINSICS(producer_api,
746
   (get_active_producers,      int(int, int))
747 748 749 750 751 752 753 754 755 756 757
);

REGISTER_INTRINSICS(crypto_api,
   (assert_sha256,  void(int, int, int))
   (sha256,         void(int, int, int))
);

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

B
Bart Wyatt 已提交
758 759
REGISTER_INTRINSICS(system_api,
   (assert,      void(int, int))
760
   (now,          int())
B
Bart Wyatt 已提交
761 762 763 764 765 766
);

REGISTER_INTRINSICS(action_api,
   (read_action,            int(int, int)  )
   (action_size,            int()          )
   (current_receiver,   int64_t()          )
767 768
   (publication_time,   int32_t()          )
   (current_sender,     int64_t()          )
B
Bart Wyatt 已提交
769 770 771
);

REGISTER_INTRINSICS(apply_context,
772 773
   (require_write_lock,    void(int64_t)   )
   (require_read_lock,     void(int64_t, int64_t)   )
B
Bart Wyatt 已提交
774
   (require_recipient,     void(int64_t)   )
775
   (require_authorization, void(int64_t), "require_auth", void(apply_context::*)(const account_name&)const)
B
Bart Wyatt 已提交
776 777 778 779 780 781 782 783 784 785 786 787
);

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)  )
);

788 789 790 791 792
REGISTER_INTRINSICS(transaction_api,
   (send_inline,           void(int, int)  )
   (send_deferred,         void(int, int, int, int)  )
);

793 794 795 796
REGISTER_INTRINSICS(memory_api,
   (memcpy,                 int(int, int, int)   )
   (memcmp,                 int(int, int, int)   )
   (memset,                 int(int, int, int)   )
B
Bucky Kittinger 已提交
797
   (sbrk,                   int(int)             )
798 799
);

800

801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836
#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_keystr_value_object,      DB_METHOD_SEQ(str));
REGISTER_INTRINSICS(db_api_key128x128_value_object,  DB_METHOD_SEQ(i128i128));
REGISTER_INTRINSICS(db_api_key64x64x64_value_object, DB_METHOD_SEQ(i64i64i64));

REGISTER_INTRINSICS(db_index_api_key_value_index_by_scope_primary,           DB_INDEX_METHOD_SEQ(i64));
REGISTER_INTRINSICS(db_index_api_keystr_value_index_by_scope_primary,        DB_INDEX_METHOD_SEQ(str));
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));
837
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_secondary, DB_INDEX_METHOD_SEQ(secondary_i64i64i64));
838 839
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_tertiary,  DB_INDEX_METHOD_SEQ(tertiary_i64i64i64));

B
Brian Johnson 已提交
840

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