wasm_interface.cpp 36.9 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>
D
Daniel Larimer 已提交
8 9 10

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

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

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

27

28

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

33
#if 0
B
Brian Johnson 已提交
34 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
   // 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;
   })
64
#endif
B
Brian Johnson 已提交
65

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

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

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

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

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

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

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

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

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

150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
      /**
       * 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
       */
169 170
      optional_info_ref fetch_info(const digest_type& code_id) {
         return with_lock([&,this](){
171 172
            auto iter = _cache.find(code_id);
            if (iter != _cache.end()) {
173
               return optional_info_ref(iter->second);
174 175
            }

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

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

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

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

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

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

236
                  auto current_memory = Runtime::getDefaultMemory(instance);
237 238

                  char *mem_ptr = &memoryRef<char>(current_memory, 0);
239
                  const auto allocated_memory = Runtime::getDefaultMemorySize(instance);
240 241 242 243 244 245 246 247 248 249 250 251 252 253
                  for (uint64_t i = 0; i < allocated_memory; ++i) {
                     if (mem_ptr[i]) {
                        mem_end = i + 1;
                     }
                  }

                  mem_image.resize(mem_end);
                  memcpy(mem_image.data(), mem_ptr, mem_end);
               } catch (...) {
                  pending_error = std::current_exception();
               }

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

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

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

273 274 275 276 277 278 279 280 281 282
            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();
            });
         }
283

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

293 294 295 296 297 298 299 300 301
      /**
       * 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) {
302
         _ios.post([&,code_id,this](){
303
            // sanitize by reseting the memory that may now be dirty
304 305
            auto& info = (*fetch_info(code_id)).get();
            char* memstart = &memoryRef<char>( getDefaultMemory(entry.instance), 0 );
306 307 308 309
            memset( memstart + info.mem_end, 0, ((1<<16) - info.mem_end) );
            memcpy( memstart, info.mem_image.data(), info.mem_end);

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

328 329 330
      // mapping of digest to an entry for the code
      map<digest_type, code_info> _cache;
      std::mutex _cache_lock;
B
Brian Johnson 已提交
331

332 333 334 335 336
      // compilation and cleanup thread
      std::thread _utility_thread;
      io_service _ios;
      optional<io_service::work> _work;
   };
B
Brian Johnson 已提交
337

338 339 340
   wasm_cache::wasm_cache()
      :_my( new wasm_cache_impl() ) {
   }
341

342 343
   wasm_cache::~wasm_cache() = default;

344 345
   wasm_cache::entry &wasm_cache::checkout( const digest_type& code_id, const char* wasm_binary, size_t wasm_binary_size ) {
      // see if there is an avaialble entry in the cache
346
      auto result = _my->try_fetch_entry(code_id);
347

348
      if (result) {
349
         return (*result).get();
D
Daniel Larimer 已提交
350
      }
351

352 353 354 355 356 357
      return _my->fetch_entry(code_id, wasm_binary, wasm_binary_size);
   }


   void wasm_cache::checkin(const digest_type& code_id, entry& code ) {
      _my->return_entry(code_id, code);
358
   }
359

360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377
   /**
    * 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;
   };

378
   void wasm_interface_impl::call(const string& entry_point, const vector<Value>& args, wasm_cache::entry& code, apply_context& context)
379
   try {
380
      FunctionInstance* call = asFunctionNullable(getInstanceExport(code.instance,entry_point) );
381 382 383 384
      if( !call ) {
         return;
      }

385
      FC_ASSERT( getFunctionType(call)->parameters.size() == args.size() );
386

387
      auto context_guard = scoped_context(current_context, code, context);
388 389 390 391 392 393 394 395 396 397 398 399
      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() ) {
   }

400 401 402 403 404 405 406 407
   wasm_interface& wasm_interface::get() {
      thread_local wasm_interface* single = nullptr;
      if( !single ) {
         single = new wasm_interface();
      }
      return *single;
   }

408
   void wasm_interface::apply( wasm_cache::entry& code, apply_context& context ) {
409 410 411 412 413 414 415
      if (context.act.scope == config::system_account_name && context.act.name == N(setcode)) {
         my->call("init", {}, code, context);
      } else {
         vector<Value> args = {Value(uint64_t(context.act.scope)),
                               Value(uint64_t(context.act.name))};
         my->call("apply", args, code, context);
      }
416 417 418 419 420
   }

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

423 424
#if 0
  DEFINE_INTRINSIC_FUNCTION2(env,assert,assert,none,i32,test,i32,msg) {
D
Daniel Larimer 已提交
425 426 427 428 429 430 431
      elog( "assert" );
      /*
      const char* m = &Runtime::memoryRef<char>( wasm_interface::get().current_memory, msg );
     std::string message( m );
     if( !test ) edump((message));
     FC_ASSERT( test, "assertion failed: ${s}", ("s",message)("ptr",msg) );
     */
