Esempio n. 1
0
static SharedBytes
CreateBytecode(const Bytes& env, const Bytes& code, const Bytes& tail, UniqueChars* error)
{
    size_t size = env.length() + code.length() + tail.length();
    if (size > MaxModuleBytes) {
        *error = DuplicateString("module too big");
        return nullptr;
    }

    MutableBytes bytecode = js_new<ShareableBytes>();
    if (!bytecode || !bytecode->bytes.resize(size))
        return nullptr;

    uint8_t* p = bytecode->bytes.begin();

    memcpy(p, env.begin(), env.length());
    p += env.length();

    memcpy(p, code.begin(), code.length());
    p += code.length();

    memcpy(p, tail.begin(), tail.length());
    p += tail.length();

    MOZ_ASSERT(p == bytecode->end());

    return bytecode;
}
Esempio n. 2
0
void GarbledCct3::gen_next_gen_inp_com(const Bytes &row, size_t kx)
{
	static Bytes tmp;

	__m128i out_key[2];
	tmp = m_prng.rand(Env::k());
	tmp.set_ith_bit(0, 0);
	tmp.resize(16, 0);
	out_key[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
	out_key[1] = _mm_xor_si128(out_key[0], m_R);

	Bytes msg(m_gen_inp_decom[0].size());
	for (size_t jx = 0; jx < Env::circuit().gen_inp_cnt(); jx++)
	{
		if (row.get_ith_bit(jx))
		{
			byte bit = m_gen_inp_mask.get_ith_bit(jx);
			msg ^= m_gen_inp_decom[2*jx+bit];
			//msg ^= m_gen_inp_decom[2*jx];
		}
	}

	__m128i in_key[2], aes_plaintext, aes_ciphertext;

	aes_plaintext = _mm_set1_epi64x((uint64_t)kx);

	tmp.assign(msg.begin(), msg.begin()+Env::key_size_in_bytes());
	tmp.resize(16, 0);
	in_key[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
	in_key[1] = _mm_xor_si128(in_key[0], m_R);

	KDF128((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)&in_key[0]);
	aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
	out_key[0] = _mm_xor_si128(out_key[0], aes_ciphertext);

	KDF128((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)&in_key[1]);
	aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
	out_key[1] = _mm_xor_si128(out_key[1], aes_ciphertext);

	const byte bit = msg.get_ith_bit(0);

	tmp.resize(16);
	_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), out_key[  bit]);
	m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

	_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), out_key[1-bit]);
	m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());
//	tmp.resize(16);
//	_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), out_key[0]);
//	std::cout << "GEN " << m_gen_inp_hash_ix << " : (" << tmp.to_hex();
//
//	tmp.resize(16);
//	_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), out_key[1]);
//	std::cout << ", " << tmp.to_hex() << ")" << std::endl;

	m_gen_inp_hash_ix++;
}
Esempio n. 3
0
bool ares::from_bytes(Date& date, Bytes const& bytes)
{
    if (bytes.size() < 7)
        return false;
    date.set(unpack_int16(bytes.begin()),   // year
             bytes.begin()[2],              // mon
             bytes.begin()[3],              // day
             bytes.begin()[4],              // hour
             bytes.begin()[5],              // min
             bytes.begin()[6]);             // sec
    return true;
}
Esempio n. 4
0
	restbed::Bytes Http::fetch(const std::string& delimiter, const std::shared_ptr<const restbed::Response>& response)
    {
        boost::system::error_code error;
        auto request = response->m_pimpl->m_request;
        const size_t size = request->m_pimpl->m_socket->read( request->m_pimpl->m_buffer, delimiter, error );
        
        if ( error )
        {
            throw runtime_error( String::format( "Socket receive failed: '%s'\n", error.message( ).data( ) ) );
        }
        
        const auto data_ptr = boost::asio::buffer_cast< const Byte* >( request->m_pimpl->m_buffer->data( ) );
        const Bytes data( data_ptr, data_ptr + size );
        request->m_pimpl->m_buffer->consume( size );
        
        auto& body = response->m_pimpl->m_body;
        
        if ( body.empty( ) )
        {
            body = data;
        }
        else
        {
            body.insert( body.end( ), data.begin( ), data.end( ) );
        }
        
        return data;
    }
