<commit_before>// -------------------------------------------------------------------------
//    @FileName         :    NFPluginLoader.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :
//    @Module           :    NFPluginLoader
//
// -------------------------------------------------------------------------

//#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include "NFCActorManager.h"
#include "NFComm/Config/NFConfig.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include "boost/thread.hpp"

#if NF_PLATFORM == NF_PLATFORM_LINUX
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#endif

#pragma comment( lib, "DbgHelp" )

#if NF_PLATFORM == NF_PLATFORM_WIN

// Dumpļ
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
    // Dumpļ
    HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    // DumpϢ
    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    dumpInfo.ExceptionPointers = pException;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;

    // дDumpļ
    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);

    CloseHandle(hDumpFile);
}

// Unhandled ExceptionĻص
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
    time_t t = time(0);
    char szDmupName[MAX_PATH];
    tm* ptm = localtime(&t);

    sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp",  ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    CreateDumpFile(szDmupName, pException);

    FatalAppExit(-1,  szDmupName);

    return EXCEPTION_EXECUTE_HANDLER;
}
#endif

void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN

    HWND hWnd = GetConsoleWindow();
    if(hWnd)
    {
        HMENU hMenu = GetSystemMenu(hWnd, FALSE);
        EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
    }

#endif
}

bool bExitApp = false;
boost::thread gThread;

void ThreadFunc()
{
    while ( !bExitApp )
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));

        std::string s;
        std::cin >> s;
        if ( 0 == stricmp( s.c_str(), "exit" ) )
        {
            bExitApp = true;
        }
    }
}

void CreateBackThread()
{
    gThread = boost::thread(boost::bind(&ThreadFunc));
    //std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}

void PrintfLogo()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    std::cout << "\n" << std::endl;

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    std::cout << "" << std::endl;
    std::cout << "                                            " << std::endl;
    std::cout << "                 NoahFrame                  " << std::endl;
    std::cout << "   Copyright (c) 2011-2015  NFrame Studio   " << std::endl;
    std::cout << "             All rights reserved.           " << std::endl;
    std::cout << "                                            " << std::endl;
    std::cout << "" << std::endl;

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    std::cout << "\n" << std::endl;
#endif // NF_PLATFORM
}

unsigned long unStartTickTime = 0;
unsigned long unLastTickTime = 0;

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
int main(int argc, char* argv[])
#elif  NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS

#endif
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
#else if NF_PLATFORM == NF_PLATFORM_LINUX
	bool is_daemon = false;

	if (argc > 1)
	{
		if (0 == NFSTRICMP((const char*)argv[1], "-d"))
		{
			is_daemon = true;
		}
	}

	daemon(nochdir, noclose);

	// ignore signals
	signal(SIGINT,  SIG_IGN);
	signal(SIGHUP,  SIG_IGN);
	signal(SIGQUIT, SIG_IGN);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTERM, SIG_IGN);

#endif
	NFCActorManager::GetSingletonPtr()->Init();
	NFCActorManager::GetSingletonPtr()->AfterInit();
    NFCActorManager::GetSingletonPtr()->CheckConfig();

    PrintfLogo();

    CloseXButton();
    CreateBackThread();

    unStartTickTime = ::NF_GetTickCount();
    unLastTickTime = unStartTickTime;

    while (!bExitApp)    //DEBUG汾RELEASE
    {
        while (true)
        {
			std::this_thread::sleep_for(std::chrono::milliseconds(1));

            if (bExitApp)
            {
                break;
            }

			unsigned long unNowTickTime = ::NF_GetTickCount();
			float fStartedTime = float(unNowTickTime - unStartTickTime) / 1000;
			float fLastTime = float(unNowTickTime - unLastTickTime) / 1000;

			if (fStartedTime < 0.001f)
			{
				fStartedTime = 0.0f;
			}

#if NF_PLATFORM == NF_PLATFORM_WIN
            __try
            {
#endif
                NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);
				unLastTickTime = unNowTickTime;
#if NF_PLATFORM == NF_PLATFORM_WIN
            }
            __except (ApplicationCrashHandler(GetExceptionInformation()))
            {
            }
#endif
        }
    }

	NFCActorManager::GetSingletonPtr()->BeforeShut();
	NFCActorManager::GetSingletonPtr()->Shut();

    NFCActorManager::GetSingletonPtr()->ReleaseInstance();

    return 0;
}
<commit_msg>daemon for linux<commit_after>// -------------------------------------------------------------------------
//    @FileName         :    NFPluginLoader.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :
//    @Module           :    NFPluginLoader
//
// -------------------------------------------------------------------------

//#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <functional>
#include <atomic>
#include "NFCActorManager.h"
#include "NFComm/Config/NFConfig.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include "boost/thread.hpp"

#if NF_PLATFORM == NF_PLATFORM_LINUX
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#endif

#pragma comment( lib, "DbgHelp" )

#if NF_PLATFORM == NF_PLATFORM_WIN

// Dumpļ
void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
    // Dumpļ
    HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    // DumpϢ
    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    dumpInfo.ExceptionPointers = pException;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;

    // дDumpļ
    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);

    CloseHandle(hDumpFile);
}

// Unhandled ExceptionĻص
long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
    time_t t = time(0);
    char szDmupName[MAX_PATH];
    tm* ptm = localtime(&t);

    sprintf(szDmupName, "%d_%d_%d_%d_%d_%d.dmp",  ptm->tm_year + 1900, ptm->tm_mon, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    CreateDumpFile(szDmupName, pException);

    FatalAppExit(-1,  szDmupName);

    return EXCEPTION_EXECUTE_HANDLER;
}
#endif

void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN

    HWND hWnd = GetConsoleWindow();
    if(hWnd)
    {
        HMENU hMenu = GetSystemMenu(hWnd, FALSE);
        EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
    }

#endif
}

bool bExitApp = false;
boost::thread gThread;

void ThreadFunc()
{
    while ( !bExitApp )
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));

        std::string s;
        std::cin >> s;
        if ( 0 == stricmp( s.c_str(), "exit" ) )
        {
            bExitApp = true;
        }
    }
}

void CreateBackThread()
{
    gThread = boost::thread(boost::bind(&ThreadFunc));
    //std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}

void InitDaemon()
{
#if NF_PLATFORM == NF_PLATFORM_LINUX
	daemon(nochdir, noclose);

	// ignore signals
	signal(SIGINT,  SIG_IGN);
	signal(SIGHUP,  SIG_IGN);
	signal(SIGQUIT, SIG_IGN);
	signal(SIGPIPE, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTERM, SIG_IGN);
#endif
}

void PrintfLogo()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    std::cout << "\n" << std::endl;

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    std::cout << "" << std::endl;
    std::cout << "                                            " << std::endl;
    std::cout << "                 NoahFrame                  " << std::endl;
    std::cout << "   Copyright (c) 2011-2015  NFrame Studio   " << std::endl;
    std::cout << "             All rights reserved.           " << std::endl;
    std::cout << "                                            " << std::endl;
    std::cout << "" << std::endl;

    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);

    std::cout << "\n" << std::endl;
#endif // NF_PLATFORM
}

unsigned long unStartTickTime = 0;
unsigned long unLastTickTime = 0;

#if NF_PLATFORM == NF_PLATFORM_WIN || NF_PLATFORM == NF_PLATFORM_LINUX || NF_PLATFORM == NF_PLATFORM_APPLE
int main(int argc, char* argv[])
#elif  NF_PLATFORM == NF_PLATFORM_ANDROID || NF_PLATFORM == NF_PLATFORM_APPLE_IOS

#endif
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
#else if NF_PLATFORM == NF_PLATFORM_LINUX
	bool bDaemon = false;

	if (argc > 1)
	{
		if (0 == NFSTRICMP((const char*)argv[1], "-d"))
		{
			bDaemon = true;
		}
	}

	if (bDaemon)
	{
		InitDaemon();
	}

#endif
	NFCActorManager::GetSingletonPtr()->Init();
	NFCActorManager::GetSingletonPtr()->AfterInit();
    NFCActorManager::GetSingletonPtr()->CheckConfig();

    PrintfLogo();

    CloseXButton();
    CreateBackThread();

    unStartTickTime = ::NF_GetTickCount();
    unLastTickTime = unStartTickTime;

    while (!bExitApp)    //DEBUG汾RELEASE
    {
        while (true)
        {
			std::this_thread::sleep_for(std::chrono::milliseconds(1));

            if (bExitApp)
            {
                break;
            }

			unsigned long unNowTickTime = ::NF_GetTickCount();
			float fStartedTime = float(unNowTickTime - unStartTickTime) / 1000;
			float fLastTime = float(unNowTickTime - unLastTickTime) / 1000;

			if (fStartedTime < 0.001f)
			{
				fStartedTime = 0.0f;
			}

#if NF_PLATFORM == NF_PLATFORM_WIN
            __try
            {
#endif
                NFCActorManager::GetSingletonPtr()->Execute(fLastTime, fStartedTime);
				unLastTickTime = unNowTickTime;
#if NF_PLATFORM == NF_PLATFORM_WIN
            }
            __except (ApplicationCrashHandler(GetExceptionInformation()))
            {
            }
#endif
        }
    }

	NFCActorManager::GetSingletonPtr()->BeforeShut();
	NFCActorManager::GetSingletonPtr()->Shut();

    NFCActorManager::GetSingletonPtr()->ReleaseInstance();

    return 0;
}
<|endoftext|>


<commit_before>// -------------------------------------------------------------------------
//    @FileName         :    NFPluginLoader.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :
//    @Module           :    NFPluginLoader
//
// -------------------------------------------------------------------------

//#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <future>
#include <functional>
#include <atomic>
#include "NFCPluginManager.h"
#include "NFComm/Config/NFConfig.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#if NF_PLATFORM == NF_PLATFORM_LINUX
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#endif

bool bExitApp = false;
std::thread gThread;
std::string strArgvList;
std::string strPluginName;
std::string strAppName;
std::string strAppID;
std::string strTitleName;

#if NF_PLATFORM == NF_PLATFORM_WIN

#pragma comment( lib, "DbgHelp" )

void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
    //Dump
    HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    dumpInfo.ExceptionPointers = pException;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;

    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);

    CloseHandle(hDumpFile);
}

long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
    time_t t = time(0);
    char szDmupName[MAX_PATH];
    tm* ptm = localtime(&t);

    sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp",  ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    CreateDumpFile(szDmupName, pException);

    FatalAppExit(-1,  szDmupName);

    return EXCEPTION_EXECUTE_HANDLER;
}
#endif

void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
	HWND hWnd = GetConsoleWindow();
	if (hWnd)
	{
		HMENU hMenu = GetSystemMenu(hWnd, FALSE);
		EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
	}
#endif
}

void ThreadFunc()
{
    while (!bExitApp)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));

        std::string s;
        std::cin >> s;
        if ( 0 == stricmp( s.c_str(), "exit" ) )
        {
            bExitApp = true;
            gThread.detach();
        }
    }
}

void CreateBackThread()
{
    gThread = std::thread(std::bind(&ThreadFunc));
    auto f = std::async (std::launch::deferred, std::bind(ThreadFunc));
    std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}

void InitDaemon()
{
#if NF_PLATFORM == NF_PLATFORM_LINUX
    daemon(1, 0);

    // ignore signals
    signal(SIGINT,  SIG_IGN);
    signal(SIGHUP,  SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGTERM, SIG_IGN);
#endif
}