432
   }
433

D
Daniel Larimer 已提交
434 435 436 437 438
   DEFINE_INTRINSIC_FUNCTION1(env,printi,printi,none,i64,val) {
     std::cerr << uint64_t(val);
   }
   DEFINE_INTRINSIC_FUNCTION1(env,printd,printd,none,i64,val) {
     //std::cerr << DOUBLE(*reinterpret_cast<double *>(&val));
439
   }
440

D
Daniel Larimer 已提交
441
   DEFINE_INTRINSIC_FUNCTION1(env,printi128,printi128,none,i32,val) {
442 443 444 445 446 447 448
      /*
      auto& wasm  = wasm_interface::get();
      auto  mem   = wasm.memory();
      auto& value = memoryRef<unsigned __int128>( mem, val );
      fc::uint128_t v(value>>64, uint64_t(value) );
      std::cerr << fc::variant(v).get_string();
      */
449

D
Daniel Larimer 已提交
450 451 452 453
   }
   DEFINE_INTRINSIC_FUNCTION1(env,printn,printn,none,i64,val) {
     std::cerr << name(val).to_string();
   }
454

455 456 457 458




D
Daniel Larimer 已提交
459 460 461
   DEFINE_INTRINSIC_FUNCTION1(env,prints,prints,none,i32,charptr) {
     auto& wasm  = wasm_interface::get();
     auto  mem   = wasm.memory();
462

D
Daniel Larimer 已提交
463 464
     const char* str = &memoryRef<const char>( mem, charptr );
     const auto allocated_memory = wasm.memory_size(); //Runtime::getDefaultMemorySize(state.instance);
465

D
Daniel Larimer 已提交
466 467
     std::cerr << std::string( str, strnlen(str, allocated_memory-charptr) );
   }
468

D
Daniel Larimer 已提交
469
DEFINE_INTRINSIC_FUNCTION2(env,readMessage,readMessage,i32,i32,destptr,i32,destsize) {
470
   FC_ASSERT( destsize > 0 );
471

D
Daniel Larimer 已提交
472
   /*
473 474
   wasm_interface& wasm = wasm_interface::get();
   auto  mem   = wasm.current_memory;
475
   char* begin = memoryArrayPtr<char>( mem, destptr, uint32_t(destsize) );
476 477

   int minlen = std::min<int>(wasm.current_validate_context->msg.data.size(), destsize);
478

D
Daniel Larimer 已提交
479
//   wdump((destsize)(wasm.current_validate_context->msg.data.size()));
480
   memcpy( begin, wasm.current_validate_context->msg.data.data(), minlen );
D
Daniel Larimer 已提交
481 482
   */
   return 0;//minlen;
A
Andrianto Lie 已提交
483 484
}

485

486

487 488 489
DEFINE_INTRINSIC_FUNCTION1(env,printi128,printi128,none,i32,val) {
  auto& wasm  = wasm_interface::get();
  auto  mem   = wasm.current_memory;
490 491 492
  auto& value = memoryRef<unsigned __int128>( mem, val );
  fc::uint128_t v(value>>64, uint64_t(value) );
  std::cerr << fc::variant(v).get_string();
493 494
}
DEFINE_INTRINSIC_FUNCTION1(env,printn,printn,none,i64,val) {
495
  std::cerr << name(val).to_string();
496
}
497

498
DEFINE_INTRINSIC_FUNCTION1(env,prints,prints,none,i32,charptr) {
499 500 501
  auto& wasm  = wasm_interface::get();
  auto  mem   = wasm.current_memory;

502
  const char* str = &memoryRef<const char>( mem, charptr );
503

D
Daniel Larimer 已提交
504
  std::cerr << std::string( str, strnlen(str, wasm.current_state->mem_end-charptr) );
505 506
}

A
Andrianto Lie 已提交
507 508 509 510 511 512 513 514 515
DEFINE_INTRINSIC_FUNCTION2(env,prints_l,prints_l,none,i32,charptr,i32,len) {
  auto& wasm  = wasm_interface::get();
  auto  mem   = wasm.current_memory;

  const char* str = &memoryRef<const char>( mem, charptr );

  std::cerr << std::string( str, len );
}

