Exemple #1
0
ib_status_t ibpp_caught_boost_exception(
    ib_engine_t*            engine,
    const boost::exception& e
)
{
    std::string message;
    int level = 1;

    message = "Unknown boost::exception thrown: ";
    if (boost::get_error_info<boost::throw_function>(e)) {
        message += *boost::get_error_info<boost::throw_function>(e);
    }
    else {
        message += "No information provided.  Please report as bug.";
    }

    if (boost::get_error_info<errinfo_level>(e)) {
        level = *boost::get_error_info<errinfo_level>(e);
    }

    if (engine) {
        ib_log(engine, level, "%s", message.c_str());
        ib_log_debug(engine, "%s",
            diagnostic_information(e).c_str()
        );
    } else {
        ib_util_log_error("%s", message.c_str());
        ib_util_log_debug("%s", diagnostic_information(e).c_str()
        );
    }

    return IB_EUNKNOWN;
}
Exemple #2
0
ib_status_t ibpp_caught_ib_exception(
    ib_engine_t* engine,
    ib_status_t  status,
    const error& e
)
{
    std::string message;
    int level = 1;

    message = std::string(ib_status_to_string(status)) + ":";
    if (boost::get_error_info<errinfo_what>(e)) {
        message += *boost::get_error_info<errinfo_what>(e);
    }
    else {
        message += "IronBee++ Exception but no explanation provided.  "
                   "Please report as bug.";
    }

    if (boost::get_error_info<errinfo_level>(e)) {
        level = *boost::get_error_info<errinfo_level>(e);
    }

    if (engine) {
        ib_log(engine, level, "%s", message.c_str());
        ib_log_debug(engine, "%s", diagnostic_information(e).c_str() );
    } else {
        ib_util_log_error("%s", message.c_str());
        ib_util_log_debug("%s", diagnostic_information(e).c_str()
        );
    }
    return status;
}
int checkRandomTest(std::function<void(json_spirit::mValue&, bool)> _doTests, json_spirit::mValue& _value, bool _debug)
{
	bool ret = 0;
	try
	{
		//redirect all output to the stream
		std::ostringstream strCout;
		std::streambuf* oldCoutStreamBuf = std::cout.rdbuf();
		if (!_debug)
		{
			std::cout.rdbuf( strCout.rdbuf() );
			std::cerr.rdbuf( strCout.rdbuf() );
		}

		_doTests(_value, false);

		//restroe output
		if (!_debug)
		{
			std::cout.rdbuf(oldCoutStreamBuf);
			std::cerr.rdbuf(oldCoutStreamBuf);
		}
	}
	catch (dev::Exception const& _e)
	{
		std::cout << "Failed test with Exception: " << diagnostic_information(_e) << std::endl;
		ret = 1;
	}
	catch (std::exception const& _e)
	{
		std::cout << "Failed test with Exception: " << _e.what() << std::endl;
		ret = 1;
	}
	return ret;
}
Exemple #4
0
void Sink::consume(Message request) {

	try {
		m_message = request;
		m_message.operator()();

		Logger::log(info, m_message.str() + std::string(" consumed."));
	}
	catch(boost::exception &ex){
		error = boost::current_exception();
		std::string msg = diagnostic_information(ex);
		Logger::log(exception, msg);
	}
}
inline
std::string
to_string( exception_ptr const & p )
{
    std::string s='\n'+diagnostic_information(p);
    std::string padding("  ");
    std::string r;
    bool f=false;
    for( std::string::const_iterator i=s.begin(),e=s.end(); i!=e; ++i )
    {
        if( f )
            r+=padding;
        char c=*i;
        r+=c;
        f=(c=='\n');
    }
    return r;
}
// copy error information to log. registered only after logger has been configured.
void catch_global()
{
#define catch_global_print(msg)  \
  std::ostringstream bt; \
  bt << msg << std::endl; \
  void* trace_elems[20]; \
  int trace_elem_count(backtrace( trace_elems, 20 )); \
  char** stack_syms(backtrace_symbols(trace_elems, trace_elem_count)); \
  for (int i = 0 ; i < trace_elem_count ; ++i ) \
    bt << stack_syms[i] << std::endl; \
  Os::Logger::instance().log(FAC_LOG, PRI_CRIT, bt.str().c_str()); \
  std::cerr << bt.str().c_str(); \
  free(stack_syms);

  try
  {
      throw;
  }
  catch (std::string& e)
  {
    catch_global_print(e.c_str());
  }
#ifdef MONGO_assert
  catch (mongo::DBException& e)
  {
    catch_global_print(e.toString().c_str());
  }
#endif
  catch (boost::exception& e)
  {
    catch_global_print(diagnostic_information(e).c_str());
  }
  catch (std::exception& e)
  {
    catch_global_print(e.what());
  }
  catch (...)
  {
    catch_global_print("Error occurred. Unknown exception type.");
  }

  std::abort();
}
int
main()
    {
    BOOST_TEST( boost::exception_ptr()==boost::exception_ptr() );
    BOOST_TEST( !(boost::exception_ptr()!=boost::exception_ptr()) );
    BOOST_TEST( !boost::exception_ptr() );

    int count=0;
    try
        {
        throw boost::enable_current_exception(derives_nothing(count));
        }
    catch(
    ... )
        {
        boost::exception_ptr p = boost::current_exception();
        BOOST_TEST(!(p==boost::exception_ptr()));
        BOOST_TEST(p!=boost::exception_ptr());
        BOOST_TEST(p);
        try
            {
            rethrow_exception(p);
            BOOST_TEST(false);
            }
        catch(
        derives_nothing & )
            {
            }
        catch(
        ... )
            {
            BOOST_TEST(false);
            }
        }
    BOOST_TEST(count==0);

    try
        {
        throw boost::enable_current_exception(derives_std_exception());
        }
    catch(
    ... )
        {
        boost::exception_ptr p = boost::current_exception();
        BOOST_TEST(!(p==boost::exception_ptr()));
        BOOST_TEST(p!=boost::exception_ptr());
        BOOST_TEST(p);
        try
            {
            rethrow_exception(p);
            BOOST_TEST(false);
            }
        catch(
        derives_std_exception & )
            {
            boost::exception_ptr p = boost::current_exception();
            BOOST_TEST(!(p==boost::exception_ptr()));
            BOOST_TEST(p!=boost::exception_ptr());
            BOOST_TEST(p);
            try
                {
                rethrow_exception(p);
                BOOST_TEST(false);
                }
            catch(
            derives_std_exception & )
                {
                }
            catch(
            ... )
                {
                BOOST_TEST(false);
                }
            }
        catch(
        ... )
            {
            BOOST_TEST(false);
            }
        }

    try
        {
        throw derives_std_exception();
        }
    catch(
    ... )
        {
        boost::exception_ptr p = boost::current_exception();
        BOOST_TEST(!(p==boost::exception_ptr()));
        BOOST_TEST(p!=boost::exception_ptr());
        BOOST_TEST(p);
        try
            {
            rethrow_exception(p);
            BOOST_TEST(false);
            }
        catch(
        boost::unknown_exception & e )
            {
#ifndef BOOST_NO_RTTI
            std::type_info const * const * t=boost::get_error_info<boost::original_exception_type>(e);
            BOOST_TEST(t!=0 && *t!=0 && **t==typeid(derives_std_exception));
#endif
            }
        catch(
        ... )
            {
            BOOST_TEST(false);
            }
        }

    test_std_exception_what<std::domain_error>();
    test_std_exception_what<std::invalid_argument>();
    test_std_exception_what<std::length_error>();
    test_std_exception_what<std::out_of_range>();
    test_std_exception_what<std::logic_error>();
    test_std_exception_what<std::range_error>();
    test_std_exception_what<std::overflow_error>();
    test_std_exception_what<std::underflow_error>();
    test_std_exception_what<std::ios_base::failure>();
    test_std_exception_what<std::runtime_error>();
    test_std_exception<std::bad_alloc>();
#ifndef BOOST_NO_TYPEID
    test_std_exception<std::bad_cast>();
    test_std_exception<std::bad_typeid>();
#endif
    test_std_exception<std::bad_exception>();
    test_std_exception<std::exception>();

    try
        {
        throw derives_std_boost_exception() << my_info(42);
        }
    catch(
    ... )
        {
        boost::exception_ptr p = boost::current_exception();
        BOOST_TEST(!(p==boost::exception_ptr()));
        BOOST_TEST(p!=boost::exception_ptr());
        BOOST_TEST(p);
        try
            {
            rethrow_exception(p);
            BOOST_TEST(false);
            }
        catch(
        boost::unknown_exception & x )
            {
            BOOST_TEST(boost::get_error_info<my_info>(x));
            if( int const * p=boost::get_error_info<my_info>(x) )
                BOOST_TEST(*p==42);
#ifndef BOOST_NO_RTTI
                {
            std::type_info const * const * t=boost::get_error_info<boost::original_exception_type>(x);
            BOOST_TEST(t && *t && **t==typeid(derives_std_boost_exception));
                }
#endif
            boost::exception_ptr p = boost::current_exception();
            BOOST_TEST(!(p==boost::exception_ptr()));
            BOOST_TEST(p!=boost::exception_ptr());
            BOOST_TEST(p);
            try
                {
                rethrow_exception(p);
                BOOST_TEST(false);
                }
            catch(
            boost::unknown_exception & x )
                {
                BOOST_TEST(boost::get_error_info<my_info>(x));
                if( int const * p=boost::get_error_info<my_info>(x) )
                    BOOST_TEST(*p==42);
#ifndef BOOST_NO_RTTI
                std::type_info const * const * t=boost::get_error_info<boost::original_exception_type>(x);
                BOOST_TEST(t && *t && **t==typeid(derives_std_boost_exception));
#endif
                }
            catch(
            ... )
                {
                BOOST_TEST(false);
                }
            }
        catch(
        ... )
            {
            BOOST_TEST(false);
            }
        }

    try
        {
        throw derives_boost_exception() << my_info(42);
        }
    catch(
    ... )
        {
        boost::exception_ptr p = boost::current_exception();
        BOOST_TEST(!(p==boost::exception_ptr()));
        BOOST_TEST(p!=boost::exception_ptr());
        BOOST_TEST(p);
        try
            {
            rethrow_exception(p);
            BOOST_TEST(false);
            }
        catch(
        boost::unknown_exception & x )
            {
            BOOST_TEST(boost::get_error_info<my_info>(x));
            if( int const * p=boost::get_error_info<my_info>(x) )
                BOOST_TEST(*p==42);
#ifndef BOOST_NO_RTTI
                {
            std::type_info const * const * t=boost::get_error_info<boost::original_exception_type>(x);
            BOOST_TEST(t && *t && **t==typeid(derives_boost_exception));
                }
#endif
            boost::exception_ptr p = boost::current_exception();
            BOOST_TEST(!(p==boost::exception_ptr()));
            BOOST_TEST(p!=boost::exception_ptr());
            BOOST_TEST(p);
            try
                {
                rethrow_exception(p);
                BOOST_TEST(false);
                }
            catch(
            boost::unknown_exception & x )
                {
                BOOST_TEST(boost::get_error_info<my_info>(x));
                if( int const * p=boost::get_error_info<my_info>(x) )
                    BOOST_TEST(*p==42);
                }
            catch(
            ... )
                {
                BOOST_TEST(false);
                }
            }
        catch(
        ... )
            {
            BOOST_TEST(false);
            }
        }

    test_throw_on_copy<std::bad_alloc,std::bad_alloc>();
    test_throw_on_copy<int,std::bad_exception>();

    try
        {
        throw boost::enable_current_exception(derives_std_boost_exception("what1"));
        }
    catch(
    ... )
        {
        boost::exception_ptr p=boost::current_exception();
            {
        std::string s=diagnostic_information(p);
        BOOST_TEST(s.find("what1")!=s.npos);
            }
        try
            {
            throw boost::enable_current_exception(derives_std_boost_exception("what2") << nested_exception(p) );
            }
        catch(
        ... )
            {
            std::string s=boost::current_exception_diagnostic_information();
            BOOST_TEST(s.find("what1")!=s.npos);
            BOOST_TEST(s.find("what2")!=s.npos);
            }
        }
    BOOST_TEST(!diagnostic_information(boost::exception_ptr()).empty());
    return boost::report_errors();
    }
