예제 #1
0
Future<Socket> accept(int fd)
{
  Try<int> accepted = network::accept(fd);
  if (accepted.isError()) {
    return Failure(accepted.error());
  }

  int s = accepted.get();
  Try<Nothing> nonblock = os::nonblock(s);
  if (nonblock.isError()) {
    LOG_IF(INFO, VLOG_IS_ON(1)) << "Failed to accept, nonblock: "
                                << nonblock.error();
    os::close(s);
    return Failure("Failed to accept, nonblock: " + nonblock.error());
  }

  Try<Nothing> cloexec = os::cloexec(s);
  if (cloexec.isError()) {
    LOG_IF(INFO, VLOG_IS_ON(1)) << "Failed to accept, cloexec: "
                                << cloexec.error();
    os::close(s);
    return Failure("Failed to accept, cloexec: " + cloexec.error());
  }

  // Turn off Nagle (TCP_NODELAY) so pipelined requests don't wait.
  // NOTE: We cast to `char*` here because the function prototypes on Windows
  // use `char*` instead of `void*`.
  int on = 1;
  if (::setsockopt(
          s,
          SOL_TCP,
          TCP_NODELAY,
          reinterpret_cast<const char*>(&on),
          sizeof(on)) < 0) {
    const string error = os::strerror(errno);
    VLOG(1) << "Failed to turn off the Nagle algorithm: " << error;
    os::close(s);
    return Failure(
      "Failed to turn off the Nagle algorithm: " + stringify(error));
  }

  Try<Socket> socket = Socket::create(Socket::DEFAULT_KIND(), s);
  if (socket.isError()) {
    os::close(s);
    return Failure("Failed to accept, create socket: " + socket.error());
  }
  return socket.get();
}
예제 #2
0
	void HeaderTagger::addHeaderForDecl(const core::NodePtr& node, const clang::Decl* decl, bool attachUserDefined) const {

		// check whether there is a declaration at all
		if (!decl) return;

		// the node was already annotated, what is the point of doint it again?
		if (insieme::annotations::c::hasIncludeAttached(node))  
			return;

		if (VLOG_IS_ON(2)){
			std::string name("UNNAMED");
			if (const clang::NamedDecl* nmd = llvm::dyn_cast<clang::NamedDecl>(decl))
				name = nmd->getQualifiedNameAsString();
			VLOG(2) << "Searching header for: " << node << " of type " << node->getNodeType() << " [clang: " << name << "]" ;
		}

		string fileName = getTopLevelInclude(decl->getLocation());

		// file must be a header file
		if (!isHeaderFile(fileName)) {
			VLOG(2) << "'" << fileName << "' not a headerfile";
			return;			// not to be attached
		}

		// do not add headers for external declarations unless those are within the std-library
		if (const clang::FunctionDecl* funDecl = llvm::dyn_cast<clang::FunctionDecl>(decl)) {
			// TODO: this is just based on integration tests - to make them work, no real foundation :(
			if( funDecl->isExternC() && 
				!(isStdLibHeader(fileName) || isIntrinsicHeader(fileName)) ) return;
		}

		// get absolute path of header file
		fs::path header = fs::canonical(fileName);

		if (auto oclHeader = isOCLHeader(header)){
			VLOG(2) << "OCL		header to be attached: " << oclHeader;
			insieme::annotations::c::attachInclude(node, *oclHeader);
			return;
		}if( auto stdLibHeader = toStdLibHeader(header) ) {
			header = *stdLibHeader;
		} else if (auto interceptedLibHeader = toInterceptedLibHeader(header) ) {
			header = *interceptedLibHeader;
		} else if( auto intrinsicHeader = toIntrinsicHeader(header) ) {
			header = *intrinsicHeader;
		} else if (auto userLibHeader = toUserLibHeader(header) ) {
			if(attachUserDefined ) {
				header = *userLibHeader;
			} else {
				return;
			}
		}

		VLOG(2) << "		header to be attached: " << header.string();

		// use resulting header
		insieme::annotations::c::attachInclude(node, header.string());
		}