void PrintfLogo()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif

    std::cout << "\n" << std::endl;
    std::cout << "************************************************" << std::endl;
    std::cout << "**                                            **" << std::endl;
    std::cout << "**                 NoahFrame                  **" << std::endl;
    std::cout << "**   Copyright (c) 2011-2016  LvSheng.Huang   **" << std::endl;
    std::cout << "**             All rights reserved.           **" << std::endl;
    std::cout << "**                                            **" << std::endl;
    std::cout << "************************************************" << std::endl;
    std::cout << "\n" << std::endl;
	std::cout << "-d Run itas daemon mode, only on linux" << std::endl;
	std::cout << "-x Closethe 'X' button, only on windows" << std::endl;
	std::cout << "Instance: name.xml File's name to instead of \"Plugin.xml\" when programs be launched, all platform" << std::endl;
	std::cout << "Instance: \"ID=number\", \"Server=GameServer\"  when programs be launched, all platform" << std::endl;
	std::cout << "\n" << std::endl;

#if NF_PLATFORM == NF_PLATFORM_WIN
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
}

void ProcessParameter(int argc, char* argv[])
{
    for (int i = 0; i < argc; i++)
	{
		strArgvList += " ";
		strArgvList += argv[i];
	}

#if NF_PLATFORM == NF_PLATFORM_WIN
	if (strArgvList.find("-x") != string::npos)
	{
		CloseXButton();
	}
#elif NF_PLATFORM == NF_PLATFORM_LINUX
    //run it as a daemon process
	if (strArgvList.find("-d") != string::npos)
	{
		InitDaemon();
    }

    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
#endif

	if (strArgvList.find(".xml") != string::npos)
	{
		for (int i = 0; i < argc; i++)
		{
			strPluginName = argv[i];
			if (strPluginName.find(".xml") != string::npos)
			{
				break;
			}
		}

		NFCPluginManager::GetSingletonPtr()->SetConfigName(strPluginName);
	}

    if (strArgvList.find("Server=") != string::npos)
	{
		for (int i = 0; i < argc; i++)
		{
			strAppName = argv[i];
			if (strAppName.find("Server=") != string::npos)
			{
                strAppName.erase(0, 7);
				break;
			}
		}

		NFCPluginManager::GetSingletonPtr()->SetAppName(strAppName);
	}

	if (strArgvList.find("ID=") != string::npos)
	{
		for (int i = 0; i < argc; i++)
		{
			strAppID = argv[i];
			if (strAppID.find("ID=") != string::npos)
			{
                strAppID.erase(0, 3);
				break;
			}
		}

		int nAppID = 0;
        if(NF_StrTo(strAppID, nAppID))
        {
            NFCPluginManager::GetSingletonPtr()->SetAppID(nAppID);
        }
	}

	strTitleName = strAppName + "[" + strAppID + "] PID[" + NFGetPID() + "]";
#if NF_PLATFORM == NF_PLATFORM_WIN
	SetConsoleTitle(strTitleName.c_str());
#else
	prctl(PR_SET_NAME, strTitleName.c_str());
	//setproctitle(strTitleName.c_str());
#endif
}

int main(int argc, char* argv[])
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
#elif NF_PLATFORM == NF_PLATFORM_LINUX
#endif

    ProcessParameter(argc, argv);

	NFCPluginManager::GetSingletonPtr()->Init();
	NFCPluginManager::GetSingletonPtr()->AfterInit();
	NFCPluginManager::GetSingletonPtr()->CheckConfig();

	PrintfLogo();
    CreateBackThread();

    while (!bExitApp)
    {
        while (true)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));

            if (bExitApp)
            {
                break;
            }

#if NF_PLATFORM == NF_PLATFORM_WIN
            __try
            {
#endif
				NFCPluginManager::GetSingletonPtr()->Execute();
#if NF_PLATFORM == NF_PLATFORM_WIN
            }
            __except (ApplicationCrashHandler(GetExceptionInformation()))
            {
            }
#endif
        }
    }

	NFCPluginManager::GetSingletonPtr()->BeforeShut();
	NFCPluginManager::GetSingletonPtr()->Shut();

	NFCPluginManager::GetSingletonPtr()->ReleaseInstance();

    return 0;
}
<commit_msg>fixed script for run NF Engine and kill processes<commit_after>// -------------------------------------------------------------------------
//    @FileName         :    NFPluginLoader.cpp
//    @Author           :    LvSheng.Huang
//    @Date             :
//    @Module           :    NFPluginLoader
//
// -------------------------------------------------------------------------

//#include <crtdbg.h>
#include <time.h>
#include <stdio.h>
#include <iostream>
#include <utility>
#include <thread>
#include <chrono>
#include <future>
#include <functional>
#include <atomic>
#include "NFCPluginManager.h"
#include "NFComm/Config/NFConfig.h"
#include "NFComm/NFPluginModule/NFPlatform.h"

#if NF_PLATFORM == NF_PLATFORM_LINUX
#include <unistd.h>
#include <netdb.h>
#include <arpa/inet.h>
#include <signal.h>
#endif

bool bExitApp = false;
std::thread gThread;
std::string strArgvList;
std::string strPluginName;
std::string strAppName;
std::string strAppID;
std::string strTitleName;

#if NF_PLATFORM == NF_PLATFORM_WIN

#pragma comment( lib, "DbgHelp" )

void CreateDumpFile(const std::string& strDumpFilePathName, EXCEPTION_POINTERS* pException)
{
    //Dump
    HANDLE hDumpFile = CreateFile(strDumpFilePathName.c_str(), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

    MINIDUMP_EXCEPTION_INFORMATION dumpInfo;
    dumpInfo.ExceptionPointers = pException;
    dumpInfo.ThreadId = GetCurrentThreadId();
    dumpInfo.ClientPointers = TRUE;

    MiniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hDumpFile, MiniDumpNormal, &dumpInfo, NULL, NULL);

    CloseHandle(hDumpFile);
}

long ApplicationCrashHandler(EXCEPTION_POINTERS* pException)
{
    time_t t = time(0);
    char szDmupName[MAX_PATH];
    tm* ptm = localtime(&t);

    sprintf_s(szDmupName, "%04d_%02d_%02d_%02d_%02d_%02d.dmp",  ptm->tm_year + 1900, ptm->tm_mon + 1, ptm->tm_mday, ptm->tm_hour, ptm->tm_min, ptm->tm_sec);
    CreateDumpFile(szDmupName, pException);

    FatalAppExit(-1,  szDmupName);

    return EXCEPTION_EXECUTE_HANDLER;
}
#endif

void CloseXButton()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
	HWND hWnd = GetConsoleWindow();
	if (hWnd)
	{
		HMENU hMenu = GetSystemMenu(hWnd, FALSE);
		EnableMenuItem(hMenu, SC_CLOSE, MF_DISABLED | MF_BYCOMMAND);
	}
#endif
}

void ThreadFunc()
{
    while (!bExitApp)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));

        std::string s;
        std::cin >> s;
        if ( 0 == stricmp( s.c_str(), "exit" ) )
        {
            bExitApp = true;
            gThread.detach();
        }
    }
}

void CreateBackThread()
{
    gThread = std::thread(std::bind(&ThreadFunc));
    auto f = std::async (std::launch::deferred, std::bind(ThreadFunc));
    std::cout << "CreateBackThread, thread ID = " << gThread.get_id() << std::endl;
}

void InitDaemon()
{
#if NF_PLATFORM == NF_PLATFORM_LINUX
    daemon(1, 0);

    // ignore signals
    signal(SIGINT,  SIG_IGN);
    signal(SIGHUP,  SIG_IGN);
    signal(SIGQUIT, SIG_IGN);
    signal(SIGPIPE, SIG_IGN);
    signal(SIGTTOU, SIG_IGN);
    signal(SIGTTIN, SIG_IGN);
    signal(SIGTERM, SIG_IGN);
#endif
}

void PrintfLogo()
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif

    std::cout << "\n" << std::endl;
    std::cout << "************************************************" << std::endl;
    std::cout << "**                                            **" << std::endl;
    std::cout << "**                 NoahFrame                  **" << std::endl;
    std::cout << "**   Copyright (c) 2011-2016  LvSheng.Huang   **" << std::endl;
    std::cout << "**             All rights reserved.           **" << std::endl;
    std::cout << "**                                            **" << std::endl;
    std::cout << "************************************************" << std::endl;
    std::cout << "\n" << std::endl;
	std::cout << "-d Run itas daemon mode, only on linux" << std::endl;
	std::cout << "-x Closethe 'X' button, only on windows" << std::endl;
	std::cout << "Instance: name.xml File's name to instead of \"Plugin.xml\" when programs be launched, all platform" << std::endl;
	std::cout << "Instance: \"ID=number\", \"Server=GameServer\"  when programs be launched, all platform" << std::endl;
	std::cout << "\n" << std::endl;

#if NF_PLATFORM == NF_PLATFORM_WIN
    SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_INTENSITY | FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
#endif
}

void ProcessParameter(int argc, char* argv[])
{
    for (int i = 0; i < argc; i++)
	{
		strArgvList += " ";
		strArgvList += argv[i];
	}

#if NF_PLATFORM == NF_PLATFORM_WIN
	if (strArgvList.find("-x") != string::npos)
	{
		CloseXButton();
	}
#elif NF_PLATFORM == NF_PLATFORM_LINUX
    //run it as a daemon process
	if (strArgvList.find("-d") != string::npos)
	{
		InitDaemon();
    }

    signal(SIGPIPE, SIG_IGN);
    signal(SIGCHLD, SIG_IGN);
#endif

	if (strArgvList.find(".xml") != string::npos)
	{
		for (int i = 0; i < argc; i++)
		{
			strPluginName = argv[i];
			if (strPluginName.find(".xml") != string::npos)
			{
				break;
			}
		}

		NFCPluginManager::GetSingletonPtr()->SetConfigName(strPluginName);
	}

    if (strArgvList.find("Server=") != string::npos)
	{
		for (int i = 0; i < argc; i++)
		{
			strAppName = argv[i];
			if (strAppName.find("Server=") != string::npos)
			{
                strAppName.erase(0, 7);
				break;
			}
		}

		NFCPluginManager::GetSingletonPtr()->SetAppName(strAppName);
	}

	if (strArgvList.find("ID=") != string::npos)
	{
		for (int i = 0; i < argc; i++)
		{
			strAppID = argv[i];
			if (strAppID.find("ID=") != string::npos)
			{
                strAppID.erase(0, 3);
				break;
			}
		}

		int nAppID = 0;
        if(NF_StrTo(strAppID, nAppID))
        {
            NFCPluginManager::GetSingletonPtr()->SetAppID(nAppID);
        }
	}

	strTitleName = strAppName + strAppID + "PID" + NFGetPID();
	strTitleName.replace(strTitleName.find("Server"), 5, "Svr");
#if NF_PLATFORM == NF_PLATFORM_WIN
	SetConsoleTitle(strTitleName.c_str());
#else
	prctl(PR_SET_NAME, strTitleName.c_str());
	//setproctitle(strTitleName.c_str());
#endif
}