M
Matias Romeo 已提交
516 517 518
DEFINE_INTRINSIC_FUNCTION2(env,printhex,printhex,none,i32,data,i32,datalen) {
  auto& wasm  = wasm_interface::get();
  auto  mem   = wasm.current_memory;
A
Andrianto Lie 已提交
519

M
Matias Romeo 已提交
520
  char* buff = memoryArrayPtr<char>(mem, data, datalen);
521
  std::cerr << fc::to_hex(buff, datalen);
M
Matias Romeo 已提交
522 523 524
}


525
DEFINE_INTRINSIC_FUNCTION1(env,free,free,none,i32,ptr) {
526 527
}

D
Daniel Larimer 已提交
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548
#define DEFINE_RECORD_READ_FUNCTIONS(OBJTYPE, FUNCPREFIX, INDEX, SCOPE) \
   DEFINE_INTRINSIC_FUNCTION5(env,load_##FUNCPREFIX##OBJTYPE,load_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(load_record, INDEX, SCOPE); \
   } \
   DEFINE_INTRINSIC_FUNCTION5(env,front_##FUNCPREFIX##OBJTYPE,front_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(front_record, INDEX, SCOPE); \
   } \
   DEFINE_INTRINSIC_FUNCTION5(env,back_##FUNCPREFIX##OBJTYPE,back_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(back_record, INDEX, SCOPE); \
   } \
   DEFINE_INTRINSIC_FUNCTION5(env,next_##FUNCPREFIX##OBJTYPE,next_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(next_record, INDEX, SCOPE); \
   } \
   DEFINE_INTRINSIC_FUNCTION5(env,previous_##FUNCPREFIX##OBJTYPE,previous_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(previous_record, INDEX, SCOPE); \
   } \
   DEFINE_INTRINSIC_FUNCTION5(env,lower_bound_##FUNCPREFIX##OBJTYPE,lower_bound_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(lower_bound_record, INDEX, SCOPE); \
   } \
   DEFINE_INTRINSIC_FUNCTION5(env,upper_bound_##FUNCPREFIX##OBJTYPE,upper_bound_##FUNCPREFIX##OBJTYPE,i32,i64,scope,i64,code,i64,table,i32,valueptr,i32,valuelen) { \
      READ_RECORD(upper_bound_record, INDEX, SCOPE); \
549
   }
B
Brian Johnson 已提交
550 551 552 553 554 555 556 557 558
DEFINE_INTRINSIC_FUNCTION2(env,account_balance_get,account_balance_get,i32,i32,charptr,i32,len) {
  auto& wasm  = wasm_interface::get();
  auto  mem   = wasm.current_memory;

  const uint32_t account_balance_size = sizeof(account_balance);
  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, charptr );

559 560
  wasm.current_apply_context->require_scope(total_balance.account);

B
Brian Johnson 已提交
561 562 563 564 565 566 567 568 569 570 571 572 573 574
  auto& db = wasm.current_apply_context->db;
  auto* balance        = db.find< balance_object,by_owner_name >( total_balance.account );
  auto* staked_balance = db.find<staked_balance_object,by_owner_name>( total_balance.account );

  if (balance == nullptr || staked_balance == nullptr)
     return false;

  total_balance.eos_balance          = asset(balance->balance, EOS_SYMBOL);
  total_balance.staked_balance       = asset(staked_balance->staked_balance);
  total_balance.unstaking_balance    = asset(staked_balance->unstaking_balance);
  total_balance.last_unstaking_time  = staked_balance->last_unstaking_time;

  return true;
}
575

D
Daniel Larimer 已提交
576 577
#define UPDATE_RECORD(UPDATEFUNC, INDEX, DATASIZE) \
   return 0;
578

D
Daniel Larimer 已提交
579 580 581 582 583 584
   /*
   auto lambda = [&](apply_context* ctx, INDEX::value_type::key_type* keys, char *data, uint32_t datalen) -> int32_t { \
      return ctx->UPDATEFUNC<INDEX::value_type>( Name(scope), Name(ctx->code.value), Name(table), keys, data, datalen); \
   }; \
   return validate<decltype(lambda), INDEX::value_type::key_type, INDEX::value_type::number_of_keys>(valueptr, DATASIZE, lambda);
   */
585