예제 #3
0
  // AsyncSSLSocket::HandshakeCallback API
  void handshakeSuc(AsyncSSLSocket* sock) noexcept override {

    const unsigned char* nextProto = nullptr;
    unsigned nextProtoLength = 0;
    sock->getSelectedNextProtocol(&nextProto, &nextProtoLength);
    if (VLOG_IS_ON(3)) {
      if (nextProto) {
        VLOG(3) << "Client selected next protocol " <<
            string((const char*)nextProto, nextProtoLength);
      } else {
        VLOG(3) << "Client did not select a next protocol";
      }
    }

    // fill in SSL-related fields from TransportInfo
    // the other fields like RTT are filled in the Acceptor
    tinfo_.ssl = true;
    tinfo_.acceptTime = acceptTime_;
    tinfo_.sslSetupTime = std::chrono::duration_cast<std::chrono::milliseconds>(
      std::chrono::steady_clock::now() - acceptTime_
    );
    tinfo_.sslSetupBytesRead = sock->getRawBytesReceived();
    tinfo_.sslSetupBytesWritten = sock->getRawBytesWritten();
    tinfo_.sslServerName = sock->getSSLServerName() ?
      std::make_shared<std::string>(sock->getSSLServerName()) : nullptr;
    tinfo_.sslCipher = sock->getNegotiatedCipherName() ?
      std::make_shared<std::string>(sock->getNegotiatedCipherName()) : nullptr;
    tinfo_.sslVersion = sock->getSSLVersion();
    tinfo_.sslCertSize = sock->getSSLCertSize();
    tinfo_.sslResume = SSLUtil::getResumeState(sock);
    tinfo_.sslClientCiphers = std::make_shared<std::string>();
    sock->getSSLClientCiphers(*tinfo_.sslClientCiphers);
    tinfo_.sslServerCiphers = std::make_shared<std::string>();
    sock->getSSLServerCiphers(*tinfo_.sslServerCiphers);
    tinfo_.sslClientComprMethods =
        std::make_shared<std::string>(sock->getSSLClientComprMethods());
    tinfo_.sslClientExts =
        std::make_shared<std::string>(sock->getSSLClientExts());
    tinfo_.sslNextProtocol = std::make_shared<std::string>();
    tinfo_.sslNextProtocol->assign(reinterpret_cast<const char*>(nextProto),
                                  nextProtoLength);

    acceptor_->updateSSLStats(
      sock,
      tinfo_.sslSetupTime,
      SSLErrorEnum::NO_ERROR
    );
    acceptor_->downstreamConnectionManager_->removeConnection(this);
    acceptor_->sslConnectionReady(std::move(socket_), clientAddr_,
        nextProto ? string((const char*)nextProto, nextProtoLength) :
                                  empty_string, tinfo_);
    delete this;
  }