int main(int argc, char* argv[])
{
#if NF_PLATFORM == NF_PLATFORM_WIN
    SetUnhandledExceptionFilter((LPTOP_LEVEL_EXCEPTION_FILTER)ApplicationCrashHandler);
#elif NF_PLATFORM == NF_PLATFORM_LINUX
#endif

    ProcessParameter(argc, argv);

	NFCPluginManager::GetSingletonPtr()->Init();
	NFCPluginManager::GetSingletonPtr()->AfterInit();
	NFCPluginManager::GetSingletonPtr()->CheckConfig();

	PrintfLogo();
    CreateBackThread();

    while (!bExitApp)
    {
        while (true)
        {
            std::this_thread::sleep_for(std::chrono::milliseconds(1));

            if (bExitApp)
            {
                break;
            }

#if NF_PLATFORM == NF_PLATFORM_WIN
            __try
            {
#endif
				NFCPluginManager::GetSingletonPtr()->Execute();
#if NF_PLATFORM == NF_PLATFORM_WIN
            }
            __except (ApplicationCrashHandler(GetExceptionInformation()))
            {
            }
#endif
        }
    }

	NFCPluginManager::GetSingletonPtr()->BeforeShut();
	NFCPluginManager::GetSingletonPtr()->Shut();

	NFCPluginManager::GetSingletonPtr()->ReleaseInstance();

    return 0;
}
<|endoftext|>


<commit_before>#include "Table.h"
#include <cstdarg>
#include <assert.h>

extern "C" {

Table* table_new(const char* name) {
	return new Table(name);
}

void table_delete(Table* t) {
	delete t;
}

size_t table_register_column(Table* t, ColumnType type, const char* name) {
	return t->RegisterColumn(type, name);
}

size_t table_get_column_count(const Table* t) {
	return t->GetColumnCount();
}

const char* table_get_column_name(const Table* t, size_t ndx) {
	return t->GetColumnName(ndx);
}

size_t table_get_column_index(const Table* t, const char* name) {
	return t->GetColumnIndex(name);
}

ColumnType table_get_column_type(const Table* t, size_t ndx) {
	return t->GetColumnType(ndx);
}

bool table_is_empty(const Table* t) {
	return t->IsEmpty();
}

size_t table_get_size(const Table* t) {
	return t->GetSize();
}

void table_clear(Table* t) {
	t->Clear();
}

void table_delete_row(Table* t, size_t ndx) {
	t->DeleteRow(ndx);
}

int table_get_int(const Table* t, size_t column_id, size_t ndx) {
	return t->Get(column_id, ndx);
}

int64_t table_get_int64(const Table* t, size_t column_id, size_t ndx) {
	return t->Get64(column_id, ndx);
}

bool table_get_bool(const Table* t, size_t column_id, size_t ndx) {
	return t->GetBool(column_id, ndx);
}

time_t table_get_date(const Table* t, size_t column_id, size_t ndx) {
	return t->GetDate(column_id, ndx);
}

const char* table_get_string(const Table* t, size_t column_id, size_t ndx) {
	return t->GetString(column_id, ndx);
}

void table_set_int(Table* t, size_t column_id, size_t ndx, int value) {
	t->Set(column_id, ndx, value);
}

void table_set_int64(Table* t, size_t column_id, size_t ndx, int64_t value) {
	t->Set64(column_id, ndx, value);
}

void table_set_bool(Table* t, size_t column_id, size_t ndx, bool value) {
	t->SetBool(column_id, ndx, value);
}

void table_set_date(Table* t, size_t column_id, size_t ndx, time_t value) {
	t->SetDate(column_id, ndx, value);
}

void table_set_string(Table* t, size_t column_id, size_t ndx, const char* value) {
	t->SetString(column_id, ndx, value);
}

void table_insert_impl(Table* t, size_t ndx, va_list ap) {
	assert(ndx <= t->GetSize());

	const size_t count = t->GetColumnCount();
	for (size_t i = 0; i < count; ++i) {
		const ColumnType type = t->GetColumnType(i);
		switch (type) {
		case COLUMN_TYPE_INT:
			{
				// int values should always be cast to 64bit in args
				const int64_t v = va_arg(ap, int64_t);
				t->InsertInt(i, ndx, v);
			}
			break;
		case COLUMN_TYPE_BOOL:
			{
				const bool v = va_arg(ap, bool);
				t->InsertBool(i, ndx, v);
			}
			break;
		case COLUMN_TYPE_DATE:
			{
				const time_t v = va_arg(ap, time_t);
				t->InsertDate(i, ndx, v);
			}
			break;
		case COLUMN_TYPE_STRING:
			{
				const char* v = va_arg(ap, const char*);
				t->InsertString(i, ndx, v);
			}
			break;
		default:
			assert(false);
		}
	}

	t->InsertDone();
}

void table_add(Table* t,  ...) {
	// initialize varable length arg list
	va_list ap;
	va_start(ap, t);

	const size_t ndx = t->GetSize();
	table_insert_impl(t, ndx, ap);

	va_end(ap);
}

void table_insert(Table* t, size_t ndx, ...) {
	// initialize varable length arg list
	va_list ap;
	va_start(ap, ndx);

	table_insert_impl(t, ndx, ap);

	va_end(ap);
}

void table_insert_int(Table* t, size_t column_id, size_t ndx, int value) {
	t->InsertInt(column_id, ndx, value);
}

void table_insert_int64(Table* t, size_t column_id, size_t ndx, int64_t value) {
	t->InsertInt(column_id, ndx, value);
}

void table_insert_bool(Table* t, size_t column_id, size_t ndx, bool value) {
	t->InsertBool(column_id, ndx, value);
}

void table_insert_date(Table* t, size_t column_id, size_t ndx, time_t value) {
	t->InsertDate(column_id, ndx, value);
}

void table_insert_string(Table* t, size_t column_id, size_t ndx, const char* value) {
	t->InsertString(column_id, ndx, value);
}

void table_insert_done(Table* t) {
	t->InsertDone();
}

bool table_has_index(const Table* t, size_t column_id) {
	return t->HasIndex(column_id);
}

void table_set_index(Table* t, size_t column_id) {
	return t->SetIndex(column_id);
}

size_t table_find_int(const Table* t, size_t column_id, int value) {
	return t->Find(column_id, value);
}

size_t table_find_int64(const Table* t, size_t column_id, int64_t value) {
	return t->Find(column_id, value);
}

size_t table_find_bool(const Table* t, size_t column_id, bool value) {
	return t->FindBool(column_id, value);
}

size_t table_find_date(const Table* t, size_t column_id, time_t value) {
	return t->FindDate(column_id, value);
}

size_t table_find_string(const Table* t, size_t column_id, const char* value) {
	return t->FindString(column_id, value);
}

TableView* table_find_all_int64(Table* t, size_t column_id, int64_t value) {
	TableView* tv = new TableView(*t);
	t->FindAll(*tv, column_id, value);
	return tv;
}

TableView* table_find_all_hamming(Table* t, size_t column_id, uint64_t value, size_t max) {
	TableView* tv = new TableView(*t);
	t->FindAllHamming(*tv, column_id, value, max);
	return tv;
}

// *** TableView ************************************

void tableview_delete(TableView* t) {
	delete t;
}

bool tableview_is_empty(const TableView* tv) {
	return tv->IsEmpty();
}

size_t tableview_get_size(const TableView* tv) {
	return tv->GetSize();
}

int tableview_get_int(const TableView* t, size_t column_id, size_t ndx) {
	return t->Get(column_id, ndx);
}

int64_t tableview_get_int64(const TableView* t, size_t column_id, size_t ndx) {
	return t->Get64(column_id, ndx);
}

bool tableview_get_bool(const TableView* t, size_t column_id, size_t ndx) {
	return t->GetBool(column_id, ndx);
}

time_t tableview_get_date(const TableView* t, size_t column_id, size_t ndx) {
	return t->GetDate(column_id, ndx);
}

const char* tableview_get_string(const TableView* t, size_t column_id, size_t ndx) {
	return t->GetString(column_id, ndx);
}

void tableview_set_int(TableView* t, size_t column_id, size_t ndx, int value) {
	t->Set(column_id, ndx, value);
}

void tableview_set_int64(TableView* t, size_t column_id, size_t ndx, int64_t value) {
	t->Set64(column_id, ndx, value);
}

void tableview_set_bool(TableView* t, size_t column_id, size_t ndx, bool value) {
	t->SetBool(column_id, ndx, value);
}

void tableview_set_date(TableView* t, size_t column_id, size_t ndx, time_t value) {
	t->SetDate(column_id, ndx, value);
}

void tableview_set_string(TableView* t, size_t column_id, size_t ndx, const char* value) {
	t->SetString(column_id, ndx, value);
}

} //extern "C"<commit_msg>Removed gcc warning<commit_after>#include "Table.h"
#include <cstdarg>
#include <assert.h>