D
Daniel Larimer 已提交
586 587 588 589 590 591 592 593 594
#define DEFINE_RECORD_UPDATE_FUNCTIONS(OBJTYPE, INDEX) \
   DEFINE_INTRINSIC_FUNCTION4(env,store_##OBJTYPE,store_##OBJTYPE,i32,i64,scope,i64,table,i32,valueptr,i32,valuelen) { \
      UPDATE_RECORD(store_record, INDEX, valuelen); \
   } \
   DEFINE_INTRINSIC_FUNCTION4(env,update_##OBJTYPE,update_##OBJTYPE,i32,i64,scope,i64,table,i32,valueptr,i32,valuelen) { \
      UPDATE_RECORD(update_record, INDEX, valuelen); \
   } \
   DEFINE_INTRINSIC_FUNCTION3(env,remove_##OBJTYPE,remove_##OBJTYPE,i32,i64,scope,i64,table,i32,valueptr) { \
      UPDATE_RECORD(remove_record, INDEX, sizeof(typename INDEX::value_type::key_type)*INDEX::value_type::number_of_keys); \
B
Brian Johnson 已提交
595 596
   }

D
Daniel Larimer 已提交
597 598
DEFINE_RECORD_READ_FUNCTIONS(i64,,key_value_index, by_scope_primary);
DEFINE_RECORD_UPDATE_FUNCTIONS(i64, key_value_index);
B
Brian Johnson 已提交
599

D
Daniel Larimer 已提交
600 601 602
DEFINE_INTRINSIC_FUNCTION1(env,requireAuth,requireAuth,none,i64,account) {
   //wasm_interface::get().current_validate_context->require_authorization( Name(account) );
}
B
Brian Johnson 已提交
603

D
Daniel Larimer 已提交
604 605 606 607 608 609 610 611 612
DEFINE_INTRINSIC_FUNCTION1(env,requireNotice,requireNotice,none,i64,account) {
   //wasm_interface::get().current_validate_context->require_authorization( Name(account) );
}
DEFINE_INTRINSIC_FUNCTION0(env,checktime,checktime,none) {
   /*
   auto dur = wasm_interface::get().current_execution_time();
   if (dur > CHECKTIME_LIMIT) {
      wlog("checktime called ${d}", ("d", dur));
      throw checktime_exceeded();
B
Brian Johnson 已提交
613
   }
D
Daniel Larimer 已提交
614 615
   */
}
616 617 618
#endif

#if defined(assert)
619
   #undef assert
620 621
#endif

B
Bart Wyatt 已提交
622
class context_aware_api {
623
   public:
B
Bart Wyatt 已提交
624
      context_aware_api(wasm_interface& wasm)
625
      :context(intrinsics_accessor::get_context(wasm).context), code(intrinsics_accessor::get_context(wasm).code)
626 627
      {}

B
Bart Wyatt 已提交
628
   protected:
B
Bucky Kittinger 已提交
629 630
      wasm_cache::entry& code;
		apply_context& 	 context;
B
Bart Wyatt 已提交
631 632 633 634 635 636 637 638 639 640 641
};

class system_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

      void assert(bool condition, const char* str) {
         std::string message( str );
         if( !condition ) edump((message));
         FC_ASSERT( condition, "assertion failed: ${s}", ("s",message));
      }
642 643 644 645

      fc::time_point_sec now() {
         return context.controller.head_block_time();
      }
B
Bart Wyatt 已提交
646 647 648 649 650 651
};

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

652 653
      int read_action(array_ptr<char> memory, size_t size) {
         FC_ASSERT(size > 0);
654
         int minlen = std::min<size_t>(context.act.data.size(), size);
655 656 657 658
         memcpy((void *)memory, context.act.data.data(), minlen);
         return minlen;
      }

B
Bart Wyatt 已提交
659 660
      int action_size() {
         return context.act.data.size();
661 662
      }

B
Bart Wyatt 已提交
663 664 665
      const name& current_receiver() {
         return context.receiver;
      }
666 667 668 669 670 671 672 673 674 675 676 677

      fc::time_point_sec publication_time() {
         return context.published;
      }

      name current_sender() {
         if (context.sender) {
            return *context.sender;
         } else {
            return name();
         }
      }
678
};
B
Brian Johnson 已提交
679

B
Bart Wyatt 已提交
680 681 682 683 684
class console_api : public context_aware_api {
   public:
      using context_aware_api::context_aware_api;

      void prints(const char *str) {
685
         context.console_append(str);
B
Bart Wyatt 已提交
686 687 688
      }

      void prints_l(array_ptr<const char> str, size_t str_len ) {
689
         context.console_append(string(str, str_len));
B
Bart Wyatt 已提交
690 691 692
      }

      void printi(uint64_t val) {
693
         context.console_append(val);
B
Bart Wyatt 已提交
694 695 696 697
      }