예제 #4
0
Future<Socket> accept(int fd)
{
  Try<int> accepted = network::accept(fd);
  if (accepted.isError()) {
    return Failure(accepted.error());
  }

  int s = accepted.get();
  Try<Nothing> nonblock = os::nonblock(s);
  if (nonblock.isError()) {
    LOG_IF(INFO, VLOG_IS_ON(1)) << "Failed to accept, nonblock: "
                                << nonblock.error();
    os::close(s);
    return Failure("Failed to accept, nonblock: " + nonblock.error());
  }

  Try<Nothing> cloexec = os::cloexec(s);
  if (cloexec.isError()) {
    LOG_IF(INFO, VLOG_IS_ON(1)) << "Failed to accept, cloexec: "
                                << cloexec.error();
    os::close(s);
    return Failure("Failed to accept, cloexec: " + cloexec.error());
  }

  // Turn off Nagle (TCP_NODELAY) so pipelined requests don't wait.
  int on = 1;
  if (setsockopt(s, SOL_TCP, TCP_NODELAY, &on, sizeof(on)) < 0) {
    const char* error = strerror(errno);
    VLOG(1) << "Failed to turn off the Nagle algorithm: " << error;
    os::close(s);
    return Failure(
      "Failed to turn off the Nagle algorithm: " + stringify(error));
  }

  Try<Socket> socket = Socket::create(Socket::DEFAULT_KIND(), s);
  if (socket.isError()) {
    return Failure("Failed to accept, create socket: " + socket.error());
  }
  return socket.get();
}
예제 #5
0
std::ostream &operator<<(std::ostream &stream, struct nl_object *n) {
  if (n == nullptr) {
    stream << "<nullptr>";
    return stream;
  }

  if (VLOG_IS_ON(3)) {
    stream << "(nl_obj=" << static_cast<const void *>(n) << ") ";
    p.dp_type = NL_DUMP_DETAILS;
  }

  nl_object_dump(n, &p);
  stream << buf.data();
  return stream;
}
예제 #6
0
std::ostream &operator<<(std::ostream &stream, const struct nl_addr *addr) {
  if (addr == nullptr) {
    stream << "<nullptr>";
    return stream;
  }

  if (VLOG_IS_ON(3)) {
    stream << "(addr_obj=" << static_cast<const void *>(addr) << ") ";
    p.dp_type = NL_DUMP_DETAILS;
  }

  nl_addr2str(addr, buf.data(), buf.capacity());
  stream << buf.data();
  return stream;
}
예제 #7
0
int64_t ThriftServer::getLoad(const std::string& counter, bool check_custom) {
  if (check_custom && getLoad_) {
    return getLoad_(counter);
  }

  int reqload = 0;
  int connload = 0;
  int queueload = 0;
  if (maxRequests_ > 0) {
    reqload = (100*(activeRequests_ + getPendingCount()))
      / ((float)maxRequests_);
  }
  auto ioGroup = getIOGroupSafe();
  auto workerFactory = ioGroup != nullptr ?
    std::dynamic_pointer_cast<wangle::NamedThreadFactory>(
      ioGroup->getThreadFactory()) : nullptr;

  if (maxConnections_ > 0) {
    int32_t connections = 0;
    forEachWorker([&](wangle::Acceptor* acceptor) mutable {
      auto worker = dynamic_cast<Cpp2Worker*>(acceptor);
      connections += worker->getPendingCount();
    });

    connload = (100*connections) / (float)maxConnections_;
  }

  auto tm = getThreadManager();
  if (tm) {
    auto codel = tm->getCodel();
    if (codel) {
      queueload = codel->getLoad();
    }
  }

  if (VLOG_IS_ON(1) && workerFactory) {
    FB_LOG_EVERY_MS(INFO, 1000 * 10)
      << workerFactory->getNamePrefix() << " load is: "
      << reqload << "% requests, "
      << connload << "% connections, "
      << queueload << "% queue time, "
      << activeRequests_ << " active reqs, "
      << getPendingCount() << " pending reqs";
  }

  int load = std::max({reqload, connload, queueload});
  return load;
}
예제 #8
0
std::ostream &operator<<(std::ostream &stream, struct rtnl_nexthop *nh) {
  if (nh == nullptr) {
    stream << "<nullptr>";
    return stream;
  }

  if (VLOG_IS_ON(3)) {
    stream << "(nh_obj=" << static_cast<const void *>(nh) << ") ";
    p.dp_type = NL_DUMP_DETAILS;
    p.dp_ivar = NH_DUMP_FROM_DETAILS;
  }

  rtnl_route_nh_dump(nh, &p);
  stream << buf.data();
  return stream;
}
void FlowControlFilter::onBody(StreamID stream,
                               std::unique_ptr<folly::IOBuf> chain,
                               uint16_t padding) {
  uint64_t amount = chain->computeChainDataLength();
  if (!recvWindow_.reserve(amount + padding)) {
    error_ = true;
    HTTPException ex = getException(
      folly::to<std::string>(
        "Failed to reserve receive window, window size=",
        recvWindow_.getSize(), ", amount=", amount));
    callback_->onError(0, ex, false);
  } else {
    if (VLOG_IS_ON(4) && recvWindow_.getSize() == 0) {
      VLOG(4) << "recvWindow full";
    }
    toAck_ += padding;
    CHECK(recvWindow_.free(padding));
    callback_->onBody(stream, std::move(chain), padding);
  }
}
예제 #10
0
// v w is the two points of the line segment, p is the test point
//float minimum_distance(cv::Mat v, cv::Mat w, cv::Mat p) {
float minimum_distance(cv::Point2f v, cv::Point2f w, cv::Point2f p, cv::Point2f& closest) {
  
  // Return minimum distance between line segment vw and point p
  float l2 = cv::norm(w - v); 
  l2 *= l2;
  //const float l2 = cv::norm(cv::Mat(v - w), cv::NORM_L1);  // i.e. |w-v|^2 -  avoid a sqrt
  if (l2 == 0.0) {
    closest = v;
    return cv::norm(p - v);   // v == w case
  }
  // Consider the line extending the segment, parameterized as v + t (w - v).
  // We find projection of point p onto the line. 
  // It falls where t = [(p-v) . (w-v)] / |w-v|^2
  const float t = ((p - v).dot(w - v)) / l2;
  if (t < 0.0) {
    closest = v;
    return cv::norm(p - v);       // Beyond the 'v' end of the segment
  } else if (t > 1.0) {
    closest = w;
    return cv::norm(p - w);  // Beyond the 'w' end of the segment
  }
    
  closest = v + t * (w - v);  // Projection falls on the segment
 
  const float dist = cv::norm(p - closest);
  if (VLOG_IS_ON(3)) {
    LOG_FIRST_N(INFO, 10) << v.x << " " << v.y << ", " 
      << w.x << " " << w.y << ", " 
      << p.x << " " << p.y << ", "
      << closest.x << " " << closest.y << ", "
      << l2 << " " << t << " " <<  dist
      ;
  }

  return dist;
}
void
PredictorMfe2dHeuristic::
predict( const IndexRange & r1
		, const IndexRange & r2
		, const OutputConstraint & outConstraint
		)
{
#if INTARNA_MULITHREADING
	#pragma omp critical(intarna_omp_logOutput)
#endif
	{ VLOG(2) <<"predicting mfe interactions heuristically in O(n^2) space and time..."; }
	// measure timing
	TIMED_FUNC_IF(timerObj,VLOG_IS_ON(9));

#if INTARNA_IN_DEBUG_MODE
	// check indices
	if (!(r1.isAscending() && r2.isAscending()) )
		throw std::runtime_error("PredictorMfe2dHeuristic::predict("+toString(r1)+","+toString(r2)+") is not sane");
#endif


	// set index offset
	energy.setOffset1(r1.from);
	energy.setOffset2(r2.from);

	// resize matrix
	hybridE.resize( std::min( energy.size1()
						, (r1.to==RnaSequence::lastPos?energy.size1()-1:r1.to)-r1.from+1 )
				, std::min( energy.size2()
						, (r2.to==RnaSequence::lastPos?energy.size2()-1:r2.to)-r2.from+1 ) );

	// temp vars
	size_t i1,i2,w1,w2;

	// init matrix
	bool isValidCell = true;
	for (i1=0; i1<hybridE.size1(); i1++) {
	for (i2=0; i2<hybridE.size2(); i2++) {

		// check if positions can form interaction
		if (	energy.isAccessible1(i1)
				&& energy.isAccessible2(i2)
				&& energy.areComplementary(i1,i2) )
		{
			// set to interaction initiation with according boundary
			hybridE(i1,i2) = BestInteraction(energy.getE_init(), i1, i2);
		} else {
			// set to infinity, ie not used
			hybridE(i1,i2) = BestInteraction(E_INF, RnaSequence::lastPos, RnaSequence::lastPos);
		}

	} // i2
	} // i1

	// init mfe for later updates
	initOptima( outConstraint );

	// compute table and update mfeInteraction
	fillHybridE();

	// trace back and output handler update
	reportOptima( outConstraint );

}
예제 #12
0
int
TLSTicketKeyManager::processTicket(SSL* ssl, unsigned char* keyName,
                                   unsigned char* iv,
                                   EVP_CIPHER_CTX* cipherCtx,
                                   HMAC_CTX* hmacCtx, int encrypt) {
  uint8_t salt[kTLSTicketKeySaltLen];
  uint8_t* saltptr = nullptr;
  uint8_t output[SHA256_DIGEST_LENGTH];
  uint8_t* hmacKey = nullptr;
  uint8_t* aesKey = nullptr;
  TLSTicketKeySource* key = nullptr;
  int result = 0;

  if (encrypt) {
    key = findEncryptionKey();
    if (key == nullptr) {
      // no keys available to encrypt
      VLOG(2) << "No TLS ticket key found";
      return -1;
    }
    VLOG(4) << "Encrypting new ticket with key name=" <<
      SSLUtil::hexlify(key->keyName_);

    // Get a random salt and write out key name
    RAND_pseudo_bytes(salt, (int)sizeof(salt));
    memcpy(keyName, key->keyName_.data(), kTLSTicketKeyNameLen);
    memcpy(keyName + kTLSTicketKeyNameLen, salt, kTLSTicketKeySaltLen);

    // Create the unique keys by hashing with the salt
    makeUniqueKeys(key->keySource_, sizeof(key->keySource_), salt, output);
    // This relies on the fact that SHA256 has 32 bytes of output
    // and that AES-128 keys are 16 bytes
    hmacKey = output;
    aesKey = output + SHA256_DIGEST_LENGTH / 2;

    // Initialize iv and cipher/mac CTX
    RAND_pseudo_bytes(iv, AES_BLOCK_SIZE);
    HMAC_Init_ex(hmacCtx, hmacKey, SHA256_DIGEST_LENGTH / 2,
                 EVP_sha256(), nullptr);
    EVP_EncryptInit_ex(cipherCtx, EVP_aes_128_cbc(), nullptr, aesKey, iv);

    result = 1;
  } else {
    key = findDecryptionKey(keyName);
    if (key == nullptr) {
      // no ticket found for decryption - will issue a new ticket
      if (VLOG_IS_ON(4)) {
        string skeyName((char *)keyName, kTLSTicketKeyNameLen);
        VLOG(4) << "Can't find ticket key with name=" <<
          SSLUtil::hexlify(skeyName)<< ", will generate new ticket";
      }

      result = 0;
    } else {
      VLOG(4) << "Decrypting ticket with key name=" <<
        SSLUtil::hexlify(key->keyName_);

      // Reconstruct the unique key via the salt
      saltptr = keyName + kTLSTicketKeyNameLen;
      makeUniqueKeys(key->keySource_, sizeof(key->keySource_), saltptr, output);
      hmacKey = output;
      aesKey = output + SHA256_DIGEST_LENGTH / 2;

      // Initialize cipher/mac CTX
      HMAC_Init_ex(hmacCtx, hmacKey, SHA256_DIGEST_LENGTH / 2,
                   EVP_sha256(), nullptr);
      EVP_DecryptInit_ex(cipherCtx, EVP_aes_128_cbc(), nullptr, aesKey, iv);

      result = 1;
    }
  }
  // result records whether a ticket key was found to decrypt this ticket,
  // not wether the session was re-used.
  if (stats_) {
    stats_->recordTLSTicket(encrypt, result);
  }

  return result;
}
예제 #13
0
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	// Takes a clang::CastExpr, converts its subExpr into IR and wraps it with the necessary IR casts
	/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	core::ExpressionPtr performClangCastOnIR(insieme::frontend::conversion::Converter& converter, const clang::CastExpr* castExpr) {
		core::ExpressionPtr expr = converter.convertExpr(castExpr->getSubExpr());
		core::TypePtr targetTy = converter.convertType(castExpr->getType());
		core::TypePtr exprTy = expr->getType();

		if(VLOG_IS_ON(2)) {
			VLOG(2) << "castExpr: ";
			castExpr->dump();
			VLOG(2) << "\n";
		}

		const core::FrontendIRBuilder& builder = converter.getIRBuilder();
		//const core::lang::BasicGenerator& basic = builder.getLangBasic();
		//core::NodeManager& mgr = converter.getNodeManager();
		
		switch(castExpr->getCastKind()) {
		////////////////////////////////////////////////////////////////////////////////////////////////////////////	
		// A conversion which causes the extraction of an r-value from the operand gl-value.
		// The result of an r-value conversion is always unqualified.
		// IR: this is the same as ref_deref: ref<a'> -> a'
		case clang::CK_LValueToRValue:
			return builder.deref(expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Numerical value type conversions
		// handled by IR numeric_cast
		case clang::CK_IntegralCast:
		case clang::CK_IntegralToFloating:
		case clang::CK_FloatingToIntegral:
		case clang::CK_FloatingCast:
			return builder.numericCast(expr, targetTy); 

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Numeric and pointer to boolean
		case clang::CK_IntegralToBoolean:
		case clang::CK_FloatingToBoolean:
		case clang::CK_PointerToBoolean:
			return utils::exprToBool(expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// A conversion which causes a bit pattern of one type to be reinterpreted as a bit pattern of another type.
		// Generally the operands must have equivalent size and unrelated types.  The pointer conversion
		// char* -> int* is a bitcast. A conversion from any pointer type to a C pointer type is a bitcast unless
		// it's actually BaseToDerived or DerivedToBase. A conversion to a block pointer or ObjC pointer type is a
		// bitcast only if the operand has the same type kind; otherwise, it's one of the specialized casts below.
		// Vector coercions are bitcasts.
		case clang::CK_BitCast:
			return implementBitcast(converter, targetTy, expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Integral to pointer. A special kind of reinterpreting conversion.
		// (char*) 0x1001aab0,  reinterpret_cast<int*>(0)
		case clang::CK_IntegralToPointer:
			return core::lang::buildPtrFromIntegral(expr, targetTy);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Pointer to integral. A special kind of reinterpreting conversion.
		// (int)((void*)0x1001aab0)
		case clang::CK_PointerToIntegral:
			return core::lang::buildPtrToIntegral(expr, targetTy);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Null pointer constant to pointer, e.g. (int*)0
		case clang::CK_NullToPointer:
			return core::lang::buildPtrNull(targetTy);

		//////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Array to pointer decay. int[10] -> int* char[5][6] -> char(*)[6]
		case clang::CK_ArrayToPointerDecay:
			return core::lang::buildPtrFromArray(expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// CK_FunctionToPointerDecay - Function to pointer decay. void(int) -> void(*)(int)
		// CK_BuiltinFnToFnPtr - Same as above, for builtin functions
		case clang::CK_FunctionToPointerDecay:
		case clang::CK_BuiltinFnToFnPtr:
			return core::lang::buildPtrOfFunction(expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// NoOps: Conversions that have no effect
		// * same type casts, CK_NoOp, e.g. int -> int
		case clang::CK_NoOp:
			return expr;
			
		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		// Unused return value: (void)fun()
		case clang::CK_ToVoid:
			return builder.unitConsume(expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_ConstructorConversion:
		//	// Conversion by constructor. struct A { A(int); }; A a = A(10);
		//	{
		//		// this should be handled by backend compiler
		//		// http://stackoverflow.com/questions/1384007/conversion-constructor-vs-conversion-operator-precedence
		//		return expr;
		//	}

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_FloatingRealToComplex:
		//case clang::CK_IntegralRealToComplex:
		//	return builder.callExpr(mgr.getLangExtension<core::lang::ComplexExtension>().getConstantToComplex(), expr);
		///*A conversion of a floating point real to a floating point complex of the original type. Injects the value as the
		//* real component with a zero imaginary component. float -> _Complex float.
		//* */
		///*Converts from an integral real to an integral complex whose element type matches the source. Injects the value as the
		//* real component with a zero imaginary component. long -> _Complex long.
		//* */

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_FloatingComplexCast:
		//case clang::CK_FloatingComplexToIntegralComplex:
		//case clang::CK_IntegralComplexCast:
		//case clang::CK_IntegralComplexToFloatingComplex:
		//	return mgr.getLangExtension<core::lang::ComplexExtension>().castComplexToComplex(expr, targetTy);
		///*Converts between different floating point complex types. _Complex float -> _Complex double.
		//* */
		///*Converts from a floating complex to an integral complex. _Complex float -> _Complex int.
		//* */
		///*Converts between different integral complex types. _Complex char -> _Complex long long _Complex unsigned int ->
		//* _Complex signed int.
		//* */
		///*Converts from an integral complex to a floating complex. _Complex unsigned -> _Complex float.
		//* */

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_FloatingComplexToReal:
		//case clang::CK_IntegralComplexToReal:
		//	return mgr.getLangExtension<core::lang::ComplexExtension>().getReal(expr);
		///*Converts a floating point complex to floating point real of the source's element type. Just discards the imaginary
		//* component. _Complex long double -> long double.
		//* */
		///*Converts an integral complex to an integral real of the source's element type by discarding the imaginary component.
		//* _Complex short -> short.
		//* */


		///////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_IntegralComplexToBoolean:
		//case clang::CK_FloatingComplexToBoolean:
		//	/*Converts a complex to bool by comparing against 0+0i.
		//	* */
		//	return mgr.getLangExtension<core::lang::ComplexExtension>().castComplexToBool(expr);

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_LValueBitCast:
		//	/* case clang::CK_LValueBitCast - A conversion which reinterprets the address of an l-value as an l-value of a different
		//	* kind. Used for reinterpret_casts of l-value expressions to reference types. bool b; reinterpret_cast<char&>(b) = 'a';
		//	* */
		//	{
		//		// if we have a cpp ref we have to unwrap the expression
		//		if(core::analysis::isAnyCppRef(expr->getType())) { expr = builder.toIRRef(expr); }
		//		// the target type is a ref type because lvalue
		//		// bitcasts look like reinterpret_cast<type&>(x)
		//		targetTy = builder.refType(targetTy);
		//		core::CallExprPtr newExpr = builder.callExpr(targetTy, gen.getRefReinterpret(), expr, builder.getTypeLiteral(GET_REF_ELEM_TYPE(targetTy)));
		//		// wrap it as cpp ref
		//		return builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getRefIRToCpp(), newExpr);
		//	}

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_MemberPointerToBoolean:
		//	/*case clang::CK_MemberPointerToBoolean - Member pointer to boolean. A check against the null member pointer.
		//	* */
		//	{
		//		if(expr->getType().isa<core::FunctionTypePtr>()) {
		//			return builder.callExpr(gen.getBoolLNot(), builder.callExpr(gen.getBool(), gen.getFuncIsNull(), expr));
		//		}
		//		frontend_assert(core::analysis::isMemberPointer(expr->getType())) << " not a memberPointer? " << expr << " : " << expr->getType();

		//		return core::analysis::getMemberPointerCheck(expr);
		//	}

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		////  PARTIALY IMPLEMENTED
		////////////////////////////////////////////////////////////////////////////////////////////////////////////

		///////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_UncheckedDerivedToBase:
		//case clang::CK_DerivedToBase:
		//	// A conversion from a C++ class pointer to a base class pointer. A *a = new B();
		//	{
		//		// TODO: do we need to check if is pointerType?
		//		// in case of pointer, the inner expression is modeled as ref< array < C, 1> >
		//		// it is needed to deref the first element
		//		expr = getCArrayElemRef(builder, expr);

		//		// unwrap CppRef if CppRef
		//		if(core::analysis::isAnyCppRef(exprTy)) { expr = core::analysis::unwrapCppRef(expr); }

		//		clang::CastExpr::path_const_iterator it;
		//		for(it = castExpr->path_begin(); it != castExpr->path_end(); ++it) {
		//			core::TypePtr targetTy = converter.convertType((*it)->getType());
		//			// if it is no ref we have to materialize it, otherwise refParent cannot be called
		//			if(expr->getType()->getNodeType() != core::NT_RefType) {
		//				// expr = builder.callExpr (mgr.getLangExtension<core::lang::IRppExtensions>().getMaterialize(), expr);
		//				expr = builder.refVar(expr);
		//			}
		//			expr = builder.refParent(expr, targetTy);
		//		}

		//		if(castExpr->getType().getTypePtr()->isPointerType()) {
		//			// is a pointer type -> return pointer
		//			expr = builder.callExpr(gen.getScalarToArray(), expr);
		//		}

		//		VLOG(2) << "cast resoult: \n" << dumpPretty(expr) << " \n of type: " << expr->getType();
		//		return expr;
		//	}

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_BaseToDerived:
		//	// A conversion from a C++ class pointer/reference to a derived class pointer/reference. B *b = static_cast<B*>(a);
		//	{
		//		// we want to know the TYPE of static_cast<TYPE>()
		//		targetTy = converter.convertType(llvm::dyn_cast<clang::ExplicitCastExpr>(castExpr)->getType());
		//		VLOG(2) << exprTy << " " << targetTy;

		//		core::ExpressionPtr retIr;

		//		// pointers:
		//		if(core::analysis::isPointerType(exprTy)) {
		//			assert_true(core::analysis::isPointerType(targetTy)) << "from pointer to non pointer is not possible";
		//			targetTy = targetTy.as<core::RefTypePtr>()->getElementType();
		//			return builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getStaticCast(), expr, builder.getTypeLiteral((targetTy)));
		//		}

		//		// NORE: All value casts are upgraded to CPP ref, this has no implications for the generated code since lvalues in clang are already refs.
		//		// 		 and makes everithing smoother and easyer
		//		if(exprTy.isa<core::RefTypePtr>()) {
		//			expr = builder.toCppRef(expr);
		//			exprTy = expr.getType();
		//		}

		//		if(core::analysis::isCppRef(exprTy)) {
		//			if(!core::analysis::isCppRef(targetTy)) { targetTy = core::analysis::getCppRef(targetTy); }
		//			retIr = builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getStaticCastRefCppToRefCpp(), expr,
		//			                         builder.getTypeLiteral((targetTy)));
		//		} else if(core::analysis::isConstCppRef(exprTy)) {
		//			if(!core::analysis::isCppRef(targetTy)) { targetTy = core::analysis::getConstCppRef(targetTy); }
		//			retIr = builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getStaticCastConstCppToConstCpp(), expr,
		//			                         builder.getTypeLiteral((targetTy)));
		//		} else {
		//			std::cerr << " === BASE TO DERIVED FAILED ===========" << std::endl;
		//			std::cerr << "####### Expr: #######" << std::endl;
		//			std::cerr << (expr);
		//			std::cerr << "\n####### Expr Type: #######" << std::endl;
		//			std::cerr << (exprTy);
		//			std::cerr << "\n####### cast Type: #######" << std::endl;
		//			std::cerr << (targetTy);
		//			std::cerr << "\n####### clang: #######" << std::endl;
		//			castExpr->dump();
		//			abort();
		//		}

		//		return retIr;
		//	}

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_Dynamic:
		//	// A C++ dynamic_cast.
		//	{
		//		// we want to know the TYPE of static_cast<TYPE>()
		//		targetTy = converter.convertType(llvm::dyn_cast<clang::ExplicitCastExpr>(castExpr)->getType());
		//		VLOG(2) << exprTy << " " << targetTy;

		//		core::ExpressionPtr retIr;

		//		// pointers:
		//		if(core::analysis::isPointerType(exprTy)) {
		//			assert_true(core::analysis::isPointerType(targetTy)) << "from pointer to non pointer is not possible";
		//			targetTy = targetTy.as<core::RefTypePtr>()->getElementType();
		//			return builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getDynamicCast(), expr, builder.getTypeLiteral((targetTy)));
		//		}

		//		// NORE: All value casts are upgraded to CPP ref, this has no implications for the generated code since lvalues in clang are already refs.
		//		// 		 and makes everithing smoother and easyer
		//		if(exprTy.isa<core::RefTypePtr>()) {
		//			expr = builder.toCppRef(expr);
		//			exprTy = expr.getType();
		//		}

		//		if(core::analysis::isCppRef(exprTy)) {
		//			if(!core::analysis::isCppRef(targetTy)) { targetTy = core::analysis::getCppRef(targetTy); }
		//			retIr = builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getDynamicCastRefCppToRefCpp(), expr,
		//			                         builder.getTypeLiteral((targetTy)));
		//		} else if(core::analysis::isConstCppRef(exprTy)) {
		//			if(!core::analysis::isCppRef(targetTy)) { targetTy = core::analysis::getConstCppRef(targetTy); }
		//			retIr = builder.callExpr(mgr.getLangExtension<core::lang::IRppExtensions>().getDynamicCastConstCppToConstCpp(), expr,
		//			                         builder.getTypeLiteral((targetTy)));
		//		} else {
		//			std::cerr << " === Dynamic cast  FAILED ===========" << std::endl;
		//			std::cerr << "####### Expr: #######" << std::endl;
		//			std::cerr << (expr);
		//			std::cerr << "\n####### Expr Type: #######" << std::endl;
		//			std::cerr << (exprTy);
		//			std::cerr << "\n####### cast Type: #######" << std::endl;
		//			std::cerr << (targetTy);
		//			std::cerr << "\n####### clang: #######" << std::endl;
		//			castExpr->dump();
		//			abort();
		//		}

		//		return retIr;
		//	}

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_NullToMemberPointer:
		//	/*case clang::CK_NullToMemberPointer - Null pointer constant to member pointer.
		//	 * int A::*mptr = 0; int (A::*fptr)(int) = nullptr;
		//	 */
		//	{ return builder.callExpr(targetTy, gen.getNullFunc(), builder.getTypeLiteral(targetTy)); }

		////////////////////////////////////////////////////////////////////////////////////////////////////////////
		//case clang::CK_UserDefinedConversion:
		//	/*case clang::CK_UserDefinedConversion - Conversion using a user defined type conversion function.i
		//	* struct A { operator int(); }; int i = int(A());
		//	* */
		//	{ return converter.convertExpr(castExpr->getSubExpr()); }

		//case clang::CK_AtomicToNonAtomic:
		//case clang::CK_NonAtomicToAtomic:
		//case clang::CK_CopyAndAutoreleaseBlockObject:
		//	std::cout << " \nCAST: " << castExpr->getCastKindName() << " not supported!!" << std::endl;
		//	std::cout << " at location: " << frontend::utils::location(castExpr->getLocStart(), converter.getSourceManager()) << std::endl;
		//	castExpr->dump();
		//	assert_fail();
		default: break; // fall through to not implemented assertion below
		}

		frontend_assert(false) << "Clang cast type not implemented: " << castExpr->getCastKindName();
		return expr;
	}
예제 #14
0
파일: Mutation.cpp 프로젝트: kzahedi/NMODE
void Mutation::__mutateAddEdge(Module *m,
                               double probability,
                               double max,
                               double minDist)
{
  VLOG(50) << ">>>>> add edge";
  LOG_MODULE;
  CfgMutationEdge *dee = Data::instance()->specification()->mutation()->edge();

  double probabilities[m->n_size()][m->n_size()];
  double d   =  0.0;

  for(int s_index = 0; s_index < m->n_size(); s_index++)
  {
    for(int d_index = 0; d_index < m->n_size(); d_index++)
    {
      probabilities[s_index][d_index] = 0.0;
    }
  }

  for(int s_index = 0; s_index < m->n_size(); s_index++)
  {
    Node *src_node = m->node(s_index);
    if(src_node->isInactive()) continue;
    if(src_node->isSource())
    {
      for(int d_index = 0; d_index < m->n_size(); d_index++)
      {
        Node *dst_node = m->node(d_index);
        if(dst_node->isInactive()) continue;
        // if(src_node->type() == TAG_CONNECTOR && dst_node->type() == TAG_CONNECTOR)
        // {
        // continue;
        // }
        if(dst_node->isDestination())
        {
          if(dst_node->contains(src_node) == false)
          {
            // USE FIXED PROBABILITY FOR ALL EDGES
            d = MAX(minDist, DIST(src_node->position(), dst_node->position()));
            if(d < MIN_DIST) d = 0;
            // probabilities[s_index][d_index] = exp(-d);
            if(dee->mode() == EDGE_ADD_MODE_UNIFORM)
            {
              probabilities[s_index][d_index] = 1.0;
            }
            else
            {
              probabilities[s_index][d_index] = 1.0/d;
            }

            VLOG(50) << "    edge from "
              << src_node->label() << " to "
              << dst_node->label() << " does not exist. setting distance to " << d;
            // probabilities[s_index][d_index] = 1.0;
          }
        }
      }
    }
  }

  double pmax =  0.0;
  if(dee->mode() == EDGE_ADD_MODE_DISTANCE)
  {
    for(int s_index = 0; s_index < m->n_size(); s_index++)
    {
      for(int d_index = 0; d_index < m->n_size(); d_index++)
      {
        if(pmax < probabilities[s_index][d_index]) pmax = probabilities[s_index][d_index];
      }
    }
  }

  if(pmax > 0.0)
  {
    for(int s_index = 0; s_index < m->n_size(); s_index++)
    {
      for(int d_index = 0; d_index < m->n_size(); d_index++)
      {
        // cout << probabilities[s_index][d_index] << " -> ";
        probabilities[s_index][d_index] = probabilities[s_index][d_index] / pmax;
        // cout << probabilities[s_index][d_index] << endl;
      }
    }
  }

  if(VLOG_IS_ON(50))
  {
    stringstream sst;
    sst << "    probabilities " << m->n_size() << "x" << m->n_size();
    sst.precision(3);
    sst.setf(ios::fixed,ios::floatfield);
    sst << "[ ";
    for(int s_index = 0; s_index < m->n_size(); s_index++)
    {
      sst << " [ " << probabilities[s_index][0];
      for(int d_index = 0; d_index < m->n_size(); d_index++)
      {
        sst << ", " << probabilities[s_index][d_index];
      }
      sst << " ]";
    }
    sst << " ]";
    VLOG(50) << sst.str();
  }

  // double p  = Random::unit();
  // VLOG(50) << "    p = " << p;
  for(int s_index = 0; s_index < m->n_size(); s_index++)
  {
    for(int d_index = 0; d_index < m->n_size(); d_index++)
    {
      double p = probabilities[s_index][d_index] * probability;
      if(Random::unit() <= p)
      {
        Node *src = m->node(s_index);
        Node *dst = m->node(d_index);
        VLOG(50) << "    adding edge from " << src->label() << " -> " << dst->label();
        VLOG(50) << "    before number of edges: " << m->e_size();
        Edge *e   = m->addEdge(src, dst, Random::rand(-max, max));
        VLOG(50) << "    adding edge from "
          << m->node(s_index)->label() << " to "
          << m->node(d_index)->label() << " with "
          << e->weight();
        VLOG(50) << "    after number of edges: " << m->e_size();
        LOG_MODULE;
        VLOG(50) << "<<<<< add edge";
        m->setModified(true);
      }
    }
  }

  LOG_MODULE;
  VLOG(50) << "<<<<< add edge";
}