extern "C" {

Table* table_new(const char* name) {
	return new Table(name);
}

void table_delete(Table* t) {
	delete t;
}

size_t table_register_column(Table* t, ColumnType type, const char* name) {
	return t->RegisterColumn(type, name);
}

size_t table_get_column_count(const Table* t) {
	return t->GetColumnCount();
}

const char* table_get_column_name(const Table* t, size_t ndx) {
	return t->GetColumnName(ndx);
}

size_t table_get_column_index(const Table* t, const char* name) {
	return t->GetColumnIndex(name);
}

ColumnType table_get_column_type(const Table* t, size_t ndx) {
	return t->GetColumnType(ndx);
}

bool table_is_empty(const Table* t) {
	return t->IsEmpty();
}

size_t table_get_size(const Table* t) {
	return t->GetSize();
}

void table_clear(Table* t) {
	t->Clear();
}

void table_delete_row(Table* t, size_t ndx) {
	t->DeleteRow(ndx);
}

int table_get_int(const Table* t, size_t column_id, size_t ndx) {
	return t->Get(column_id, ndx);
}

int64_t table_get_int64(const Table* t, size_t column_id, size_t ndx) {
	return t->Get64(column_id, ndx);
}

bool table_get_bool(const Table* t, size_t column_id, size_t ndx) {
	return t->GetBool(column_id, ndx);
}

time_t table_get_date(const Table* t, size_t column_id, size_t ndx) {
	return t->GetDate(column_id, ndx);
}

const char* table_get_string(const Table* t, size_t column_id, size_t ndx) {
	return t->GetString(column_id, ndx);
}

void table_set_int(Table* t, size_t column_id, size_t ndx, int value) {
	t->Set(column_id, ndx, value);
}

void table_set_int64(Table* t, size_t column_id, size_t ndx, int64_t value) {
	t->Set64(column_id, ndx, value);
}

void table_set_bool(Table* t, size_t column_id, size_t ndx, bool value) {
	t->SetBool(column_id, ndx, value);
}

void table_set_date(Table* t, size_t column_id, size_t ndx, time_t value) {
	t->SetDate(column_id, ndx, value);
}

void table_set_string(Table* t, size_t column_id, size_t ndx, const char* value) {
	t->SetString(column_id, ndx, value);
}

void table_insert_impl(Table* t, size_t ndx, va_list ap) {
	assert(ndx <= t->GetSize());

	const size_t count = t->GetColumnCount();
	for (size_t i = 0; i < count; ++i) {
		const ColumnType type = t->GetColumnType(i);
		switch (type) {
		case COLUMN_TYPE_INT:
			{
				// int values should always be cast to 64bit in args
				const int64_t v = va_arg(ap, int64_t);
				t->InsertInt(i, ndx, v);
			}
			break;
		case COLUMN_TYPE_BOOL:
			{
				const int v = va_arg(ap, int);
				t->InsertBool(i, ndx, v);
			}
			break;
		case COLUMN_TYPE_DATE:
			{
				const time_t v = va_arg(ap, time_t);
				t->InsertDate(i, ndx, v);
			}
			break;
		case COLUMN_TYPE_STRING:
			{
				const char* v = va_arg(ap, const char*);
				t->InsertString(i, ndx, v);
			}
			break;
		default:
			assert(false);
		}
	}

	t->InsertDone();
}

void table_add(Table* t,  ...) {
	// initialize varable length arg list
	va_list ap;
	va_start(ap, t);

	const size_t ndx = t->GetSize();
	table_insert_impl(t, ndx, ap);

	va_end(ap);
}

void table_insert(Table* t, size_t ndx, ...) {
	// initialize varable length arg list
	va_list ap;
	va_start(ap, ndx);

	table_insert_impl(t, ndx, ap);

	va_end(ap);
}

void table_insert_int(Table* t, size_t column_id, size_t ndx, int value) {
	t->InsertInt(column_id, ndx, value);
}

void table_insert_int64(Table* t, size_t column_id, size_t ndx, int64_t value) {
	t->InsertInt(column_id, ndx, value);
}

void table_insert_bool(Table* t, size_t column_id, size_t ndx, bool value) {
	t->InsertBool(column_id, ndx, value);
}

void table_insert_date(Table* t, size_t column_id, size_t ndx, time_t value) {
	t->InsertDate(column_id, ndx, value);
}

void table_insert_string(Table* t, size_t column_id, size_t ndx, const char* value) {
	t->InsertString(column_id, ndx, value);
}

void table_insert_done(Table* t) {
	t->InsertDone();
}

bool table_has_index(const Table* t, size_t column_id) {
	return t->HasIndex(column_id);
}

void table_set_index(Table* t, size_t column_id) {
	return t->SetIndex(column_id);
}

size_t table_find_int(const Table* t, size_t column_id, int value) {
	return t->Find(column_id, value);
}

size_t table_find_int64(const Table* t, size_t column_id, int64_t value) {
	return t->Find(column_id, value);
}

size_t table_find_bool(const Table* t, size_t column_id, bool value) {
	return t->FindBool(column_id, value);
}

size_t table_find_date(const Table* t, size_t column_id, time_t value) {
	return t->FindDate(column_id, value);
}

size_t table_find_string(const Table* t, size_t column_id, const char* value) {
	return t->FindString(column_id, value);
}

TableView* table_find_all_int64(Table* t, size_t column_id, int64_t value) {
	TableView* tv = new TableView(*t);
	t->FindAll(*tv, column_id, value);
	return tv;
}

TableView* table_find_all_hamming(Table* t, size_t column_id, uint64_t value, size_t max) {
	TableView* tv = new TableView(*t);
	t->FindAllHamming(*tv, column_id, value, max);
	return tv;
}

// *** TableView ************************************

void tableview_delete(TableView* t) {
	delete t;
}

bool tableview_is_empty(const TableView* tv) {
	return tv->IsEmpty();
}

size_t tableview_get_size(const TableView* tv) {
	return tv->GetSize();
}

int tableview_get_int(const TableView* t, size_t column_id, size_t ndx) {
	return t->Get(column_id, ndx);
}

int64_t tableview_get_int64(const TableView* t, size_t column_id, size_t ndx) {
	return t->Get64(column_id, ndx);
}

bool tableview_get_bool(const TableView* t, size_t column_id, size_t ndx) {
	return t->GetBool(column_id, ndx);
}

time_t tableview_get_date(const TableView* t, size_t column_id, size_t ndx) {
	return t->GetDate(column_id, ndx);
}

const char* tableview_get_string(const TableView* t, size_t column_id, size_t ndx) {
	return t->GetString(column_id, ndx);
}

void tableview_set_int(TableView* t, size_t column_id, size_t ndx, int value) {
	t->Set(column_id, ndx, value);
}

void tableview_set_int64(TableView* t, size_t column_id, size_t ndx, int64_t value) {
	t->Set64(column_id, ndx, value);
}

void tableview_set_bool(TableView* t, size_t column_id, size_t ndx, bool value) {
	t->SetBool(column_id, ndx, value);
}

void tableview_set_date(TableView* t, size_t column_id, size_t ndx, time_t value) {
	t->SetDate(column_id, ndx, value);
}

void tableview_set_string(TableView* t, size_t column_id, size_t ndx, const char* value) {
	t->SetString(column_id, ndx, value);
}

} //extern "C"
<|endoftext|>


<commit_before>// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

// +build

#define SYZ_EXECUTOR
#include "common_akaros.h"

#include "executor_posix.h"

#include "syscalls_akaros.h"

#include "executor.h"

#include <sys/mman.h>

uint32 output;

static void child();

int main(int argc, char** argv)
{
	if (argc == 2 && strcmp(argv[1], "version") == 0) {
		puts(GOOS " " GOARCH " " SYZ_REVISION " " GIT_REVISION);
		return 0;
	}
	if (argc == 2 && strcmp(argv[1], "child") == 0) {
		child();
		doexit(0);
	}

	use_temporary_dir();
	main_init();
	reply_handshake();

	for (;;) {
		char cwdbuf[128] = "/syz-tmpXXXXXX";
		mkdtemp(cwdbuf);
		int pid = fork();
		if (pid < 0)
			fail("fork failed");
		if (pid == 0) {
			if (chdir(cwdbuf))
				fail("chdir failed");
			execl(argv[0], argv[0], "child", NULL);
			fail("execl failed");
			return 0;
		}
		int status = 0;
		while (waitpid(pid, &status, 0) != pid) {
		}
		status = WEXITSTATUS(status);
		if (status == kFailStatus)
			fail("child failed");
		if (status == kErrorStatus)
			error("child errored");
		remove_dir(cwdbuf);
		reply_execute(0);
	}
	return 0;
}

static void child()
{
	install_segv_handler();
	if (mmap((void*)SYZ_DATA_OFFSET, SYZ_NUM_PAGES * SYZ_PAGE_SIZE, PROT_READ | PROT_WRITE,
		 MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) != (void*)SYZ_DATA_OFFSET)
		fail("mmap of data segment failed");
	receive_execute();
	close(kInPipeFd);
	execute_one();
}

long execute_syscall(const call_t* c, long a0, long a1, long a2, long a3, long a4, long a5, long a6, long a7, long a8)
{
	return syscall(c->sys_nr, a0, a1, a2, a3, a4, a5, a6, a7, a8);
}

void cover_open()
{
}

void cover_enable(thread_t* th)
{
}

void cover_reset(thread_t* th)
{
}

uint32 cover_read_size(thread_t* th)
{
	return 0;
}

bool cover_check(uint32 pc)
{
	return true;
}

bool cover_check(uint64 pc)
{
	return true;
}

uint32* write_output(uint32 v)
{
	return &output;
}

void write_completed(uint32 completed)
{
}

bool kcov_comparison_t::ignore() const
{
	return false;
}
<commit_msg>executor: add timeout for akaros<commit_after>// Copyright 2017 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

// +build

#define SYZ_EXECUTOR
#include "common_akaros.h"

#include "executor_posix.h"

#include "syscalls_akaros.h"

#include "executor.h"

#include <sys/mman.h>

uint32 output;

static void child();

int main(int argc, char** argv)
{
	if (argc == 2 && strcmp(argv[1], "version") == 0) {
		puts(GOOS " " GOARCH " " SYZ_REVISION " " GIT_REVISION);
		return 0;
	}
	if (argc == 2 && strcmp(argv[1], "child") == 0) {
		child();
		doexit(0);
	}

	use_temporary_dir();
	main_init();
	reply_handshake();

	for (;;) {
		char cwdbuf[128] = "/syz-tmpXXXXXX";
		mkdtemp(cwdbuf);
		int pid = fork();
		if (pid < 0)
			fail("fork failed");
		if (pid == 0) {
			if (chdir(cwdbuf))
				fail("chdir failed");
			execl(argv[0], argv[0], "child", NULL);
			fail("execl failed");
			return 0;
		}

		int status = 0;
		uint64 start = current_time_ms();
		for (;;) {
			int res = waitpid(-1, &status, WNOHANG);
			if (res == pid)
				break;
			usleep(1000);
			if (current_time_ms() - start < 6 * 1000)
				continue;
			kill(pid, SIGKILL);
			while (waitpid(-1, &status, 0) != pid) {
			}
			break;
		}
		status = WEXITSTATUS(status);
		if (status == kFailStatus)
			fail("child failed");
		if (status == kErrorStatus)
			error("child errored");
		remove_dir(cwdbuf);
		reply_execute(0);
	}
	return 0;
}

static void child()
{
	install_segv_handler();
	if (mmap((void*)SYZ_DATA_OFFSET, SYZ_NUM_PAGES * SYZ_PAGE_SIZE, PROT_READ | PROT_WRITE,
		 MAP_ANON | MAP_PRIVATE | MAP_FIXED, -1, 0) != (void*)SYZ_DATA_OFFSET)
		fail("mmap of data segment failed");
	receive_execute();
	close(kInPipeFd);
	execute_one();
}

long execute_syscall(const call_t* c, long a0, long a1, long a2, long a3, long a4, long a5, long a6, long a7, long a8)
{
	return syscall(c->sys_nr, a0, a1, a2, a3, a4, a5, a6, a7, a8);
}

void cover_open()
{
}

void cover_enable(thread_t* th)
{
}

void cover_reset(thread_t* th)
{
}

uint32 cover_read_size(thread_t* th)
{
	return 0;
}

bool cover_check(uint32 pc)
{
	return true;
}

bool cover_check(uint64 pc)
{
	return true;
}

uint32* write_output(uint32 v)
{
	return &output;
}

void write_completed(uint32 completed)
{
}

bool kcov_comparison_t::ignore() const
{
	return false;
}
<|endoftext|>


<commit_before>#include "dataitem.h"

Results::Results(){
}

Results::~Results(){
}

void Results::clear(){
    GrowthRate.clear();
    GrowthErr.clear();
    AppcCa.clear();
    AppcCaErr.clear();
}

DataItem::DataItem()
{
}

DataItem::~DataItem()
{
}

bool DataItem::is_valid(){
    if( (DripInt.length() == DripErr.length())
            && (FilmThick.length() == FilmErr.length())
            && (Temp.length() == TempErr.length())
            && (pCO2.length() == pCO2Err.length())
            && (cCa.length() == cCaErr.length()))
        return true;
    else
        return false;
}

int DataItem::lenght(){
    if(is_valid())
        return DateTimes.length();
    else
        return 0;
}

void DataItem::clear(){
    DateTimes.clear();
    DripInt.clear();
    DripErr.clear();
    FilmThick.clear();
    FilmErr.clear();
    Temp.clear();
    TempErr.clear();
    pCO2.clear();
    pCO2Err.clear();
    cCa.clear();
    cCaErr.clear();
}

Avg::Avg(){
    dated =0;
}

void Avg::calc(){
    double sum = 0, xvar = 0;
    for(int i = 0; i < data.size(); i++){
        sum += data.at(i);
    }
    mean = sum/(double) data.size();

    for(int i = 0; i < data.size(); i++){
        xvar += pow((data.at(i)- mean), 2);
    }
    variance = xvar/(data.size()-1);
    sd = pow(variance,2);
}

void Avg::setdate(QDateTime start, QDateTime end){
    time_t mid, stime, etime;

    mid = stime = etime = 0;

    stime = start.toTime_t();
    etime = end.toTime_t();

    mid = (stime + etime) / 2;
    date.fromTime_t(mid);
    dated = mid;
}
<commit_msg>Made dataitem.cpp work on windows<commit_after>#include "dataitem.h"

