Esempio n. 1
0
int CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
	WNDCLASS wc = {};
	wc.style = CS_HREDRAW | CS_VREDRAW;
	wc.lpfnWndProc = wndProc;
	wc.hInstance = hInstance;
	wc.hCursor = LoadCursor(NULL, IDC_ARROW);
	wc.lpszClassName = L"GameOfLifeWindowClass";

	if (!RegisterClass(&wc)) {
		MessageBox(NULL, L"RegisterClass failed!", NULL, NULL);
		return 1;
	}

	int windowWidth = globalWindowWidth = DEFAULT_WINDOW_WIDTH;
	int windowHeight = globalWindowHeight = DEFAULT_WINDOW_HEIGHT;

	RECT clientRect = { 0, 0, windowWidth, windowHeight };
	DWORD windowStyle = WS_OVERLAPPEDWINDOW | WS_VISIBLE;
	AdjustWindowRect(&clientRect, windowStyle, NULL);
	HWND hWnd = CreateWindowEx(NULL, wc.lpszClassName, L"Game of Life", windowStyle, 300, 0,
		clientRect.right - clientRect.left, clientRect.bottom - clientRect.top, NULL, NULL,	hInstance, NULL);

	if (!hWnd) {
		MessageBox(NULL, L"CreateWindowEx failed!", NULL, NULL);
		return 1;
	}

	ShowWindow(hWnd, nCmdShow);
	UpdateWindow(hWnd);

	LARGE_INTEGER perfCounterFrequency = { 0 };
	QueryPerformanceFrequency(&perfCounterFrequency);
	LARGE_INTEGER perfCounter = { 0 };
	QueryPerformanceCounter(&perfCounter);
	LARGE_INTEGER prevPerfCounter = { 0 };
	
	float dt = 0.0f;
	float realDt = dt;
	const float targetFps = 60.0f;
	const float targetDt = 1.0f / targetFps;
	
	srand((unsigned int)time(NULL));

	GameState *gameState = (GameState *)malloc(sizeof(GameState));
	memset(gameState, 0, sizeof(GameState));
	initGame(gameState, windowWidth, windowHeight);

	bool gameIsRunning = true;

	while (gameIsRunning) {
		prevPerfCounter = perfCounter;
		QueryPerformanceCounter(&perfCounter);
		dt = (float)(perfCounter.QuadPart - prevPerfCounter.QuadPart) / (float)perfCounterFrequency.QuadPart;
		realDt = dt;
		if (dt > targetDt)
			dt = targetDt;

		MSG msg;
		while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
			switch (msg.message) {
			case WM_QUIT:
				gameIsRunning = false;
				break;
			case WM_KEYDOWN:
			case WM_KEYUP:
				switch (msg.wParam) {
				case VK_ESCAPE:
					gameIsRunning = false;
					break;
				}
				break;
			default:
				TranslateMessage(&msg);
				DispatchMessage(&msg);
				break;
			}
		}

		//
		// UPDATE
		//

		// When the window is resized, reinitialize the game with the new window size.
		if (globalWindowWidth != windowWidth || globalWindowHeight != windowHeight) {
			windowWidth = globalWindowWidth;
			windowHeight = globalWindowHeight;
			initGame(gameState, globalWindowWidth, globalWindowHeight);
		}

		// Handle the left mouse button: make the clicked cell alive.
		if (GetKeyState(VK_LBUTTON) & (1 << 15)) {
			POINT mousePos;
			GetCursorPos(&mousePos);
			ScreenToClient(hWnd, &mousePos);

			int row = mousePos.y / CELL_HEIGHT_PX;
			int col = mousePos.x / CELL_WIDTH_PX;

			if (row < gameState->cellRows && col < gameState->cellCols) {
				bool *cell = gameState->cells + row*gameState->cellCols + col;
				*cell = true;
			}
		}

		gameState->tickTimer += dt;
		if (gameState->tickTimer > TICK_DURATION) {
			gameState->tickTimer = 0;

			for (int row = 0; row < gameState->cellRows; ++row) {
				for (int col = 0; col < gameState->cellCols; ++col) {
					bool *cell = gameState->cells + row*gameState->cellCols + col;
					bool *newCell = gameState->newCells + row*gameState->cellCols + col;
					*newCell = *cell;
					int liveNeighbours = getLiveNeighbourCount(gameState, row, col);
					if (*cell) {
						if (liveNeighbours < 2 || liveNeighbours > 3)
							*newCell = false;
					}
					else {
						if (liveNeighbours == 3)
							*newCell = true;
					}
				}
			}

			bool *tmp = gameState->cells;
			gameState->cells = gameState->newCells;
			gameState->newCells = tmp;
		}

		//
		// RENDER
		//

		for (int row = 0; row < gameState->cellRows; ++row) {
			for (int col = 0; col < gameState->cellCols; ++col) {
				bool *cell = gameState->cells + row*gameState->cellCols + col;
				int color = *cell ? CELL_COLOR_ALIVE : CELL_COLOR_DEAD;
				for (int r = 0; r < CELL_HEIGHT_PX; ++r) {
					for (int c = 0; c < CELL_WIDTH_PX; ++c) {
						int *pixel = gameState->bitmapBuffer + (row*CELL_HEIGHT_PX + r)*gameState->cellCols*CELL_WIDTH_PX + col*CELL_WIDTH_PX + c;
						*pixel = color;
					}
				}
			}
		}

		HDC hDC = GetDC(hWnd);
		StretchDIBits(hDC, 0, 0, gameState->bitmapWidth, gameState->bitmapHeight,
			0, 0, gameState->bitmapWidth, gameState->bitmapHeight,
			gameState->bitmapBuffer, gameState->bitmapInfo, DIB_RGB_COLORS, SRCCOPY);
		ReleaseDC(hWnd, hDC);

#if 0
		char textBuffer[256];
		sprintf(textBuffer, "dt: %f, fps: %f\n", realDt, 1.0f/realDt);
		OutputDebugStringA(textBuffer);
#endif
	}

	return 0;
}
Esempio n. 2
0
static void exiting(void)
{
    OutputDebugStringA("winfsp-tests: exiting\n");

    RemoveNetShareIfNeeded();
}
Esempio n. 3
0
inline int OutputDebugStringF(const char* pszFormat, ...)
{
    int ret = 0;
    if (fPrintToConsole)
    {
        // print to console
        va_list arg_ptr;
        va_start(arg_ptr, pszFormat);
        ret = vprintf(pszFormat, arg_ptr);
        va_end(arg_ptr);
    }
    else
    {
        // print to debug.log
        static FILE* fileout = NULL;

        if (!fileout)
        {
            char pszFile[MAX_PATH+100];
            GetDataDir(pszFile);
            strlcat(pszFile, "/debug.log", sizeof(pszFile));
            fileout = fopen(pszFile, "a");
            if (fileout) setbuf(fileout, NULL); // unbuffered
        }
        if (fileout)
        {
            static bool fStartedNewLine = true;

            // Debug print useful for profiling
            if (fLogTimestamps && fStartedNewLine)
                fprintf(fileout, "%s ", DateTimeStrFormat("%x %H:%M:%S", GetTime()).c_str());
            if (pszFormat[strlen(pszFormat) - 1] == '\n')
                fStartedNewLine = true;
            else
                fStartedNewLine = false;

            va_list arg_ptr;
            va_start(arg_ptr, pszFormat);
            ret = vfprintf(fileout, pszFormat, arg_ptr);
            va_end(arg_ptr);
        }
    }

#ifdef __WXMSW__
    if (fPrintToDebugger)
    {
        static CCriticalSection cs_OutputDebugStringF;

        // accumulate a line at a time
        CRITICAL_BLOCK(cs_OutputDebugStringF)
        {
            static char pszBuffer[50000];
            static char* pend;
            if (pend == NULL)
                pend = pszBuffer;
            va_list arg_ptr;
            va_start(arg_ptr, pszFormat);
            int limit = END(pszBuffer) - pend - 2;
            int ret = _vsnprintf(pend, limit, pszFormat, arg_ptr);
            va_end(arg_ptr);
            if (ret < 0 || ret >= limit)
            {
                pend = END(pszBuffer) - 2;
                *pend++ = '\n';
            }
            else
                pend += ret;
            *pend = '\0';
            char* p1 = pszBuffer;
            char* p2;
            while (p2 = strchr(p1, '\n'))
            {
                p2++;
                char c = *p2;
                *p2 = '\0';
                OutputDebugStringA(p1);
                *p2 = c;
                p1 = p2;
            }
            if (p1 != pszBuffer)
                memmove(pszBuffer, p1, pend - p1 + 1);
            pend -= (p1 - pszBuffer);
        }
    }
#endif
    return ret;
}
Esempio n. 4
0
static void vprintf_stderr_common(const char* format, va_list args)
{
#if USE(CF) && !OS(WINDOWS)
    if (strstr(format, "%@")) {
        CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8);

#if COMPILER(CLANG)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wformat-nonliteral"
#endif
        CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args);
#if COMPILER(CLANG)
#pragma clang diagnostic pop
#endif
        CFIndex length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8);
        char* buffer = (char*)malloc(length + 1);

        CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8);

#if USE(APPLE_SYSTEM_LOG)
        asl_log(0, 0, ASL_LEVEL_NOTICE, "%s", buffer);
#endif
        fputs(buffer, stderr);

        free(buffer);
        CFRelease(str);
        CFRelease(cfFormat);
        return;
    }

#if USE(APPLE_SYSTEM_LOG)
    va_list copyOfArgs;
    va_copy(copyOfArgs, args);
    asl_vlog(0, 0, ASL_LEVEL_NOTICE, format, copyOfArgs);
    va_end(copyOfArgs);
#endif

    // Fall through to write to stderr in the same manner as other platforms.

#elif HAVE(ISDEBUGGERPRESENT)
    if (IsDebuggerPresent()) {
        size_t size = 1024;

        do {
            char* buffer = (char*)malloc(size);

            if (buffer == NULL)
                break;

            if (vsnprintf(buffer, size, format, args) != -1) {
                OutputDebugStringA(buffer);
                free(buffer);
                break;
            }

            free(buffer);
            size *= 2;
        } while (size > 1024);
    }
#endif
    vfprintf(stderr, format, args);
}
Esempio n. 5
0
    bool EventCallback::OnException( IProcess* process, DWORD threadId, bool firstChance, const EXCEPTION_RECORD* exceptRec )
    {
        const DWORD DefaultState = EXCEPTION_STOP_SECOND_CHANCE;

        OutputDebugStringA( "EventCallback::OnException\n" );

        HRESULT     hr = S_OK;
        RefPtr<ExceptionEvent>      event;
        RefPtr<Program>             prog;
        RefPtr<Thread>              thread;

        if ( !mEngine->FindProgram( process->GetId(), prog ) )
            return false;

        if ( !prog->FindThread( threadId, thread ) )
            return false;

        prog->NotifyException( firstChance, exceptRec );

        hr = MakeCComObject( event );
        if ( FAILED( hr ) )
            return false;

        event->Init( prog.Get(), firstChance, exceptRec, prog->CanPassExceptionToDebuggee() );

        DWORD state = DefaultState;
        ExceptionInfo info;
        bool found = false;

        if ( event->GetSearchKey() == ExceptionEvent::Name )
        {
            found = mEngine->FindExceptionInfo( event->GetGUID(), event->GetExceptionName(), info );
        }
        else // search by code
        {
            found = mEngine->FindExceptionInfo( event->GetGUID(), event->GetCode(), info );
        }

        // if not found, then check against the catch-all entry
        if ( !found )
            found = mEngine->FindExceptionInfo( event->GetGUID(), event->GetRootExceptionName(), info );

        if ( found )
        {
            if ( event->GetSearchKey() == ExceptionEvent::Code )
                event->SetExceptionName( info.bstrExceptionName );
            state = info.dwState;
        }

        if ( (  firstChance && ( state & EXCEPTION_STOP_FIRST_CHANCE ) ) ||
             ( !firstChance && ( state & EXCEPTION_STOP_SECOND_CHANCE ) ) )
        {
            hr = SendEvent( event.Get(), prog.Get(), thread.Get() );
            return false;
        }
        else
        {
            RefPtr<MessageTextEvent>    msgEvent;
            CComBSTR                    desc;

            hr = MakeCComObject( msgEvent );
            if ( FAILED( hr ) )
                return true;

            hr = event->GetExceptionDescription( &desc );
            if ( FAILED( hr ) )
                return true;

            desc.Append( L"\n" );

            msgEvent->Init( MT_REASON_EXCEPTION, desc );

            hr = SendEvent( msgEvent.Get(), prog.Get(), thread.Get() );
            return true; // wants to continue
        }
    }
