Beispiel #1
0
/*
 *  TheUnhandledExceptionFilter
 *      Logs an unhandled exception
 */
static LONG CALLBACK TheUnhandledExceptionFilter(LPEXCEPTION_POINTERS pException)
{
    // Logs exception into buffer and calls the callback
    auto Log = [pException](char* buffer, size_t size, bool reg, bool stack, bool trace)
    {
        if(LogException(buffer, size, (LPEXCEPTION_POINTERS)pException, reg, stack, trace))
            ExceptionCallback(buffer);
    };

    // Try to make a very descriptive exception, for that we need to malloc a huge buffer...
    if(auto buffer = (char*) malloc(max_logsize_ever))
    {
        Log(buffer, max_logsize_ever, true, true, true);
        free(buffer);
    }
    else
    {
        // Use a static buffer, no need for any allocation
        static const auto size = max_logsize_basic + max_logsize_regs + max_logsize_stackdump;
        static char static_buf[size];
        static_assert(size <= max_static_buffer, "Static buffer is too big");

        Log(buffer = static_buf, sizeof(static_buf), true, true, false);
    }


    // Continue exception propagation
    return (PrevFilter? PrevFilter(pException) : EXCEPTION_CONTINUE_SEARCH);  // I'm not really sure about this return
}
Beispiel #2
0
/**
 * \fn void CheckLogDelete(Log *log)
 * \brief Check to see if logs need to be removed due to old age
 * \param log A log class variable
 */