Esempio n. 5
0
  bool RmpUsb::Receive(Bytes& rData, size_t size)
  {
    rData.resize(size + CRC_FEEDBACK_SIZE);

    boost::system::error_code errorCode;
    size_t bytesReceived = m_pImpl->Read(rData, TIMEOUT, errorCode);

    if (errorCode.value() != boost::system::errc::success)
    {
      SEGWAY_LOG(DEBUG, "Fail to receive usb packet: " << errorCode.message());

      return false;
    }
    
    if (bytesReceived != (size + CRC_FEEDBACK_SIZE))
    {
      SEGWAY_LOG(DEBUG, "Received usb packet of unexpected size: " << bytesReceived << ", expected: " << size + CRC_FEEDBACK_SIZE);
      
      return false;
    }
 
    if (!IsCrcValid(rData, bytesReceived))
    {
      SEGWAY_LOG(ERROR, "CRC mismatched on usb receive.");

      return false;
    }

    rData.erase(rData.begin() + size, rData.end());

    return true;
  }
Esempio n. 6
0
static UniqueChars
DecodeExportName(JSContext* cx, Decoder& d, CStringSet* dupSet)
{
    Bytes fieldBytes;
    if (!d.readBytes(&fieldBytes)) {
        Fail(cx, d, "expected export name");
        return nullptr;
    }

    if (memchr(fieldBytes.begin(), 0, fieldBytes.length())) {
        Fail(cx, d, "null in export names not yet supported");
        return nullptr;
    }

    if (!fieldBytes.append(0))
        return nullptr;

    UniqueChars fieldName((char*)fieldBytes.extractRawBuffer());
    if (!fieldName)
        return nullptr;

    CStringSet::AddPtr p = dupSet->lookupForAdd(fieldName.get());
    if (p) {
        Fail(cx, d, "duplicate export");
        return nullptr;
    }

    if (!dupSet->add(p, fieldName.get()))
        return nullptr;

    return Move(fieldName);
}
 void SkipGzipHeader(Bytes& data)
 {
   ::z_stream gz = {};
   ::gz_header header = {};
   int ret = ::inflateInit2(&gz, 15 + 32);
   gz.next_in = reinterpret_cast< ::Bytef *>(&(*data)[0]);
   gz.avail_in = (::uInt) data->size();
   ret = ::inflateGetHeader(&gz, &header);
   while (ret == Z_OK && !header.done)
   {
     Byte buf;
     gz.next_out = reinterpret_cast< ::Bytef *>(&buf);
     gz.avail_out = 1;
     ret = ::inflate(&gz, Z_BLOCK);
   }
   ::inflateEnd(&gz);
   size_t skip = gz.total_in;
   data->erase(data->begin(), data->begin() + skip);
 }