Esempio n. 6
0
/*******************************************************************
Dutil_Trace

*******************************************************************/
extern "C" void DAPI Dutil_Trace(
    __in_z LPCSTR szFile, 
    __in int iLine, 
    __in REPORT_LEVEL rl, 
    __in_z __format_string LPCSTR szFormat, 
    ...
    )
{
    AssertSz(REPORT_NONE != rl, "REPORT_NONE is not a valid tracing level");

    HRESULT hr = S_OK;
    char szOutput[DUTIL_STRING_BUFFER] = { };
    char szMsg[DUTIL_STRING_BUFFER] = { };

    if (Dutil_rlCurrentTrace < rl)
    {
        return;
    }

    va_list args;
    va_start(args, szFormat);
    hr = ::StringCchVPrintfA(szOutput, countof(szOutput), szFormat, args);
    va_end(args);

    if (SUCCEEDED(hr))
    {
        LPCSTR szPrefix = "Trace/u";
        switch (rl)
        {
        case REPORT_STANDARD:
            szPrefix = "Trace/s";
            break;
        case REPORT_VERBOSE:
            szPrefix = "Trace/v";
            break;
        case REPORT_DEBUG:
            szPrefix = "Trace/d";
            break;
        }

        if (Dutil_fTraceFilenames)
        {
            hr = ::StringCchPrintfA(szMsg, countof(szMsg), "%s [%s,%d]: %s\r\n", szPrefix, szFile, iLine, szOutput);
        }
        else
        {
            hr = ::StringCchPrintfA(szMsg, countof(szMsg), "%s: %s\r\n", szPrefix, szOutput);
        }

        if (SUCCEEDED(hr))
        {
            OutputDebugStringA(szMsg);
        }
        // else fall through to the case below
    }

    if (FAILED(hr))
    {
        if (Dutil_fTraceFilenames)
        {
            ::StringCchPrintfA(szMsg, countof(szMsg), "Trace [%s,%d]: message too long, skipping\r\n", szFile, iLine);
        }
        else
        {
            ::StringCchPrintfA(szMsg, countof(szMsg), "Trace: message too long, skipping\r\n");
        }

        szMsg[countof(szMsg)-1] = '\0';
        OutputDebugStringA(szMsg);
    }
}
Esempio n. 7
0
/*******************************************************************
Dutil_AssertMsg

*******************************************************************/
extern "C" void DAPI Dutil_AssertMsg(
    __in_z LPCSTR szMessage
    )
{
    static BOOL fInAssert = FALSE; // TODO: make this thread safe (this is a cheap hack to prevent re-entrant Asserts)

    HRESULT hr = S_OK;
    DWORD er = ERROR_SUCCESS;

    int id = IDRETRY;
    HKEY hkDebug = NULL;
    HANDLE hAssertFile = INVALID_HANDLE_VALUE;
    char szPath[MAX_PATH] = { };
    DWORD cch = 0;

    if (fInAssert)
    {
        return;
    }
    fInAssert = TRUE;

    char szMsg[DUTIL_STRING_BUFFER];
    hr = ::StringCchCopyA(szMsg, countof(szMsg), szMessage);
    ExitOnFailure(hr, "failed to copy message while building assert message");

    if (Dutil_pfnDisplayAssert)
    {
        // call custom function to display the assert string
        if (!Dutil_pfnDisplayAssert(szMsg))
        {
            ExitFunction();
        }
    }
    else
    {
        OutputDebugStringA(szMsg);
    }

    if (!Dutil_fNoAsserts)
    {
        er = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Delivery\\Debug", 0, KEY_QUERY_VALUE, &hkDebug);
        if (ERROR_SUCCESS == er)
        {
            cch = countof(szPath);
            er = ::RegQueryValueExA(hkDebug, "DeliveryAssertsLog", NULL, NULL, reinterpret_cast<BYTE*>(szPath), &cch);
            szPath[countof(szPath) - 1] = '\0'; // ensure string is null terminated since registry won't guarantee that.
            if (ERROR_SUCCESS == er)
            {
                hAssertFile = ::CreateFileA(szPath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
                if (INVALID_HANDLE_VALUE != hAssertFile)
                {
                    ::SetFilePointer(hAssertFile, 0, 0, FILE_END);
                    ::StringCchCatA(szMsg, countof(szMsg), "\r\n");
                    ::WriteFile(hAssertFile, szMsg, lstrlenA(szMsg), &cch, NULL);
                }
            }
        }

        // if anything went wrong while fooling around with the registry, just show the usual assert dialog box
        if (ERROR_SUCCESS != er)
        {
            hr = ::StringCchCatA(szMsg, countof(szMsg), "\nAbort=Debug, Retry=Skip, Ignore=Skip all");
            ExitOnFailure(hr, "failed to concat string while building assert message");

            id = ::MessageBoxA(0, szMsg, "Debug Assert Message",
                MB_SERVICE_NOTIFICATION | MB_TOPMOST | 
                MB_DEFBUTTON2 | MB_ABORTRETRYIGNORE);
        }
    }

    if (id == IDABORT)
    {
        if (Dutil_hAssertModule)
        {
            ::GetModuleFileNameA(Dutil_hAssertModule, szPath, countof(szPath));

            hr = ::StringCchPrintfA(szMsg, countof(szMsg), "Module is running from: %s\nIf you are not using pdb-stamping, place your PDB near the module and attach to process id: %d (0x%x)", szPath, ::GetCurrentProcessId(), ::GetCurrentProcessId());
            if (SUCCEEDED(hr))
            {
                ::MessageBoxA(0, szMsg, "Debug Assert Message", MB_SERVICE_NOTIFICATION | MB_TOPMOST | MB_OK);
            }
        }

        ::DebugBreak();
    }
    else if (id == IDIGNORE)
    {
        Dutil_fNoAsserts = TRUE;
    }

LExit:
    ReleaseFileHandle(hAssertFile);
    ReleaseRegKey(hkDebug);
    fInAssert = FALSE;
}
	virtual void  RunFrame ()	{
		char log[1024];
		sprintf(log,"RunFrame() "		);
		OutputDebugStringA(log);
		);
Esempio n. 9
0
STDMETHODIMP_(BOOL) CDb3Mmap::WriteContactSetting(MCONTACT contactID, DBCONTACTWRITESETTING *dbcws)
{
	if (dbcws == NULL || dbcws->szSetting == NULL || dbcws->szModule == NULL || m_bReadOnly)
		return 1;

	// the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name
	int settingNameLen = (int)mir_strlen(dbcws->szSetting);
	int moduleNameLen = (int)mir_strlen(dbcws->szModule);
	if (settingNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("WriteContactSetting() got a > 255 setting name length. \n");
#endif
		return 1;
	}
	if (moduleNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("WriteContactSetting() got a > 255 module name length. \n");
#endif
		return 1;
	}

	// used for notifications
	DBCONTACTWRITESETTING dbcwNotif = *dbcws;
	if (dbcwNotif.value.type == DBVT_WCHAR) {
		if (dbcwNotif.value.pszVal != NULL) {
			char* val = mir_utf8encodeW(dbcwNotif.value.pwszVal);
			if (val == NULL)
				return 1;

			dbcwNotif.value.pszVal = (char*)alloca(mir_strlen(val) + 1);
			mir_strcpy(dbcwNotif.value.pszVal, val);
			mir_free(val);
			dbcwNotif.value.type = DBVT_UTF8;
		}
		else return 1;
	}

	if (dbcwNotif.szModule == NULL || dbcwNotif.szSetting == NULL)
		return 1;

	DBCONTACTWRITESETTING dbcwWork = dbcwNotif;

	mir_ptr<BYTE> pEncoded(NULL);
	bool bIsEncrypted = false;
	switch (dbcwWork.value.type) {
	case DBVT_BYTE: case DBVT_WORD: case DBVT_DWORD:
		break;

	case DBVT_ASCIIZ: case DBVT_UTF8:
		bIsEncrypted = m_bEncrypted || IsSettingEncrypted(dbcws->szModule, dbcws->szSetting);
	LBL_WriteString:
		if (dbcwWork.value.pszVal == NULL)
			return 1;
		dbcwWork.value.cchVal = (WORD)mir_strlen(dbcwWork.value.pszVal);
		if (bIsEncrypted) {
			size_t len;
			BYTE *pResult = m_crypto->encodeString(dbcwWork.value.pszVal, &len);
			if (pResult != NULL) {
				pEncoded = dbcwWork.value.pbVal = pResult;
				dbcwWork.value.cpbVal = (WORD)len;
				dbcwWork.value.type = DBVT_ENCRYPTED;
			}
		}
		break;

	case DBVT_UNENCRYPTED:
		dbcwNotif.value.type = dbcwWork.value.type = DBVT_UTF8;
		goto LBL_WriteString;

	case DBVT_BLOB: case DBVT_ENCRYPTED:
		if (dbcwWork.value.pbVal == NULL)
			return 1;
		break;
	default:
		return 1;
	}

	mir_cslockfull lck(m_csDbAccess);

	DWORD ofsBlobPtr, ofsContact = GetContactOffset(contactID);
	if (ofsContact == 0) {
		_ASSERT(false); // contact doesn't exist?
		return 2;
	}

	char *szCachedSettingName = m_cache->GetCachedSetting(dbcwWork.szModule, dbcwWork.szSetting, moduleNameLen, settingNameLen);
	log3("set [%08p] %s (%p)", hContact, szCachedSettingName, szCachedSettingName);

	// we don't cache blobs and passwords
	if (dbcwWork.value.type != DBVT_BLOB && dbcwWork.value.type != DBVT_ENCRYPTED && !bIsEncrypted) {
		DBVARIANT *pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 1);
		if (pCachedValue != NULL) {
			bool bIsIdentical = false;
			if (pCachedValue->type == dbcwWork.value.type) {
				switch (dbcwWork.value.type) {
				case DBVT_BYTE:   bIsIdentical = pCachedValue->bVal == dbcwWork.value.bVal;  break;
				case DBVT_WORD:   bIsIdentical = pCachedValue->wVal == dbcwWork.value.wVal;  break;
				case DBVT_DWORD:  bIsIdentical = pCachedValue->dVal == dbcwWork.value.dVal;  break;
				case DBVT_UTF8:
				case DBVT_ASCIIZ: bIsIdentical = mir_strcmp(pCachedValue->pszVal, dbcwWork.value.pszVal) == 0; break;
				}
				if (bIsIdentical)
					return 0;
			}
			m_cache->SetCachedVariant(&dbcwWork.value, pCachedValue);
		}
		if (szCachedSettingName[-1] != 0) {
			lck.unlock();
			log2(" set resident as %s (%p)", printVariant(&dbcwWork.value), pCachedValue);
			NotifyEventHooks(hSettingChangeEvent, contactID, (LPARAM)&dbcwWork);
			return 0;
		}
	}
	else m_cache->GetCachedValuePtr(contactID, szCachedSettingName, -1);

	log1(" write database as %s", printVariant(&dbcwWork.value));

	DWORD ofsModuleName = GetModuleNameOfs(dbcwWork.szModule);
	DBContact dbc = *(DBContact*)DBRead(ofsContact, NULL);
	if (dbc.signature != DBCONTACT_SIGNATURE)
		return 1;

	// make sure the module group exists
	PBYTE pBlob;
	int bytesRequired, bytesRemaining;
	DBContactSettings dbcs;
	DWORD ofsSettingsGroup = GetSettingsGroupOfsByModuleNameOfs(&dbc, ofsModuleName);
	if (ofsSettingsGroup == 0) {  //module group didn't exist - make it
		switch (dbcwWork.value.type) {
		case DBVT_ASCIIZ: case DBVT_UTF8:
			bytesRequired = dbcwWork.value.cchVal + 2;
			break;
		case DBVT_BLOB: case DBVT_ENCRYPTED:
			bytesRequired = dbcwWork.value.cpbVal + 2;
			break;
		default:
			bytesRequired = dbcwWork.value.type;
		}
		bytesRequired += 2 + settingNameLen;
		bytesRequired += (DB_SETTINGS_RESIZE_GRANULARITY - (bytesRequired % DB_SETTINGS_RESIZE_GRANULARITY)) % DB_SETTINGS_RESIZE_GRANULARITY;
		ofsSettingsGroup = CreateNewSpace(bytesRequired + offsetof(DBContactSettings, blob));
		dbcs.signature = DBCONTACTSETTINGS_SIGNATURE;
		dbcs.ofsNext = dbc.ofsFirstSettings;
		dbcs.ofsModuleName = ofsModuleName;
		dbcs.cbBlob = bytesRequired;
		dbcs.blob[0] = 0;
		dbc.ofsFirstSettings = ofsSettingsGroup;
		DBWrite(ofsContact, &dbc, sizeof(DBContact));
		DBWrite(ofsSettingsGroup, &dbcs, sizeof(DBContactSettings));
		ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
		pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
	}
	else {
		dbcs = *(DBContactSettings*)DBRead(ofsSettingsGroup, &bytesRemaining);

		// find if the setting exists
		ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
		pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
		while (pBlob[0]) {
			NeedBytes(settingNameLen + 1);
			if (pBlob[0] == settingNameLen && !memcmp(pBlob + 1, dbcwWork.szSetting, settingNameLen))
				break;
			NeedBytes(1);
			MoveAlong(pBlob[0] + 1);
			NeedBytes(3);
			MoveAlong(1 + GetSettingValueLength(pBlob));
			NeedBytes(1);
		}

		// setting already existed, and up to end of name is in cache
		if (pBlob[0]) {
			MoveAlong(1 + settingNameLen);
			// if different type or variable length and length is different
			NeedBytes(3);
			if (pBlob[0] != dbcwWork.value.type ||
				((pBlob[0] == DBVT_ASCIIZ || pBlob[0] == DBVT_UTF8) && *(PWORD)(pBlob + 1) != dbcwWork.value.cchVal) ||
				((pBlob[0] == DBVT_BLOB || pBlob[0] == DBVT_ENCRYPTED) && *(PWORD)(pBlob + 1) != dbcwWork.value.cpbVal))
			{
				// bin it
				NeedBytes(3);
				int nameLen = 1 + settingNameLen;
				int valLen = 1 + GetSettingValueLength(pBlob);
				DWORD ofsSettingToCut = ofsBlobPtr - nameLen;
				MoveAlong(valLen);
				NeedBytes(1);
				while (pBlob[0]) {
					MoveAlong(pBlob[0] + 1);
					NeedBytes(3);
					MoveAlong(1 + GetSettingValueLength(pBlob));
					NeedBytes(1);
				}
				DBMoveChunk(ofsSettingToCut, ofsSettingToCut + nameLen + valLen, ofsBlobPtr + 1 - ofsSettingToCut);
				ofsBlobPtr -= nameLen + valLen;
				pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
			}
			else {
				// replace existing setting at pBlob
				MoveAlong(1);	// skip data type
				switch (dbcwWork.value.type) {
				case DBVT_BYTE:  DBWrite(ofsBlobPtr, &dbcwWork.value.bVal, 1); break;
				case DBVT_WORD:  DBWrite(ofsBlobPtr, &dbcwWork.value.wVal, 2); break;
				case DBVT_DWORD: DBWrite(ofsBlobPtr, &dbcwWork.value.dVal, 4); break;
				case DBVT_BLOB:
					DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
					break;
				case DBVT_ENCRYPTED:
					DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
					break;
				case DBVT_UTF8:
				case DBVT_ASCIIZ:
					DBWrite(ofsBlobPtr + 2, dbcwWork.value.pszVal, dbcwWork.value.cchVal);
					break;
				}
				// quit
				DBFlush(1);
				lck.unlock();
				// notify
				NotifyEventHooks(hSettingChangeEvent, contactID, (LPARAM)&dbcwNotif);
				return 0;
			}
		}
	}

	// cannot do a simple replace, add setting to end of list
	// pBlob already points to end of list
	// see if it fits
	switch (dbcwWork.value.type) {
	case DBVT_ASCIIZ: case DBVT_UTF8:
		bytesRequired = dbcwWork.value.cchVal + 2;
		break;
	case DBVT_BLOB: case DBVT_ENCRYPTED:
		bytesRequired = dbcwWork.value.cpbVal + 2;
		break;
	default:
		bytesRequired = dbcwWork.value.type;
	}

	bytesRequired += 2 + settingNameLen;
	bytesRequired += ofsBlobPtr + 1 - (ofsSettingsGroup + offsetof(DBContactSettings, blob));

	if ((DWORD)bytesRequired > dbcs.cbBlob) {
		// doesn't fit: move entire group
		DBContactSettings *dbcsPrev;
		DWORD ofsDbcsPrev, ofsNew;

		InvalidateSettingsGroupOfsCacheEntry(ofsSettingsGroup);
		bytesRequired += (DB_SETTINGS_RESIZE_GRANULARITY - (bytesRequired % DB_SETTINGS_RESIZE_GRANULARITY)) % DB_SETTINGS_RESIZE_GRANULARITY;
		// find previous group to change its offset
		ofsDbcsPrev = dbc.ofsFirstSettings;
		if (ofsDbcsPrev == ofsSettingsGroup) ofsDbcsPrev = 0;
		else {
			dbcsPrev = (DBContactSettings*)DBRead(ofsDbcsPrev, NULL);
			while (dbcsPrev->ofsNext != ofsSettingsGroup) {
				if (dbcsPrev->ofsNext == 0) DatabaseCorruption(NULL);
				ofsDbcsPrev = dbcsPrev->ofsNext;
				dbcsPrev = (DBContactSettings*)DBRead(ofsDbcsPrev, NULL);
			}
		}

		// create the new one
		ofsNew = ReallocSpace(ofsSettingsGroup, dbcs.cbBlob + offsetof(DBContactSettings, blob), bytesRequired + offsetof(DBContactSettings, blob));

		dbcs.cbBlob = bytesRequired;

		DBWrite(ofsNew, &dbcs, offsetof(DBContactSettings, blob));
		if (ofsDbcsPrev == 0) {
			dbc.ofsFirstSettings = ofsNew;
			DBWrite(ofsContact, &dbc, sizeof(DBContact));
		}
		else {
			dbcsPrev = (DBContactSettings*)DBRead(ofsDbcsPrev, NULL);
			dbcsPrev->ofsNext = ofsNew;
			DBWrite(ofsDbcsPrev, dbcsPrev, offsetof(DBContactSettings, blob));
		}
		ofsBlobPtr += ofsNew - ofsSettingsGroup;
		ofsSettingsGroup = ofsNew;
		pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
	}

	// we now have a place to put it and enough space: make it
	DBWrite(ofsBlobPtr, &settingNameLen, 1);
	DBWrite(ofsBlobPtr + 1, (PVOID)dbcwWork.szSetting, settingNameLen);
	MoveAlong(1 + settingNameLen);
	DBWrite(ofsBlobPtr, &dbcwWork.value.type, 1);
	MoveAlong(1);
	switch (dbcwWork.value.type) {
	case DBVT_BYTE: DBWrite(ofsBlobPtr, &dbcwWork.value.bVal, 1); MoveAlong(1); break;
	case DBVT_WORD: DBWrite(ofsBlobPtr, &dbcwWork.value.wVal, 2); MoveAlong(2); break;
	case DBVT_DWORD: DBWrite(ofsBlobPtr, &dbcwWork.value.dVal, 4); MoveAlong(4); break;

	case DBVT_BLOB:
		DBWrite(ofsBlobPtr, &dbcwWork.value.cpbVal, 2);
		DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
		MoveAlong(2 + dbcwWork.value.cpbVal);
		break;

	case DBVT_ENCRYPTED:
		DBWrite(ofsBlobPtr, &dbcwWork.value.cpbVal, 2);
		DBWrite(ofsBlobPtr + 2, dbcwWork.value.pbVal, dbcwWork.value.cpbVal);
		MoveAlong(2 + dbcwWork.value.cpbVal);
		break;

	case DBVT_UTF8: case DBVT_ASCIIZ:
		DBWrite(ofsBlobPtr, &dbcwWork.value.cchVal, 2);
		DBWrite(ofsBlobPtr + 2, dbcwWork.value.pszVal, dbcwWork.value.cchVal);
		MoveAlong(2 + dbcwWork.value.cchVal);
		break;
	}

	BYTE zero = 0;
	DBWrite(ofsBlobPtr, &zero, 1);

	// quit
	DBFlush(1);
	lck.unlock();

	// notify
	NotifyEventHooks(hSettingChangeEvent, contactID, (LPARAM)&dbcwNotif);
	return 0;
}
Esempio n. 10
0
BOOL CreateOpenGLRenderContext(HWND hWnd)
{
	BOOL bResult;
	char buffer[128];
	PIXELFORMATDESCRIPTOR pfd = {
		sizeof(PIXELFORMATDESCRIPTOR),  //  size of this pfd  
		1,                     // version number  
		PFD_DRAW_TO_WINDOW |   // support window  
		PFD_SUPPORT_OPENGL |   // support OpenGL  
		PFD_DOUBLEBUFFER,      // double buffered  
		PFD_TYPE_RGBA,         // RGBA type  
		32,                    // 24-bit color depth  
		0, 0, 0, 0, 0, 0,      // color bits ignored  
		0,                     // no alpha buffer  
		0,                     // shift bit ignored  
		0,                     // no accumulation buffer  
		0, 0, 0, 0,            // accum bits ignored  
		24,                    // 32-bit z-buffer      
		8,                     // no stencil buffer  
		0,                     // no auxiliary buffer  
		PFD_MAIN_PLANE,        // main layer  
		0,                     // reserved  
		0, 0, 0                // layer masks ignored  
	};

	hDC = GetDC(hWnd);
	if (hDC == NULL)
	{
		OutputDebugStringA("Error: GetDC Failed!\n");
		return FALSE;
	}

	int pixelFormatIndex;
	pixelFormatIndex = ChoosePixelFormat(hDC, &pfd);
	if (pixelFormatIndex == 0)
	{
		sprintf(buffer, "Error %d: ChoosePixelFormat Failed!\n", GetLastError());
		OutputDebugStringA(buffer);
		return FALSE;
	}
	bResult = SetPixelFormat(hDC, pixelFormatIndex, &pfd);
	if (pixelFormatIndex == FALSE)
	{
		OutputDebugStringA("SetPixelFormat Failed!\n");
		return FALSE;
	}

	openGLRC = wglCreateContext(hDC);
	if (openGLRC == NULL)
	{
		sprintf(buffer, "Error %d: wglCreateContext Failed!\n", GetLastError());
		OutputDebugStringA(buffer);
		return FALSE;
	}
	bResult = wglMakeCurrent(hDC, openGLRC);
	if (bResult == FALSE)
	{
		sprintf(buffer, "Error %d: wglMakeCurrent Failed!\n", GetLastError());
		OutputDebugStringA(buffer);
		return FALSE;
	}

	sprintf(buffer, "OpenGL version info: %s\n", (char*)glGetString(GL_VERSION));
	OutputDebugStringA(buffer);
	return TRUE;
}
Esempio n. 11
0
void ReserveBottomMemory()
{
#ifdef _WIN64
    static bool s_initialized = false;
    if ( s_initialized )
        return;
    s_initialized = true;
 
    // Start by reserving large blocks of address space, and then
    // gradually reduce the size in order to capture all of the
    // fragments. Technically we should continue down to 64 KB but
    // stopping at 1 MB is sufficient to keep most allocators out.
 
    const size_t LOW_MEM_LINE = 0x100000000LL;
    size_t totalReservation = 0;
    size_t numVAllocs = 0;
    size_t numHeapAllocs = 0;
    size_t oneMB = 1024 * 1024;
    for (size_t size = 256 * oneMB; size >= oneMB; size /= 2)
    {
        for (;;)
        {
            void* p = VirtualAlloc(0, size, MEM_RESERVE, PAGE_NOACCESS);
            if (!p)
                break;
 
            if ((size_t)p >= LOW_MEM_LINE)
            {
                // We don't need this memory, so release it completely.
                VirtualFree(p, 0, MEM_RELEASE);
                break;
            }
 
            totalReservation += size;
            ++numVAllocs;
        }
    }
 
    // Now repeat the same process but making heap allocations, to use up
    // the already reserved heap blocks that are below the 4 GB line.
    HANDLE heap = GetProcessHeap();
    for (size_t blockSize = 64 * 1024; blockSize >= 16; blockSize /= 2)
    {
        for (;;)
        {
            void* p = HeapAlloc(heap, 0, blockSize);
            if (!p)
                break;
 
            if ((size_t)p >= LOW_MEM_LINE)
            {
                // We don't need this memory, so release it completely.
                HeapFree(heap, 0, p);
                break;
            }
 
            totalReservation += blockSize;
            ++numHeapAllocs;
        }
    }
 
    // Perversely enough the CRT doesn't use the process heap. Suck up
    // the memory the CRT heap has already reserved.
    for (size_t blockSize = 64 * 1024; blockSize >= 16; blockSize /= 2)
    {
        for (;;)
        {
            void* p = malloc(blockSize);
            if (!p)
                break;
 
            if ((size_t)p >= LOW_MEM_LINE)
            {
                // We don't need this memory, so release it completely.
                free(p);
                break;
            }
 
            totalReservation += blockSize;
            ++numHeapAllocs;
        }
    }
 
    // Print diagnostics showing how many allocations we had to make in
    // order to reserve all of low memory, typically less than 200.
    char buffer[1000];
    sprintf_s(buffer, "Reserved %1.3f MB (%d vallocs,"
                      "%d heap allocs) of low-memory.\n",
            totalReservation / (1024 * 1024.0),
            (int)numVAllocs, (int)numHeapAllocs);
    OutputDebugStringA(buffer);
#endif
}
Esempio n. 12
0
void DbgMsgTest()
{
	OutputDebugStringA("Message 1 without newline");
	OutputDebugStringA("Message 2 without newline");
	OutputDebugStringA("Message 3 with newline\n");
	OutputDebugStringA("Message with\nembedded newline\n");
	OutputDebugStringA("This should look like a table in a non-proportionally spaced font like 'Courier'");
	OutputDebugStringA("Colomn1\tColomn2\tColomn3\tColomn4\tColomn5");
	OutputDebugStringA("1\t\t2\t\t3\t\t4\t\t5");
	OutputDebugStringA("A\t\tB\t\tC\t\tD\t\tE");
	OutputDebugStringA("11\t\t12\t\t13\t\t14\t\t15");
	OutputDebugStringA("\t\t22\t\t23A\t\t24\t\t25");
	OutputDebugStringA("\t\t\t\t33\t\t34\t\t35");
	OutputDebugStringA("2LongLine: Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Very Long Message that ends in a single newline. Message ends HERE.\n");
}
Esempio n. 13
0
int main(int argc, char* argv[])
{
	std::cout << "DbgMsgSrc, pid: " << GetCurrentProcessId() << std::endl;
	//OutputDebugStringA("ping");
	//return 0;

	// get un-spoofable executable file name 
	//char buf[260];
	//GetMappedFileName(GetCurrentProcess(), _tmain, buf, sizeof(buf));
	//printf("%S\n", buf);

	//HANDLE handle1 = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
	//HANDLE handle2 = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
	//HANDLE handle3 = ::OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, GetCurrentProcessId());
	//printf(" %p, %p, %p\n", handle1, handle2, handle3);

	int lastArgc = argc - 1;
	for (int i = 1; i < argc; ++i)
	{
		std::string arg(argv[i]);
		if (arg == "-1")
		{
			Output("titan_crash_debugview_43mb.log");
			return 0;
		}
		else if (arg == "-2")
		{
			if (i == lastArgc)
			{
				PrintUsage();
				return -1;
			}
			Output(argv[i + 1]);
			return 0;
		}
		else if (arg == "-3")
		{
			EndlessTest();
			return 0;
		}
		else if (arg == "-s")		// run separate process test
		{
			SeparateProcessTest();
			return 0;
		}
		else if (arg == "-w")
		{
			std::cout << "Send OutputDebugStringA 'WithoutNewLine ' (15 bytes)\n";
			OutputDebugStringA("WithoutNewLine ");
			return 0;
		}
		else if (arg == "-n")
		{
			std::cout << "Send OutputDebugStringA 'WithNewLine\\n' (12 bytes)\n";
			OutputDebugStringA("WithNewLine\n");
			return 0;
		}
		else if (arg == "-e")
		{
			std::cout << "Send empty OutputDebugStringA message (0 bytes)\n";
			OutputDebugStringA("");			//empty message
			return 0;
		}
		else if (arg == "-4")
		{
			std::cout << "Send 2x OutputDebugStringA 'WithNewLine\\n (24 bytes)'\n";
			OutputDebugStringA("WithNewLine\n");
			OutputDebugStringA("WithNewLine\n");
			return 0;
		}
		else if (arg == "-5")
		{
			std::cout << "Send OutputDebugStringA '1\\n2\\n3\\n' (6 bytes)\n";
			OutputDebugStringA("1\n2\n3\n");
			return 0;
		}
		else if (arg == "-6")
		{
			std::cout << "Send OutputDebugStringA '1 ' '2 ' '3\\n' in separate messages (6 bytes)\n";
			OutputDebugStringA("1 ");
			OutputDebugStringA("2 ");
			OutputDebugStringA("3\n");
			return 0;
		}
		else if (arg == "-7")
		{
			DbgMsgTest();
			return 0;
		}
		else if (arg == "-8")
		{
			if (i == lastArgc)
			{
				PrintUsage();
				return -1;
			}
			int n = atoi(argv[i + 1]);
			DbgMsgSrc(n);
			return 0;
		}
		else if (arg == "-9")
		{
			DbgMsgClearTest();
			return 0;
		}
		else if (arg == "-A")
		{
			CoutCerrTest();
			return 0;
		}
		else if (arg == "-B")
		{
			CoutCerrTest2();
			return 0;
		}
		else if (arg == "-C")
		{
			SocketTest();
			return 0;
		}
		else
		{
			Output(arg);
			return 0;
		}
	}
	PrintUsage();
	return 0;
}
Esempio n. 14
0
void Log::output(const char* str)
{
	OutputDebugStringA(str);
}
Esempio n. 15
0
BOOL InjectDll(DWORD dwPID, char *szDllName)  
{  
    HANDLE hProcess2 = NULL;  
    LPVOID pRemoteBuf = NULL;  
    FARPROC pThreadProc = NULL;  

	PROCESS_INFORMATION pi;
	STARTUPINFO si;
	BOOL bResult = FALSE;
	DWORD dwSessionId = -1;
	DWORD winlogonPid = -1;
	HANDLE hUserToken,hUserTokenDup,hPToken,hProcess;
	DWORD dwCreationFlags;
	TCHAR wcQMountPath[256];
	TCHAR wcQMountArgs[256];

	memset(wcQMountPath,0,sizeof(wcQMountPath));
	memset(wcQMountArgs,0,sizeof(wcQMountArgs));

	//dwSessionId = WTSGetActiveConsoleSessionId();

	HMODULE hModuleKern = LoadLibrary( TEXT("KERNEL32.dll") );
	if( hModuleKern != NULL ) 
	{
		DWORD	(__stdcall *funcWTSGetActiveConsoleSessionId) (void);

		funcWTSGetActiveConsoleSessionId = (DWORD  (__stdcall *)(void))GetProcAddress( hModuleKern, "WTSGetActiveConsoleSessionId" );
		if( funcWTSGetActiveConsoleSessionId != NULL ) 
		{
			dwSessionId = funcWTSGetActiveConsoleSessionId();
		}
	}
	if( hModuleKern != NULL ) 
	{
		// ¥í©`¥É¤·¤¿DLL¤ò½â·Å
		FreeLibrary( hModuleKern );
	}
	OutputDebugStringA("LaunchAppIntoDifferentSession is called.\n");

	//
	// Find the winlogon process
	//
	PROCESSENTRY32 procEntry;

	HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	if (hSnap == INVALID_HANDLE_VALUE){
		return FALSE;
	}

	procEntry.dwSize = sizeof(PROCESSENTRY32);
	if (!Process32First(hSnap, &procEntry)){
		return FALSE;
	}

	do
	{
		if (stricmp(procEntry.szExeFile, "winlogon.exe") == 0)
		{
			//
			// We found a winlogon process...make sure it's running in the console session
			//
			DWORD winlogonSessId = 0;
			if (ProcessIdToSessionId(procEntry.th32ProcessID, &winlogonSessId) && winlogonSessId == dwSessionId){
				winlogonPid = procEntry.th32ProcessID;
				break;
			}
		}
	} while (Process32Next(hSnap, &procEntry));

	if (-1 == winlogonPid) {
	}



	//WTSQueryUserToken(dwSessionId,&hUserToken);
    BOOL    (__stdcall *funcWTSQueryUserToken) (ULONG, PHANDLE);
	HMODULE hModuleWTS = LoadLibrary( TEXT("Wtsapi32.dll") );
	if( hModuleWTS != NULL ) 
	{
		BOOL    (__stdcall *funcWTSQueryUserToken) (ULONG, PHANDLE);

		funcWTSQueryUserToken = (BOOL  (__stdcall *)(ULONG, PHANDLE))GetProcAddress( hModuleWTS, "WTSQueryUserToken" );
		if( funcWTSQueryUserToken != NULL ) 
		{
			funcWTSQueryUserToken(dwSessionId,&hUserToken);
		}
	}
	if( hModuleWTS != NULL ) 
	{
		// ¥í©`¥É¤·¤¿DLL¤ò½â·Å
		FreeLibrary( hModuleKern );
	}

	dwCreationFlags = NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE;
	ZeroMemory(&si, sizeof(STARTUPINFO));
	si.cb= sizeof(STARTUPINFO);
	si.lpDesktop = "winsta0\\default";
	ZeroMemory(&pi, sizeof(pi));
	TOKEN_PRIVILEGES tp;
	LUID luid;
	hProcess = OpenProcess(MAXIMUM_ALLOWED,FALSE,winlogonPid);

	if( !::OpenProcessToken(hProcess,
							TOKEN_ADJUST_PRIVILEGES|TOKEN_QUERY|TOKEN_DUPLICATE|
							TOKEN_ASSIGN_PRIMARY|TOKEN_ADJUST_SESSIONID|TOKEN_READ|TOKEN_WRITE,
							&hPToken))
	{
		//OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]: OpenProcessToken(Error=%d)\n",GetLastError());
	}

	if (!LookupPrivilegeValue(NULL,SE_DEBUG_NAME,&luid))
	{
		//OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]:LookupPrivilegeValue.(Error=%d)\n",GetLastError());
	}

	tp.PrivilegeCount =1;
	tp.Privileges[0].Luid =luid;
	tp.Privileges[0].Attributes =SE_PRIVILEGE_ENABLED;

	DuplicateTokenEx(hPToken,MAXIMUM_ALLOWED,NULL,SecurityIdentification,TokenPrimary,&hUserTokenDup);
	int dup = GetLastError();

	//
	//Adjust Token privilege
	//
	SetTokenInformation(hUserTokenDup,TokenSessionId,(void*)dwSessionId,sizeof(DWORD));

	if (!AdjustTokenPrivileges(hUserTokenDup,FALSE,&tp,sizeof(TOKEN_PRIVILEGES),(PTOKEN_PRIVILEGES)NULL,NULL))
	{
		//OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]: AdjustTokenPrivileges.(Error=%d)\n",GetLastError());
	}

	if (GetLastError()== ERROR_NOT_ALL_ASSIGNED)
	{
		//OutputDebugPrintf("Failed[LaunchAppIntoDifferentSession]: Token does not have the provilege\n");
	}

	LPVOID pEnv =NULL;

	if(CreateEnvironmentBlock(&pEnv,hUserTokenDup,TRUE)){
		dwCreationFlags |= CREATE_UNICODE_ENVIRONMENT;
	}
	else
	{
		pEnv=NULL;
	}

    
    DWORD dwBufSize = strlen(szDllName)+1;  
    if ( !(hProcess2 = OpenProcess(PROCESS_ALL_ACCESS, FALSE, dwPID)) )  
    {  
        printf("[´íÎó] OpenProcess(%d) µ÷ÓÃʧ°Ü£¡´íÎó´úÂë: [%d]/n",   
        dwPID, GetLastError());  
        return FALSE;  
    }  
    pRemoteBuf = VirtualAllocEx(hProcess, NULL, dwBufSize,   
                                MEM_COMMIT, PAGE_READWRITE);  
    WriteProcessMemory(hProcess, pRemoteBuf, (LPVOID)szDllName,   
                       dwBufSize, NULL);  
    pThreadProc = GetProcAddress(GetModuleHandle("kernel32.dl"),   
                                 "LoadLibraryA");  
    if( !MyCreateRemoteThread(hProcess, (LPTHREAD_START_ROUTINE)pThreadProc, pRemoteBuf) )  
    {  
        printf("[´íÎó] CreateRemoteThread() µ÷ÓÃʧ°Ü£¡´íÎó´úÂë: [%d]/n", GetLastError());  
        return FALSE;  
    }  
    VirtualFreeEx(hProcess2, pRemoteBuf, 0, MEM_RELEASE);  
    CloseHandle(hProcess2);  

	CloseHandle(hProcess);
	CloseHandle(hUserToken);
	CloseHandle(hUserTokenDup);
	CloseHandle(hPToken);

    return TRUE;  
}  
Esempio n. 16
0
int CDb3Mmap::GetContactSettingWorker(MCONTACT contactID, LPCSTR szModule, LPCSTR szSetting, DBVARIANT *dbv, int isStatic)
{
	if (szSetting == NULL || szModule == NULL)
		return 1;

	// the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name
	int settingNameLen = (int)mir_strlen(szSetting);
	int moduleNameLen = (int)mir_strlen(szModule);
	if (settingNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("GetContactSettingWorker() got a > 255 setting name length. \n");
#endif
		return 1;
	}
	if (moduleNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("GetContactSettingWorker() got a > 255 module name length. \n");
#endif
		return 1;
	}

	mir_cslock lck(m_csDbAccess);

LBL_Seek:
	char *szCachedSettingName = m_cache->GetCachedSetting(szModule, szSetting, moduleNameLen, settingNameLen);
	log3("get [%08p] %s (%p)", hContact, szCachedSettingName, szCachedSettingName);

	DBVARIANT *pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 0);
	if (pCachedValue != NULL) {
		if (pCachedValue->type == DBVT_ASCIIZ || pCachedValue->type == DBVT_UTF8) {
			int cbOrigLen = dbv->cchVal;
			char *cbOrigPtr = dbv->pszVal;
			memcpy(dbv, pCachedValue, sizeof(DBVARIANT));
			if (isStatic) {
				int cbLen = 0;
				if (pCachedValue->pszVal != NULL)
					cbLen = (int)mir_strlen(pCachedValue->pszVal);

				cbOrigLen--;
				dbv->pszVal = cbOrigPtr;
				if (cbLen < cbOrigLen)
					cbOrigLen = cbLen;
				memcpy(dbv->pszVal, pCachedValue->pszVal, cbOrigLen);
				dbv->pszVal[cbOrigLen] = 0;
				dbv->cchVal = cbLen;
			}
			else {
				dbv->pszVal = (char*)mir_alloc(mir_strlen(pCachedValue->pszVal) + 1);
				mir_strcpy(dbv->pszVal, pCachedValue->pszVal);
			}
		}
		else memcpy(dbv, pCachedValue, sizeof(DBVARIANT));

		log2("get cached %s (%p)", printVariant(dbv), pCachedValue);
		return (pCachedValue->type == DBVT_DELETED) ? 1 : 0;
	}

	// never look db for the resident variable
	if (szCachedSettingName[-1] != 0)
		return 1;

	DBCachedContact *cc;
	DWORD ofsContact = GetContactOffset(contactID, &cc);

	DWORD ofsModuleName = GetModuleNameOfs(szModule);

	DBContact dbc = *(DBContact*)DBRead(ofsContact, NULL);
	if (dbc.signature != DBCONTACT_SIGNATURE)
		return 1;

	DWORD ofsSettingsGroup = GetSettingsGroupOfsByModuleNameOfs(&dbc, ofsModuleName);
	if (ofsSettingsGroup) {
		int bytesRemaining;
		unsigned varLen;
		DWORD ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
		PBYTE pBlob = DBRead(ofsBlobPtr, &bytesRemaining);
		while (pBlob[0]) {
			NeedBytes(1 + settingNameLen);
			if (pBlob[0] == settingNameLen && !memcmp(pBlob + 1, szSetting, settingNameLen)) {
				MoveAlong(1 + settingNameLen);
				NeedBytes(5);
				if (isStatic && (pBlob[0] & DBVTF_VARIABLELENGTH) && VLT(dbv->type) != VLT(pBlob[0]))
					return 1;

				BYTE iType = dbv->type = pBlob[0];
				switch (iType) {
				case DBVT_DELETED: /* this setting is deleted */
					dbv->type = DBVT_DELETED;
					return 2;

				case DBVT_BYTE:  dbv->bVal = pBlob[1]; break;
				case DBVT_WORD:  memmove(&(dbv->wVal), (PWORD)(pBlob + 1), 2); break;
				case DBVT_DWORD: memmove(&(dbv->dVal), (PDWORD)(pBlob + 1), 4); break;

				case DBVT_UTF8:
				case DBVT_ASCIIZ:
					varLen = *(PWORD)(pBlob + 1);
					NeedBytes(int(3 + varLen));
					if (isStatic) {
						dbv->cchVal--;
						if (varLen < dbv->cchVal)
							dbv->cchVal = varLen;
						memmove(dbv->pszVal, pBlob + 3, dbv->cchVal); // decode
						dbv->pszVal[dbv->cchVal] = 0;
						dbv->cchVal = varLen;
					}
					else {
						dbv->pszVal = (char*)mir_alloc(1 + varLen);
						memmove(dbv->pszVal, pBlob + 3, varLen);
						dbv->pszVal[varLen] = 0;
					}
					break;

				case DBVT_BLOB:
					varLen = *(PWORD)(pBlob + 1);
					NeedBytes(int(3 + varLen));
					if (isStatic) {
						if (varLen < dbv->cpbVal)
							dbv->cpbVal = varLen;
						memmove(dbv->pbVal, pBlob + 3, dbv->cpbVal);
					}
					else {
						dbv->pbVal = (BYTE *)mir_alloc(varLen);
						memmove(dbv->pbVal, pBlob + 3, varLen);
					}
					dbv->cpbVal = varLen;
					break;

				case DBVT_ENCRYPTED:
					if (m_crypto == NULL)
						return 1;
					else {
						varLen = *(PWORD)(pBlob + 1);
						NeedBytes(int(3 + varLen));
						size_t realLen;
						ptrA decoded(m_crypto->decodeString(pBlob + 3, varLen, &realLen));
						if (decoded == NULL)
							return 1;

						varLen = (WORD)realLen;
						dbv->type = DBVT_UTF8;
						if (isStatic) {
							dbv->cchVal--;
							if (varLen < dbv->cchVal)
								dbv->cchVal = varLen;
							memmove(dbv->pszVal, decoded, dbv->cchVal);
							dbv->pszVal[dbv->cchVal] = 0;
							dbv->cchVal = varLen;
						}
						else {
							dbv->pszVal = (char*)mir_alloc(1 + varLen);
							memmove(dbv->pszVal, decoded, varLen);
							dbv->pszVal[varLen] = 0;
						}
					}
					break;
				}

				/**** add to cache **********************/
				if (iType != DBVT_BLOB && iType != DBVT_ENCRYPTED) {
					pCachedValue = m_cache->GetCachedValuePtr(contactID, szCachedSettingName, 1);
					if (pCachedValue != NULL) {
						m_cache->SetCachedVariant(dbv, pCachedValue);
						log3("set cached [%08p] %s (%p)", hContact, szCachedSettingName, pCachedValue);
					}
				}

				return 0;
			}
			NeedBytes(1);
			MoveAlong(pBlob[0] + 1);
			NeedBytes(3);
			MoveAlong(1 + GetSettingValueLength(pBlob));
			NeedBytes(1);
		}
	}

	// try to get the missing mc setting from the active sub
	if (cc && cc->IsMeta() && ValidLookupName(szModule, szSetting)) {
		if (contactID = db_mc_getDefault(contactID)) {
			if (szModule = GetContactProto(contactID)) {
				moduleNameLen = (int)mir_strlen(szModule);
				goto LBL_Seek;
			}
		}
	}

	logg();
	return 1;
}
Esempio n. 17
0
	void FBOutputDebugString(const char* msg){
#if defined(_PLATFORM_WINDOWS_)
		OutputDebugStringA(msg);		
#else
#endif
	}