Results::Results(){
}

Results::~Results(){
}

void Results::clear(){
    GrowthRate.clear();
    GrowthErr.clear();
    AppcCa.clear();
    AppcCaErr.clear();
}

DataItem::DataItem()
{
}

DataItem::~DataItem()
{
}

bool DataItem::is_valid(){
    if( (DripInt.length() == DripErr.length())
            && (FilmThick.length() == FilmErr.length())
            && (Temp.length() == TempErr.length())
            && (pCO2.length() == pCO2Err.length())
            && (cCa.length() == cCaErr.length()))
        return true;
    else
        return false;
}

int DataItem::lenght(){
    if(is_valid())
        return DateTimes.length();
    else
        return 0;
}

void DataItem::clear(){
    DateTimes.clear();
    DripInt.clear();
    DripErr.clear();
    FilmThick.clear();
    FilmErr.clear();
    Temp.clear();
    TempErr.clear();
    pCO2.clear();
    pCO2Err.clear();
    cCa.clear();
    cCaErr.clear();
}

Avg::Avg(){
    dated =0;
}

void Avg::calc(){
    double sum = 0, xvar = 0;
    for(int i = 0; i < data.size(); i++){
        sum += data.at(i);
    }
    mean = sum/(double) data.size();

    for(int i = 0; i < data.size(); i++){
        xvar += pow((data.at(i)- mean), 2);
    }
    variance = xvar/(data.size()-1);
    sd = pow(variance,2);
}

void Avg::setdate(QDateTime start, QDateTime end){
    qint64 temp, stime, etime;
    time_t mid;

    mid = stime = etime = 0;

    stime = (qint64)start.toTime_t();
    etime = (qint64)end.toTime_t();

    // Only way I could get this to work on Windows, what a world...
    temp = (stime + etime);
    mid = (time_t)(temp / 2);
    date.fromTime_t(mid);
    dated = mid;
}
<|endoftext|>


<commit_before>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#if defined __linux__ || defined BSD
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#elif defined WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <iphlpapi.h>
#endif

#include "libtorrent/enum_net.hpp"

namespace libtorrent
{
	namespace
	{
		address sockaddr_to_address(sockaddr const* sin)
		{
			if (sin->sa_family == AF_INET)
			{
				typedef asio::ip::address_v4::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size());
				return address_v4(b);
			}
			else if (sin->sa_family == AF_INET6)
			{
				typedef asio::ip::address_v6::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size());
				return address_v6(b);
			}
			return address();
		}
	}

	bool in_subnet(address const& addr, ip_interface const& iface)
	{
		if (addr.is_v4() != iface.interface_address.is_v4()) return false;
		// since netmasks seems unreliable for IPv6 interfaces
		// (MacOS X returns AF_INET addresses as bitmasks) assume
		// that any IPv6 address belongs to the subnet of any
		// interface with an IPv6 address
		if (addr.is_v6()) return true;

		return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong())
			== (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong());
	}

	bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec)
	{
		std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);
		if (ec) return false;
		for (std::vector<ip_interface>::const_iterator i = net.begin()
			, end(net.end()); i != end; ++i)
		{
			if (in_subnet(addr, *i)) return true;
		}
		return false;
	}

	std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec)
	{
		std::vector<ip_interface> ret;

#if defined __linux__ || defined BSD
		int s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s < 0)
		{
			ec = asio::error::fault;
			return ret;
		}
		ifconf ifc;
		char buf[1024];
		ifc.ifc_len = sizeof(buf);
		ifc.ifc_buf = buf;
		if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
		{
			close(s);
			ec = asio::error_code(errno, asio::error::system_category);
			return ret;
		}

		char *ifr = (char*)ifc.ifc_req;
		int remaining = ifc.ifc_len;

		while (remaining)
		{
			ifreq const& item = *reinterpret_cast<ifreq*>(ifr);

			if (item.ifr_addr.sa_family == AF_INET
				|| item.ifr_addr.sa_family == AF_INET6)
			{
				ip_interface iface;
				iface.interface_address = sockaddr_to_address(&item.ifr_addr);

				ifreq netmask = item;
				if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0)
				{
					close(s);
					ec = asio::error_code(errno, asio::error::system_category);
					return ret;
				}
				iface.netmask = sockaddr_to_address(&netmask.ifr_addr);
				ret.push_back(iface);
			}

#if defined BSD
			int current_size = item.ifr_addr.sa_len + IFNAMSIZ;
#elif defined __linux__
			int current_size = sizeof(ifreq);
#endif
			ifr += current_size;
			remaining -= current_size;
		}
		close(s);

#elif defined WIN32

		SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s == SOCKET_ERROR)
		{
			ec = asio::error::fault;
			return ret;
		}

		INTERFACE_INFO buffer[30];
		DWORD size;

		if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer,
			sizeof(buffer), &size, 0, 0) != 0)
		{
			closesocket(s);
			ec = asio::error::fault;
			return ret;
		}
		closesocket(s);

		int n = size / sizeof(INTERFACE_INFO);

		ip_interface iface;
		for (int i = 0; i < n; ++i)
		{
			iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address);
			iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address);
			if (iface.interface_address == address_v4::any()) continue;
			ret.push_back(iface);
		}

#else
#warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK
		// make a best guess of the interface we're using and its IP
		udp::resolver r(ios);
		udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(), "0"));
		ip_interface iface;
		for (;i != udp::resolver_iterator(); ++i)
		{
			iface.interface_address = i->endpoint().address();
			if (iface.interface_address.is_v4())
				iface.netmask = iface.interface_address.to_v4().netmask();
			ret.push_back(iface);
		}
#endif
		return ret;
	}

	address router_for_interface(address const interface, asio::error_code& ec)
	{
#ifdef WIN32

		// Load Iphlpapi library
		HMODULE iphlp = LoadLibraryA("Iphlpapi.dll");
		if (!iphlp)
		{
			ec = asio::error::fault;
			return address_v4::any();
		}

		// Get GetAdaptersInfo() pointer
		typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG);
		GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo");
		if (!GetAdaptersInfo)
		{
			FreeLibrary(iphlp);
			ec = asio::error::fault;
			return address_v4::any();
		}

		PIP_ADAPTER_INFO adapter_info = 0;
		ULONG out_buf_size = 0;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW)
		{
			FreeLibrary(iphlp);
			ec = asio::error::fault;
			return address_v4::any();
		}

		adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size);
		if (!adapter_info)
		{
			FreeLibrary(iphlp);
			ec = asio::error::fault;
			return address_v4::any();
		}

		address ret;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR)
		{
			PIP_ADAPTER_INFO adapter = adapter_info;
			while (adapter != 0)
			{
				if (interface == address::from_string(adapter->IpAddressList.IpAddress.String, ec))
				{
					ret = address::from_string(adapter->GatewayList.IpAddress.String, ec);
					break;
				}
				adapter = adapter->Next;
			}
		}

		// Free memory
		free(adapter_info);
		FreeLibrary(iphlp);

		return ret;

#else
		// TODO: temporary implementation
		if (!interface.is_v4())
		{
			ec = asio::error::fault;
			return address_v4::any();
		}
		return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1);
#endif
	}

}

<commit_msg>fixes to make enum_net.cpp actually work<commit_after>/*

Copyright (c) 2007, Arvid Norberg
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in
      the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of its
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

*/

#if defined __linux__ || defined BSD
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <net/if.h>
#elif defined WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <windows.h>
#include <iphlpapi.h>
#endif

#include "libtorrent/enum_net.hpp"
#include <asio/ip/host_name.hpp>

namespace libtorrent
{
	namespace
	{
		address sockaddr_to_address(sockaddr const* sin)
		{
			if (sin->sa_family == AF_INET)
			{
				typedef asio::ip::address_v4::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in const*)sin)->sin_addr, b.size());
				return address_v4(b);
			}
			else if (sin->sa_family == AF_INET6)
			{
				typedef asio::ip::address_v6::bytes_type bytes_t;
				bytes_t b;
				memcpy(&b[0], &((sockaddr_in6 const*)sin)->sin6_addr, b.size());
				return address_v6(b);
			}
			return address();
		}
	}

	bool in_subnet(address const& addr, ip_interface const& iface)
	{
		if (addr.is_v4() != iface.interface_address.is_v4()) return false;
		// since netmasks seems unreliable for IPv6 interfaces
		// (MacOS X returns AF_INET addresses as bitmasks) assume
		// that any IPv6 address belongs to the subnet of any
		// interface with an IPv6 address
		if (addr.is_v6()) return true;

		return (addr.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong())
			== (iface.interface_address.to_v4().to_ulong() & iface.netmask.to_v4().to_ulong());
	}

	bool in_local_network(asio::io_service& ios, address const& addr, asio::error_code& ec)
	{
		std::vector<ip_interface> const& net = enum_net_interfaces(ios, ec);
		if (ec) return false;
		for (std::vector<ip_interface>::const_iterator i = net.begin()
			, end(net.end()); i != end; ++i)
		{
			if (in_subnet(addr, *i)) return true;
		}
		return false;
	}

	std::vector<ip_interface> enum_net_interfaces(asio::io_service& ios, asio::error_code& ec)
	{
		std::vector<ip_interface> ret;
// covers linux, MacOS X and BSD distributions
#if defined __linux__ || (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__
		int s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s < 0)
		{
			ec = asio::error::fault;
			return ret;
		}
		ifconf ifc;
		char buf[1024];
		ifc.ifc_len = sizeof(buf);
		ifc.ifc_buf = buf;
		if (ioctl(s, SIOCGIFCONF, &ifc) < 0)
		{
			close(s);
			ec = asio::error_code(errno, asio::error::system_category);
			return ret;
		}

		char *ifr = (char*)ifc.ifc_req;
		int remaining = ifc.ifc_len;

		while (remaining)
		{
			ifreq const& item = *reinterpret_cast<ifreq*>(ifr);

			if (item.ifr_addr.sa_family == AF_INET
				|| item.ifr_addr.sa_family == AF_INET6)
			{
				ip_interface iface;
				iface.interface_address = sockaddr_to_address(&item.ifr_addr);

				ifreq netmask = item;
				if (ioctl(s, SIOCGIFNETMASK, &netmask) < 0)
				{
					if (iface.interface_address.is_v6())
					{
						// this is expected to fail (at least on MacOS X)
						iface.netmask = address_v6::any();
					}
					else
					{
						close(s);
						ec = asio::error_code(errno, asio::error::system_category);
						return ret;
					}
				}
				else
				{
					iface.netmask = sockaddr_to_address(&netmask.ifr_addr);
				}
				ret.push_back(iface);
			}

#if (defined __APPLE__ && __MACH__) || defined __FreeBSD__ || defined __NetBSD__ \
	|| defined __OpenBSD__ || defined __bsdi__ || defined __DragonFly__
			int current_size = item.ifr_addr.sa_len + IFNAMSIZ;
#elif defined __linux__
			int current_size = sizeof(ifreq);
#endif
			ifr += current_size;
			remaining -= current_size;
		}
		close(s);

