wasm_interface.cpp 15.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10
#include <eos/chain/wasm_interface.hpp>
#include "Platform/Platform.h"
#include "WAST/WAST.h"
#include "Runtime/Runtime.h"
#include "Runtime/Linker.h"
#include "Runtime/Intrinsics.h"
#include "IR/Module.h"
#include "IR/Operators.h"
#include "IR/Validate.h"
#include <eos/chain/key_value_object.hpp>
11
#include <eos/chain/account_object.hpp>
12 13 14 15

namespace eos { namespace chain {
   using namespace IR;
   using namespace Runtime;
16

17 18 19 20
   wasm_interface::wasm_interface() {
   }

DEFINE_INTRINSIC_FUNCTION4(env,store,store,none,i32,keyptr,i32,keylen,i32,valueptr,i32,valuelen ) {
D
Daniel Larimer 已提交
21
//   ilog( "store ${keylen}  ${vallen}", ("keylen",keylen)("vallen",valuelen) );
22 23 24 25 26 27 28 29 30 31
   FC_ASSERT( keylen > 0 );
   FC_ASSERT( valuelen >= 0 );

   auto& wasm  = wasm_interface::get();

   FC_ASSERT( wasm.current_apply_context, "no apply context found" );

   auto& db    = wasm.current_apply_context->mutable_db;
   auto& scope = wasm.current_apply_context->scope;
   auto  mem   = wasm.current_memory;
32 33
   char* key   = memoryArrayPtr<char>( mem, keyptr, keylen);
   char* value = memoryArrayPtr<char>( mem, valueptr, valuelen);
34 35
   string keystr( key, key+keylen);

D
Daniel Larimer 已提交
36
//   if( valuelen == 8 ) idump(( *((int64_t*)value)));
37

38 39 40 41

   const auto* obj = db.find<key_value_object,by_scope_key>( boost::make_tuple(scope, keystr) );
   if( obj ) {
      db.modify( *obj, [&]( auto& o ) {
N
Nathan Hourt 已提交
42
         o.value.assign(value, valuelen);
43 44 45 46 47 48 49 50
      });
   } else {
      db.create<key_value_object>( [&](auto& o) {
         o.scope = scope;
         o.key.insert( 0, key, keylen );
         o.value.insert( 0, value, valuelen );
      });
   }
51
}
52 53 54 55 56 57
DEFINE_INTRINSIC_FUNCTION1(env,name_to_int64,name_to_int64,i64,i32,cstr) {
   auto& wasm  = wasm_interface::get();
   auto  mem   = wasm.current_memory;
   const char* str   = memoryArrayPtr<const char>( mem, cstr, 13);
   return Name(str).value;
}
58

59 60 61 62 63 64 65 66 67 68
DEFINE_INTRINSIC_FUNCTION2(env,remove,remove,i32,i32,keyptr,i32,keylen) {
   FC_ASSERT( keylen > 0 );

   auto& wasm  = wasm_interface::get();

   FC_ASSERT( wasm.current_apply_context, "no apply context found" );

   auto& db    = wasm.current_apply_context->mutable_db;
   auto& scope = wasm.current_apply_context->scope;
   auto  mem   = wasm.current_memory;
69
   char* key   = memoryArrayPtr<char>( mem, keyptr, keylen);
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
   string keystr( key, key+keylen);

   const auto* obj = db.find<key_value_object,by_scope_key>( boost::make_tuple(scope, keystr) );
   if( obj ) {
			db.remove( *obj );
      return true;
   }
   return false;
}

DEFINE_INTRINSIC_FUNCTION3(env,memcpy,memcpy,i32,i32,dstp,i32,srcp,i32,len) {
   auto& wasm          = wasm_interface::get();
   auto  mem           = wasm.current_memory;
   char* dst           = &memoryRef<char>( mem, dstp);
   const char* src     = &memoryRef<const char>( mem, srcp );
85
   //char* dst_end       = &memoryRef<char>( mem, dstp+uint32_t(len));
86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
   const char* src_end = &memoryRef<const char>( mem, srcp+uint32_t(len) );

#warning TODO: wasm memcpy has undefined behavior if memory ranges overlap
/*
   if( dst > src )
			FC_ASSERT( dst < src_end && src < dst_end, "overlap of memory range is undefined", ("d",dstp)("s",srcp)("l",len) );
   else
			FC_ASSERT( src < dst_end && dst < src_end, "overlap of memory range is undefined", ("d",dstp)("s",srcp)("l",len) );
*/
   memcpy( dst, src, uint32_t(len) );
   return dstp;
}


DEFINE_INTRINSIC_FUNCTION2(env,Varint_unpack,Varint_unpack,none,i32,streamptr,i32,valueptr) {
   auto& wasm  = wasm_interface::get();
   auto  mem   = wasm.current_memory;

104
   uint32_t* stream = memoryArrayPtr<uint32_t>( mem, streamptr, 3 );
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
   const char* pos = &memoryRef<const char>( mem, stream[1] );
   const char* end = &memoryRef<const char>( mem, stream[2] );
   uint32_t& value = memoryRef<uint32_t>( mem, valueptr );

   fc::unsigned_int vi;
   fc::datastream<const char*> ds(pos,end-pos);
   fc::raw::unpack( ds, vi );
   value = vi.value;

   stream[1] += ds.pos() - pos;
}

DEFINE_INTRINSIC_FUNCTION2(env,AccountName_unpack,AccountName_unpack,none,i32,streamptr,i32,accountptr) {
   auto& wasm  = wasm_interface::get();
   auto  mem   = wasm.current_memory;


122
   uint32_t* stream = memoryArrayPtr<uint32_t>( mem, streamptr, 3 );
123 124 125
   const char* pos = &memoryRef<const char>( mem, stream[1] );
   const char* end = &memoryRef<const char>( mem, stream[2] );
   AccountName* name = &memoryRef<AccountName>( mem, accountptr );
D
Daniel Larimer 已提交
126
   memset( name, 0, 32 );
127 128 129 130 131 132 133

   fc::datastream<const char*> ds( pos, end - pos );
   fc::raw::unpack( ds, *name );

   stream[1] += ds.pos() - pos;
}

134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164
DEFINE_INTRINSIC_FUNCTION2(env,send,send,i32,i32,trx_buffer, i32,trx_buffer_size ) {
   auto& wasm  = wasm_interface::get();
   auto  mem   = wasm.current_memory;
   const char* buffer = &memoryRef<const char>( mem, trx_buffer );

   FC_ASSERT( trx_buffer_size > 0 );
   FC_ASSERT( wasm.current_apply_context, "not in apply context" );

   fc::datastream<const char*> ds(buffer, trx_buffer_size );
   eos::chain::generated_transaction gtrx;
   eos::chain::Transaction& trx = gtrx;
   fc::raw::unpack( ds, trx );

/**
 *  The code below this section provides sanity checks that the generated message is well formed
 *  before being accepted. These checks do not need to be applied during reindex.
 */
#warning TODO: reserve per-thread static memory for MAX TRX SIZE 
/** make sure that packing what we just unpacked produces expected output */
   auto test = fc::raw::pack( trx );
   FC_ASSERT( 0 == memcmp( buffer, test.data(), test.size() ) );

/** TODO: make sure that we can call validate() on the message and it passes, this is thread safe and
 *   ensures the type is properly registered and can be deserialized... one issue is that this could
 *   construct a RECURSIVE virtual machine state which means the wasm_interface state needs to be a STACK vs
 *   a per-thread global.
 **/

   wasm.current_apply_context->generated.emplace_back( std::move(gtrx) );
}

165 166


167
DEFINE_INTRINSIC_FUNCTION4(env,load,load,i32,i32,keyptr,i32,keylen,i32,valueptr,i32,valuelen ) {
D
Daniel Larimer 已提交
168
//   ilog( "load ${keylen}  ${vallen}", ("keylen",keylen)("vallen",valuelen) );
169 170 171 172 173 174 175 176 177 178
   FC_ASSERT( keylen > 0 );
   FC_ASSERT( valuelen >= 0 );

   auto& wasm  = wasm_interface::get();

   FC_ASSERT( wasm.current_apply_context, "no apply context found" );

   auto& db    = wasm.current_apply_context->mutable_db;
   auto& scope = wasm.current_apply_context->scope;
   auto  mem   = wasm.current_memory;
179 180
   char* key   = memoryArrayPtr<char>( mem, keyptr, keylen );
   char* value = memoryArrayPtr<char>( mem, valueptr, valuelen );
181 182 183 184
   string keystr( key, key+keylen);

   const auto* obj = db.find<key_value_object,by_scope_key>( boost::make_tuple(scope, keystr) );
   if( obj == nullptr ) return -1;
N
Nathan Hourt 已提交
185
   auto copylen =  std::min<size_t>(obj->value.size(),valuelen);
186
   if( copylen ) {
N
Nathan Hourt 已提交
187
      obj->value.copy(value, copylen);
188
   }
N
Nathan Hourt 已提交
189
   return copylen;
190 191
}

192 193 194 195
DEFINE_INTRINSIC_FUNCTION2(env,readMessage,readMessage,i32,i32,destptr,i32,destsize) {
   FC_ASSERT( destsize > 0 );
   wasm_interface& wasm = wasm_interface::get();
   auto  mem   = wasm.current_memory;
196
   char* begin = memoryArrayPtr<char>( mem, destptr, destsize );
197 198 199 200 201 202

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

203 204 205
DEFINE_INTRINSIC_FUNCTION2(env,assert,assert,none,i32,test,i32,msg) {
  std::string message = &Runtime::memoryRef<char>( wasm_interface::get().current_memory, msg );
  if( !test ) edump((message));
206
  FC_ASSERT( test, "assertion failed: ${s}", ("s",message)("ptr",msg) );
207
}
208

209 210 211 212
DEFINE_INTRINSIC_FUNCTION0(env,messageSize,messageSize,i32) {
   return wasm_interface::get().current_validate_context->msg.data.size();
}

213
DEFINE_INTRINSIC_FUNCTION1(env,malloc,malloc,i32,i32,size) {
214 215 216 217 218 219 220 221
   FC_ASSERT( size > 0 );
   int32_t& end = Runtime::memoryRef<int32_t>( Runtime::getDefaultMemory(wasm_interface::get().current_module), 0);
   int32_t old_end = end;
   end += 8*((size+7)/8);
   FC_ASSERT( end > old_end );
   return old_end;
}

222
DEFINE_INTRINSIC_FUNCTION1(env,printi,printi,none,i64,val) {
223
  std::cerr << uint64_t(val);
224
//  idump((val));
225
}
226

227
DEFINE_INTRINSIC_FUNCTION1(env,print,print,none,i32,charptr) {
228 229 230
  auto& wasm  = wasm_interface::get();
  auto  mem   = wasm.current_memory;

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

233 234
  std::cerr << std::string( str, strlen(str) );
//	wlog( std::string( str, strlen(size) ) );
235 236
}

237
DEFINE_INTRINSIC_FUNCTION1(env,free,free,none,i32,ptr) {
238 239
}

240
DEFINE_INTRINSIC_FUNCTION1(env,toUpper,toUpper,none,i32,charptr) {
241 242 243 244 245 246 247 248 249 250 251 252 253
   std::cerr << "TO UPPER CALLED\n";// << charptr << "\n";
//   std::cerr << "moduleInstance: " << moduleInstance << "\n";
  // /*U8* base = */Runtime::getMemoryBaseAddress( Runtime::getDefaultMemory(moduleInstance) );
   //std::cerr << "Base Address: " << (int64_t)base;
   //char* c = (char*)(base + charptr);
   char& c = Runtime::memoryRef<char>( Runtime::getDefaultMemory(wasm_interface::get().current_module), charptr );
//   std::cerr << "char: " << c <<"\n";
//   if( c > 'Z' ) c -= 32;
//   return 0;
}

   wasm_interface& wasm_interface::get() {
      static wasm_interface*  wasm = nullptr;
254
      if( !wasm )
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270
      {
         wlog( "Runtime::init" );
	       Runtime::init();
         wasm = new wasm_interface();
      }
      return *wasm;
   }



   struct RootResolver : Runtime::Resolver
   {
      std::map<std::string,Resolver*> moduleNameToResolverMap;

     bool resolve(const std::string& moduleName,const std::string& exportName,ObjectType type,ObjectInstance*& outObject) override
     {
271 272 273 274
         // Try to resolve an intrinsic first.
         if(IntrinsicResolver::singleton.resolve(moduleName,exportName,type,outObject)) { return true; }
         FC_ASSERT( !"unresolvable", "${module}.${export}", ("module",moduleName)("export",exportName) );
         return false;
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
     }
   };


   char* wasm_interface::vm_allocate( int bytes ) {
			FunctionInstance* alloc_function = asFunctionNullable(getInstanceExport(current_module,"alloc"));
	    const FunctionType* functionType = getFunctionType(alloc_function);
      FC_ASSERT( functionType->parameters.size() == 1 );
	    std::vector<Value> invokeArgs(1);
      invokeArgs[0] = U32(bytes);

      auto result = Runtime::invokeFunction(alloc_function,invokeArgs);

      return &memoryRef<char>( current_memory, result.i32 );
   }

   U32 wasm_interface::vm_pointer_to_offset( char* ptr ) {
      return U32(ptr - &memoryRef<char>(current_memory,0));
   }

295 296
   void  wasm_interface::vm_call( std::string name ) {
   try {
297
      try {
D
Daniel Larimer 已提交
298
         name += "_" + std::string( current_validate_context->msg.recipient ) + "_";
299
         name += std::string( current_validate_context->msg.type );
300

301
				 FunctionInstance* apply = asFunctionNullable(getInstanceExport(current_module,name.c_str()));
D
Daniel Larimer 已提交
302 303 304
		 		 if( !apply ) {
             return; /// if not found then it is a no-op
         } 
305

306
				 const FunctionType* functionType = getFunctionType(apply);
307 308
				 FC_ASSERT( functionType->parameters.size() == 0 );
				 std::vector<Value> args(0);
309 310 311 312 313 314

         auto& state = *current_state;
         char* memstart = &memoryRef<char>( current_memory, 0 );
         memset( memstart + state.mem_end, 0, ((1<<16) - state.mem_end) );
         memcpy( memstart, state.init_memory.data(), state.mem_end);

315 316 317 318 319 320
				 Runtime::invokeFunction(apply,args);
      } catch( const Runtime::Exception& e ) {
          edump((std::string(describeExceptionCause(e.cause))));
					edump((e.callStack));
					throw;
      }
321 322
   } FC_CAPTURE_AND_RETHROW( (name)(current_validate_context->msg.type) ) }

D
Daniel Larimer 已提交
323 324 325
   void  wasm_interface::vm_precondition() { vm_call("precondition" ); } 
   void  wasm_interface::vm_apply()        { vm_call("apply" );        }
   void  wasm_interface::vm_validate()     { vm_call("validate");       }
326

327
   void  wasm_interface::vm_onInit()
328 329
   { try {
      try {
330
         // wlog( "on_init" );
331
				 FunctionInstance* apply = asFunctionNullable(getInstanceExport(current_module,"init"));
332 333 334 335 336 337 338 339 340
		 		 if( !apply ) {
           wlog( "no onInit method found" );
					 return; /// if not found then it is a no-op
         }

				 const FunctionType* functionType = getFunctionType(apply);
				 FC_ASSERT( functionType->parameters.size() == 0 );

				 std::vector<Value> args(0);
341 342 343 344 345 346 347

				 Runtime::invokeFunction(apply,args);
      } catch( const Runtime::Exception& e ) {
          edump((std::string(describeExceptionCause(e.cause))));
					edump((e.callStack));
					throw;
      }
348
   } FC_CAPTURE_AND_RETHROW() }
349

350 351 352 353 354 355 356 357 358
   void wasm_interface::validate( message_validate_context& c ) {

      current_validate_context       = &c;
      current_precondition_context   = nullptr;
      current_apply_context          = nullptr;

      load( c.scope, c.db );
      vm_validate();
   }
359 360 361 362 363 364 365 366 367 368
   void wasm_interface::precondition( precondition_validate_context& c ) {
   try {

      current_validate_context       = &c;
      current_precondition_context   = &c;

      load( c.scope, c.db );
      vm_precondition();

   } FC_CAPTURE_AND_RETHROW() }
369 370


371 372
   void wasm_interface::apply( apply_context& c ) {
    try {
373 374 375 376 377

      current_validate_context       = &c;
      current_precondition_context   = &c;
      current_apply_context          = &c;

378
      load( c.scope, c.db );
379 380 381 382 383 384
      vm_apply();

   } FC_CAPTURE_AND_RETHROW() }

   void wasm_interface::init( apply_context& c ) {
    try {
385 386 387 388
      current_validate_context       = &c;
      current_precondition_context   = &c;
      current_apply_context          = &c;

389
      load( c.scope, c.db );
390
      vm_onInit();
391 392 393

   } FC_CAPTURE_AND_RETHROW() }

394

395

396 397 398 399 400 401 402 403 404 405
   void wasm_interface::load( const AccountName& name, const chainbase::database& db ) {
      const auto& recipient = db.get<account_object,by_name>( name );

      auto& state = instances[name];
      if( state.code_version != recipient.code_version ) {
         if( state.instance ) {
            /// TODO: free existing instance and module
#warning TODO: free existing module if the code has been updated, currently leak memory
            state.instance     = nullptr;
            state.module       = nullptr;
406
            state.code_version = fc::sha256();
407 408 409 410 411
         }
         state.module = new IR::Module();

        try
        {
412
          wlog( "LOADING CODE" );
413 414 415 416 417 418 419 420 421 422
          Serialization::MemoryInputStream stream((const U8*)recipient.code.data(),recipient.code.size());
          WASM::serialize(stream,*state.module);

          RootResolver rootResolver;
          LinkResult linkResult = linkModule(*state.module,rootResolver);
          state.instance = instantiateModule( *state.module, std::move(linkResult.resolvedImports) );
          FC_ASSERT( state.instance );
          current_memory = Runtime::getDefaultMemory(state.instance);

          char* memstart = &memoryRef<char>( current_memory, 0 );
423
         // state.init_memory.resize(1<<16); /// TODO: actually get memory size
424
          std::cerr <<"INIT MEMORY: \n";
425
          for( uint32_t i = 0; i < 10000; ++i )
426 427 428 429 430 431 432
              if( memstart[i] ) {
                   state.mem_end = i;
						//		 std::cerr << (char)memstart[i];
              }

          state.init_memory.resize(state.mem_end);
          memcpy( state.init_memory.data(), memstart, state.mem_end ); //state.init_memory.size() );
433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455
          std::cerr <<"\n";
          state.code_version = recipient.code_version;
        }
        catch(Serialization::FatalSerializationException exception)
        {
          std::cerr << "Error deserializing WebAssembly binary file:" << std::endl;
          std::cerr << exception.message << std::endl;
          throw;
        }
        catch(IR::ValidationException exception)
        {
          std::cerr << "Error validating WebAssembly binary file:" << std::endl;
          std::cerr << exception.message << std::endl;
          throw;
        }
        catch(std::bad_alloc)
        {
          std::cerr << "Memory allocation failed: input is likely malformed" << std::endl;
          throw;
        }
      }
      current_module = state.instance;
      current_memory = getDefaultMemory( current_module );
456
      current_state  = &state;
457
   }
458 459 460


} }