Esempio n. 18
0
STDMETHODIMP_(BOOL) CDb3Mmap::DeleteContactSetting(MCONTACT contactID, LPCSTR szModule, LPCSTR szSetting)
{
	if (!szModule || !szSetting)
		return 1;

	// the db format can't tolerate more than 255 bytes of space (incl. null) for settings+module name
	int settingNameLen = (int)mir_strlen(szSetting);
	int moduleNameLen = (int)mir_strlen(szModule);
	if (settingNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("DeleteContactSetting() got a > 255 setting name length. \n");
#endif
		return 1;
	}
	if (moduleNameLen > 0xFE) {
#ifdef _DEBUG
		OutputDebugStringA("DeleteContactSetting() got a > 255 module name length. \n");
#endif
		return 1;
	}

	MCONTACT saveContact = contactID;
	{
		mir_cslock lck(m_csDbAccess);
		char *szCachedSettingName = m_cache->GetCachedSetting(szModule, szSetting, moduleNameLen, settingNameLen);
		if (szCachedSettingName[-1] == 0) { // it's not a resident variable
			DWORD ofsModuleName = GetModuleNameOfs(szModule);
			DWORD ofsContact = GetContactOffset(contactID);
			DBContact *dbc = (DBContact*)DBRead(ofsContact, NULL);
			if (dbc->signature != DBCONTACT_SIGNATURE)
				return 1;

			// make sure the module group exists
			DWORD ofsSettingsGroup = GetSettingsGroupOfsByModuleNameOfs(dbc, ofsModuleName);
			if (ofsSettingsGroup == 0)
				return 1;

			// find if the setting exists
			DWORD ofsBlobPtr = ofsSettingsGroup + offsetof(DBContactSettings, blob);
			int bytesRemaining;
			PBYTE pBlob = (PBYTE)DBRead(ofsBlobPtr, &bytesRemaining);
			while (pBlob[0]) {
				NeedBytes(settingNameLen + 1);
				if (pBlob[0] == settingNameLen && !memcmp(pBlob + 1, szSetting, settingNameLen))
					break;
				NeedBytes(1);
				MoveAlong(pBlob[0] + 1);
				NeedBytes(3);
				MoveAlong(1 + GetSettingValueLength(pBlob));
				NeedBytes(1);
			}
			if (!pBlob[0]) //setting didn't exist
				return 1;

			// bin it
			MoveAlong(1 + settingNameLen);
			NeedBytes(3);
			int nameLen = 1 + settingNameLen;
			int valLen = 1 + GetSettingValueLength(pBlob);
			DWORD ofsSettingToCut = ofsBlobPtr - nameLen;
			MoveAlong(valLen);
			NeedBytes(1);
			while (pBlob[0]) {
				MoveAlong(pBlob[0] + 1);
				NeedBytes(3);
				MoveAlong(1 + GetSettingValueLength(pBlob));
				NeedBytes(1);
			}
			DBMoveChunk(ofsSettingToCut, ofsSettingToCut + nameLen + valLen, ofsBlobPtr + 1 - ofsSettingToCut);
			DBFlush(1);

			// remove a value from cache anyway
			m_cache->GetCachedValuePtr(saveContact, szCachedSettingName, -1);
		}
		else { // resident variable
			// if a value doesn't exist, simply return error
			if (m_cache->GetCachedValuePtr(saveContact, szCachedSettingName, -1) == NULL)
				return 1;
		}
	}

	// notify
	DBCONTACTWRITESETTING dbcws = { 0 };
	dbcws.szModule = szModule;
	dbcws.szSetting = szSetting;
	dbcws.value.type = DBVT_DELETED;
	NotifyEventHooks(hSettingChangeEvent, saveContact, (LPARAM)&dbcws);
	return 0;
}
Esempio n. 19
0
/*******************************************************************
Dutil_TraceError

*******************************************************************/
extern "C" void DAPI Dutil_TraceError(
    __in_z LPCSTR szFile, 
    __in int iLine, 
    __in REPORT_LEVEL rl, 
    __in HRESULT hrError, 
    __in_z __format_string LPCSTR szFormat, 
    ...
    )
{
    HRESULT hr = S_OK;
    char szOutput[DUTIL_STRING_BUFFER] = { };
    char szMsg[DUTIL_STRING_BUFFER] = { };

    // if this is NOT an error report and we're not logging at this level, bail
    if (REPORT_ERROR != rl && Dutil_rlCurrentTrace < rl)
    {
        return;
    }

    va_list args;
    va_start(args, szFormat);
    hr = ::StringCchVPrintfA(szOutput, countof(szOutput), szFormat, args);
    va_end(args);

    if (SUCCEEDED(hr))
    {
        if (Dutil_fTraceFilenames)
        {
            if (FAILED(hrError))
            {
                hr = ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError 0x%x [%s,%d]: %s\r\n", hrError, szFile, iLine, szOutput);
            }
            else
            {
                hr = ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError [%s,%d]: %s\r\n", szFile, iLine, szOutput);
            }
        }
        else
        {
            if (FAILED(hrError))
            {
                hr = ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError 0x%x: %s\r\n", hrError, szOutput);
            }
            else
            {
                hr = ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError: %s\r\n", szOutput);
            }
        }

        if (SUCCEEDED(hr))
        {
            OutputDebugStringA(szMsg);
        }
        // else fall through to the failure case below
    }

    if (FAILED(hr))
    {
        if (Dutil_fTraceFilenames)
        {
            if (FAILED(hrError))
            {
                ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError 0x%x [%s,%d]: message too long, skipping\r\n", hrError, szFile, iLine);
            }
            else
            {
                ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError [%s,%d]: message too long, skipping\r\n", szFile, iLine);
            }
        }
        else
        {
            if (FAILED(hrError))
            {
                ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError 0x%x: message too long, skipping\r\n", hrError);
            }
            else
            {
                ::StringCchPrintfA(szMsg, countof(szMsg), "TraceError: message too long, skipping\r\n");
            }
        }

        szMsg[countof(szMsg)-1] = '\0';
        OutputDebugStringA(szMsg);
    }
}
Esempio n. 20
0
void Log(enum LogType type, const char* fmt, ...)
{
#ifdef DISABLE_LOG
    SP_UNREFERENCED_PARAMETER(type);
    SP_UNREFERENCED_PARAMETER(fmt);
    return;
#else

    AMDTScopeLock s(&sMutex);

    bool s_LogConsole = false;

    const char* s_LogFunction = __FUNCTION__;

    va_list arg_ptr;

    va_start(arg_ptr, fmt);

    // check to see if logging of the level is enabled, or if s_LogConsole is specified
    // if not, don't process it.
    if (type > OptionLogLevel)
    {
        va_end(arg_ptr);
        return;
    }

    // Define buffer to store maximum current log message.
    // Different destinations will receive a subset of this string.
    // On Win32 the entire string is passed to OutputDebugString()

    char fullString[SP_LOG_MAX_LENGTH] = "\0";
    int nLen = 0;
    int nSize;
    bool truncated = false;

    char* pLogString; // String to print to logfile
    char* pConsole;   // String to print to console doesn't include debug information
    char* pRaw;       // Raw string passed in without any additional decoration

    switch (type)
    {
        case traceENTER:

            if (truncated == false)
            {
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Enter: %s() ", s_LogFunction);

                if ((truncated = (nSize == -1)) == false)
                {
                    nLen += nSize;
                }
            }

            break;

        case traceEXIT:
            logIndent -= SP_LOG_INDENT_SIZE;

            if (logIndent < 0)
            {
                logIndent = 0;
            }

            truncated = (nLen == SP_LOG_MAX_LENGTH);

            if (truncated == false)
            {
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Exit : %s() ", s_LogFunction);

                if ((truncated = (nSize == -1)) == false)
                {
                    nLen += nSize;
                }
            }

            break;

        default:
            break;
    }

#ifdef WIN32

    if (truncated == false)
    {
        // Prepend "CodeXL GPU Profiler: " for windows OutputDebugString() messages
        nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "CodeXL GPU Profiler: ");

        if ((truncated = (nSize == -1)) == false)
        {
            nLen += nSize;
        }
    }