#elif defined WIN32

		SOCKET s = socket(AF_INET, SOCK_DGRAM, 0);
		if (s == SOCKET_ERROR)
		{
			ec = asio::error_code(WSAGetLastError(), asio::error::system_category);
			return ret;
		}

		INTERFACE_INFO buffer[30];
		DWORD size;

		if (WSAIoctl(s, SIO_GET_INTERFACE_LIST, 0, 0, buffer,
			sizeof(buffer), &size, 0, 0) != 0)
		{
			ec = asio::error_code(WSAGetLastError(), asio::error::system_category);
			closesocket(s);
			return ret;
		}
		closesocket(s);

		int n = size / sizeof(INTERFACE_INFO);

		ip_interface iface;
		for (int i = 0; i < n; ++i)
		{
			iface.interface_address = sockaddr_to_address(&buffer[i].iiAddress.Address);
			iface.netmask = sockaddr_to_address(&buffer[i].iiNetmask.Address);
			if (iface.interface_address == address_v4::any()) continue;
			ret.push_back(iface);
		}

#else
#warning THIS OS IS NOT RECOGNIZED, enum_net_interfaces WILL PROBABLY NOT WORK
		// make a best guess of the interface we're using and its IP
		udp::resolver r(ios);
		udp::resolver::iterator i = r.resolve(udp::resolver::query(asio::ip::host_name(ec), "0"), ec);
		if (ec) return ret;
		ip_interface iface;
		for (;i != udp::resolver_iterator(); ++i)
		{
			iface.interface_address = i->endpoint().address();
			if (iface.interface_address.is_v4())
				iface.netmask = address_v4::netmask(iface.interface_address.to_v4());
			ret.push_back(iface);
		}
#endif
		return ret;
	}

	address router_for_interface(address const interface, asio::error_code& ec)
	{
#ifdef WIN32

		// Load Iphlpapi library
		HMODULE iphlp = LoadLibraryA("Iphlpapi.dll");
		if (!iphlp)
		{
			ec = asio::error::fault;
			return address_v4::any();
		}

		// Get GetAdaptersInfo() pointer
		typedef DWORD (WINAPI *GetAdaptersInfo_t)(PIP_ADAPTER_INFO, PULONG);
		GetAdaptersInfo_t GetAdaptersInfo = (GetAdaptersInfo_t)GetProcAddress(iphlp, "GetAdaptersInfo");
		if (!GetAdaptersInfo)
		{
			FreeLibrary(iphlp);
			ec = asio::error::fault;
			return address_v4::any();
		}

		PIP_ADAPTER_INFO adapter_info = 0;
		ULONG out_buf_size = 0;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) != ERROR_BUFFER_OVERFLOW)
		{
			FreeLibrary(iphlp);
			ec = asio::error::fault;
			return address_v4::any();
		}

		adapter_info = (IP_ADAPTER_INFO*)malloc(out_buf_size);
		if (!adapter_info)
		{
			FreeLibrary(iphlp);
			ec = asio::error::fault;
			return address_v4::any();
		}

		address ret;
		if (GetAdaptersInfo(adapter_info, &out_buf_size) == NO_ERROR)
		{
			PIP_ADAPTER_INFO adapter = adapter_info;
			while (adapter != 0)
			{
				if (interface == address::from_string(adapter->IpAddressList.IpAddress.String, ec))
				{
					ret = address::from_string(adapter->GatewayList.IpAddress.String, ec);
					break;
				}
				adapter = adapter->Next;
			}
		}

		// Free memory
		free(adapter_info);
		FreeLibrary(iphlp);

		return ret;

#else
		// TODO: temporary implementation
		if (!interface.is_v4())
		{
			ec = asio::error::fault;
			return address_v4::any();
		}
		return address_v4((interface.to_v4().to_ulong() & 0xffffff00) | 1);
#endif
	}

}

<|endoftext|>


<commit_before>#include <assert.h>
#include "Box2D/Box2D.h"
#include "ev_box2d.h"

struct ev_world {
};

ev_world* ev_world_create(void)
{
    b2World *world = new b2World(b2Vec2(0,-9.8f));
    return (ev_world*)world;
}

void ev_world_destroy(ev_world *world)
{
    assert( world != NULL );
    delete (b2World*)world;
}

ev_vec2 ev_world_get_gravity(ev_world *world)
{
    b2World *b2_world;
    ev_vec2  gravity = { 0.0f, 0.0f };
    assert( world != NULL );

    if( world ) {
        b2_world = (b2World*)world;
        b2Vec2 b_gravity = b2_world->GetGravity();
        gravity.x = b_gravity.x;
        gravity.y = b_gravity.y;
    }
    return gravity;
}
<commit_msg>actually this is much cleaner<commit_after>#include <assert.h>
#include "Box2D/Box2D.h"
#include "ev_box2d.h"

class ev_contact_listener : public b2ContactListener
{
public:
    virtual void BeginContact(b2Contact *b) {
    }
    virtual void EndContact(b2Contact *b) {
    }
};

struct ev_world {
    ev_world() : world(b2Vec2(0,-9.8)) { }
    ev_contact_listener listener;
    b2World world;
};

ev_world* ev_world_create(void)
{
    ev_world *world;

    world = new (ev_malloc(sizeof(ev_world))) ev_world;

    return (ev_world*)world;
}

void ev_world_destroy(ev_world *world)
{
    assert( world != NULL );
    delete world;
}

ev_vec2 ev_world_get_gravity(ev_world *world)
{
    ev_vec2  gravity = { 0.0f, 0.0f };
    assert( world != NULL );

    if( world ) {
        b2Vec2 b_gravity = world->world.GetGravity();
        gravity.x = b_gravity.x;
        gravity.y = b_gravity.y;
    }
    return gravity;
}
<|endoftext|>


<commit_before>/******************************************************************************

    Unified text output interface; designed for wrapping Bitmap & TrueType
  font objects to co-exist under one roof.

  Copyright (c) 2013 Jeffrey Carpenter
  All rights reserved.

******************************************************************************/
#include "nomlib/gfx/Text.hpp"

namespace nom {

Text::Text ( void )
{
NOM_LOG_CLASSINFO;

  this->font.reset();
  this->file_type = Unknown;
}

Text::~Text ( void )
{
NOM_LOG_CLASSINFO;

  this->font.reset();
}

bool Text::Load ( const std::string& filename, int32 font_size )
{
  OSXFS file;
  std::string extension = "\0";

  extension = file.getFileType ( filename );

  // If we find that the file MIME type is not TTF, we first will try loading
  // the input file as a bitmap font
  if ( extension.compare ( "application/x-font-ttf" ) != 0 )
  {
    this->font = std::shared_ptr<IFont> ( new BitmapFont );
    this->font->Load ( filename, nom::Color ( 110, 144, 190 ), font_size, true );

    if ( this->font != nullptr )
    {
      this->setFontType ( FontType::Bitmap );

      return true;
    }
  }
  else // Try as a TrueType font
  {
    this->font = std::shared_ptr<IFont> ( new TrueTypeFont );

    this->font->Load ( filename, nom::Color::Black, font_size, false );

    if ( this->font != nullptr )
    {
      this->setFontType ( FontType::TrueType );

      return true;
    }
  }

  // If we reach this point, neither a TrueType or a bitmap font was found to be
  // usable
  this->setFontType ( FontType::Unknown );

  return false;
}

FontType Text::getFontType ( void )
{
  return this->file_type;
}

void Text::setFontType ( enum FontType type )
{
  this->file_type = type;
}

const std::string& Text::getText ( void ) const
{
  return this->font->getText();
}

int32 Text::getFontWidth ( void ) const
{
  return this->font->getFontWidth();
}

int32 Text::getFontHeight ( void ) const
{
  return this->font->getFontHeight();
}

FontStyle Text::getFontStyle ( void ) const
{
  return this->font->getFontStyle();
}

const Color Text::getColor ( void ) const
{
  return this->font->getColor();
}

const Coords Text::getPosition ( void ) const
{
  return this->font->getPosition();
}

void Text::setText ( const std::string& text )
{
  this->font->setText ( text );
}

void Text::setColor ( const Color& color )
{
  this->font->setColor ( color );
}

void Text::setPosition ( const Coords& coords )
{
  this->font->setPosition ( coords );
}

void Text::setFontSize ( int32 size )
{
  this->font->setFontSize( size );
}

void Text::setFontStyle ( uint8 style, uint8 options )
{
  this->font->setFontStyle ( style, options );
}

void Text::Update ( void )
{
  if ( this->font )
    this->font->Update();
}

void Text::Draw ( void* video_buffer )
{
  if ( this->font )
    this->font->Draw ( video_buffer );
}

} // namespace nom
<commit_msg>Remove nom:: (un-necessary as we are already in the namespace)<commit_after>/******************************************************************************

    Unified text output interface; designed for wrapping Bitmap & TrueType
  font objects to co-exist under one roof.

  Copyright (c) 2013 Jeffrey Carpenter
  All rights reserved.

******************************************************************************/
#include "nomlib/gfx/Text.hpp"

namespace nom {

Text::Text ( void )
{
NOM_LOG_CLASSINFO;

  this->font.reset();
  this->file_type = Unknown;
}

Text::~Text ( void )
{
NOM_LOG_CLASSINFO;

  this->font.reset();
}

bool Text::Load ( const std::string& filename, int32 font_size )
{
  OSXFS file;
  std::string extension = "\0";

  extension = file.getFileType ( filename );

  // If we find that the file MIME type is not TTF, we first will try loading
  // the input file as a bitmap font
  if ( extension.compare ( "application/x-font-ttf" ) != 0 )
  {
    this->font = std::shared_ptr<IFont> ( new BitmapFont );
    this->font->Load ( filename, Color ( 110, 144, 190 ), font_size, true );

    if ( this->font != nullptr )
    {
      this->setFontType ( FontType::Bitmap );

      return true;
    }
  }
  else // Try as a TrueType font
  {
    this->font = std::shared_ptr<IFont> ( new TrueTypeFont );

    this->font->Load ( filename, Color::Black, font_size, false );

    if ( this->font != nullptr )
    {
      this->setFontType ( FontType::TrueType );

      return true;
    }
  }

  // If we reach this point, neither a TrueType or a bitmap font was found to be
  // usable
  this->setFontType ( FontType::Unknown );

  return false;
}

FontType Text::getFontType ( void )
{
  return this->file_type;
}

void Text::setFontType ( enum FontType type )
{
  this->file_type = type;
}

const std::string& Text::getText ( void ) const
{
  return this->font->getText();
}

int32 Text::getFontWidth ( void ) const
{
  return this->font->getFontWidth();
}

int32 Text::getFontHeight ( void ) const
{
  return this->font->getFontHeight();
}

FontStyle Text::getFontStyle ( void ) const
{
  return this->font->getFontStyle();
}

const Color Text::getColor ( void ) const
{
  return this->font->getColor();
}

const Coords Text::getPosition ( void ) const
{
  return this->font->getPosition();
}

void Text::setText ( const std::string& text )
{
  this->font->setText ( text );
}

void Text::setColor ( const Color& color )
{
  this->font->setColor ( color );
}

void Text::setPosition ( const Coords& coords )
{
  this->font->setPosition ( coords );
}

void Text::setFontSize ( int32 size )
{
  this->font->setFontSize( size );
}

void Text::setFontStyle ( uint8 style, uint8 options )
{
  this->font->setFontStyle ( style, options );
}

void Text::Update ( void )
{
  if ( this->font )
    this->font->Update();
}

void Text::Draw ( void* video_buffer )
{
  if ( this->font )
    this->font->Draw ( video_buffer );
}

} // namespace nom
<|endoftext|>