Esempio n. 8
0
static bool
GetProperty(JSContext* cx, HandleObject obj, const Bytes& bytes, MutableHandleValue v)
{
    JSAtom* atom = AtomizeUTF8Chars(cx, (char*)bytes.begin(), bytes.length());
    if (!atom)
        return false;

    RootedId id(cx, AtomToId(atom));
    return GetProperty(cx, obj, obj, id, v);
}
Esempio n. 9
0
bool
ModuleGenerator::finishLinkData(Bytes& code)
{
    // Inflate the global bytes up to page size so that the total bytes are a
    // page size (as required by the allocator functions).
    linkData_.globalDataLength = AlignBytes(linkData_.globalDataLength, gc::SystemPageSize());

    // Add links to absolute addresses identified symbolically.
    for (size_t i = 0; i < masm_.numAsmJSAbsoluteAddresses(); i++) {
        AsmJSAbsoluteAddress src = masm_.asmJSAbsoluteAddress(i);
        if (!linkData_.symbolicLinks[src.target].append(src.patchAt.offset()))
            return false;
    }

    // Relative link metadata: absolute addresses that refer to another point within
    // the asm.js module.

    // CodeLabels are used for switch cases and loads from floating-point /
    // SIMD values in the constant pool.
    for (size_t i = 0; i < masm_.numCodeLabels(); i++) {
        CodeLabel cl = masm_.codeLabel(i);
        LinkData::InternalLink inLink(LinkData::InternalLink::CodeLabel);
        inLink.patchAtOffset = masm_.labelToPatchOffset(*cl.patchAt());
        inLink.targetOffset = cl.target()->offset();
        if (!linkData_.internalLinks.append(inLink))
            return false;
    }

#if defined(JS_CODEGEN_X86)
    // Global data accesses in x86 need to be patched with the absolute
    // address of the global. Globals are allocated sequentially after the
    // code section so we can just use an InternalLink.
    for (GlobalAccess a : masm_.globalAccesses()) {
        LinkData::InternalLink inLink(LinkData::InternalLink::RawPointer);
        inLink.patchAtOffset = masm_.labelToPatchOffset(a.patchAt);
        inLink.targetOffset = code.length() + a.globalDataOffset;
        if (!linkData_.internalLinks.append(inLink))
            return false;
    }
#elif defined(JS_CODEGEN_X64)
    // Global data accesses on x64 use rip-relative addressing and thus we can
    // patch here, now that we know the final codeLength.
    for (GlobalAccess a : masm_.globalAccesses()) {
        void* from = code.begin() + a.patchAt.offset();
        void* to = code.end() + a.globalDataOffset;
        X86Encoding::SetRel32(from, to);
    }
#else
    // Global access is performed using the GlobalReg and requires no patching.
    MOZ_ASSERT(masm_.globalAccesses().length() == 0);
#endif

    return true;
}
Esempio n. 10
0
 Bytes Http::fetch( const size_t length, const shared_ptr< Response >& response )
 {
     if ( response == nullptr )
     {
         throw invalid_argument( String::empty );
     }
     
     auto request = response->m_pimpl->m_request;
     
     if ( request == nullptr or request->m_pimpl->m_buffer == nullptr or request->m_pimpl->m_socket == nullptr )
     {
         throw invalid_argument( String::empty );
     }
     
     Bytes data = { };
     
     if ( length > request->m_pimpl->m_buffer->size( ) )
     {
         error_code error;
         const size_t size = length - request->m_pimpl->m_buffer->size( );
         
         request->m_pimpl->m_socket->read( request->m_pimpl->m_buffer, size, error );
         
         if ( error and error not_eq asio::error::eof )
         {
             throw runtime_error( String::format( "Socket receive failed: '%s'", error.message( ).data( ) ) );
         }
         
         const auto data_ptr = asio::buffer_cast< const Byte* >( request->m_pimpl->m_buffer->data( ) );
         data = Bytes( data_ptr, data_ptr + length );
         request->m_pimpl->m_buffer->consume( length );
     }
     else
     {
         const auto data_ptr = asio::buffer_cast< const Byte* >( request->m_pimpl->m_buffer->data( ) );
         data = Bytes( data_ptr, data_ptr + length );
         request->m_pimpl->m_buffer->consume( length );
     }
     
     auto& body = response->m_pimpl->m_body;
     
     if ( body.empty( ) )
     {
         body = data;
     }
     else
     {
         body.insert( body.end( ), data.begin( ), data.end( ) );
     }
     
     return data;
 }