#endif

    pLogString = &fullString[nLen]; // logfile message doesn't include above WIN32 section

#if (defined SP_LOG_DEBUG) && (defined _DEBUG)
    char* s_LogFile = __FILE__;
    int s_LogLine = __LINE__;

    if (truncated == false)
    {
        // In debug builds, include the __FILE__, __LINE__ and __FUNCTION__ information
        nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "%s(%d) : %s(): ", s_LogFile, s_LogLine, s_LogFunction);

        if ((truncated = (nSize == -1)) == false)
        {
            nLen += nSize;
        }
    }

#endif

    //// Prepend accurate timestamp
    //if ( truncated == false )
    //{
    //   std::string time = StringUtils::GetTimeString();
    //   nSize = _snprintf_s( &fullString[nLen], SP_LOG_MAX_LENGTH - nLen, _TRUNCATE, "%-14s: ", time.c_str() );
    //   if ( ( truncated = ( nSize == -1 ) ) == false )
    //   {
    //      nLen += nSize;
    //   }
    //}

    pConsole = &fullString[nLen];  // String to print to console starts here

    if (truncated == false)
    {
        // Add the message type string
        switch (type)
        {
            case logERROR:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Error:   ");
                break;

            case logWARNING:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Warning: ");
                break;

            case logMESSAGE:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Message: ");
                break;

            case logTRACE:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Trace:   ");
                break;

            case logASSERT:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Assert:  ");
                break;

            case logRAW:
                // Skip
                nSize = 0;
                break;

            case traceENTER:
            case traceEXIT:
            case traceMESSAGE:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Trace:  ");
                break;

            default:
                nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "Unknown: ");
                break;
        }

        if ((truncated = (nSize == -1)) == false)
        {
            nLen += nSize;
        }
    }

    // Add the module identifier
    if (s_LogModule && (truncated == false))
    {
        nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "%-14s: ", s_LogModule);

        if ((truncated = (nSize == -1)) == false)
        {
            nLen += nSize;
        }
    }

    if (truncated == false)
    {
        if (OptionLogLevel >= logTRACE - logERROR)
        {
            // Add the indent
            for (int i = 0; (i < logIndent) && (nLen < SP_LOG_MAX_LENGTH); i++, nLen++)
            {
                fullString[nLen] = ' ';
            }

            truncated = (nLen == SP_LOG_MAX_LENGTH);
        }
    }

    pRaw = &fullString[nLen];  // Raw undecorated string starts here

    // Add the actual Log Message
    if (truncated == false)
    {
        nSize = SP_vsnprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, fmt, arg_ptr);

        if ((truncated = (nSize == -1)) == false)
        {
            nLen += nSize;
        }
    }

    // Check if message has been truncated and clean up accordingly

    if (truncated == true)
    {
        // Truncation occurred - change end of line to reflect this
        char truncationString[] = " ... \n";
        SP_sprintf(&fullString[SP_LOG_MAX_LENGTH - sizeof(truncationString)], sizeof(truncationString), "%s", truncationString);
    }

    if (type > logTRACE)
    {
        // For trace messages - force a "\n" at the end
        if (truncated == false)
        {
            nSize = SP_snprintf(&fullString[nLen], SP_LOG_MAX_LENGTH - nLen, "\n");

            if ((truncated = (nSize == -1)) == false)
            {
                nLen += nSize;
            }
        }
    }

    // Message Constructed. Print to Log, Console, and OutputDebugString as necessary
    //
    if (type == logRAW)
    {
        if (s_LogConsole)
        {
            // Send string to console
            printf("%s", pRaw);
        }

        _logWrite(pRaw);
    }
    else
    {
        if (s_LogConsole)
        {
            // Console messages are always printed in console and in log file
            // regardless of logLEVEL
            printf("%s", pConsole);
            _logWrite(pLogString);
#ifdef WIN32
            SP_TODO("revisit use of OutputDebugStringA for Unicode support")
            OutputDebugStringA(fullString);
#endif
        }
        else
        {
            // not a console message - filter based on log level
            if ((type - logERROR) <= OptionLogLevel)
            {
                if (type == logTRACE)
                {
                    // Trace messages also go to the console
                    printf("%s", pConsole);
                }

                _logWrite(pLogString);
#ifdef WIN32
                SP_TODO("revisit use of OutputDebugStringA for Unicode support")
                OutputDebugStringA(fullString);
#endif
            }
        }
    }

    va_end(arg_ptr);