<commit_before>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: graphics.cpp 17 2005-03-08 23:58:43Z pavlenko $

// mapnik
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/global.hpp>

// cairo
#ifdef HAVE_CAIRO
#include <cairomm/surface.h>
#endif

#include <iostream>

namespace mapnik
{
image_32::image_32(int width,int height)
    :width_(width),
     height_(height),
     data_(width,height) {}

image_32::image_32(const image_32& rhs)
    :width_(rhs.width_),
     height_(rhs.height_),
     data_(rhs.data_)  {}

#ifdef HAVE_CAIRO
image_32::image_32(Cairo::RefPtr<Cairo::ImageSurface> rhs)
    :width_(rhs->get_width()),
     height_(rhs->get_height()),
     data_(rhs->get_width(),rhs->get_height())
{
    if (rhs->get_format() != Cairo::FORMAT_ARGB32)
    {
        std::cerr << "Unable to convert this Cairo format\n";
        return; // throw exception ??
    }

    int stride = rhs->get_stride() / 4;

    unsigned int out_row[width_];
    const unsigned int *in_row = (const unsigned int *)rhs->get_data();

    for (unsigned int row = 0; row < height_; row++, in_row += stride)
    {
        for (unsigned int column = 0; column < width_; column++)
        {
            unsigned int in = in_row[column];
            unsigned int a = (in >> 24) & 0xff;
            unsigned int r = (in >> 16) & 0xff;
            unsigned int g = (in >> 8) & 0xff;
            unsigned int b = (in >> 0) & 0xff;

#define DE_ALPHA(x) do {                        \
                if (a == 0) x = 0;              \
                else x = x * 255 / a;           \
                if (x > 255) x = 255;           \
            } while(0)

            DE_ALPHA(r);
            DE_ALPHA(g);
            DE_ALPHA(b);

            out_row[column] = color(r, g, b, a).rgba();
        }
        data_.setRow(row, out_row, width_);
    }
}
#endif

image_32::~image_32() {}

void image_32::set_grayscale_to_alpha()
{

}

void image_32::set_color_to_alpha(const color& c)
{

}

void image_32::set_alpha(float opacity)
{
{
    for (int y = 0; y < height_; ++y)
    {
        unsigned int* row_to =  data_.getRow(y);
        for (int x = 0; x < width_; ++x)
        {
            unsigned rgba = row_to[x];

#ifdef MAPNIK_BIG_ENDIAN
            unsigned a0 = (rgba & 0xff);
            //unsigned a1 = int( (rgba & 0xff) * opacity );
            unsigned a1 = opacity;

            if (a0 == a1) continue;

            unsigned r = (rgba >> 24) & 0xff;
            unsigned g = (rgba >> 16 ) & 0xff;
            unsigned b = (rgba >> 8) & 0xff;

            row_to[x] = (a1) | (b << 8) |  (g << 16) | (r << 24) ;

#else
            unsigned a0 = (rgba >> 24) & 0xff;
            //unsigned a1 = int( ((rgba >> 24) & 0xff) * opacity );
            unsigned a1 = opacity;
            if (a0 == a1) continue;

            unsigned r = rgba & 0xff;
            unsigned g = (rgba >> 8 ) & 0xff;
            unsigned b = (rgba >> 16) & 0xff;

            row_to[x] = (a1 << 24)| (b << 16) |  (g << 8) | (r) ;
#endif
        }
    }
}

}

void image_32::set_background(const color& background)
{
    background_=background;
    data_.set(background_.rgba());
}

const color& image_32::get_background() const
{
    return background_;
}
}
<commit_msg>add impl for grayscale_to_alpha (e.g. devseed world glass effect) - #609<commit_after>/*****************************************************************************
 *
 * This file is part of Mapnik (c++ mapping toolkit)
 *
 * Copyright (C) 2006 Artem Pavlenko
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *****************************************************************************/
//$Id: graphics.cpp 17 2005-03-08 23:58:43Z pavlenko $

// mapnik
#include <mapnik/graphics.hpp>
#include <mapnik/image_util.hpp>
#include <mapnik/global.hpp>

// cairo
#ifdef HAVE_CAIRO
#include <cairomm/surface.h>
#endif

#include <iostream>

namespace mapnik
{
image_32::image_32(int width,int height)
    :width_(width),
     height_(height),
     data_(width,height) {}

image_32::image_32(const image_32& rhs)
    :width_(rhs.width_),
     height_(rhs.height_),
     data_(rhs.data_)  {}

#ifdef HAVE_CAIRO
image_32::image_32(Cairo::RefPtr<Cairo::ImageSurface> rhs)
    :width_(rhs->get_width()),
     height_(rhs->get_height()),
     data_(rhs->get_width(),rhs->get_height())
{
    if (rhs->get_format() != Cairo::FORMAT_ARGB32)
    {
        std::cerr << "Unable to convert this Cairo format\n";
        return; // throw exception ??
    }

    int stride = rhs->get_stride() / 4;

    unsigned int out_row[width_];
    const unsigned int *in_row = (const unsigned int *)rhs->get_data();

    for (unsigned int row = 0; row < height_; row++, in_row += stride)
    {
        for (unsigned int column = 0; column < width_; column++)
        {
            unsigned int in = in_row[column];
            unsigned int a = (in >> 24) & 0xff;
            unsigned int r = (in >> 16) & 0xff;
            unsigned int g = (in >> 8) & 0xff;
            unsigned int b = (in >> 0) & 0xff;

#define DE_ALPHA(x) do {                        \
                if (a == 0) x = 0;              \
                else x = x * 255 / a;           \
                if (x > 255) x = 255;           \
            } while(0)

            DE_ALPHA(r);
            DE_ALPHA(g);
            DE_ALPHA(b);

            out_row[column] = color(r, g, b, a).rgba();
        }
        data_.setRow(row, out_row, width_);
    }
}
#endif

image_32::~image_32() {}

void image_32::set_grayscale_to_alpha()
{
    for (int y = 0; y < height_; ++y)
    {
        unsigned int* row_from = data_.getRow(y);
        for (int x = 0; x < width_; ++x)
        {
            unsigned rgba = row_from[x];
            unsigned r = rgba & 0xff;
            unsigned g = (rgba >> 8 ) & 0xff;
            unsigned b = (rgba >> 16) & 0xff;

            // magic numbers for grayscale
            unsigned a = (int)((r * .3) + (g * .59) + (b * .11));

            row_from[x] = (a << 24)| (255 << 16) |  (255 << 8) | (255) ;
        }
    }
}

void image_32::set_color_to_alpha(const color& c)
{

}

void image_32::set_alpha(float opacity)
{
{
    for (int y = 0; y < height_; ++y)
    {
        unsigned int* row_to =  data_.getRow(y);
        for (int x = 0; x < width_; ++x)
        {
            unsigned rgba = row_to[x];

#ifdef MAPNIK_BIG_ENDIAN
            unsigned a0 = (rgba & 0xff);
            unsigned a1 = int( (rgba & 0xff) * opacity );

            if (a0 == a1) continue;

            unsigned r = (rgba >> 24) & 0xff;
            unsigned g = (rgba >> 16 ) & 0xff;
            unsigned b = (rgba >> 8) & 0xff;

            row_to[x] = (a1) | (b << 8) |  (g << 16) | (r << 24) ;

#else
            unsigned a0 = (rgba >> 24) & 0xff;
            unsigned a1 = int( ((rgba >> 24) & 0xff) * opacity );
            //unsigned a1 = opacity;
            if (a0 == a1) continue;

            unsigned r = rgba & 0xff;
            unsigned g = (rgba >> 8 ) & 0xff;
            unsigned b = (rgba >> 16) & 0xff;

            row_to[x] = (a1 << 24)| (b << 16) |  (g << 8) | (r) ;
#endif
        }
    }
}

}

void image_32::set_background(const color& background)
{
    background_=background;
    data_.set(background_.rgba());
}

const color& image_32::get_background() const
{
    return background_;
}
}
<|endoftext|>


<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QDir>
#include <QGraphicsLinearLayout>
#include <QGraphicsGridLayout>

#include <DuiContentItem>
#include <DuiImageWidget>
#include <DuiAbstractCellCreator>
#include <DuiLabel>

#include "utils.h"
#include "duigridpage.h"
#include "gridmodel.h"

class ContentItemCreator : public DuiAbstractCellCreator<DuiImageWidget>
{
public:
    void updateCell(const QModelIndex &index, DuiWidget *cell) const;
    QSizeF cellSize() const;
};

void ContentItemCreator::updateCell(const QModelIndex &index, DuiWidget *cell) const
{
    if(!cell)
        return;

    DuiImageWidget *imageWidget = qobject_cast<DuiImageWidget*>(cell);

    DuiImageWidget *badge = new DuiImageWidget(imageWidget);
    badge->setObjectName("badge");
    badge->setPixmap( QPixmap( QDir(IMAGES_DIR).canonicalPath() + QDir::separator() + "star.png") );

    QVariant data = index.data(Qt::DecorationRole);
    QPixmap pixmap = data.value<QPixmap>();

    imageWidget->setPixmap(pixmap);
}

QSizeF ContentItemCreator::cellSize() const
{
    return QSizeF(260, 260);
}

DuiGridPage::DuiGridPage()
{
    setPannableAreaInteractive(true);
    gid = TemplatePage::ListsGridsAndMenus;
}

DuiGridPage::~DuiGridPage()
{
}

void DuiGridPage::createContent()
{
    DuiApplicationPage::createContent();

    DuiTheme::addPixmapDirectory(QDir(MEDIA_ART_DIR).canonicalPath());
    DuiWidget * panel = centralWidget();
    QGraphicsLinearLayout * layout = new QGraphicsLinearLayout(Qt::Vertical);
    panel->setLayout(layout);

    list = new DuiList(panel);
    list->setColumns(3);
    list->setObjectName("wgGrid");
    layout->addItem(list);

    ContentItemCreator * cellCreator = new ContentItemCreator();
    list->setCellCreator(cellCreator);

    GridModel * model = new GridModel(QSize(250, 250), Utils::mediaArtDir());
    list->setItemModel(model);
}

void DuiGridPage::retranslateUi()
{
    setTitle(qtTrId("xx_gridpage_title"));
}

QString DuiGridPage::timedemoTitle()
{
    return "Grid";
}
<commit_msg>Changes: add engineering English comment to duigridpage.cpp<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (directui@nokia.com)
**
** This file is part of libdui.
**
** If you have questions regarding the use of this file, please contact
** Nokia at directui@nokia.com.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/

#include <QDir>
#include <QGraphicsLinearLayout>
#include <QGraphicsGridLayout>

#include <DuiContentItem>
#include <DuiImageWidget>
#include <DuiAbstractCellCreator>
#include <DuiLabel>

#include "utils.h"
#include "duigridpage.h"
#include "gridmodel.h"

class ContentItemCreator : public DuiAbstractCellCreator<DuiImageWidget>
{
public:
    void updateCell(const QModelIndex &index, DuiWidget *cell) const;
    QSizeF cellSize() const;
};

void ContentItemCreator::updateCell(const QModelIndex &index, DuiWidget *cell) const
{
    if(!cell)
        return;

    DuiImageWidget *imageWidget = qobject_cast<DuiImageWidget*>(cell);

    DuiImageWidget *badge = new DuiImageWidget(imageWidget);
    badge->setObjectName("badge");
    badge->setPixmap( QPixmap( QDir(IMAGES_DIR).canonicalPath() + QDir::separator() + "star.png") );

    QVariant data = index.data(Qt::DecorationRole);
    QPixmap pixmap = data.value<QPixmap>();

    imageWidget->setPixmap(pixmap);
}