Esempio n. 11
0
/* static */ UniqueCodeSegment
CodeSegment::create(JSContext* cx,
                    const Bytes& bytecode,
                    const LinkData& linkData,
                    const Metadata& metadata,
                    HandleWasmMemoryObject memory)
{
    MOZ_ASSERT(bytecode.length() % gc::SystemPageSize() == 0);
    MOZ_ASSERT(linkData.globalDataLength % gc::SystemPageSize() == 0);
    MOZ_ASSERT(linkData.functionCodeLength < bytecode.length());

    auto cs = cx->make_unique<CodeSegment>();
    if (!cs)
        return nullptr;

    cs->bytes_ = AllocateCodeSegment(cx, bytecode.length() + linkData.globalDataLength);
    if (!cs->bytes_)
        return nullptr;

    uint8_t* codeBase = cs->base();

    cs->functionCodeLength_ = linkData.functionCodeLength;
    cs->codeLength_ = bytecode.length();
    cs->globalDataLength_ = linkData.globalDataLength;
    cs->interruptCode_ = codeBase + linkData.interruptOffset;
    cs->outOfBoundsCode_ = codeBase + linkData.outOfBoundsOffset;
    cs->unalignedAccessCode_ = codeBase + linkData.unalignedAccessOffset;
    cs->badIndirectCallCode_ = codeBase + linkData.badIndirectCallOffset;

    {
        JitContext jcx(CompileRuntime::get(cx->compartment()->runtimeFromAnyThread()));
        AutoFlushICache afc("CodeSegment::create");
        AutoFlushICache::setRange(uintptr_t(codeBase), cs->codeLength());

        memcpy(codeBase, bytecode.begin(), bytecode.length());
        StaticallyLink(*cs, linkData, cx);
        if (memory)
            SpecializeToMemory(*cs, metadata, memory);
    }

    if (!ExecutableAllocator::makeExecutable(codeBase, cs->codeLength())) {
        ReportOutOfMemory(cx);
        return nullptr;
    }

    if (!SendCodeRangesToProfiler(cx, *cs, bytecode, metadata))
        return nullptr;

    return cs;
}
Esempio n. 12
0
	restbed::Bytes Http::fetch(const std::size_t length, const std::shared_ptr<const restbed::Response>& response)
    {
        Bytes data = { };
        auto request = response->get_request( );
        
        if ( length > request->m_pimpl->m_buffer->size( ) )
        {
            boost::system::error_code error;
            const size_t adjusted_length = length - request->m_pimpl->m_buffer->size( );
            
            const size_t size = request->m_pimpl->m_socket->read( request->m_pimpl->m_buffer, adjusted_length, error );
            
            if ( error and error not_eq boost::asio::error::eof )
            {
                throw runtime_error( String::format( "Socket receive failed: '%s'\n", error.message( ).data( ) ) );
            }
            
            const auto data_ptr = boost::asio::buffer_cast< const Byte* >( request->m_pimpl->m_buffer->data( ) );
            data = Bytes( data_ptr, data_ptr + size );
            request->m_pimpl->m_buffer->consume( size );
        }
        else
        {
            const auto data_ptr = boost::asio::buffer_cast< const Byte* >( request->m_pimpl->m_buffer->data( ) );
            data = Bytes( data_ptr, data_ptr + length );
            request->m_pimpl->m_buffer->consume( length );
        }
        
        auto& body = response->m_pimpl->m_body;
        
        if ( body.empty( ) )
        {
            body = data;
        }
        else
        {
            body.insert( body.end( ), data.begin( ), data.end( ) );
        }
        
        return data;
    }