#endif
}
void
Messenger::onDataReceived(
	::net::IStream::TId streamId,
	const unsigned char* buf,
	size_t bufSize)
{
	util::ScopedLock lock(&s_sync);

	try
	{
		// Append data to corresponding data buffer

		TStreamData::iterator dd = m_streamData.find(streamId);
		if (dd == m_streamData.end())
		{
			dd = m_streamData.insert(std::make_pair(streamId, TData(0))).first;
		}

		TData& data = dd->second;

		// Required data length
		size_t dataSize = data.size();
		size_t requiredLen = dataSize + bufSize;
		size_t availableLen = data.capacity();

#ifndef NDEBUG
		{
			char buf2[128];
			memset(buf2, 0, sizeof(buf2));
			sprintf(buf2, "%p data before: ", reinterpret_cast<void*>(streamId));
			OutputDebugStringA(buf2);

			if (0 < data.size())
				dumpBinBuffer(&data[0], data.size());
			else
				OutputDebugStringA("<empty>\n");
		}
#endif // !NDEBUG

		// Resize data buffer if it is not large enough
		if (availableLen < requiredLen)
		{
			// Reserve 20% more
			size_t reserve = static_cast<size_t>(requiredLen * 1.2);

			if (reserve < KMSG_INITIAL_DATA_BUF_SIZE)
				reserve = KMSG_INITIAL_DATA_BUF_SIZE;

			data.reserve(reserve);
		}

		data.resize(requiredLen);

		// Copy data to buffer
		memcpy(&data[dataSize], buf, bufSize);

		// Try to extract message from data
		while (sizeof(MessageHeader) <= (dataSize = data.size()))
		{
			MessageHeader header;
			memset(&header, 0, sizeof(header));

			assert(data.size() == dataSize);

			unsigned char* pData = &data[0];
			memcpy(&header, pData, sizeof(header));

			util::T_UI4 messageSize = header.payloadSize + sizeof(MessageHeader); // two bytes at the beginning are message type and payload length
			if (messageSize <= dataSize)
			{
				TMessagePtr message;

				try
				{
					if (!m_messageFactory)
					{
						assert(!"Message factory must be set before receiving messages");
						throw std::logic_error("Internal error");
					}

					chkptr(m_messageFactory);
					message = m_messageFactory->createMessage(header.messageType);

					{
						util::ScopedLock lock(&m_memStreamSync);
						util::MemoryStream memstream(pData + sizeof(MessageHeader), pData + messageSize);
						message->load(memstream);
					}

					// Remove message bytes from data
					{
						TData::iterator bb = data.begin();
						std::advance(bb, messageSize);

#ifndef NDEBUG
						size_t dataSizeBefore = data.size();
						assert(dataSizeBefore >= messageSize);
#endif // !NDEBUG

						data.erase(data.begin(), bb);

#ifndef NDEBUG
						size_t dataSizeAfter = data.size();
						assert(dataSizeAfter + messageSize == dataSizeBefore);
						assert(dd->second.size() == dataSizeAfter);

						{
							char buf2[128];
							memset(buf2, 0, sizeof(buf2));
							sprintf(buf2, "%p data after: ", reinterpret_cast<void*>(streamId));
							OutputDebugStringA(buf2);

							if (0 < data.size())
								dumpBinBuffer(&data[0], data.size());
							else
								OutputDebugStringA("<empty>\n");
						}
#endif // !NDEBUG
					}

					TMessengerDelegates::iterator ii = m_messengerDelegates.find(streamId);
					if (ii == m_messengerDelegates.end())
					{
						assert(0);
						throw util::Error("Stream not found");
					}

					IMessengerDelegate* delegate_ = ii->second;
					chkptr(delegate_);

					delegate_->onMessageReceived(streamId, message);
				}
				catch (const std::exception& x)
				{
#ifndef NDEBUG
					const char* szMsg = x.what();
#endif
					// Unknown messages and message handling errors are simple discarded
					ignore_unused(x);
					assert(!"Unknown message type or message handling error");
				}
				catch (...)
				{
					// Unknown messages and message handling errors are simple discarded
					assert(!"Unknown message type or message handling error");
				}
			}
			else
			{
				// Not enough data
				break;
			}
		}
	}
	catch (const std::exception& x)
	{
		// Some error (probably bad_alloc) occured while processing stream data.
		// In this case stream is assumed to be in incosistent state and thus is not used any more.
		net::StreamListener::instance().closeStream(streamId, x.what());
	}
	catch (...)
	{
		// Some unknown error occured while processing stream data.
		// In this case stream is assumed to be in incosistent state and thus is not used any more.
		net::StreamListener::instance().closeStream(streamId, "Unknown error");
	}
}
Esempio n. 22
0
	bool read_data(char* data, size_type offset, size_type size, size_type& read_size)
	{
		boost::mutex::scoped_lock lock(m_notify_mutex);
		const torrent_info& info = m_handle.get_torrent_info();
		bool ret = false;

		read_size = 0;

#if defined(_DEBUG) && defined(WIN32)
		unsigned int time = GetTickCount();
#endif
		// 计算偏移所在的片.
		int index = offset / info.piece_length();
		BOOST_ASSERT(index >= 0 && index < info.num_pieces());
		if (index >= info.num_pieces() || index < 0)
			return ret;
		torrent_status status = m_handle.status();
		if (!status.pieces.empty())
		{
			if (status.state != torrent_status::downloading &&
				status.state != torrent_status::finished &&
				status.state != torrent_status::seeding)
				return ret;

			// 设置下载位置.
			std::vector<int> pieces;

			pieces = m_handle.piece_priorities();
			std::for_each(pieces.begin(), pieces.end(), boost::lambda::_1 = 1);
			pieces[index] = 7;
			m_handle.prioritize_pieces(pieces);

			if (status.pieces.get_bit(index))
			{
				// 保存参数信息.
				m_current_buffer = data;
				m_read_offset = offset;
				m_read_size = &read_size;
				m_request_size = size;

				// 提交请求.
				m_handle.read_piece(index, boost::bind(&extern_read_op::on_read, this, _1, _2, _3));

				// 等待请求返回.
				m_notify.wait(lock);

				// 读取字节数.
				if (read_size != 0)
					ret = true;
			}
		}
		else
		{
			// 直接读取文件.
			if (m_file_path.string() == "" || !m_file.is_open())
			{
				boost::filesystem::path path = m_handle.save_path();
				const file_storage& stor = info.files();
				std::string name = stor.name();
				m_file_path = path / name;
				name = convert_to_native(m_file_path.string());

				// 打开文件, 直接从文件读取数据.
				if (!m_file.is_open())
				{
					m_file.open(name.c_str(), std::ios::in | std::ios::binary);
					if (!m_file.is_open())
						return ret;
				}
			}

			if (!m_file.is_open())
				return ret;

            m_file.clear();
            m_file.seekg(offset, std::ios::beg);
            m_file.read(data, size);
            read_size = m_file.gcount();

			if (read_size != -1)
				ret = true;
		}

#if defined(_DEBUG) && defined(WIN32)
		static unsigned int cur_time = GetTickCount();
			char str_info[8192] = { 0 };
			char *ptr = (char*)str_info;
		if (GetTickCount() - cur_time >= 5000)
		{
			cur_time = GetTickCount();
			sprintf(str_info, "request: %d, size: %d, request time: %d, peers: %d\n", 
				index, (int)size, cur_time - time, status.num_peers);
			ptr = ptr + strlen(str_info);
			for (int i = 0; i < status.pieces.size() / 8; i++)
			{
				if (i % 32 == 0)
				{
					sprintf(ptr, "\n");
					ptr += 1;
				}
				sprintf(ptr, "%02X", (unsigned char)status.pieces.bytes()[i]);
				ptr += 2;
			}
			if (status.pieces.size() % 8 != 0)
			{
				sprintf(ptr, "%02X", (unsigned char)status.pieces.bytes()[status.pieces.size() / 8]);
				ptr += 2;
			}

			sprintf(ptr, "\n\n");

			// 显示当前正在下载的分片信息.
			std::string out;
			char str[500];
			std::vector<cached_piece_info> pieces;
			torrent_handle &h = m_handle;
			std::vector<partial_piece_info> queue;
			std::vector<peer_info> peers;

			m_ses.get_cache_info(h.info_hash(), pieces);
			h.get_download_queue(queue);
			h.get_peer_info(peers);

			std::sort(queue.begin(), queue.end(), boost::bind(&partial_piece_info::piece_index, _1)
				< boost::bind(&partial_piece_info::piece_index, _2));

			std::sort(pieces.begin(), pieces.end(), boost::bind(&cached_piece_info::last_use, _1)
				> boost::bind(&cached_piece_info::last_use, _2));

			for (std::vector<cached_piece_info>::iterator i = pieces.begin();
				i != pieces.end(); ++i)
			{
				partial_piece_info* pp = 0;
				partial_piece_info tmp;
				tmp.piece_index = i->piece;
				std::vector<partial_piece_info>::iterator ppi
					= std::lower_bound(queue.begin(), queue.end(), tmp
					, boost::bind(&partial_piece_info::piece_index, _1)
					< boost::bind(&partial_piece_info::piece_index, _2));
				if (ppi != queue.end() && ppi->piece_index == i->piece) pp = &*ppi;

				print_piece(pp, &*i, peers, out);

					if (pp) queue.erase(ppi);
			}

			for (std::vector<partial_piece_info>::iterator i = queue.begin()
				 , end(queue.end()); i != end; ++i)
			{
					print_piece(&*i, 0, peers, out);
			}
			snprintf(str, sizeof(str), "%s %s: read cache %s %s: downloading %s %s: cached %s %s: flushed\n"
				, esc("34;7"), esc("0") // read cache
				, esc("33;7"), esc("0") // downloading
				, esc("36;7"), esc("0") // cached
				, esc("32;7"), esc("0")); // flushed
			out += str;
			out += "___________________________________\n";

			strcat(str_info, out.c_str());

			OutputDebugStringA(str_info);
			printf(str_info);
		}
#endif

		return ret;
	}