QSizeF ContentItemCreator::cellSize() const
{
    return QSizeF(260, 260);
}

DuiGridPage::DuiGridPage()
{
    setPannableAreaInteractive(true);
    gid = TemplatePage::ListsGridsAndMenus;
}

DuiGridPage::~DuiGridPage()
{
}

void DuiGridPage::createContent()
{
    DuiApplicationPage::createContent();

    DuiTheme::addPixmapDirectory(QDir(MEDIA_ART_DIR).canonicalPath());
    DuiWidget * panel = centralWidget();
    QGraphicsLinearLayout * layout = new QGraphicsLinearLayout(Qt::Vertical);
    panel->setLayout(layout);

    list = new DuiList(panel);
    list->setColumns(3);
    list->setObjectName("wgGrid");
    layout->addItem(list);

    ContentItemCreator * cellCreator = new ContentItemCreator();
    list->setCellCreator(cellCreator);

    GridModel * model = new GridModel(QSize(250, 250), Utils::mediaArtDir());
    list->setItemModel(model);
    retranslateUi();
}

void DuiGridPage::retranslateUi()
{
    //% "Grid page"
    setTitle(qtTrId("xx_gridpage_title"));
    if (!isContentCreated())
        return;
}

QString DuiGridPage::timedemoTitle()
{
    return "Grid";
}
<|endoftext|>


<commit_before>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <ReadData.hpp>

namespace AstroData {

RingBufferError::RingBufferError() {}

RingBufferError::~RingBufferErrror() throw () {}

const char * RingBufferError::what() const throw() {
    return ("Impossible to read from the PSRDada ring buffer.").c_str();
}

} // AstroData

<commit_msg>Fixing a typo.<commit_after>// Copyright 2015 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include <ReadData.hpp>

namespace AstroData {

RingBufferError::RingBufferError() {}

RingBufferError::~RingBufferError() throw () {}

const char * RingBufferError::what() const throw() {
    return ("Impossible to read from the PSRDada ring buffer.").c_str();
}

} // AstroData

<|endoftext|>


<commit_before>/*
 * LibusbDevice.cpp
 *
 * Copyright (C) ST-Ericsson SA 2011
 * Authors: Srimanta Panda <srimanta.panda@stericsson.com>,
 *          Ola Borgelin <ola.borgelin@stericsson.com>,
 *          Karin Hedlund <karin.hedlund@stericsson.com>,
 *          Markus Andersson <markus.m.andersson@stericsson.com> for ST-Ericsson.
 * License terms: 3-clause BSD license
 *
 */

#include "stdafx.h"
#include "LibusbDevice.h"
#include "Debug.h"
#include "CommException.h"
#include <libusb.h>

using namespace std;

#define MIN(A, B) ((A) < (B) ? (A) : (B))

LibusbDevice::LibusbDevice(libusb_device* device): device_(device)
{
    int status = libusb_open(device_, &handle_);

    if (status != LIBUSB_SUCCESS) {
        throw CommException("failed to open usb device", COMM_DEVICE_LIBUSB_FAILED_TO_OPEN_PORT);
    }

    status = libusb_claim_interface(handle_, 0);

    if (status != LIBUSB_SUCCESS) {
        libusb_close(handle_);
        throw CommException("failed to claim device interface", COMM_DEVICE_LIBUSB_FAILED_TO_CLAIM_INTERFACE);
    }

    libusb_config_descriptor* config;
    libusb_get_active_config_descriptor(device, &config);
    Debug::info("LibusbDevice: found %d endpoints", config->interface->altsetting->bNumEndpoints);

    for (int i = 0; i != config->interface->altsetting->bNumEndpoints; ++i) {
        if (config->interface->altsetting->endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_IN) {
            inEndpoint_ = config->interface->altsetting->endpoint[i].bEndpointAddress;
            Debug::info("LibusbDevice: in endpoint set to 0x%02x", inEndpoint_);
        } else {
            outEndpoint_ = config->interface->altsetting->endpoint[i].bEndpointAddress;
            Debug::info("LibusbDevice: out endpoint set to 0x%02x", outEndpoint_);
        }
    }

    libusb_free_config_descriptor(config);

    libusb_get_device_descriptor(device, &descriptor_);

    readBufferLength_ = 0;
    readBufferHead_ = readBuffer_;
}

LibusbDevice::~LibusbDevice()
{
    libusb_release_interface(handle_, 0);
    libusb_close(handle_);
}

int LibusbDevice::read(void *buffer, size_t size)
{
    Debug::info("LibusbDevice read: called with size %d", size);
    unsigned char* dest = static_cast<unsigned char*>(buffer);

    while (true) {
        if (readBufferLength_) {
            size_t toCopy = MIN(readBufferLength_, size);
            memcpy(dest, readBufferHead_, toCopy);
            dest += toCopy;
            size -= toCopy;
            readBufferLength_ -= toCopy;

            if (readBufferLength_ != 0) {
                readBufferHead_ += toCopy;
            } else {
                readBufferHead_ = readBuffer_;
            }
        }

        if (size == 0) {
            break;
        }

        int transfered;
        int error = libusb_bulk_transfer(handle_, inEndpoint_, readBuffer_, READ_BUFFER_SIZE, &transfered, 100000);

        if (isReadCanceled_) {
            Debug::info("LibusbDevice read: canceled...");
            Debug::hexdump("read canceled", dest, transfered);
            isReadCanceled_ = false;
            return COMM_DEVICE_CANCEL;
        }

        if (error) {
            if (error == LIBUSB_ERROR_TIMEOUT) {
                continue;
            } else {
                Debug::info("LibusbDevice read: error %d occured", error);
                return error;
            }
        }

        readBufferLength_ = transfered;
    }

    Debug::info("LibusbDevice read: complete");
    return 0;
}

int LibusbDevice::write(void *buffer, size_t size)
{
    Debug::info("LibusbDevice write: called with size %d", size);
    unsigned char* src = static_cast<unsigned char*>(buffer);

    while (size) {
        int transfered;
        //Call with timeout to enable possible cancel
        int error = libusb_bulk_transfer(handle_, outEndpoint_, src, size, &transfered, 0);

        if (error) {
            if (error == LIBUSB_ERROR_TIMEOUT) {
                continue;
            } else {
                return error;
            }
        }

        size -= transfered;
        src += transfered;
    }

    Debug::info("LibusbDevice write: complete");
    return 0;
}

int LibusbDevice::getVendorId()
{
    return descriptor_.idVendor;
}

libusb_device* LibusbDevice::getPort()
{
    return device_;
}
<commit_msg>Split large writes into 16k chunks.<commit_after>/*
 * LibusbDevice.cpp
 *
 * Copyright (C) ST-Ericsson SA 2011
 * Authors: Srimanta Panda <srimanta.panda@stericsson.com>,
 *          Ola Borgelin <ola.borgelin@stericsson.com>,
 *          Karin Hedlund <karin.hedlund@stericsson.com>,
 *          Markus Andersson <markus.m.andersson@stericsson.com> for ST-Ericsson.
 * License terms: 3-clause BSD license
 *
 */

#include "stdafx.h"
#include "LibusbDevice.h"
#include "Debug.h"
#include "CommException.h"
#include <libusb.h>

using namespace std;

#define MIN(A, B) ((A) < (B) ? (A) : (B))

#define CHUNKSIZE 16384 //16 kB

LibusbDevice::LibusbDevice(libusb_device* device): device_(device)
{
    int status = libusb_open(device_, &handle_);

    if (status != LIBUSB_SUCCESS) {
        throw CommException("failed to open usb device", COMM_DEVICE_LIBUSB_FAILED_TO_OPEN_PORT);
    }

    status = libusb_claim_interface(handle_, 0);

    if (status != LIBUSB_SUCCESS) {
        libusb_close(handle_);
        throw CommException("failed to claim device interface", COMM_DEVICE_LIBUSB_FAILED_TO_CLAIM_INTERFACE);
    }

    libusb_config_descriptor* config;
    libusb_get_active_config_descriptor(device, &config);
    Debug::info("LibusbDevice: found %d endpoints", config->interface->altsetting->bNumEndpoints);

    for (int i = 0; i != config->interface->altsetting->bNumEndpoints; ++i) {
        if (config->interface->altsetting->endpoint[i].bEndpointAddress & LIBUSB_ENDPOINT_IN) {
            inEndpoint_ = config->interface->altsetting->endpoint[i].bEndpointAddress;
            Debug::info("LibusbDevice: in endpoint set to 0x%02x", inEndpoint_);
        } else {
            outEndpoint_ = config->interface->altsetting->endpoint[i].bEndpointAddress;
            Debug::info("LibusbDevice: out endpoint set to 0x%02x", outEndpoint_);
        }
    }

    libusb_free_config_descriptor(config);

    libusb_get_device_descriptor(device, &descriptor_);

    readBufferLength_ = 0;
    readBufferHead_ = readBuffer_;
}

LibusbDevice::~LibusbDevice()
{
    libusb_release_interface(handle_, 0);
    libusb_close(handle_);
}

int LibusbDevice::read(void *buffer, size_t size)
{
    Debug::info("LibusbDevice read: called with size %d", size);
    unsigned char* dest = static_cast<unsigned char*>(buffer);

    while (true) {
        if (readBufferLength_) {
            size_t toCopy = MIN(readBufferLength_, size);
            memcpy(dest, readBufferHead_, toCopy);
            dest += toCopy;
            size -= toCopy;
            readBufferLength_ -= toCopy;

            if (readBufferLength_ != 0) {
                readBufferHead_ += toCopy;
            } else {
                readBufferHead_ = readBuffer_;
            }
        }

        if (size == 0) {
            break;
        }

        int transfered;
        int error = libusb_bulk_transfer(handle_, inEndpoint_, readBuffer_, READ_BUFFER_SIZE, &transfered, 100000);

        if (isReadCanceled_) {
            Debug::info("LibusbDevice read: canceled...");
            Debug::hexdump("read canceled", dest, transfered);
            isReadCanceled_ = false;
            return COMM_DEVICE_CANCEL;
        }

        if (error) {
            if (error == LIBUSB_ERROR_TIMEOUT) {
                continue;
            } else {
                Debug::info("LibusbDevice read: error %d occured", error);
                return error;
            }
        }

        readBufferLength_ = transfered;
    }

    Debug::info("LibusbDevice read: complete");
    return 0;
}

int LibusbDevice::write(void *buffer, size_t size)
{
    Debug::info("LibusbDevice write: called with size %d", size);
    unsigned char* src = static_cast<unsigned char*>(buffer);

    while (size) {
        int transfered;
        int chunkSize = size > CHUNKSIZE ? CHUNKSIZE : size;

        //Call with timeout to enable possible cancel
        int error = libusb_bulk_transfer(handle_, outEndpoint_, src, chunkSize, &transfered, 0);

        if (error) {
            if (error == LIBUSB_ERROR_TIMEOUT) {
                continue;
            } else {
                return error;
            }
        }

        size -= transfered;
        src += transfered;
    }

    Debug::info("LibusbDevice write: complete");
    return 0;
}

int LibusbDevice::getVendorId()
{
    return descriptor_.idVendor;
}

libusb_device* LibusbDevice::getPort()
{
    return device_;
}
<|endoftext|>