Esempio n. 13
0
 Bytes Http::fetch( const string& delimiter, const shared_ptr< Response >& response )
 {
     if ( response == nullptr )
     {
         throw invalid_argument( String::empty );
     }
     
     auto request = response->m_pimpl->m_request;
     
     if ( request == nullptr or request->m_pimpl->m_buffer == nullptr or request->m_pimpl->m_socket == nullptr )
     {
         throw invalid_argument( String::empty );
     }
     
     error_code error;
     const size_t size = request->m_pimpl->m_socket->read( request->m_pimpl->m_buffer, delimiter, error );
     
     if ( error )
     {
         throw runtime_error( String::format( "Socket receive failed: '%s'", error.message( ).data( ) ) );
     }
     
     const auto data_ptr = asio::buffer_cast< const Byte* >( request->m_pimpl->m_buffer->data( ) );
     const Bytes data( data_ptr, data_ptr + size );
     request->m_pimpl->m_buffer->consume( size );
     
     auto& body = response->m_pimpl->m_body;
     
     if ( body.empty( ) )
     {
         body = data;
     }
     else
     {
         body.insert( body.end( ), data.begin( ), data.end( ) );
     }
     
     return data;
 }
Esempio n. 14
0
 string Uri::decode( const Bytes& value )
 {
     return decode( string( value.begin( ), value.end( ) ) );
 }
void GarbledCct::gen_next_gate(const Gate &current_gate)
{
	__m128i current_zero_key;

	if (current_gate.m_tag == Circuit::GEN_INP)
	{
		__m128i a[2];

		// zero_key = m_prng.rand(Env::k());
		static Bytes tmp;

		tmp = m_prng.rand(Env::k());
		tmp.resize(16, 0);
		current_zero_key = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));

		// a[0] = m_M[2*m_gen_inp_ix+0].to_bytes().hash(Env::k());
		tmp = m_M[2*m_gen_inp_ix+0].to_bytes().hash(Env::k());
		tmp.resize(16, 0);
		a[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));

		// a[1] = m_M[2*m_gen_inp_ix+1].to_bytes().hash(Env::k());
		tmp = m_M[2*m_gen_inp_ix+1].to_bytes().hash(Env::k());
		tmp.resize(16, 0);
		a[1] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));

		// a[0] ^= zero_key; a[1] ^= zero_key ^ R;
		a[0] = _mm_xor_si128(a[0], current_zero_key);
		a[1] = _mm_xor_si128(a[1], _mm_xor_si128(current_zero_key, m_R));

		uint8_t bit = m_gen_inp_mask.get_ith_bit(m_gen_inp_ix);

		// m_o_bufr += a[bit];
		_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), a[bit]);
		m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

		// m_o_bufr += a[1-bit];
		_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), a[1-bit]);
		m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

		m_gen_inp_ix++;
	}
	else if (current_gate.m_tag == Circuit::EVL_INP)
	{
		__m128i a[2];

		// zero_key = m_prng.rand(Env::k());
		static Bytes tmp;

		tmp = m_prng.rand(Env::k());
		tmp.resize(16, 0);
		current_zero_key = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));

		// a[0] = (*m_ot_keys)[2*m_evl_inp_ix+0];
		tmp = (*m_ot_keys)[2*m_evl_inp_ix+0];
		tmp.resize(16, 0);
		a[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));

		// a[1] = (*m_ot_keys)[2*m_evl_inp_ix+1];
		tmp = (*m_ot_keys)[2*m_evl_inp_ix+1];
		tmp.resize(16, 0);
		a[1] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));

		// a[0] ^= zero_key; a[1] ^= zero_key ^ R;
		a[0] = _mm_xor_si128(a[0], current_zero_key);
		a[1] = _mm_xor_si128(a[1], _mm_xor_si128(current_zero_key, m_R));

		// m_o_bufr += a[0];
		_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), a[0]);
		m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

		// m_o_bufr += a[1];
		_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), a[1]);
		m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

		m_evl_inp_ix++;
	}
	else
	{
		const vector<uint64_t> &inputs = current_gate.m_input_idx;
		assert(inputs.size() == 1 || inputs.size() == 2);

#ifdef FREE_XOR
		if (is_xor(current_gate))
		{
			current_zero_key = inputs.size() == 2?
				_mm_xor_si128(m_w[inputs[0]], m_w[inputs[1]]) : _mm_load_si128(m_w+inputs[0]);
		}
		else
#endif
		if (inputs.size() == 2) // 2-arity gates
		{
			uint8_t bit;
			__m128i aes_key[2], aes_plaintext, aes_ciphertext;
			__m128i X[2], Y[2], Z[2];
			static Bytes tmp(16, 0);

			aes_plaintext = _mm_set1_epi64x(m_gate_ix);

			X[0] = _mm_load_si128(m_w+inputs[0]);
			Y[0] = _mm_load_si128(m_w+inputs[1]);

			X[1] = _mm_xor_si128(X[0], m_R); // X[1] = X[0] ^ R
			Y[1] = _mm_xor_si128(Y[0], m_R); // Y[1] = Y[0] ^ R

			const uint8_t perm_x = _mm_extract_epi8(X[0], 0) & 0x01; // permutation bit for X
			const uint8_t perm_y = _mm_extract_epi8(Y[0], 0) & 0x01; // permutation bit for Y
			const uint8_t de_garbled_ix = (perm_y<<1)|perm_x;

			// encrypt the 0-th entry : (X[x], Y[y])
			aes_key[0] = _mm_load_si128(X+perm_x);
			aes_key[1] = _mm_load_si128(Y+perm_y);

			KDF256((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)aes_key);
			aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask); // clear extra bits so that only k bits left
			bit = current_gate.m_table[de_garbled_ix];

#ifdef GRR
			// GRR technique: using zero entry's key as one of the output keys
			_mm_store_si128(Z+bit, aes_ciphertext);
			Z[1-bit] = _mm_xor_si128(Z[bit], m_R);
			current_zero_key = _mm_load_si128(Z);
#else
			tmp = m_prng.rand(Env::k());
			tmp.resize(16, 0);
			Z[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
			Z[1] = _mm_xor_si128(Z[0], m_R);

			aes_ciphertext = _mm_xor_si128(aes_ciphertext, Z[bit]);
			_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), aes_ciphertext);
			m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());