Esempio n. 23
0
    void EventCallback::OnModuleLoad( IProcess* process, IModule* coreModule )
    {
        OutputDebugStringA( "EventCallback::OnModuleLoad\n" );

        HRESULT     hr = S_OK;
        RefPtr<ModuleLoadEvent>     event;
        RefPtr<Program>             prog;
        RefPtr<Module>              mod;
        CComPtr<IDebugModule2>      mod2;

        if ( !mEngine->FindProgram( process->GetId(), prog ) )
            return;

        hr = prog->CreateModule( coreModule, mod );
        if ( FAILED( hr ) )
            return;

        hr = prog->AddModule( mod.Get() );
        if ( FAILED( hr ) )
            return;

        hr = mod->LoadSymbols( false );
        // later we'll check if symbols were loaded

        hr = mEngine->BindPendingBPsToModule( mod.Get(), prog.Get() );

        hr = MakeCComObject( event );
        if ( FAILED( hr ) )
            return;

        hr = mod->QueryInterface( __uuidof( IDebugModule2 ), (void**) &mod2 );
        if ( FAILED( hr ) )
            return;

        // TODO: message
        event->Init( mod2, NULL, true );

        SendEvent( event.Get(), prog.Get(), NULL );

        //-------------------------

        RefPtr<SymbolSearchEvent>       symEvent;
        CComPtr<IDebugModule3>          mod3;
        MODULE_INFO_FLAGS               flags = 0;
        RefPtr<MagoST::ISession>        session;
        CComBSTR                        name;

        mod->GetName( name );

        hr = mod->QueryInterface( __uuidof( IDebugModule3 ), (void**) &mod3 );
        if ( FAILED( hr ) )
            return;

        hr = MakeCComObject( symEvent );
        if ( FAILED( hr ) )
            return;

        if ( mod->GetSymbolSession( session ) )
            flags |= MIF_SYMBOLS_LOADED;

        symEvent->Init( mod3, name.m_str, flags );

        hr = SendEvent( symEvent.Get(), prog.Get(), NULL );
    }