      void printi128(const unsigned __int128& val) {
         fc::uint128_t v(val>>64, uint64_t(val) );
698
         context.console_append(fc::variant(v).get_string());
B
Bart Wyatt 已提交
699 700 701
      }

      void printd( wasm_double val ) {
702
         context.console_append(val.str());
B
Bart Wyatt 已提交
703 704 705
      }

      void printn(const name& value) {
706
         context.console_append(value.to_string());
B
Bart Wyatt 已提交
707 708 709
      }

      void printhex(array_ptr<const char> data, size_t data_len ) {
710
         context.console_append(fc::to_hex(data, data_len));
B
Bart Wyatt 已提交
711 712 713
      }
};

714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
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);
729
         return (context.*(method))(t_id, keys, record_data, record_len) + sizeof(KeyArrayType);
730 731 732 733 734 735
      }

   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) {
736 737 738 739
         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;

740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772
      }

      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) {
         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 = reinterpret_cast<KeyType *>((char *)data);

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

773
      return (context.*(method))(t_id, keys, record_data, record_len) + sizeof(KeyArrayType);
774 775 776 777 778 779
   }

   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) {
780 781 782
         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;
783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810
      }

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

};

811
class memory_api : public context_aware_api {
812
   public:
813 814
		using context_aware_api::context_aware_api;

815 816 817 818 819 820 821 822 823

      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 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859
      char* memset( array_ptr<char> dest, int value, size_t length ) {
		   return (char *)::memset( dest, value, length );
      }

      uint32_t sbrk(int num_bytes) {
         // TODO: omitted checktime	function from previous version of sbrk, may need to be put back in at some point
         constexpr uint32_t NBPPL2         = IR::numBytesPerPageLog2;
         constexpr uint32_t max_mem        = 1024 * 1024;
         const auto         default_mem    = Runtime::getDefaultMemory(code.instance);
         const uint32_t     num_pages      = Runtime::getMemoryNumPages(default_mem);
         // limit this min to 32 bit space 
         const uint32_t     min_bytes      = (num_pages << NBPPL2) > UINT32_MAX ? UINT32_MAX : num_pages << NBPPL2;
         static uint32_t    _num_bytes     = min_bytes;
         const uint32_t     prev_num_bytes = _num_bytes;


         // round the absolute value of num_bytes to an alignment boundary
         num_bytes = (num_bytes + 7) & ~7;

         if ((num_bytes > 0) && (prev_num_bytes > (max_mem - num_bytes)))  // test if allocating too much memory (overflowed)
            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
         _num_bytes += num_bytes;
         const uint32_t num_desired_pages = (_num_bytes + IR::numBytesPerPage - 1) >> NBPPL2;

         // 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;
   }
860 861
};

862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
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 ) {
877 878 879
         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");
880

881 882 883 884 885 886 887
            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)));
888 889 890 891
      }

};

B
Bart Wyatt 已提交
892 893
REGISTER_INTRINSICS(system_api,
   (assert,      void(int, int))
894
   (now,          int())
B
Bart Wyatt 已提交
895 896 897 898 899 900
);

REGISTER_INTRINSICS(action_api,
   (read_action,            int(int, int)  )
   (action_size,            int()          )
   (current_receiver,   int64_t()          )
901 902
   (publication_time,   int32_t()          )
   (current_sender,     int64_t()          )
B
Bart Wyatt 已提交
903 904 905 906 907 908
);

REGISTER_INTRINSICS(apply_context,
   (require_write_scope,   void(int64_t)   )
   (require_read_scope,    void(int64_t)   )
   (require_recipient,     void(int64_t)   )
909
   (require_authorization, void(int64_t), "require_auth", void(apply_context::*)(const account_name&)const)
B
Bart Wyatt 已提交
910 911 912 913 914 915 916 917 918 919 920 921
);

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

922 923 924 925 926
REGISTER_INTRINSICS(transaction_api,
   (send_inline,           void(int, int)  )
   (send_deferred,         void(int, int, int, int)  )
);

927 928 929 930 931 932 933
REGISTER_INTRINSICS(memory_api,
   (memcpy,                 int(int, int, int)   )
   (memcmp,                 int(int, int, int)   )
   (memset,                 int(int, int, int)   )
	(sbrk,						 int(int)				 )
);

934

935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
#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));
971
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_secondary, DB_INDEX_METHOD_SEQ(secondary_i64i64i64));
972 973
REGISTER_INTRINSICS(db_index_api_key64x64x64_value_index_by_scope_tertiary,  DB_INDEX_METHOD_SEQ(tertiary_i64i64i64));

B
Brian Johnson 已提交
974

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