void CheckLogDelete(Log *log)
{
	Flux::string dir = binary_dir + "/logs/";

	if(!TextFile::IsDirectory(dir))
	{
		Log(LOG_TERMINAL) << "Directory " << dir << " does not exist, making new directory.";
#ifndef _WIN32

		if(mkdir(dir.c_str(), S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH) != 0)
			throw LogException("Failed to create directory " + dir + ": " + Flux::string(strerror(errno)));

#else

		if(!CreateDirectory(dir.c_str(), NULL))
			throw LogException("Failed to create directory " + dir + ": " + Flux::string(strerror(errno)));

#endif

	}

	Flux::vector files = TextFile::DirectoryListing(dir);

	if(log)
		files.push_back(log->filename);

	if(files.empty())
		Log(LOG_TERMINAL) << "No Logs!";

	for(Flux::vector::iterator it = files.begin(); it != files.end(); ++it)
	{
		Flux::string file = dir + (*it);

		if(TextFile::IsFile(file))
		{
			Flux::string t = file.isolate('-', ' ').strip('-');
			int timestamp = static_cast<int>(t);

			if(timestamp > (time(NULL) - 86400 * Config->LogAge) && timestamp != starttime)
			{
				Delete(file.c_str());
				Log(LOG_DEBUG) << "Deleted old logfile " << file;
			}
		}
	}
}
void GLogicEngineCPP::HandleClockTick(DWORD64 clock_msec)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_clock_tick(clock_msec);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleClockTick()", e.what());
		}
		catch (...)
		{
			LogException("HandleClockTick()");
		}
	}
}
Beispiel #4
0
void AdjacencyMatrix::removeEdge(Edge* edge)
{
    Node* n1 = edge->getNode1();
    Node* n2 = edge->getNode2();
    if(!edge || !n1 || !n2)
        throw LogException("invalid edge",__LINE__,__FILE__);
    if(!getEdge(n1,n2))
        throw LogException("edge is not in the matrix",__LINE__,__FILE__);   //the edge is not in the matrix

    int idx1 = getNodeIndex(n1);
    int idx2 = getNodeIndex(n2);
    if(idx1==-1 || idx2==-1)
        throw LogException("an extremity is not in the matrix",__LINE__,__FILE__);   //a node does not exist

    this->SquareMatrix<Edge*>::set(idx1, idx2, nullptr);
    if(!edge->isOriented())
        this->SquareMatrix<Edge*>::set(idx2, idx1, nullptr);
}
void GLogicEngineCPP::HandleHTTPResponse(const char * location_ID, INT32 http_request_id, INT32 http_response_code, const std::string & http_response)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_http_response(location_ID, http_request_id, http_response_code, http_response);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleHTTPResponse(\"%s\")", e.what(), location_ID);
		}
		catch (...)
		{
			LogException("HandleHTTPResponse(\"%s\")", location_ID);
		}
	}
}
void GLogicEngineCPP::HandleReplaceVulgarWords(const char * location_ID, const std::string & text, const std::string & params)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_replace_vulgar_words(CurrentSTime(), location_ID, text, params);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleReplaceVulgarWords(\"%s\", \"%s\")", e.what(), location_ID, text.c_str());
		}
		catch (...)
		{
			LogException("HandleReplaceVulgarWords(\"%s\", \"%s\")", location_ID, text.c_str());
		}
	}
}
void GLogicEngineCPP::HandleGetLocationsIdsLike(const char * location_ID, INT32 request_id, const std::set<std::string> & locations_ids)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_get_locations_ids_like(location_ID, request_id, locations_ids);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleGetLocationsIdsLike(\"%s\", %d)", e.what(), location_ID, request_id);
		}
		catch (...)
		{
			LogException("HandleGetLocationsIdsLike(\"%s\", %d)", location_ID, request_id);
		}
	}
}
void JniCallbackBase::CheckAndLogJavaException(JNIEnv* env) const
{
  if (env->ExceptionCheck())
  {
    JniLocalReference<jthrowable> throwable(env, env->ExceptionOccurred());
    env->ExceptionClear();
    LogException(env, *throwable);
  }
}
void GLogicEngineCPP::HandlePrintStatistics(strstream & s)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_print_statistics(s);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandlePrintStatistics()", e.what());
		}
		catch (...)
		{
			LogException("HandlePrintStatistics()");
		}
	}
}
void GLogicEngineCPP::HandleCreateLocationNotification(const char * location_ID, const char * new_location_ID, const char * new_location_data, bool creation_success)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_create_location(location_ID, new_location_ID, new_location_data, creation_success);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleCreateLocationNotification(\"%s\", \"%s\")", e.what(), location_ID, new_location_ID);
		}
		catch (...)
		{
			LogException("HandleCreateLocationNotification(\"%s\", \"%s\")", location_ID, new_location_ID);
		}
	}
}
void GLogicEngineCPP::HandleFlushLocationNotification(const char * location_ID, const char * location_data, bool flush_success)
{
	if (logic_base)
	{
		try
		{
			logic_base->on_flush_location(location_ID, location_data, flush_success);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleFlushLocationNotification(\"%s\")", e.what(), location_ID);
		}
		catch (...)
		{
			LogException("HandleFlushLocationNotification(\"%s\")", location_ID);
		}
	}
}
void GLogicEngineCPP::HandleInitiateGentleClose()
{
	if (logic_base)
	{
		try
		{
			logic_base->on_initiate_gentle_close();
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleInitiateGentleClose()", e.what());
		}
		catch (...)
		{
			LogException("HandleInitiateGentleClose()");
		}
	}
}
bool GLogicEngineCPP::HandleLogicMessage(INT32 user_id, const char * location_ID, INT32 access, DWORD64 msg_time, const std::string & command, const std::string & params)
{
	try
	{
		INT32 gamestate_ID = gamestate_ID_from_location_ID(location_ID);
		if (gamestate_ID == 0)
		{
			logic_base->handle_user_location_message(msg_time, user_id, location_ID, command, params);
			return true;
		}

		if (access == EGS_PLAYER)
		{
			if (logic_base)
			{
				logic_base->handle_player_message(msg_time, user_id, gamestate_ID, command, params);
			}
		}
		else if (access == EGS_FRIEND)
		{
			if (logic_base)
			{
				logic_base->handle_friend_message(msg_time, user_id, gamestate_ID, command, params);
			}
		}
		else
		{
			if (logic_base)
			{
				logic_base->handle_stranger_message(msg_time, user_id, gamestate_ID, command, params);
			}
		}
	}
	catch (std::exception & e)
	{
		LogException("{%s} HandleLogicMessage(\"%s\", \"%s\", \"%s\")", e.what(), location_ID, command.c_str(), params.c_str());
	}
	catch (...)
	{
		LogException("HandleLogicMessage(\"%s\", \"%s\", \"%s\")", location_ID, command.c_str(), params.c_str());
	}
	return true;
}
bool GLogicEngineCPP::HandleInitScript(const std::string & config_str)
{
	if (logic_base)
	{
		try
		{
			return logic_base->on_init_global_config(CurrentSTime(), config_str);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleInitScript()", e.what());
		}
		catch (...)
		{
			LogException("HandleInitScript()");
		}
	}
	return false;
}
bool GLogicEngineCPP::HandleGlobalMessage(const std::string & command, const std::string & params)
{
	if (logic_base)
	{
		try
		{
			logic_base->handle_global_message(CurrentSTime(), command, params);
		}
		catch (std::exception & e)
		{
			LogException("{%s} HandleGlobalMessage(\"%s\", \"%s\")", e.what(), command.c_str(), params.c_str());
		}
		catch (...)
		{
			LogException("HandleGlobalMessage(\"%s\", \"%s\")", command.c_str(), params.c_str());
		}
	}
	return true;
}
/*static*/ double MathExt::logb(const double base, const double x)
{
	const double tol = MathConstant::EPS;
	if (base <= 0.0 || (-tol <= base - 1.0 && base - 1.0 <= tol))
	{
		//std::ostringstream stream;
		//stream << "swl::MathExt::logb() at " << __LINE__ << " in " << __FILE__;
		//throw std::invalid_argument(stream.str().c_str());
		throw LogException(LogException::L_ERROR, "invalid argument", __FILE__, __LINE__, __FUNCTION__);
	}
	if (x <= 0.0)
	{
		//std::ostringstream stream;
		//stream << "swl::MathExt::logb() at " << __LINE__ << " in " << __FILE__;
		//throw std::domain_error(stream.str().c_str());
		throw LogException(LogException::L_ERROR, "domain error", __FILE__, __LINE__, __FUNCTION__);
	}

	return std::log(x) / std::log(base);
}
Beispiel #17
0
// ------------------------------------------------------------------------- //
//  * HandleServerException( TDCLServer*, TDCLException* )
// ------------------------------------------------------------------------- //
void
TDCLLogApplication::HandleServerException(
							TDCLServer* inServer,
							TDCLException* inException )
{
	(void) ::fprintf( mLogFile,
				"Exception au niveau du serveur [%p]!\n",
				inServer );

	LogException( inException );
}
/*static*/ unsigned long MathExt::binomial(const unsigned long lhs, const unsigned long rhs)
{
	if (lhs < rhs)
	{
		//std::ostringstream stream;
		//stream << "swl::MathExt::binomial() at " << __LINE__ << " in " << __FILE__;
		//throw std::invalid_argument(stream.str().c_str());
		throw LogException(LogException::L_ERROR, "invalid argument", __FILE__, __LINE__, __FUNCTION__);
	}
	return factorial(lhs) / (factorial(lhs - rhs) * factorial(rhs));
}
Beispiel #19
0
// ------------------------------------------------------------------------- //
//  * HandleLinkException( TDCLLink*, TDCLException* )
// ------------------------------------------------------------------------- //
void
TDCLLogApplication::HandleLinkException(
							TDCLLink* inLink,
							TDCLException* inException )
{
	(void) ::fprintf( mLogFile,
				"Exception au niveau du lien [%p]!\n",
				inLink );

	LogException( inException );
}
Beispiel #20
0
// ------------------------------------------------------------------------- //
//  * HandleCommLayerException( TDCLCommLayer*, TDCLException* )
// ------------------------------------------------------------------------- //
void
TDCLLogApplication::HandleCommLayerException(
							TDCLCommLayer* inCommLayer,
							TDCLException* inException )
{
	(void) ::fprintf( mLogFile,
				"Exception au niveau de la couche de communication [%p]!\n",
				inCommLayer );

	LogException( inException );
}
// combination or binomial
/*static*/ double MathExt::binomial(const double lhs, const double rhs, const double& tol /*= MathConstant::EPS*/)
{
	if (lhs < rhs)
	{
		//std::ostringstream stream;
		//stream << "swl::MathExt::binomial() at " << __LINE__ << " in " << __FILE__;
		//throw std::invalid_argument(stream.str().c_str());
		throw LogException(LogException::L_ERROR, "invalid argument", __FILE__, __LINE__, __FUNCTION__);
	}
	return factorial(lhs, tol) / (factorial(lhs - rhs, tol) * factorial(rhs, tol));
}
/*static*/ double MathExt::atanh(const double x)
{
	if (x <= -1.0 || x >= 1.0)
	{
		// when x <= -1.0 || x >= 1.0, a solution is a conmplex number
		//std::ostringstream stream;
		//stream << "swl::MathExt::atanh() at " << __LINE__ << " in " << __FILE__;
		//throw std::domain_error(stream.str().c_str());
		throw LogException(LogException::L_ERROR, "domain error", __FILE__, __LINE__, __FUNCTION__);
	}

	return std::log(std::sqrt((1.0 + x) / (1.0 - x)));
}
bool GdiPrintContext::resize(const int x1, const int y1, const int x2, const int y2)
{
/*
	if (isActivated()) return false;
	drawRegion_ = Region2<int>(x1, y1, x2, y2);

	deleteOffScreenBitmap();

	return createOffScreen();
*/
	//throw std::runtime_error("GdiPrintContext::resize() must not to be called"); 
	throw LogException(LogException::L_ERROR, "this function must not to be called", __FILE__, __LINE__, __FUNCTION__);
}
Beispiel #24
0
template <> acl::UserData Unserialize<acl::UserData>(const mongo::BSONObj& obj)
{
  try
  { 
    acl::UserData user;
    user.id = obj["uid"].Int();
    user.name = obj["name"].String();
    UnserializeContainer(obj["ip masks"].Array(), user.ipMasks);
    user.password = obj["password"].String();
    user.salt = obj["salt"].String();
    user.flags = obj["flags"].String();
    user.primaryGid = obj["primary gid"].Int();
    UnserializeContainer(obj["secondary gids"].Array(), user.secondaryGids);
    UnserializeContainer(obj["gadmin gids"].Array(), user.gadminGids);
    
    user.creator = obj["creator"].Int();
    mongo::BSONElement oid;
    obj.getObjectID(oid);
    user.created = ToGregDate(oid.OID().asDateT());
    
    user.homeDir = obj["home dir"].String();
    user.startUpDir = obj["startup dir"].String();
    user.idleTime = obj["idle time"].Int();
    
    if (obj["expires"].type() != mongo::jstNULL)
      user.expires.reset(ToGregDate(obj["expires"].Date()));
    
    user.numLogins = obj["num logins"].Int();
    user.comment = obj["comment"].String();
    user.tagline = obj["tagline"].String();
    user.maxDownSpeed = obj["max down speed"].Long();
    user.maxUpSpeed = obj["max up speed"].Long();
    user.maxSimDown = obj["max sim down"].Int();
    user.maxSimUp = obj["max sim up"].Int();
    user.loggedIn = obj["logged in"].Int();
    if (obj["last login"].type() != mongo::jstNULL)
      user.lastLogin.reset(ToPosixTime(obj["last login"].Date()));
    
    UnserializeMap(obj["ratio"].Array(), "section", "value", user.ratio);
    UnserializeMap(obj["credits"].Array(), "section", "value", user.credits);
    UnserializeMap(obj["weekly allotment"].Array(), "section", "value", user.weeklyAllotment);
    
    return user;
  }
  catch (const mongo::DBException& e)
  {
    LogException("Unserialize user", e, obj);
    throw e;
  }
}
Beispiel #25
0
void DebugBreakorAV(int val)
{
    if (IsDebuggerPresent())
    {
        if (val == 0)
            __debugbreak();
        if (breakOnDebugBreakorAV)
            __debugbreak();
    } 

    int exception_code = EXCEPTIONCODE_DebugBreakorAV + val;
    // assert((EXCEPTIONCODE_DebugBreakorAV <= exception_code) && (exception_code < EXCEPTIONCODE_DebugBreakorAV_MAX))
    LogException(exception_code, "DebugBreak or AV Exception %d", val);
}
Beispiel #26
0
void terrama2::core::ProcessLogger::setDataSource(te::da::DataSource* dataSource)
{
  isValid_ = false;

  dataSource_.reset(dataSource);

  try
  {
    dataSource_->open();

    if(!dataSource_->isOpened())
    {
      throw LogException();
    }
  }
  catch(std::exception& e)
  {
    QString errMsg = QObject::tr("Could not connect to database");
    TERRAMA2_LOG_ERROR() << errMsg << ": " << e.what();
    throw LogException() << ErrorDescription(errMsg);
  }

  isValid_ = true;
}
Beispiel #27
0
long long TransfersUser(acl::UserID uid, ::stats::Timeframe timeframe, 
      const std::string& section, ::stats::Direction direction)
{
  mongo::BSONObjBuilder match;
  match.append("direction", util::EnumToString(direction));
  if (!section.empty())
    match.append("section", section);
  else
  {
    mongo::BSONArrayBuilder sections;
    for (const auto& kv : cfg::Get().Sections())
      sections.append(kv.first);
    match.appendElements(BSON("section" << BSON("$nin" << sections.arr())));
  }
  match.appendElements(Serialize(timeframe));
  
  mongo::BSONObj cmd = BSON("aggregate" << "transfers" << "pipeline" <<
    BSON_ARRAY(
      BSON("$match" << match.obj()) <<
      BSON("$group" << 
        BSON("_id" << (uid == -1 ? "" : "$uid") <<
          "total" << BSON("$sum" << "$kbytes")
        ))));
  
  
  mongo::BSONObj result;
  NoErrorConnection conn;
  if (conn.RunCommand(cmd, result))
  {
    try
    {
      auto elems = result["result"].Array();
      if (!elems.empty())
      {
        return elems[0]["total"].Long();
      }
    }
    catch (const mongo::DBException& e)
    {
      LogException("Unserialize transfers total", e, result);
    }
  }
  
  return 0;
}
/*static*/ unsigned long MathExt::factorial(const unsigned long n)
{
	unsigned long ulFactorial = 1ul;
	
	if (n == 0ul || n == 1ul) return 1ul;
	for (unsigned long k = n; k > 1ul; --k)
	{
		if (std::numeric_limits<unsigned long>::max() / ulFactorial < k)
		{
			//std::ostringstream stream;
			//stream << "swl::MathExt::factorial() at " << __LINE__ << " in " << __FILE__;
			//throw std::overflow_error(stream.str().c_str());
			throw LogException(LogException::L_ERROR, "overflow error", __FILE__, __LINE__, __FUNCTION__);
		}
		ulFactorial *= k;
	}
	return ulFactorial;
}
/*static*/ double MathExt::factorial(const double n, const double& tol /*= MathConstant::EPS*/)
{
	double dFactorial = 1.0;
	
	if ((-tol <= n && n <= tol) || (-tol <= n - 1.0 && n - 1.0 <= tol)) return 1.0;
	for (unsigned long k = (unsigned long)round(n); k > 1ul; --k)
	{
		if (std::numeric_limits<double>::max() / dFactorial < k)
		{
			//std::ostringstream stream;
			//stream << "swl::MathExt::factorial() at " << __LINE__ << " in " << __FILE__;
			//throw std::overflow_error(stream.str().c_str());
			throw LogException(LogException::L_ERROR, "overflow error", __FILE__, __LINE__, __FUNCTION__);
		}
		dFactorial *= k;
	}
	return dFactorial;
}
Beispiel #30
0
long long XfertimeCorrection(acl::UserID          uid, 
                             long long            kBytes,
                             time_t               modTime, 
                             ::stats::Direction   direction)
{
  long long xfertime = -1; 
  util::Time t(modTime);

  auto cmd = BSON("aggregate" << "transfers" << "pipeline" << 
    BSON_ARRAY(
        BSON("$match" << 
          BSON("year" << t.Year() << "month" << t.Month()  <<
               "week" << t.Week() << "day" << t.Day() <<
               "direction" << util::EnumToString(direction))) <<
        BSON("$group" << 
          BSON("_id" << uid << 
            "total kbytes" << BSON("$sum" << "$kbytes") <<
            "total xfertime" << BSON("$sum" << "$xfertime")
      ))));

  NoErrorConnection conn;
  mongo::BSONObj result;
  if (conn.RunCommand(cmd, result))
  {
    auto elems = result["result"].Array();
    if (!elems.empty())
    {
      try
      {
        long long totalXfertime = elems[0]["total xfertime"].Long();
        if (totalXfertime > 0)
          xfertime = std::ceil(static_cast<double>(totalXfertime) / elems[0]["total kbytes"].Long() * kBytes);
        else
          xfertime = 0;
      }
      catch (const mongo::DBException& e)
      {
        LogException("Unserialize upload decr avg speed", e, result);
      }
    }
  }
  
  return xfertime;
}