Esempio n. 24
0
void AsyncGetValue( HWND hWnd )
{
	OutputDebugStringA("AsyncGetValue\n");
	PostThreadMessage(thread_id_accget_, WM_USER, 0, (LPARAM)hWnd);
}
Esempio n. 25
0
 void EventCallback::OnProcessStart( IProcess* process )
 {
     OutputDebugStringA( "EventCallback::OnProcessStart\n" );
 }
Esempio n. 26
0
static void vprintf_stderr_common(const char* format, va_list args)
{
#if PLATFORM(MAC)
    if (strstr(format, "%@")) {
        CFStringRef cfFormat = CFStringCreateWithCString(NULL, format, kCFStringEncodingUTF8);
        CFStringRef str = CFStringCreateWithFormatAndArguments(NULL, NULL, cfFormat, args);

        int length = CFStringGetMaximumSizeForEncoding(CFStringGetLength(str), kCFStringEncodingUTF8);
        char* buffer = (char*)malloc(length + 1);

        CFStringGetCString(str, buffer, length, kCFStringEncodingUTF8);

        fputs(buffer, stderr);

        free(buffer);
        CFRelease(str);
        CFRelease(cfFormat);
    } else
#elif PLATFORM(BREWMP)
    // When str is 0, the return value is the number of bytes needed
    // to accept the result including null termination.
    int size = vsnprintf(0, 0, format, args);
    if (size > 0) {
        Vector<char> buffer(size);
        vsnprintf(buffer.data(), size, format, args);
        printLog(buffer);
    }

#elif HAVE(ISDEBUGGERPRESENT)
    if (IsDebuggerPresent()) {
        size_t size = 1024;

        do {
            char* buffer = (char*)malloc(size);

            if (buffer == NULL)
                break;

            if (_vsnprintf(buffer, size, format, args) != -1) {
#if OS(WINCE)
                // WinCE only supports wide chars
                wchar_t* wideBuffer = (wchar_t*)malloc(size * sizeof(wchar_t));
                if (wideBuffer == NULL)
                    break;
                for (unsigned int i = 0; i < size; ++i) {
                    if (!(wideBuffer[i] = buffer[i]))
                        break;
                }
                OutputDebugStringW(wideBuffer);
                free(wideBuffer);
#else
                OutputDebugStringA(buffer);
#endif
                free(buffer);
                break;
            }

            free(buffer);
            size *= 2;
        } while (size > 1024);
    }
#endif
#if OS(SYMBIAN)
    vfprintf(stdout, format, args);
#else
    vfprintf(stderr, format, args);
#endif
}
Esempio n. 27
0
void DbgMsg(char *lpszFile, int Line, char *lpszMsg, ...)
{
    va_list mylist;
    va_start(mylist, lpszMsg);

    func_sprintf f_sprintf = (func_sprintf)GetProcAddress(
        LoadLibraryA("msvcrt.dll"),
        "sprintf"
    );
    if (f_sprintf == NULL)
    {
        return;
    }

    func_vsprintf f_vsprintf = (func_vsprintf)GetProcAddress(
        LoadLibraryA("msvcrt.dll"),
        "vsprintf"
    );
    if (f_vsprintf == NULL)
    {
        return;
    }

    func__vscprintf f__vscprintf = (func__vscprintf)GetProcAddress(
        LoadLibraryA("msvcrt.dll"),
        "_vscprintf"
    );
    if (f__vscprintf == NULL)
    {
        return;
    }

    size_t len = f__vscprintf(lpszMsg, mylist) + 0x100;

    char *lpszBuff = (char *)LocalAlloc(LMEM_FIXED, len);
    if (lpszBuff == NULL)
    {
        va_end(mylist);
        return;
    }

    char *lpszOutBuff = (char *)LocalAlloc(LMEM_FIXED, len);
    if (lpszOutBuff == NULL)
    {
        LocalFree(lpszBuff);
        va_end(mylist);
        return;
    }

    f_vsprintf(lpszBuff, lpszMsg, mylist);	
    va_end(mylist);

    f_sprintf(
        lpszOutBuff, "[%.5d] .\\%s(%d) : %s", 
        GetCurrentProcessId(), GetNameFromFullPath(lpszFile), Line, lpszBuff
    );

    OutputDebugStringA(lpszOutBuff);

    HANDLE hStd = GetStdHandle(STD_OUTPUT_HANDLE);
    if (hStd != INVALID_HANDLE_VALUE)
    {
        DWORD dwWritten = 0;
        WriteFile(hStd, lpszBuff, lstrlenA(lpszBuff), &dwWritten, NULL);    
    }

    LocalFree(lpszOutBuff);
    LocalFree(lpszBuff);
}
Esempio n. 28
0
void RARCH_LOG_V(const char *tag, const char *fmt, va_list ap)
{
#if TARGET_OS_IPHONE
#if TARGET_IPHONE_SIMULATOR
   vprintf(fmt, ap);
#else
   static aslclient asl_client;
   static int asl_initialized = 0;
   if (!asl_initialized)
   {
      asl_client      = asl_open(
            file_path_str(FILE_PATH_PROGRAM_NAME),
            "com.apple.console",
            ASL_OPT_STDERR | ASL_OPT_NO_DELAY);
      asl_initialized = 1;
   }
   aslmsg msg = asl_new(ASL_TYPE_MSG);
   asl_set(msg, ASL_KEY_READ_UID, "-1");
   if (tag)
      asl_log(asl_client, msg, ASL_LEVEL_NOTICE, "%s", tag);
   asl_vlog(asl_client, msg, ASL_LEVEL_NOTICE, fmt, ap);
   asl_free(msg);
#endif
#elif defined(_XBOX1)
   {
      /* FIXME: Using arbitrary string as fmt argument is unsafe. */
      char msg_new[1024];
      char buffer[1024];

      msg_new[0] = buffer[0] = '\0';
      snprintf(msg_new, sizeof(msg_new), "%s: %s %s",
            file_path_str(FILE_PATH_PROGRAM_NAME),
            tag ? tag : "",
            fmt);
      wvsprintf(buffer, msg_new, ap);
      OutputDebugStringA(buffer);
   }
#elif defined(ANDROID)
   {
      int prio = ANDROID_LOG_INFO;
      if (tag)
      {
         if (string_is_equal(file_path_str(FILE_PATH_LOG_WARN), tag))
            prio = ANDROID_LOG_WARN;
         else if (string_is_equal(file_path_str(FILE_PATH_LOG_ERROR), tag))
            prio = ANDROID_LOG_ERROR;
      }

      if (log_file_initialized)
      {
         vfprintf(log_file_fp, fmt, ap);
         fflush(log_file_fp);
      }
      else
         __android_log_vprint(prio,
               file_path_str(FILE_PATH_PROGRAM_NAME),
               fmt,
               ap);
   }
#else

   {
#if defined(HAVE_QT) || defined(__WINRT__)
      char buffer[1024];
#endif
      FILE *fp = (FILE*)retro_main_log_file();

#if defined(HAVE_QT) || defined(__WINRT__)
      buffer[0] = '\0';
      vsnprintf(buffer, sizeof(buffer), fmt, ap);

      if (fp)
      {
         fprintf(fp, "%s %s", tag ? tag : file_path_str(FILE_PATH_LOG_INFO), buffer);
         fflush(fp);
      }

#if defined(HAVE_QT)
      ui_companion_driver_log_msg(buffer);
#endif

#if defined(__WINRT__)
      OutputDebugStringA(buffer);
#endif
#else
#if defined(NXLINK) && !defined(HAVE_FILE_LOGGER)
          if (nxlink_connected)
             mutexLock(&nxlink_mtx);
#endif
      if (fp)
      {
         fprintf(fp, "%s ",
               tag ? tag : file_path_str(FILE_PATH_LOG_INFO));
         vfprintf(fp, fmt, ap);
         fflush(fp);
      }
#if defined(NXLINK) && !defined(HAVE_FILE_LOGGER)
      if (nxlink_connected)
         mutexUnlock(&nxlink_mtx);
#endif

#endif
   }
#endif
}
Esempio n. 29
0
void _PR_InitLog(void)
{
    char *ev;

    _pr_logLock = PR_NewLock();

    ev = PR_GetEnv("NSPR_LOG_MODULES");
    if (ev && ev[0]) {
        char module[64];  /* Security-Critical: If you change this
                           * size, you must also change the sscanf
                           * format string to be size-1.
                           */
        PRBool isSync = PR_FALSE;
        PRIntn evlen = strlen(ev), pos = 0;
        PRInt32 bufSize = DEFAULT_BUF_SIZE;
        while (pos < evlen) {
            PRIntn level = 1, count = 0, delta = 0;
            count = sscanf(&ev[pos], "%63[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-]%n:%d%n",
                           module, &delta, &level, &delta);
            pos += delta;
            if (count == 0) break;

            /*
            ** If count == 2, then we got module and level. If count
            ** == 1, then level defaults to 1 (module enabled).
            */
            if (strcasecmp(module, "sync") == 0) {
                isSync = PR_TRUE;
            } else if (strcasecmp(module, "bufsize") == 0) {
                if (level >= LINE_BUF_SIZE) {
                    bufSize = level;
                }
            } else if (strcasecmp(module, "timestamp") == 0) {
                outputTimeStamp = PR_TRUE;
            } else {
                PRLogModuleInfo *lm = logModules;
                PRBool skip_modcheck =
                    (0 == strcasecmp (module, "all")) ? PR_TRUE : PR_FALSE;

                while (lm != NULL) {
                    if (skip_modcheck) lm -> level = (PRLogModuleLevel)level;
                    else if (strcasecmp(module, lm->name) == 0) {
                        lm->level = (PRLogModuleLevel)level;
                        break;
                    }
                    lm = lm->next;
                }
            }
            /*found:*/
            count = sscanf(&ev[pos], " , %n", &delta);
            pos += delta;
            if (count == EOF) break;
        }
        PR_SetLogBuffering(isSync ? 0 : bufSize);

#ifdef XP_UNIX
        if ((getuid() != geteuid()) || (getgid() != getegid())) {
            return;
        }
#endif /* XP_UNIX */

        ev = PR_GetEnv("NSPR_LOG_FILE");
        if (ev && ev[0]) {
            if (!PR_SetLogFile(ev)) {
#ifdef XP_PC
                char* str = PR_smprintf("Unable to create nspr log file '%s'\n", ev);
                if (str) {
                    OutputDebugStringA(str);
                    PR_smprintf_free(str);
                }
#else
                fprintf(stderr, "Unable to create nspr log file '%s'\n", ev);
#endif
            }
        } else {
#ifdef _PR_USE_STDIO_FOR_LOGGING
            logFile = stderr;
#else
            logFile = _pr_stderr;
#endif
        }
    }
}
Esempio n. 30
0
int32_t CWelsTraceWinDgb::WriteString (int32_t iLevel, const char* pStr) {
  OutputDebugStringA (pStr);

  return strlen (pStr);
}