Exemple #8
0
void doTransactionTests(json_spirit::mValue& _v, bool _fillin)
{
	for (auto& i: _v.get_obj())
	{
		cerr << i.first << endl;
		mObject& o = i.second.get_obj();

		if (_fillin)
		{
			TBOOST_REQUIRE((o.count("transaction") > 0));
			mObject tObj = o["transaction"].get_obj();

			//Construct Rlp of the given transaction
			RLPStream rlpStream = createRLPStreamFromTransactionFields(tObj);
			o["rlp"] = toHex(rlpStream.out(), 2, HexPrefix::Add);

			try
			{
				Transaction txFromFields(rlpStream.out(), CheckTransaction::Everything);
				if (!txFromFields.signature().isValid())
					BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );

				o["sender"] = toString(txFromFields.sender());				
				o["transaction"] = ImportTest::makeAllFieldsHex(tObj);
			}
			catch(Exception const& _e)
			{
				//Transaction is InValid
				cnote << "Transaction Exception: " << diagnostic_information(_e);
				o.erase(o.find("transaction"));
				if (o.count("expect") > 0)
				{
					bool expectInValid = (o["expect"].get_str() == "invalid");
					if (Options::get().checkState)
							{TBOOST_CHECK_MESSAGE(expectInValid, "Check state: Transaction '" << i.first << "' is expected to be valid!");}
						else
							{TBOOST_WARN_MESSAGE(expectInValid, "Check state: Transaction '" << i.first << "' is expected to be valid!");}

					o.erase(o.find("expect"));
				}
			}

			//Transaction is Valid
			if (o.count("expect") > 0)
			{
				bool expectValid = (o["expect"].get_str() == "valid");
				if (Options::get().checkState)
						{TBOOST_CHECK_MESSAGE(expectValid, "Check state: Transaction '" << i.first << "' is expected to be invalid!");}
					else
						{TBOOST_WARN_MESSAGE(expectValid, "Check state: Transaction '" << i.first << "' is expected to be invalid!");}

				o.erase(o.find("expect"));
			}
		}
		else
		{			
			TBOOST_REQUIRE((o.count("rlp") > 0));
			Transaction txFromRlp;
			try
			{
				bytes stream = importByteArray(o["rlp"].get_str());
				RLP rlp(stream);
				txFromRlp = Transaction(rlp.data(), CheckTransaction::Everything);
				if (!txFromRlp.signature().isValid())
					BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
			}
			catch(Exception const& _e)
			{
				cnote << i.first;
				cnote << "Transaction Exception: " << diagnostic_information(_e);
				TBOOST_CHECK_MESSAGE((o.count("transaction") == 0), "A transaction object should not be defined because the RLP is invalid!");
				continue;
			}
			catch(...)
			{
				TBOOST_CHECK_MESSAGE((o.count("transaction") == 0), "A transaction object should not be defined because the RLP is invalid!");
				continue;
			}

			TBOOST_REQUIRE((o.count("transaction") > 0));

			mObject tObj = o["transaction"].get_obj();
			Transaction txFromFields(createRLPStreamFromTransactionFields(tObj).out(), CheckTransaction::Everything);

			//Check the fields restored from RLP to original fields
			TBOOST_CHECK_MESSAGE((txFromFields.data() == txFromRlp.data()), "Data in given RLP not matching the Transaction data!");
			TBOOST_CHECK_MESSAGE((txFromFields.value() == txFromRlp.value()), "Value in given RLP not matching the Transaction value!");
			TBOOST_CHECK_MESSAGE((txFromFields.gasPrice() == txFromRlp.gasPrice()), "GasPrice in given RLP not matching the Transaction gasPrice!");
			TBOOST_CHECK_MESSAGE((txFromFields.gas() == txFromRlp.gas()),"Gas in given RLP not matching the Transaction gas!");
			TBOOST_CHECK_MESSAGE((txFromFields.nonce() == txFromRlp.nonce()),"Nonce in given RLP not matching the Transaction nonce!");
			TBOOST_CHECK_MESSAGE((txFromFields.receiveAddress() == txFromRlp.receiveAddress()), "Receive address in given RLP not matching the Transaction 'to' address!");
			TBOOST_CHECK_MESSAGE((txFromFields.sender() == txFromRlp.sender()), "Transaction sender address in given RLP not matching the Transaction 'vrs' signature!");
			TBOOST_CHECK_MESSAGE((txFromFields == txFromRlp), "However, txFromFields != txFromRlp!");
			TBOOST_REQUIRE ((o.count("sender") > 0));

			Address addressReaded = Address(o["sender"].get_str());
			TBOOST_CHECK_MESSAGE((txFromFields.sender() == addressReaded || txFromRlp.sender() == addressReaded), "Signature address of sender does not match given sender address!");
		}
	}//for
}//doTransactionTests
Exemple #9
0
int main(int argc, char** argv)
{
  std::ostringstream oss;
  oss << "Usage: " << argv[0] << " [additional options]";
  po::options_description desc(oss.str());
  desc.add_options()
    ("help,h", "produce this message")
    ("debug,d", "enable debug mode")
    ("logfile,l", po::value<std::string>(), "set the logfile to use")
    ("interval,i", po::value<int>(), "set the broadcast interval")
    ("interface,I", po::value<std::vector<std::string> >(), "interface to use for multicast")
    ("address,a", po::value<std::vector<std::string> >(), "address to listen on")
    ;
  po::variables_map vm;

  // Begin processing of commandline parameters.
  try {
    po::store(po::command_line_parser(argc, argv).
        options(desc).run(), vm);
    po::notify(vm);
  } catch (std::exception& e) {
    std::cerr << "Cannot process commandline options: " << e.what() << std::endl;
    exit(-1);
  }

  bool debug = false;
  std::string logfile = "/tmp/hexadaemon.log";
  int interval = 2;
  std::vector<std::string> interfaces;
  std::vector<std::string> addresses;

  if (vm.count("help")) {
    std::cout << desc << std::endl;
    return 1;
  }

  if (vm.count("debug")) {
    std::cout << "debug enabled" << std::endl;
    debug = true;
  }

  if (vm.count("logfile")) {
    logfile = vm["logfile"].as<std::string>();
    debug && std::cout << "logfile: " << logfile << std::endl;
  }

  if (vm.count("interval")) {
    interval = vm["interval"].as<int>();
    std::cout << "interval: " << interval << std::endl;
  }

  if (vm.count("interface")) {
    interfaces = vm["interface"].as<std::vector<std::string> >();
    for (std::vector<std::string>::iterator it = interfaces.begin(); it != interfaces.end(); ++it)
      debug && std::cout << "interface: " << *it << std::endl;
  } else {
    std::cerr << "You have to specify at least one interface." << std::endl;
    return 1;
  }


  if (vm.count("address")) {
    addresses = vm["address"].as<std::vector<std::string> >();
    for (std::vector<std::string>::iterator it = addresses.begin(); it != addresses.end(); ++it)
      debug && std::cout << "address: " << *it << std::endl;
  } else {
    std::cerr << "You have to specify at least one address." << std::endl;
    return 1;
  }

  try
  {
    boost::asio::io_service io_service;

    // Initialise the server before becoming a daemon. If the process is
    // started from a shell, this means any errors will be reported back to the
    // user.
    //udp_daytime_server server(io_service);
    hexadaemon::HexabusServer *server;
    server = new hexadaemon::HexabusServer(io_service, interfaces, addresses, interval, debug);

    // Register signal handlers so that the daemon may be shut down. You may
    // also want to register for other signals, such as SIGHUP to trigger a
    // re-read of a configuration file.
    boost::asio::signal_set signals(io_service, SIGINT, SIGTERM);
    signals.async_wait(
      boost::bind(&boost::asio::io_service::stop, &io_service));

    if ( !debug ) {
      // Inform the io_service that we are about to become a daemon. The
      // io_service cleans up any internal resources, such as threads, that may
      // interfere with forking.
      io_service.notify_fork(boost::asio::io_service::fork_prepare);

      // Fork the process and have the parent exit. If the process was started
      // from a shell, this returns control to the user. Forking a new process is
      // also a prerequisite for the subsequent call to setsid().
      if (pid_t pid = fork())
      {
        if (pid > 0)
        {
          // We're in the parent process and need to exit.
          //
          // When the exit() function is used, the program terminates without
          // invoking local variables' destructors. Only global variables are
          // destroyed. As the io_service object is a local variable, this means
          // we do not have to call:
          //
          //   io_service.notify_fork(boost::asio::io_service::fork_parent);
          //
          // However, this line should be added before each call to exit() if
          // using a global io_service object. An additional call:
          //
          //   io_service.notify_fork(boost::asio::io_service::fork_prepare);
          //
          // should also precede the second fork().
          exit(0);
        }
        else
        {
          syslog(LOG_ERR | LOG_USER, "First fork failed: %m");
          return 1;
        }
      }

      // Make the process a new session leader. This detaches it from the
      // terminal.
      setsid();

      // A process inherits its working directory from its parent. This could be
      // on a mounted filesystem, which means that the running daemon would
      // prevent this filesystem from being unmounted. Changing to the root
      // directory avoids this problem.
      chdir("/");

      // The file mode creation mask is also inherited from the parent process.
      // We don't want to restrict the permissions on files created by the
      // daemon, so the mask is cleared.
      umask(0);

      // A second fork ensures the process cannot acquire a controlling terminal.
      if (pid_t pid = fork())
      {
        if (pid > 0)
        {
          exit(0);
        }
        else
        {
          syslog(LOG_ERR | LOG_USER, "Second fork failed: %m");
          return 1;
        }
      }

      // Close the standard streams. This decouples the daemon from the terminal
      // that started it.
      close(0);
      close(1);
      close(2);

      // We don't want the daemon to have any standard input.
      if (open("/dev/null", O_RDONLY) < 0)
      {
        syslog(LOG_ERR | LOG_USER, "Unable to open /dev/null: %m");
        return 1;
      }

      // Send standard output to a log file.
      const char* output = logfile.c_str();
      const int flags = O_WRONLY | O_CREAT | O_APPEND;
      const mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;
      if (open(output, flags, mode) < 0)
      {
        syslog(LOG_ERR | LOG_USER, "Unable to open output file %s: %m", output);
        return 1;
      }

      // Also send standard error to the same log file.
      if (dup(1) < 0)
      {
        syslog(LOG_ERR | LOG_USER, "Unable to dup output descriptor: %m");
        return 1;
      }

      // Inform the io_service that we have finished becoming a daemon. The
      // io_service uses this opportunity to create any internal file descriptors
      // that need to be private to the new process.
      io_service.notify_fork(boost::asio::io_service::fork_child);

      // The io_service can now be used normally.
      syslog(LOG_INFO | LOG_USER, "HexabusDaemon started");
    }
    io_service.run();
    if ( !debug )
      syslog(LOG_INFO | LOG_USER, "HexabusDaemon stopped");
  }
  catch (hexabus::NetworkException& e)
  {
    std::cerr << "An error occured during " << e.reason() << ": " << e.code().message() << std::endl;
  }
  catch (hexabus::GenericException& e)
  {
    std::cerr << "An error occured during " << e.reason() << std::endl;
  }
  catch (boost::exception& e)
  {
    std::cerr << "Boost Exception: " << diagnostic_information(e) << std::endl;
  }
  catch (std::exception& e)
  {
    syslog(LOG_ERR | LOG_USER, "Exception: %s", e.what());
    std::cerr << "Exception: " << e.what() << std::endl;
  }
}
Exemple #10
0
void print_exception(std::exception_ptr ep, const string& prefix, int level)
{
	std::ostringstream ss;

	if (!prefix.empty())
		ss << prefix << ": ";



	// print exception
	try
	{
		std::rethrow_exception(ep);
	}
	catch (const std::exception& e)
	{
		const boost::exception* be = boost::exception_detail::get_boost_exception(&e);
		if (be)
		{
			if (e.what() != string("Unknown exception"))
				ss << e.what() << endl;

			if (const char* const* api_function = boost::get_error_info<boost::errinfo_api_function>(*be))
				ss << *api_function << ": ";

			if (const DWORD* errcode = boost::get_error_info<e_last_error>(*be))
				ss << GetLastErrorString(*errcode) << endl;

			if (auto nt_status = boost::get_error_info<e_nt_status>(*be))
				ss << GetNTStatusString(*nt_status) << endl;
			
			//ss << "\n" << boost::diagnostic_information_what(*be) << "\n";
			if (optional<string> src = throw_location(*be))
				ss << "at " << *src << endl;

			ss << diagnostic_information(*be);
		}
		else
			ss << e.what() << endl;
	}
	catch (...)
	{
		ss << "unkown exception" << endl;
	}
	cerr << std::regex_replace(ss.str(), std::regex("^"), string(level, ' '));



	// print std or boost nested exception
	try
	{
		std::rethrow_exception(ep);
	}
	catch (const std::exception& e)
	{
		try
		{
			std::rethrow_if_nested(e);

			const boost::exception* be = boost::exception_detail::get_boost_exception(&e);
			if (be)
			{
				if (const boost::exception_ptr* nested = boost::get_error_info<boost::errinfo_nested_exception>(*be))
					boost::rethrow_exception(*nested);
			}
		}
		catch (...)
		{
			print_exception(std::current_exception(), "caused by", level + 1);
		}
	}
	catch (...) {}
}
Exemple #11
0
void doVMTests(json_spirit::mValue& v, bool _fillin)
{
	processCommandLineOptions();

	for (auto& i: v.get_obj())
	{
		cnote << i.first;
		mObject& o = i.second.get_obj();

		BOOST_REQUIRE(o.count("env") > 0);
		BOOST_REQUIRE(o.count("pre") > 0);
		BOOST_REQUIRE(o.count("exec") > 0);

		FakeExtVM fev;
		fev.importEnv(o["env"].get_obj());
		fev.importState(o["pre"].get_obj());

		if (_fillin)
			o["pre"] = mValue(fev.exportState());

		fev.importExec(o["exec"].get_obj());
		if (fev.code.empty())
		{
			fev.thisTxCode = get<3>(fev.addresses.at(fev.myAddress));
			fev.code = fev.thisTxCode;
		}

		bytes output;
		u256 gas;
		bool vmExceptionOccured = false;
		auto startTime = std::chrono::high_resolution_clock::now();
		try
		{
			auto vm = eth::VMFactory::create(fev.gas);
			output = vm->go(fev, fev.simpleTrace()).toBytes();
			gas = vm->gas();
		}
		catch (VMException const& _e)
		{
			cnote << "Safe VM Exception";
			vmExceptionOccured = true;
		}
		catch (Exception const& _e)
		{
			cnote << "VM did throw an exception: " << diagnostic_information(_e);
			BOOST_ERROR("Failed VM Test with Exception: " << _e.what());
		}
		catch (std::exception const& _e)
		{
			cnote << "VM did throw an exception: " << _e.what();
			BOOST_ERROR("Failed VM Test with Exception: " << _e.what());
		}

		auto endTime = std::chrono::high_resolution_clock::now();
		auto argc = boost::unit_test::framework::master_test_suite().argc;
		auto argv = boost::unit_test::framework::master_test_suite().argv;
		for (auto i = 0; i < argc; ++i)
		{	       
			if (std::string(argv[i]) == "--show-times")
			{
				auto testDuration = endTime - startTime;
				cnote << "Execution time: "
				      << std::chrono::duration_cast<std::chrono::milliseconds>(testDuration).count()
				      << " ms";
				break;
			}
		}

		// delete null entries in storage for the sake of comparison

		for (auto  &a: fev.addresses)
		{
			vector<u256> keystoDelete;
			for (auto &s: get<2>(a.second))
			{
				if (s.second == 0)
					keystoDelete.push_back(s.first);
			}
			for (auto const key: keystoDelete )
			{
				get<2>(a.second).erase(key);
			}
		}


		if (_fillin)
		{
			o["env"] = mValue(fev.exportEnv());
			o["exec"] = mValue(fev.exportExec());
			if (!vmExceptionOccured)
			{
				o["post"] = mValue(fev.exportState());
				o["callcreates"] = fev.exportCallCreates();
				o["out"] = "0x" + toHex(output);
				fev.push(o, "gas", gas);
				o["logs"] = exportLog(fev.sub.logs);
			}
		}
		else
		{
			if (o.count("post") > 0)	// No exceptions expected
			{
				BOOST_CHECK(!vmExceptionOccured);

				BOOST_REQUIRE(o.count("post") > 0);
				BOOST_REQUIRE(o.count("callcreates") > 0);
				BOOST_REQUIRE(o.count("out") > 0);
				BOOST_REQUIRE(o.count("gas") > 0);
				BOOST_REQUIRE(o.count("logs") > 0);

				dev::test::FakeExtVM test;
				test.importState(o["post"].get_obj());
				test.importCallCreates(o["callcreates"].get_array());
				test.sub.logs = importLog(o["logs"].get_array());

				checkOutput(output, o);

				BOOST_CHECK_EQUAL(toInt(o["gas"]), gas);

				auto& expectedAddrs = test.addresses;
				auto& resultAddrs = fev.addresses;
				for (auto&& expectedPair : expectedAddrs)
				{
					auto& expectedAddr = expectedPair.first;
					auto resultAddrIt = resultAddrs.find(expectedAddr);
					if (resultAddrIt == resultAddrs.end())
						BOOST_ERROR("Missing expected address " << expectedAddr);
					else
					{
						auto& expectedState = expectedPair.second;
						auto& resultState = resultAddrIt->second;
						BOOST_CHECK_MESSAGE(std::get<0>(expectedState) == std::get<0>(resultState), expectedAddr << ": incorrect balance " << std::get<0>(resultState) << ", expected " << std::get<0>(expectedState));
						BOOST_CHECK_MESSAGE(std::get<1>(expectedState) == std::get<1>(resultState), expectedAddr << ": incorrect txCount " << std::get<1>(resultState) << ", expected " << std::get<1>(expectedState));
						BOOST_CHECK_MESSAGE(std::get<3>(expectedState) == std::get<3>(resultState), expectedAddr << ": incorrect code");

						checkStorage(std::get<2>(expectedState), std::get<2>(resultState), expectedAddr);
					}
				}

				checkAddresses<std::map<Address, std::tuple<u256, u256, std::map<u256, u256>, bytes> > >(test.addresses, fev.addresses);
				BOOST_CHECK(test.callcreates == fev.callcreates);

				checkLog(fev.sub.logs, test.sub.logs);
			}
			else	// Exception expected
				BOOST_CHECK(vmExceptionOccured);
		}
	}
}
void searchPath(const CmdLineOptions &myOptions, boost::shared_ptr<BoundedQueue<std::string>> fileQueue, boost::exception_ptr & error)
{
  if (myOptions.debug > 1)
    std::cout << "Started search of path: " << myOptions.root_search_path << std::endl;
  
  fs::path p,sym_path,abs_path, temp_path;
  fs::recursive_directory_iterator end, it(myOptions.root_search_path);
  try {
    // use absolute paths for comparisons
    abs_path = fs::canonical(myOptions.root_search_path);
    do {     // Can't use for loop because we need a try block. See below
      try {
	p = it->path();
        if (fs::is_symlink(p)) {
	  temp_path = fs::canonical(p);
	  if (fs::is_directory(temp_path)) {
	    if (abs_path <= temp_path) {
	      if (myOptions.debug > 2) {
		std::cout << "Skipping " << p.string()
			  << " because it is a symlink to the path: " << temp_path.string() << std::endl;
	      }
	      // since its a directory, can skip file handling code below
	      it.no_push();
	    }
	    // continue recursing directory
	  }
	  else { // this is a file
	    if (p.extension().string() == ".txt") { // more efficient to filter on extension than lexigraphical compare
	      if (abs_path <= temp_path.remove_filename()) { // modifies sym_path
		if (myOptions.debug > 2) {
		  std::cout << "Skipping " << p.string()
			    << " because it is a symlink to the path: " << fs::canonical(p).string() << std::endl;
		}
		// skip this file
		it.no_push();
	      }
	    }
	    /* The symlink is to a regular file, so just fall through */
	  }
	}
	else if (fs::is_regular_file(p)) {
	  if (p.extension().string() == ".txt") {
	    if (myOptions.debug > 1) {
	      std::cout << "searchWorker: " << p.string() << " placed on queue\n";
	    }
	    // we want to place a copy of the string on the queue, but the queue is written in a way to 
	    // accept rvalue arguments
	    std::string _file = p.string();
	    fileQueue->send(std::move(_file));
	  }
	}
	try{  // boost bug 6821: recursive_directory_iterator: increment fails with 'access denied'
	  ++it;
	}
	catch(const boost::filesystem::filesystem_error& e) {
	  if(e.code() == boost::system::errc::permission_denied) {
	    std::cerr << "Search permission is denied for:  " << p.string() << "\n";
	  }
	  it.no_push();
	}
      }
      catch(const boost::filesystem::filesystem_error& e) {
	if(e.code() == boost::system::errc::permission_denied) {
	  std::cerr << "Search permission is denied for:  " << p.string() << "\n";
	}
	else if(e.code() == boost::system::errc::no_such_file_or_directory) {
	  std::cerr << "Symlink " << p.string() << " points to non-existent file\n";
	}
	else if(e.code() == boost::system::errc::too_many_symbolic_link_levels) {
	  std::cerr << "Encountered too many symbolic link levels at: " << p.string() << " . Not continuing\n";
	  // boost bug 5652 -- fixed in 1.49.0
	}
	else {
	  /* Not sure how to hande other errors, so continue propogating */
	  std::cerr << "Fatal error detected in directory search: " << e.what() << std::endl;
	  // shut down threads
	  fileQueue->send("");
	  throw boost::enable_current_exception(recursive_directory_iterator_error()) <<
	    boost::errinfo_errno(errno);
	}
	it.no_push();
	++it;
      }
    } while (it != end);

    // finished with indexing root path now
    // place termination character on queue
    fileQueue->send("");
    
    // all errors were handled, so don't pass any outside this thread
    error = boost::exception_ptr();
  }
  catch (const boost::exception& e) {
    std::cout << "searchWorker encountered unexpected exception" << diagnostic_information(e) << std::endl;
    error = boost::current_exception();
  }
  catch (...) {
    error = boost::current_exception();
  }

  if (myOptions.debug > 1)
    std::cout << "Finished search of path: " << myOptions.root_search_path << std::endl;
}
Exemple #13
0
int main(int argc, const char **argv) {
  mfast::template_registry registry;

  try {
    int i = 1;

    std::string command_name = "fast_type_gen";

    const char *export_symbol = nullptr;
    const char *outer_namespace = nullptr;
    const char *header_extension = ".h";
    const char *inline_extension = ".inl";
    const char *source_extension = ".cpp";

    bool show_usage = false;
    bool bad_arguments = false;

    while ((i < argc) && (std::strlen(argv[i]) > 1) && (argv[i][0] == '-') && (std::strcmp(argv[i], "--") != 0) && !bad_arguments) {
      const char *flag = &argv[i][1];
      if (*flag == '-') {
        ++flag;
        if (std::strcmp(flag, "help") == 0) {
          show_usage = true;
        } else if (check_long_option(command_name, argc, argv, i, "--export-symbol", export_symbol, bad_arguments)) {
        } else if (check_long_option(command_name, argc, argv, i, "--namespace", outer_namespace, bad_arguments)) {
        } else if (check_long_option(command_name, argc, argv, i, "--header-extension", header_extension, bad_arguments)) {
        } else if (check_long_option(command_name, argc, argv, i, "--inline-extension", inline_extension, bad_arguments)) {
        } else if (check_long_option(command_name, argc, argv, i, "--source-extension", source_extension, bad_arguments)) {
        } else {
          std::cerr << command_name << ": illegal option -- " << flag << std::endl;
          bad_arguments = true;
        }
      } else {
        while ((i < argc) && *flag && !bad_arguments) {
          if (*flag == 'h') {
            show_usage = true;
            ++flag;
          } else if (check_short_option(command_name, argc, argv, i, flag, 'E', export_symbol, bad_arguments)) {
          } else if (check_short_option(command_name, argc, argv, i, flag, 'n', outer_namespace, bad_arguments)) {
          } else if (check_short_option(command_name, argc, argv, i, flag, 'H', header_extension, bad_arguments)) {
          } else if (check_short_option(command_name, argc, argv, i, flag, 'I', inline_extension, bad_arguments)) {
          } else if (check_short_option(command_name, argc, argv, i, flag, 'C', source_extension, bad_arguments)) {
          } else {
            std::cerr << command_name << ": illegal option -- " << *flag << std::endl;
            bad_arguments = true;
          }
        }
      }
      ++i;
    }
    if ((i < argc) && (std::strcmp(argv[i], "--") == 0))
      ++i;
    if (show_usage || bad_arguments || (i >= argc)) {
      std::ostream &output = show_usage ? std::cout : std::cerr;
      output << "usage: " << command_name << " [-E symbol] [-H extension] [-I extension] [-C extension] file ...\n"
                "       generate C++ bindings for FAST types\n";
      if (show_usage) {
        output << "\n"
                  "Options and arguments:\n"
                  "  -h, --help                  show usage and exit\n"
                  "  -E, --export-symbol=SYM     qualifier for generated types\n"
                  "  -n, --namespace=NS          namespace for generated code\n"
                  "  -C, --source-extension=EXT  source filename extension (default .cpp)\n"
                  "  -H, --header-extension=EXT  header filename extension (default .h)\n"
                  "  -I, --inline-extension=EXT  inline function filename extension (default .inl)\n"
                  "  file ...                    XML FAST message template inputs\n";
      }
      return (bad_arguments || (!show_usage && (i >= argc))) ? -1 : 0;
    }

    std::vector<mfast::dynamic_templates_description> descriptions;

    std::vector<std::string> filebases;

    mfast::simple_template_repo_t repo;

    for (int j = 0; i < argc; ++i, ++j) {

      std::ifstream ifs(argv[i]);

      if (!ifs) {
        std::cerr << command_name << ": " << argv[i] << " load failed" << std::endl;
        return -1;
      }

      std::string xml((std::istreambuf_iterator<char>(ifs)),
                      std::istreambuf_iterator<char>());

      //path f(path(argv[i]).stem());

#ifdef _WINDOWS
      char filebase_buf[_MAX_FNAME];
      _splitpath(argv[i], NULL, NULL, filebase_buf, NULL);
      boost::string_ref filebase = static_cast<const char*>(filebase_buf);
#else
      boost::string_ref filebase(argv[i]);
      filebase = filebase.substr(filebase.find_last_of('/') + 1);
      filebase = filebase.substr(0, filebase.find_last_of('.'));
#endif
      filebases.push_back(codegen_base::cpp_name(filebase));

      descriptions.emplace_back(xml.c_str(), filebases[j].c_str(), &registry);
    }

    repo.build(descriptions.begin(), descriptions.end());

    for (std::size_t j = 0; j < filebases.size(); ++j) {
      mfast::dynamic_templates_description &desc = descriptions[j];
      const std::string &filebase = filebases[j];

      hpp_gen header_gen(filebase.c_str(), header_extension);
      if (outer_namespace)
        header_gen.set_outer_ns(outer_namespace);
      if (export_symbol)
        header_gen.set_export_symbol(export_symbol);
      header_gen.set_inl_fileext(inline_extension);
      header_gen.generate(desc);

      inl_gen inline_gen(filebase.c_str(), inline_extension);
      if (outer_namespace)
        inline_gen.set_outer_ns(outer_namespace);
      inline_gen.generate(desc);

      cpp_gen source_gen(filebase.c_str(), source_extension);
      if (outer_namespace)
        source_gen.set_outer_ns(outer_namespace);
      source_gen.set_hpp_fileext(header_extension);
      source_gen.generate(desc);
    }
  } catch (boost::exception &e) {
    std::cerr << diagnostic_information(e);
    return -1;
  } catch (std::exception &e) {
    std::cerr << e.what() << "\n";
    return -1;
  }

  return 0;
}