#endif

			// encrypt the 1st entry : (X[1-x], Y[y])
			aes_key[0] = _mm_xor_si128(aes_key[0], m_R);

			KDF256((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)aes_key);
			aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
			bit = current_gate.m_table[0x01^de_garbled_ix];
			aes_ciphertext = _mm_xor_si128(aes_ciphertext, Z[bit]);
			_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), aes_ciphertext);
			m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

			// encrypt the 2nd entry : (X[x], Y[1-y])
			aes_key[0] = _mm_xor_si128(aes_key[0], m_R);
			aes_key[1] = _mm_xor_si128(aes_key[1], m_R);

			KDF256((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)aes_key);
			aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
			bit = current_gate.m_table[0x02^de_garbled_ix];
			aes_ciphertext = _mm_xor_si128(aes_ciphertext, Z[bit]);
			_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), aes_ciphertext);
			m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());

			// encrypt the 3rd entry : (X[1-x], Y[1-y])
			aes_key[0] = _mm_xor_si128(aes_key[0], m_R);

			KDF256((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)aes_key);
			aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
			bit = current_gate.m_table[0x03^de_garbled_ix];
			aes_ciphertext = _mm_xor_si128(aes_ciphertext, Z[bit]);
			_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), aes_ciphertext);
			m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());
		}
		else // 1-arity gates
		{
			uint8_t bit;
			__m128i aes_key, aes_plaintext, aes_ciphertext;
			__m128i X[2], Z[2];
			static Bytes tmp;

			tmp.assign(16, 0);

			aes_plaintext = _mm_set1_epi64x(m_gate_ix);

			X[0] = _mm_load_si128(m_w+inputs[0]);
			X[1] = _mm_xor_si128(X[0], m_R);

			const uint8_t perm_x = _mm_extract_epi8(X[0], 0) & 0x01;

			// 0-th entry : X[x]
			aes_key = _mm_load_si128(X+perm_x);
			KDF128((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)&aes_key);
			aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
			bit = current_gate.m_table[perm_x];

#ifdef GRR
			_mm_store_si128(Z+bit, aes_ciphertext);
			Z[1-bit] = _mm_xor_si128(Z[bit], m_R);
			current_zero_key = _mm_load_si128(Z);
#else
			tmp = m_prng.rand(Env::k());
			tmp.resize(16, 0);
			Z[0] = _mm_loadu_si128(reinterpret_cast<__m128i*>(&tmp[0]));
			Z[1] = _mm_xor_si128(Z[0], m_R);

			aes_ciphertext = _mm_xor_si128(aes_ciphertext, Z[bit]);
			_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), aes_ciphertext);
			m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());
#endif

			// 1-st entry : X[1-x]
			aes_key = _mm_xor_si128(aes_key, m_R);

			KDF128((uint8_t*)&aes_plaintext, (uint8_t*)&aes_ciphertext, (uint8_t*)&aes_key);
			aes_ciphertext = _mm_and_si128(aes_ciphertext, m_clear_mask);
			bit = current_gate.m_table[0x01^perm_x];
			aes_ciphertext = _mm_xor_si128(aes_ciphertext, Z[bit]);
			_mm_storeu_si128(reinterpret_cast<__m128i*>(&tmp[0]), aes_ciphertext);
			m_o_bufr.insert(m_o_bufr.end(), tmp.begin(), tmp.begin()+Env::key_size_in_bytes());
		}

		if (current_gate.m_tag == Circuit::EVL_OUT)
		{
			m_o_bufr.push_back(_mm_extract_epi8(current_zero_key, 0) & 0x01); // permutation bit
		}
		else if (current_gate.m_tag == Circuit::GEN_OUT)
		{
			m_o_bufr.push_back(_mm_extract_epi8(current_zero_key, 0) & 0x01); // permutation bit

//			// TODO: C[ix_0] = w[ix0] || randomness, C[ix_1] = w[ix1] || randomness
//			m_o_bufr += (key_pair[0] + m_prng.rand(Env::k())).hash(Env::k());
//			m_o_bufr += (key_pair[1] + m_prng.rand(Env::k())).hash(Env::k());
		}
	}

	_mm_store_si128(m_w+current_gate.m_idx, current_zero_key);

	m_gate_ix++;
}
Esempio n. 16
0
SharedModule
ModuleGenerator::finish(const ShareableBytes& bytecode)
{
    MOZ_ASSERT(!activeFunc_);
    MOZ_ASSERT(finishedFuncDefs_);

    // Now that all asm.js tables have been created and the compiler threads are
    // done, shrink the (no longer shared) tables vector down to size.
    if (isAsmJS() && !shared_->tables.resize(numTables_))
        return nullptr;

    if (!finishFuncExports())
        return nullptr;

    if (!finishCodegen())
        return nullptr;

    // Round up the code size to page size since this is eventually required by
    // the executable-code allocator and for setting memory protection.
    uint32_t bytesNeeded = masm_.bytesNeeded();
    uint32_t padding = ComputeByteAlignment(bytesNeeded, gc::SystemPageSize());

    // Use initLengthUninitialized so there is no round-up allocation nor time
    // wasted zeroing memory.
    Bytes code;
    if (!code.initLengthUninitialized(bytesNeeded + padding))
        return nullptr;

    // Delay flushing of the icache until CodeSegment::create since there is
    // more patching to do before this code becomes executable.
    {
        AutoFlushICache afc("ModuleGenerator::finish", /* inhibit = */ true);
        masm_.executableCopy(code.begin());
    }

    // Zero the padding, since we used resizeUninitialized above.
    memset(code.begin() + bytesNeeded, 0, padding);

    // Convert the CallSiteAndTargetVector (needed during generation) to a
    // CallSiteVector (what is stored in the Module).
    if (!metadata_->callSites.appendAll(masm_.callSites()))
        return nullptr;

    // The MacroAssembler has accumulated all the memory accesses during codegen.
    metadata_->memoryAccesses = masm_.extractMemoryAccesses();
    metadata_->boundsChecks = masm_.extractBoundsChecks();

    // Copy over data from the ModuleGeneratorData.
    metadata_->memoryUsage = shared_->memoryUsage;
    metadata_->minMemoryLength = shared_->minMemoryLength;
    metadata_->maxMemoryLength = shared_->maxMemoryLength;
    metadata_->tables = Move(shared_->tables);
    metadata_->globals = Move(shared_->globals);

    // These Vectors can get large and the excess capacity can be significant,
    // so realloc them down to size.
    metadata_->memoryAccesses.podResizeToFit();
    metadata_->boundsChecks.podResizeToFit();
    metadata_->codeRanges.podResizeToFit();
    metadata_->callSites.podResizeToFit();
    metadata_->callThunks.podResizeToFit();

    // Assert CodeRanges are sorted.
#ifdef DEBUG
    uint32_t lastEnd = 0;
    for (const CodeRange& codeRange : metadata_->codeRanges) {
        MOZ_ASSERT(codeRange.begin() >= lastEnd);
        lastEnd = codeRange.end();
    }
#endif

    if (!finishLinkData(code))
        return nullptr;

    return SharedModule(js_new<Module>(Move(code),
                                       Move(linkData_),
                                       Move(imports_),
                                       Move(exports_),
                                       Move(dataSegments_),
                                       Move(elemSegments_),
                                       *metadata_,
                                       bytecode));
}
Esempio n. 17
0
 void ByteStream::appendBytes(const Bytes& bytes)
 {
     m_bytes.insert(m_bytes.end(), bytes.begin(), bytes.end());
 }
Esempio n. 18
0
Bytes& StbFontRenderer::RenderText(
    const FontPtr&        data,
    const FontProperties& properties,
    cstring               text,
    Bytes&                output,
    Size&                 imageSize)
{
    using irect = rect<int>;

    auto stb_data = &data->info;
    auto scale    = properties.scale;

    Bytes stringData = Bytes::CreateString(text);
    szptr bit_w      = 0;
    int   x          = 0;

    /* We use this to find kerning character */
    auto shadowChar = stringData.begin();

    for(auto c : stringData)
    {
        irect bbox = {};
        stbtt_GetCodepointBitmapBox(
            stb_data, c, scale, scale, &bbox.x, &bbox.y, &bbox.w, &bbox.h);

        int y = properties.ascent + bbox.y, ax = 0, kern = 0;

        stbtt_GetCodepointHMetrics(stb_data, c, &ax, nullptr);
        kern = stbtt_GetCodepointKernAdvance(stb_data, c, *shadowChar);

        x += scale * (ax + kern);

        imageSize.w = CMath::max<u32>(imageSize.w, x + (bbox.w - bbox.x));
        imageSize.h = CMath::max<u32>(imageSize.h, y + (bbox.h - bbox.y));
    }

    bit_w      = C_FCAST<szptr>(imageSize.w);
    output     = Bytes::Alloc(imageSize.area());
    shadowChar = stringData.begin();
    x          = 0;

    for(auto c : stringData)
    {
        ++shadowChar;

        irect bbox = {};
        stbtt_GetCodepointBitmapBox(
            stb_data, c, scale, scale, &bbox.x, &bbox.y, &bbox.w, &bbox.h);

        int y = properties.ascent + bbox.y, ax = 0, kern = 0;

        szptr offset = C_FCAST<szptr>(x + y * bit_w);

        stbtt_MakeCodepointBitmap(
            stb_data,
            &output[offset],
            (bbox.w - bbox.x),
            (bbox.h - bbox.y),
            bit_w,
            scale,
            scale,
            c);

        stbtt_GetCodepointHMetrics(stb_data, c, &ax, nullptr);
        kern = stbtt_GetCodepointKernAdvance(stb_data, c, *shadowChar);

        x += scale * (ax + kern);
    }

    return output;
}